Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

feat: Human Input node (Frontend Part) (#31631)

Wu Tianweifedd097f632c
diff --git a/web/__mocks__/provider-context.ts b/web/__mocks__/provider-context.ts
index 373c2f86d3a..d3296bacd04 100644
--- a/web/__mocks__/provider-context.ts
+++ b/web/__mocks__/provider-context.ts
@@ -35,6 +35,7 @@ export const baseProviderContextValue: ProviderContextState = {
refreshLicenseLimit: noop,
isAllowTransferWorkspace: false,
isAllowPublishAsCustomKnowledgePipelineTemplate: false,
+ humanInputEmailDeliveryEnabled: false,
}
export const createMockProviderContextValue = (overrides: Partial<ProviderContextState> = {}): ProviderContextState => {
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/svg-attribute-error-reproduction.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/svg-attribute-error-reproduction.spec.tsx
index fc27f84c608..fffc1ff2a56 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/svg-attribute-error-reproduction.spec.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/__tests__/svg-attribute-error-reproduction.spec.tsx
@@ -8,7 +8,6 @@ describe('SVG Attribute Error Reproduction', () => {
// Capture console errors
const originalError = console.error
let errorMessages: string[] = []
-
beforeEach(() => {
errorMessages = []
console.error = vi.fn((message) => {
diff --git a/web/app/(humanInputLayout)/form/[token]/form.tsx b/web/app/(humanInputLayout)/form/[token]/form.tsx
new file mode 100644
index 00000000000..d027ef8b7d1
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/form.tsx
@@ -0,0 +1,289 @@
+'use client'
+import type { ButtonProps } from '@/app/components/base/button'
+import type { FormInputItem, UserAction } from '@/app/components/workflow/nodes/human-input/types'
+import type { SiteInfo } from '@/models/share'
+import type { HumanInputFormError } from '@/service/use-share'
+import {
+ RiCheckboxCircleFill,
+ RiErrorWarningFill,
+ RiInformation2Fill,
+} from '@remixicon/react'
+import { produce } from 'immer'
+import { useParams } from 'next/navigation'
+import * as React from 'react'
+import { useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import AppIcon from '@/app/components/base/app-icon'
+import Button from '@/app/components/base/button'
+import ContentItem from '@/app/components/base/chat/chat/answer/human-input-content/content-item'
+import ExpirationTime from '@/app/components/base/chat/chat/answer/human-input-content/expiration-time'
+import { getButtonStyle } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
+import Loading from '@/app/components/base/loading'
+import DifyLogo from '@/app/components/base/logo/dify-logo'
+import useDocumentTitle from '@/hooks/use-document-title'
+import { useGetHumanInputForm, useSubmitHumanInputForm } from '@/service/use-share'
+import { cn } from '@/utils/classnames'
+
+export type FormData = {
+ site: { site: SiteInfo }
+ form_content: string
+ inputs: FormInputItem[]
+ resolved_default_values: Record<string, string>
+ user_actions: UserAction[]
+ expiration_time: number
+}
+
+const FormContent = () => {
+ const { t } = useTranslation()
+
+ const { token } = useParams<{ token: string }>()
+ useDocumentTitle('')
+
+ const [inputs, setInputs] = useState<Record<string, string>>({})
+ const [success, setSuccess] = useState(false)
+
+ const { mutate: submitForm, isPending: isSubmitting } = useSubmitHumanInputForm()
+
+ const { data: formData, isLoading, error } = useGetHumanInputForm(token)
+
+ const expired = (error as HumanInputFormError | null)?.code === 'human_input_form_expired'
+ const submitted = (error as HumanInputFormError | null)?.code === 'human_input_form_submitted'
+ const rateLimitExceeded = (error as HumanInputFormError | null)?.code === 'web_form_rate_limit_exceeded'
+
+ const splitByOutputVar = (content: string): string[] => {
+ const outputVarRegex = /(\{\{#\$output\.[^#]+#\}\})/g
+ const parts = content.split(outputVarRegex)
+ return parts.filter(part => part.length > 0)
+ }
+
+ const contentList = useMemo(() => {
+ if (!formData?.form_content)
+ return []
+ return splitByOutputVar(formData.form_content)
+ }, [formData?.form_content])
+
+ useEffect(() => {
+ if (!formData?.inputs)
+ return
+ const initialInputs: Record<string, string> = {}
+ formData.inputs.forEach((item) => {
+ initialInputs[item.output_variable_name] = item.default.type === 'variable' ? formData.resolved_default_values[item.output_variable_name] || '' : item.default.value
+ })
+ setInputs(initialInputs)
+ }, [formData?.inputs, formData?.resolved_default_values])
+
+ // use immer
+ const handleInputsChange = (name: string, value: string) => {
+ const newInputs = produce(inputs, (draft) => {
+ draft[name] = value
+ })
+ setInputs(newInputs)
+ }
+
+ const submit = (actionID: string) => {
+ submitForm(
+ { token, data: { inputs, action: actionID } },
+ {
+ onSuccess: () => {
+ setSuccess(true)
+ },
+ },
+ )
+ }
+
+ if (isLoading) {
+ return (
+ <Loading type="app" />
+ )
+ }
+
+ if (success) {
+ return (
+ <div className={cn('flex h-full w-full flex-col items-center justify-center')}>
+ <div className="min-w-[480px] max-w-[640px]">
+ <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-sm">
+ <div className="h-[56px] w-[56px] shrink-0 rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
+ <RiCheckboxCircleFill className="h-8 w-8 text-text-success" />
+ </div>
+ <div className="grow">
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.thanks', { ns: 'share' })}</div>
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.recorded', { ns: 'share' })}</div>
+ </div>
+ <div className="system-2xs-regular-uppercase shrink-0 text-text-tertiary">{t('humanInput.submissionID', { id: token, ns: 'share' })}</div>
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className={cn(
+ 'flex shrink-0 items-center gap-1.5 px-1',
+ )}
+ >
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ if (expired) {
+ return (
+ <div className={cn('flex h-full w-full flex-col items-center justify-center')}>
+ <div className="min-w-[480px] max-w-[640px]">
+ <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-sm">
+ <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
+ <RiInformation2Fill className="h-8 w-8 text-text-accent" />
+ </div>
+ <div className="grow">
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.sorry', { ns: 'share' })}</div>
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.expired', { ns: 'share' })}</div>
+ </div>
+ <div className="system-2xs-regular-uppercase shrink-0 text-text-tertiary">{t('humanInput.submissionID', { id: token, ns: 'share' })}</div>
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className={cn(
+ 'flex shrink-0 items-center gap-1.5 px-1',
+ )}
+ >
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ if (submitted) {
+ return (
+ <div className={cn('flex h-full w-full flex-col items-center justify-center')}>
+ <div className="min-w-[480px] max-w-[640px]">
+ <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-sm">
+ <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
+ <RiInformation2Fill className="h-8 w-8 text-text-accent" />
+ </div>
+ <div className="grow">
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.sorry', { ns: 'share' })}</div>
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.completed', { ns: 'share' })}</div>
+ </div>
+ <div className="system-2xs-regular-uppercase shrink-0 text-text-tertiary">{t('humanInput.submissionID', { id: token, ns: 'share' })}</div>
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className={cn(
+ 'flex shrink-0 items-center gap-1.5 px-1',
+ )}
+ >
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ if (rateLimitExceeded) {
+ return (
+ <div className={cn('flex h-full w-full flex-col items-center justify-center')}>
+ <div className="min-w-[480px] max-w-[640px]">
+ <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-sm">
+ <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
+ <RiErrorWarningFill className="h-8 w-8 text-text-destructive" />
+ </div>
+ <div className="grow">
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.rateLimitExceeded', { ns: 'share' })}</div>
+ </div>
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className={cn(
+ 'flex shrink-0 items-center gap-1.5 px-1',
+ )}
+ >
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ if (!formData) {
+ return (
+ <div className={cn('flex h-full w-full flex-col items-center justify-center')}>
+ <div className="min-w-[480px] max-w-[640px]">
+ <div className="border-components-divider-subtle flex h-[320px] flex-col gap-4 rounded-[20px] border bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-sm">
+ <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl border border-components-panel-border-subtle bg-background-default-dodge p-3">
+ <RiErrorWarningFill className="h-8 w-8 text-text-destructive" />
+ </div>
+ <div className="grow">
+ <div className="title-4xl-semi-bold text-text-primary">{t('humanInput.formNotFound', { ns: 'share' })}</div>
+ </div>
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className={cn(
+ 'flex shrink-0 items-center gap-1.5 px-1',
+ )}
+ >
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ }
+
+ const site = formData.site.site
+
+ return (
+ <div className={cn('mx-auto flex h-full w-full max-w-[720px] flex-col items-center')}>
+ <div className="mt-4 flex w-full shrink-0 items-center gap-3 py-3">
+ <AppIcon
+ size="large"
+ iconType={site.icon_type}
+ icon={site.icon}
+ background={site.icon_background}
+ imageUrl={site.icon_url}
+ />
+ <div className="system-xl-semibold grow text-text-primary">{site.title}</div>
+ </div>
+ <div className="h-0 w-full grow overflow-y-auto">
+ <div className="border-components-divider-subtle rounded-[20px] border bg-chat-bubble-bg p-4 shadow-lg backdrop-blur-sm">
+ {contentList.map((content, index) => (
+ <ContentItem
+ key={index}
+ content={content}
+ formInputFields={formData.inputs}
+ inputs={inputs}
+ onInputChange={handleInputsChange}
+ />
+ ))}
+ <div className="flex flex-wrap gap-1 py-1">
+ {formData.user_actions.map((action: UserAction) => (
+ <Button
+ key={action.id}
+ disabled={isSubmitting}
+ variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
+ onClick={() => submit(action.id)}
+ >
+ {action.title}
+ </Button>
+ ))}
+ </div>
+ <ExpirationTime expirationTime={formData.expiration_time * 1000} />
+ </div>
+ <div className="flex flex-row-reverse px-2 py-3">
+ <div className={cn(
+ 'flex shrink-0 items-center gap-1.5 px-1',
+ )}
+ >
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('chat.poweredBy', { ns: 'share' })}</div>
+ <DifyLogo size="small" />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default React.memo(FormContent)
diff --git a/web/app/(humanInputLayout)/form/[token]/page.tsx b/web/app/(humanInputLayout)/form/[token]/page.tsx
new file mode 100644
index 00000000000..a7e2305b2be
--- /dev/null
+++ b/web/app/(humanInputLayout)/form/[token]/page.tsx
@@ -0,0 +1,13 @@
+'use client'
+import * as React from 'react'
+import FormContent from './form'
+
+const FormPage = () => {
+ return (
+ <div className="h-full min-w-[300px] bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
+ <FormContent />
+ </div>
+ )
+}
+
+export default React.memo(FormPage)
diff --git a/web/app/(shareLayout)/components/authenticated-layout.tsx b/web/app/(shareLayout)/components/authenticated-layout.tsx
index 113f3b56804..c874990448d 100644
--- a/web/app/(shareLayout)/components/authenticated-layout.tsx
+++ b/web/app/(shareLayout)/components/authenticated-layout.tsx
@@ -47,7 +47,7 @@ const AuthenticatedLayout = ({ children }: { children: React.ReactNode }) => {
await webAppLogout(shareCode!)
const url = getSigninUrl()
router.replace(url)
- }, [getSigninUrl, router, webAppLogout, shareCode])
+ }, [getSigninUrl, router, shareCode])
if (appInfoError) {
return (
diff --git a/web/app/(shareLayout)/components/splash.tsx b/web/app/(shareLayout)/components/splash.tsx
index 9f89a039933..a2b847f74fc 100644
--- a/web/app/(shareLayout)/components/splash.tsx
+++ b/web/app/(shareLayout)/components/splash.tsx
@@ -31,7 +31,7 @@ const Splash: FC<PropsWithChildren> = ({ children }) => {
await webAppLogout(shareCode!)
const url = getSigninUrl()
router.replace(url)
- }, [getSigninUrl, router, webAppLogout, shareCode])
+ }, [getSigninUrl, router, shareCode])
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsx
index 0fc364cb7eb..1348e3111fd 100644
--- a/web/app/components/app/app-publisher/index.tsx
+++ b/web/app/components/app/app-publisher/index.tsx
@@ -115,6 +115,7 @@ export type AppPublisherProps = {
missingStartNode?: boolean
hasTriggerNode?: boolean // Whether workflow currently contains any trigger nodes (used to hide missing-start CTA when triggers exist).
startNodeLimitExceeded?: boolean
+ hasHumanInputNode?: boolean
}
const PUBLISH_SHORTCUT = ['ctrl', '⇧', 'P']
@@ -138,13 +139,14 @@ const AppPublisher = ({
missingStartNode = false,
hasTriggerNode = false,
startNodeLimitExceeded = false,
+ hasHumanInputNode = false,
}: AppPublisherProps) => {
const { t } = useTranslation()
const [published, setPublished] = useState(false)
const [open, setOpen] = useState(false)
const [showAppAccessControl, setShowAppAccessControl] = useState(false)
- const [isAppAccessSet, setIsAppAccessSet] = useState(true)
+
const [embeddingModalOpen, setEmbeddingModalOpen] = useState(false)
const appDetail = useAppStore(state => state.appDetail)
@@ -161,6 +163,13 @@ const AppPublisher = ({
const { data: appAccessSubjects, isLoading: isGettingAppWhiteListSubjects } = useAppWhiteListSubjects(appDetail?.id, open && systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS)
const openAsyncWindow = useAsyncWindowOpen()
+ const isAppAccessSet = useMemo(() => {
+ if (appDetail && appAccessSubjects) {
+ return !(appDetail.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS && appAccessSubjects.groups?.length === 0 && appAccessSubjects.members?.length === 0)
+ }
+ return true
+ }, [appAccessSubjects, appDetail])
+
const noAccessPermission = useMemo(() => systemFeatures.webapp_auth.enabled && appDetail && appDetail.access_mode !== AccessMode.EXTERNAL_MEMBERS && !userCanAccessApp?.result, [systemFeatures, appDetail, userCanAccessApp])
const disabledFunctionButton = useMemo(() => (!publishedAt || missingStartNode || noAccessPermission), [publishedAt, missingStartNode, noAccessPermission])
@@ -171,25 +180,13 @@ const AppPublisher = ({
return t('noUserInputNode', { ns: 'app' })
if (noAccessPermission)
return t('noAccessPermission', { ns: 'app' })
- }, [missingStartNode, noAccessPermission, publishedAt])
+ }, [missingStartNode, noAccessPermission, publishedAt, t])
useEffect(() => {
if (systemFeatures.webapp_auth.enabled && open && appDetail)
refetch()
}, [open, appDetail, refetch, systemFeatures])
- useEffect(() => {
- if (appDetail && appAccessSubjects) {
- if (appDetail.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS && appAccessSubjects.groups?.length === 0 && appAccessSubjects.members?.length === 0)
- setIsAppAccessSet(false)
- else
- setIsAppAccessSet(true)
- }
- else {
- setIsAppAccessSet(true)
- }
- }, [appAccessSubjects, appDetail])
-
const handlePublish = useCallback(async (params?: ModelAndParameter | PublishWorkflowParams) => {
try {
await onPublish?.(params)
@@ -461,7 +458,7 @@ const AppPublisher = ({
{t('common.accessAPIReference', { ns: 'workflow' })}
</SuggestedAction>
</Tooltip>
- {appDetail?.mode === AppModeEnum.WORKFLOW && (
+ {appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && (
<WorkflowToolConfigureButton
disabled={workflowToolDisabled}
published={!!toolPublished}
diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsx
index b13eec2e3d6..40519dcb36f 100644
--- a/web/app/components/app/log/list.tsx
+++ b/web/app/components/app/log/list.tsx
@@ -68,6 +68,7 @@ type IDrawerContext = {
}
type StatusCount = {
+ paused: number
success: number
failed: number
partial_success: number
@@ -93,7 +94,15 @@ const statusTdRender = (statusCount: StatusCount) => {
if (!statusCount)
return null
- if (statusCount.partial_success + statusCount.failed === 0) {
+ if (statusCount.paused > 0) {
+ return (
+ <div className="system-xs-semibold-uppercase inline-flex items-center gap-1">
+ <Indicator color="yellow" />
+ <span className="text-util-colors-warning-warning-600">Pending</span>
+ </div>
+ )
+ }
+ else if (statusCount.partial_success + statusCount.failed === 0) {
return (
<div className="system-xs-semibold-uppercase inline-flex items-center gap-1">
<Indicator color="green" />
@@ -296,7 +305,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
if (abortControllerRef.current === controller)
abortControllerRef.current = null
}
- }, [detail.id, hasMore, timezone, t, appDetail, detail?.model_config?.configs?.introduction])
+ }, [detail.id, hasMore, timezone, t, appDetail])
// Derive chatItemTree, threadChatItems, and oldestAnswerIdRef from allChatItems
useEffect(() => {
@@ -411,7 +420,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })
return false
}
- }, [allChatItems, appDetail?.id, t])
+ }, [allChatItems, appDetail?.id, notify, t])
const fetchInitiated = useRef(false)
@@ -504,7 +513,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {
finally {
setIsLoading(false)
}
- }, [detail.id, hasMore, isLoading, timezone, t, appDetail, detail?.model_config?.configs?.introduction])
+ }, [detail.id, hasMore, isLoading, timezone, t, appDetail])
const handleScroll = useCallback(() => {
const scrollableDiv = document.getElementById('scrollableDiv')
diff --git a/web/app/components/app/overview/apikey-info-panel/apikey-info-panel.test-utils.tsx b/web/app/components/app/overview/apikey-info-panel/apikey-info-panel.test-utils.tsx
index 17857ec702d..54763907df8 100644
--- a/web/app/components/app/overview/apikey-info-panel/apikey-info-panel.test-utils.tsx
+++ b/web/app/components/app/overview/apikey-info-panel/apikey-info-panel.test-utils.tsx
@@ -53,6 +53,7 @@ const defaultProviderContext = {
refreshLicenseLimit: noop,
isAllowTransferWorkspace: false,
isAllowPublishAsCustomKnowledgePipelineTemplate: false,
+ humanInputEmailDeliveryEnabled: false,
}
const defaultModalContext: ModalContextState = {
diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsx
index c39282a0223..22358805a76 100644
--- a/web/app/components/app/text-generate/item/index.tsx
+++ b/web/app/components/app/text-generate/item/index.tsx
@@ -8,7 +8,7 @@ import {
RiClipboardLine,
RiFileList3Line,
RiPlayList2Line,
- RiReplay15Line,
+ RiResetLeftLine,
RiSparklingFill,
RiSparklingLine,
RiThumbDownLine,
@@ -18,10 +18,12 @@ import { useBoolean } from 'ahooks'
import copy from 'copy-to-clipboard'
import { useParams } from 'next/navigation'
import * as React from 'react'
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useAppStore } from '@/app/components/app/store'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
+import HumanInputFilledFormList from '@/app/components/base/chat/chat/answer/human-input-filled-form-list'
+import HumanInputFormList from '@/app/components/base/chat/chat/answer/human-input-form-list'
import WorkflowProcessItem from '@/app/components/base/chat/chat/answer/workflow-process'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import Loading from '@/app/components/base/loading'
@@ -29,7 +31,8 @@ import { Markdown } from '@/app/components/base/markdown'
import NewAudioButton from '@/app/components/base/new-audio-button'
import Toast from '@/app/components/base/toast'
import { fetchTextGenerationMessage } from '@/service/debug'
-import { AppSourceType, fetchMoreLikeThis, updateFeedback } from '@/service/share'
+import { AppSourceType, fetchMoreLikeThis, submitHumanInputForm, updateFeedback } from '@/service/share'
+import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import { cn } from '@/utils/classnames'
import ResultTab from './result-tab'
@@ -121,7 +124,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({
const [isQuerying, { setTrue: startQuerying, setFalse: stopQuerying }] = useBoolean(false)
const childProps = {
- isInWebApp: true,
+ isInWebApp,
content: completionRes,
messageId: childMessageId,
depth: depth + 1,
@@ -202,16 +205,22 @@ const GenerationItem: FC<IGenerationItemProps> = ({
}
const [currentTab, setCurrentTab] = useState<string>('DETAIL')
- const showResultTabs = !!workflowProcessData?.resultText || !!workflowProcessData?.files?.length
+ const showResultTabs = !!workflowProcessData?.resultText || !!workflowProcessData?.files?.length || (workflowProcessData?.humanInputFormDataList && workflowProcessData?.humanInputFormDataList.length > 0) || (workflowProcessData?.humanInputFilledFormDataList && workflowProcessData?.humanInputFilledFormDataList.length > 0)
const switchTab = async (tab: string) => {
setCurrentTab(tab)
}
useEffect(() => {
- if (workflowProcessData?.resultText || !!workflowProcessData?.files?.length)
+ if (workflowProcessData?.resultText || !!workflowProcessData?.files?.length || (workflowProcessData?.humanInputFormDataList && workflowProcessData?.humanInputFormDataList.length > 0) || (workflowProcessData?.humanInputFilledFormDataList && workflowProcessData?.humanInputFilledFormDataList.length > 0))
switchTab('RESULT')
else
switchTab('DETAIL')
- }, [workflowProcessData?.files?.length, workflowProcessData?.resultText])
+ }, [workflowProcessData?.files?.length, workflowProcessData?.resultText, workflowProcessData?.humanInputFormDataList, workflowProcessData?.humanInputFilledFormDataList])
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: { inputs: Record<string, string>, action: string }) => {
+ if (appSourceType === AppSourceType.installedApp)
+ await submitHumanInputFormService(formToken, formData)
+ else
+ await submitHumanInputForm(formToken, formData)
+ }, [appSourceType])
return (
<>
@@ -275,7 +284,24 @@ const GenerationItem: FC<IGenerationItemProps> = ({
)}
</div>
{!isError && (
- <ResultTab data={workflowProcessData} content={content} currentTab={currentTab} />
+ <>
+ {currentTab === 'RESULT' && workflowProcessData.humanInputFormDataList && workflowProcessData.humanInputFormDataList.length > 0 && (
+ <div className="px-4 pt-4">
+ <HumanInputFormList
+ humanInputFormDataList={workflowProcessData.humanInputFormDataList}
+ onHumanInputFormSubmit={handleSubmitHumanInputForm}
+ />
+ </div>
+ )}
+ {currentTab === 'RESULT' && workflowProcessData.humanInputFilledFormDataList && workflowProcessData.humanInputFilledFormDataList.length > 0 && (
+ <div className="px-4 pt-4">
+ <HumanInputFilledFormList
+ humanInputFilledFormDataList={workflowProcessData.humanInputFilledFormDataList}
+ />
+ </div>
+ )}
+ <ResultTab data={workflowProcessData} content={content} currentTab={currentTab} />
+ </>
)}
</>
)}
@@ -348,7 +374,7 @@ const GenerationItem: FC<IGenerationItemProps> = ({
)}
{isInWebApp && isError && (
<ActionButton onClick={onRetry}>
- <RiReplay15Line className="h-4 w-4" />
+ <RiResetLeftLine className="h-4 w-4" />
</ActionButton>
)}
{isInWebApp && !isWorkflow && !isTryApp && (
diff --git a/web/app/components/app/workflow-log/list.tsx b/web/app/components/app/workflow-log/list.tsx
index b9597c8ea1f..262efad7819 100644
--- a/web/app/components/app/workflow-log/list.tsx
+++ b/web/app/components/app/workflow-log/list.tsx
@@ -81,6 +81,14 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {
</div>
)
}
+ if (status === 'paused') {
+ return (
+ <div className="system-xs-semibold-uppercase inline-flex items-center gap-1">
+ <Indicator color="yellow" />
+ <span className="text-util-colors-warning-warning-600">Pending</span>
+ </div>
+ )
+ }
if (status === 'running') {
return (
<div className="system-xs-semibold-uppercase inline-flex items-center gap-1">
diff --git a/web/app/components/base/action-button/index.css b/web/app/components/base/action-button/index.css
index 3c1a10b86f3..4ede34aeb5a 100644
--- a/web/app/components/base/action-button/index.css
+++ b/web/app/components/base/action-button/index.css
@@ -26,6 +26,10 @@
@apply p-0.5 w-6 h-6 rounded-lg
}
+ .action-btn-s {
+ @apply w-5 h-5 rounded-[6px]
+ }
+
.action-btn-xs {
@apply p-0 w-4 h-4 rounded
}
diff --git a/web/app/components/base/action-button/index.tsx b/web/app/components/base/action-button/index.tsx
index c91d4720870..d182193b007 100644
--- a/web/app/components/base/action-button/index.tsx
+++ b/web/app/components/base/action-button/index.tsx
@@ -18,6 +18,7 @@ const actionButtonVariants = cva(
variants: {
size: {
xs: 'action-btn-xs',
+ s: 'action-btn-s',
m: 'action-btn-m',
l: 'action-btn-l',
xl: 'action-btn-xl',
diff --git a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
index 38a3f6c6b2e..304425b9a7b 100644
--- a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
+++ b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
@@ -2,6 +2,7 @@ import type { FileEntity } from '../../file-uploader/types'
import type {
ChatConfig,
ChatItem,
+ ChatItemInTree,
OnSend,
} from '../types'
import { useCallback, useEffect, useMemo, useState } from 'react'
@@ -16,7 +17,9 @@ import {
fetchSuggestedQuestions,
getUrl,
stopChatMessageResponding,
+ submitHumanInputForm,
} from '@/service/share'
+import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import { TransferMethod } from '@/types/app'
import { cn } from '@/utils/classnames'
import { formatBooleanInputs } from '@/utils/model-config'
@@ -73,9 +76,9 @@ const ChatWrapper = () => {
}, [appParams, currentConversationItem?.introduction])
const {
chatList,
- setTargetMessageId,
handleSend,
handleStop,
+ handleSwitchSibling,
isResponding: respondingState,
suggestedQuestions,
} = useChat(
@@ -122,8 +125,11 @@ const ChatWrapper = () => {
if (fileIsUploading)
return true
+
+ if (chatList.some(item => item.isAnswer && item.humanInputFormDataList && item.humanInputFormDataList.length > 0))
+ return true
return false
- }, [inputsFormValue, inputsForms, allInputsHidden])
+ }, [allInputsHidden, inputsForms, chatList, inputsFormValue])
useEffect(() => {
if (currentChatInstanceRef.current)
@@ -134,6 +140,40 @@ const ChatWrapper = () => {
setIsResponding(respondingState)
}, [respondingState, setIsResponding])
+ // Resume paused workflows when chat history is loaded
+ useEffect(() => {
+ if (!appPrevChatTree || appPrevChatTree.length === 0)
+ return
+
+ // Find the last answer item with workflow_run_id that needs resumption (DFS - find deepest first)
+ let lastPausedNode: ChatItemInTree | undefined
+ const findLastPausedWorkflow = (nodes: ChatItemInTree[]) => {
+ nodes.forEach((node) => {
+ // DFS: recurse to children first
+ if (node.children && node.children.length > 0)
+ findLastPausedWorkflow(node.children)
+
+ // Track the last node with humanInputFormDataList
+ if (node.isAnswer && node.workflow_run_id && node.humanInputFormDataList && node.humanInputFormDataList.length > 0)
+ lastPausedNode = node
+ })
+ }
+
+ findLastPausedWorkflow(appPrevChatTree)
+
+ // Only resume the last paused workflow
+ if (lastPausedNode) {
+ handleSwitchSibling(
+ lastPausedNode.id,
+ {
+ onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, appSourceType, appId),
+ onConversationComplete: currentConversationId ? undefined : handleNewConversationCompleted,
+ isPublicAPI: appSourceType === AppSourceType.webApp,
+ },
+ )
+ }
+ }, [])
+
const doSend: OnSend = useCallback((message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {
const data: any = {
query: message,
@@ -149,10 +189,10 @@ const ChatWrapper = () => {
{
onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, appSourceType, appId),
onConversationComplete: isHistoryConversation ? undefined : handleNewConversationCompleted,
- isPublicAPI: !isInstalledApp,
+ isPublicAPI: appSourceType === AppSourceType.webApp,
},
)
- }, [chatList, handleNewConversationCompleted, handleSend, currentConversationId, currentConversationInputs, newConversationInputs, isInstalledApp, appId])
+ }, [inputsForms, currentConversationId, currentConversationInputs, newConversationInputs, chatList, handleSend, appSourceType, appId, isHistoryConversation, handleNewConversationCompleted])
const doRegenerate = useCallback((chatItem: ChatItem, editedQuestion?: { message: string, files?: FileEntity[] }) => {
const question = editedQuestion ? chatItem : chatList.find(item => item.id === chatItem.parentMessageId)!
@@ -160,12 +200,27 @@ const ChatWrapper = () => {
doSend(editedQuestion ? editedQuestion.message : question.content, editedQuestion ? editedQuestion.files : question.message_files, true, isValidGeneratedAnswer(parentAnswer) ? parentAnswer : null)
}, [chatList, doSend])
+ const doSwitchSibling = useCallback((siblingMessageId: string) => {
+ handleSwitchSibling(siblingMessageId, {
+ onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, appSourceType, appId),
+ onConversationComplete: currentConversationId ? undefined : handleNewConversationCompleted,
+ isPublicAPI: appSourceType === AppSourceType.webApp,
+ })
+ }, [handleSwitchSibling, currentConversationId, handleNewConversationCompleted, appSourceType, appId])
+
const messageList = useMemo(() => {
if (currentConversationId || chatList.length > 1)
return chatList
// Without messages we are in the welcome screen, so hide the opening statement from chatlist
return chatList.filter(item => !item.isOpeningStatement)
- }, [chatList])
+ }, [chatList, currentConversationId])
+
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: any) => {
+ if (isInstalledApp)
+ await submitHumanInputFormService(formToken, formData)
+ else
+ await submitHumanInputForm(formToken, formData)
+ }, [isInstalledApp])
const [collapsed, setCollapsed] = useState(!!currentConversationId)
@@ -274,6 +329,7 @@ const ChatWrapper = () => {
inputsForm={inputsForms}
onRegenerate={doRegenerate}
onStopResponding={handleStop}
+ onHumanInputFormSubmit={handleSubmitHumanInputForm}
chatNode={(
<>
{chatNode}
@@ -286,7 +342,7 @@ const ChatWrapper = () => {
answerIcon={answerIcon}
hideProcessDetail
themeBuilder={themeBuilder}
- switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)}
+ switchSibling={doSwitchSibling}
inputDisabled={inputDisabled}
sidebarCollapseState={sidebarCollapseState}
questionIcon={
diff --git a/web/app/components/base/chat/chat-with-history/hooks.tsx b/web/app/components/base/chat/chat-with-history/hooks.tsx
index ad1de38d07b..da344a9789d 100644
--- a/web/app/components/base/chat/chat-with-history/hooks.tsx
+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx
@@ -1,3 +1,4 @@
+import type { ExtraContent } from '../chat/type'
import type {
Callback,
ChatConfig,
@@ -9,6 +10,7 @@ import type {
AppData,
ConversationItem,
} from '@/models/share'
+import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
import { useLocalStorageState } from 'ahooks'
import { noop } from 'es-toolkit/function'
import { produce } from 'immer'
@@ -57,6 +59,24 @@ function getFormattedChatList(messages: any[]) {
parentMessageId: item.parent_message_id || undefined,
})
const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
+ const humanInputFormDataList: HumanInputFormData[] = []
+ const humanInputFilledFormDataList: HumanInputFilledFormData[] = []
+ let workflowRunId = ''
+ if (item.status === 'paused') {
+ item.extra_contents?.forEach((content: ExtraContent) => {
+ if (content.type === 'human_input' && !content.submitted) {
+ humanInputFormDataList.push(content.form_definition)
+ workflowRunId = content.workflow_run_id
+ }
+ })
+ }
+ else if (item.status === 'normal') {
+ item.extra_contents?.forEach((content: ExtraContent) => {
+ if (content.type === 'human_input' && content.submitted) {
+ humanInputFilledFormDataList.push(content.form_submission_data)
+ }
+ })
+ }
newChatList.push({
id: item.id,
content: item.answer,
@@ -66,6 +86,9 @@ function getFormattedChatList(messages: any[]) {
citation: item.retriever_resources,
message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id, upload_file_id: item.upload_file_id }))),
parentMessageId: `question-${item.id}`,
+ humanInputFormDataList,
+ humanInputFilledFormDataList,
+ workflow_run_id: workflowRunId,
})
})
return newChatList
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx b/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx
new file mode 100644
index 00000000000..3ed777d41e4
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/content-item.tsx
@@ -0,0 +1,54 @@
+import type { ContentItemProps } from './type'
+import * as React from 'react'
+import { useMemo } from 'react'
+import { Markdown } from '@/app/components/base/markdown'
+import Textarea from '@/app/components/base/textarea'
+
+const ContentItem = ({
+ content,
+ formInputFields,
+ inputs,
+ onInputChange,
+}: ContentItemProps) => {
+ const isInputField = (field: string) => {
+ const outputVarRegex = /\{\{#\$output\.[^#]+#\}\}/
+ return outputVarRegex.test(field)
+ }
+
+ const extractFieldName = (str: string): string => {
+ const outputVarRegex = /\{\{#\$output\.([^#]+)#\}\}/
+ const match = str.match(outputVarRegex)
+ return match ? match[1] : ''
+ }
+
+ const fieldName = useMemo(() => {
+ return extractFieldName(content)
+ }, [content])
+
+ const formInputField = useMemo(() => {
+ return formInputFields.find(field => field.output_variable_name === fieldName)
+ }, [formInputFields, fieldName])
+
+ if (!isInputField(content)) {
+ return (
+ <Markdown content={content} />
+ )
+ }
+
+ if (!formInputField)
+ return null
+
+ return (
+ <div className="py-3">
+ {formInputField.type === 'paragraph' && (
+ <Textarea
+ className="h-[104px] sm:text-xs"
+ value={inputs[fieldName]}
+ onChange={(e) => { onInputChange(fieldName, e.target.value) }}
+ />
+ )}
+ </div>
+ )
+}
+
+export default React.memo(ContentItem)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/content-wrapper.tsx b/web/app/components/base/chat/chat/answer/human-input-content/content-wrapper.tsx
new file mode 100644
index 00000000000..acd154e30a4
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/content-wrapper.tsx
@@ -0,0 +1,64 @@
+import { RiArrowDownSLine, RiArrowRightSLine } from '@remixicon/react'
+import { useCallback, useState } from 'react'
+import BlockIcon from '@/app/components/workflow/block-icon'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { cn } from '@/utils/classnames'
+
+type ContentWrapperProps = {
+ nodeTitle: string
+ children: React.ReactNode
+ showExpandIcon?: boolean
+ className?: string
+ expanded?: boolean
+}
+
+const ContentWrapper = ({
+ nodeTitle,
+ children,
+ showExpandIcon = false,
+ className,
+ expanded = false,
+}: ContentWrapperProps) => {
+ const [isExpanded, setIsExpanded] = useState(expanded)
+
+ const handleToggleExpand = useCallback(() => {
+ setIsExpanded(!isExpanded)
+ }, [isExpanded])
+
+ return (
+ <div className={cn('rounded-2xl border-[0.5px] border-components-panel-border bg-background-section p-2 shadow-md', className)}>
+ <div className="flex items-center gap-2 p-2">
+ {/* node icon */}
+ <BlockIcon type={BlockEnum.HumanInput} className="shrink-0" />
+ {/* node name */}
+ <div
+ className="system-sm-semibold-uppercase grow truncate text-text-primary"
+ title={nodeTitle}
+ >
+ {nodeTitle}
+ </div>
+ {showExpandIcon && (
+ <div className="shrink-0 cursor-pointer" onClick={handleToggleExpand}>
+ {
+ isExpanded
+ ? (
+ <RiArrowDownSLine className="size-4" />
+ )
+ : (
+ <RiArrowRightSLine className="size-4" />
+ )
+ }
+ </div>
+ )}
+ </div>
+ {(!showExpandIcon || isExpanded) && (
+ <div className="px-2 py-1">
+ {/* human input form content */}
+ {children}
+ </div>
+ )}
+ </div>
+ )
+}
+
+export default ContentWrapper
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/executed-action.tsx b/web/app/components/base/chat/chat/answer/human-input-content/executed-action.tsx
new file mode 100644
index 00000000000..ccdfcb624bb
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/executed-action.tsx
@@ -0,0 +1,30 @@
+import type { ExecutedAction as ExecutedActionType } from './type'
+import { memo } from 'react'
+import { Trans } from 'react-i18next'
+import Divider from '@/app/components/base/divider'
+import { TriggerAll } from '@/app/components/base/icons/src/vender/workflow'
+
+type ExecutedActionProps = {
+ executedAction: ExecutedActionType
+}
+
+const ExecutedAction = ({
+ executedAction,
+}: ExecutedActionProps) => {
+ return (
+ <div className="flex flex-col gap-y-1 py-1">
+ <Divider className="mb-2 mt-1 w-[30px]" />
+ <div className="system-xs-regular flex items-center gap-x-1 text-text-tertiary">
+ <TriggerAll className="size-3.5 shrink-0" />
+ <Trans
+ i18nKey="nodes.humanInput.userActions.triggered"
+ ns="workflow"
+ components={{ strong: <span className="system-xs-medium text-text-secondary"></span> }}
+ values={{ actionName: executedAction.id }}
+ />
+ </div>
+ </div>
+ )
+}
+
+export default memo(ExecutedAction)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/expiration-time.tsx b/web/app/components/base/chat/chat/answer/human-input-content/expiration-time.tsx
new file mode 100644
index 00000000000..786440dc6b6
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/expiration-time.tsx
@@ -0,0 +1,46 @@
+'use client'
+import { RiAlertFill, RiTimeLine } from '@remixicon/react'
+import { useTranslation } from 'react-i18next'
+import { useLocale } from '@/context/i18n'
+import { cn } from '@/utils/classnames'
+import { getRelativeTime, isRelativeTimeSameOrAfter } from './utils'
+
+type ExpirationTimeProps = {
+ expirationTime: number
+}
+
+const ExpirationTime = ({
+ expirationTime,
+}: ExpirationTimeProps) => {
+ const { t } = useTranslation()
+ const locale = useLocale()
+ const relativeTime = getRelativeTime(expirationTime, locale)
+ const isSameOrAfter = isRelativeTimeSameOrAfter(expirationTime)
+
+ return (
+ <div
+ className={cn(
+ 'system-xs-regular mt-1 flex items-center gap-x-1 text-text-tertiary',
+ !isSameOrAfter && 'text-text-warning',
+ )}
+ >
+ {
+ isSameOrAfter
+ ? (
+ <>
+ <RiTimeLine className="size-3.5" />
+ <span>{t('humanInput.expirationTimeNowOrFuture', { relativeTime, ns: 'share' })}</span>
+ </>
+ )
+ : (
+ <>
+ <RiAlertFill className="size-3.5" />
+ <span>{t('humanInput.expiredTip', { ns: 'share' })}</span>
+ </>
+ )
+ }
+ </div>
+ )
+}
+
+export default ExpirationTime
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx b/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx
new file mode 100644
index 00000000000..0b5d54ab7ea
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/human-input-form.tsx
@@ -0,0 +1,61 @@
+'use client'
+import type { HumanInputFormProps } from './type'
+import type { ButtonProps } from '@/app/components/base/button'
+import type { UserAction } from '@/app/components/workflow/nodes/human-input/types'
+import * as React from 'react'
+import { useCallback, useState } from 'react'
+import Button from '@/app/components/base/button'
+import ContentItem from './content-item'
+import { getButtonStyle, initializeInputs, splitByOutputVar } from './utils'
+
+const HumanInputForm = ({
+ formData,
+ onSubmit,
+}: HumanInputFormProps) => {
+ const formToken = formData.form_token
+ const defaultInputs = initializeInputs(formData.inputs, formData.resolved_default_values || {})
+ const contentList = splitByOutputVar(formData.form_content)
+ const [inputs, setInputs] = useState(defaultInputs)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+
+ const handleInputsChange = useCallback((name: string, value: string) => {
+ setInputs(prev => ({
+ ...prev,
+ [name]: value,
+ }))
+ }, [])
+
+ const submit = async (formToken: string, actionID: string, inputs: Record<string, string>) => {
+ setIsSubmitting(true)
+ await onSubmit?.(formToken, { inputs, action: actionID })
+ setIsSubmitting(false)
+ }
+
+ return (
+ <>
+ {contentList.map((content, index) => (
+ <ContentItem
+ key={index}
+ content={content}
+ formInputFields={formData.inputs}
+ inputs={inputs}
+ onInputChange={handleInputsChange}
+ />
+ ))}
+ <div className="flex flex-wrap gap-1 py-1">
+ {formData.actions.map((action: UserAction) => (
+ <Button
+ key={action.id}
+ disabled={isSubmitting}
+ variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
+ onClick={() => submit(formToken, action.id, inputs)}
+ >
+ {action.title}
+ </Button>
+ ))}
+ </div>
+ </>
+ )
+}
+
+export default React.memo(HumanInputForm)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted-content.tsx b/web/app/components/base/chat/chat/answer/human-input-content/submitted-content.tsx
new file mode 100644
index 00000000000..68d55f7d646
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted-content.tsx
@@ -0,0 +1,16 @@
+import * as React from 'react'
+import { Markdown } from '@/app/components/base/markdown'
+
+type SubmittedContentProps = {
+ content: string
+}
+
+const SubmittedContent = ({
+ content,
+}: SubmittedContentProps) => {
+ return (
+ <Markdown content={content} />
+ )
+}
+
+export default React.memo(SubmittedContent)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx b/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx
new file mode 100644
index 00000000000..bf598d4c5db
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/submitted.tsx
@@ -0,0 +1,25 @@
+import type { SubmittedHumanInputContentProps } from './type'
+import { useMemo } from 'react'
+import ExecutedAction from './executed-action'
+import SubmittedContent from './submitted-content'
+
+export const SubmittedHumanInputContent = ({
+ formData,
+}: SubmittedHumanInputContentProps) => {
+ const { rendered_content, action_id, action_text } = formData
+
+ const executedAction = useMemo(() => {
+ return {
+ id: action_id,
+ title: action_text,
+ }
+ }, [action_id, action_text])
+
+ return (
+ <>
+ <SubmittedContent content={rendered_content} />
+ {/* Executed Action */}
+ <ExecutedAction executedAction={executedAction} />
+ </>
+ )
+}
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/tips.tsx b/web/app/components/base/chat/chat/answer/human-input-content/tips.tsx
new file mode 100644
index 00000000000..54cfc8c5a5a
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/tips.tsx
@@ -0,0 +1,43 @@
+import { memo } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import Divider from '@/app/components/base/divider'
+import { useSelector as useAppSelector } from '@/context/app-context'
+
+type TipsProps = {
+ showEmailTip: boolean
+ isEmailDebugMode: boolean
+ showDebugModeTip: boolean
+}
+
+const Tips = ({
+ showEmailTip,
+ isEmailDebugMode,
+ showDebugModeTip,
+}: TipsProps) => {
+ const { t } = useTranslation()
+ const email = useAppSelector(s => s.userProfile.email)
+
+ return (
+ <>
+ <Divider className="!my-2 w-[30px]" />
+ <div className="space-y-1 pt-1">
+ {showEmailTip && !isEmailDebugMode && (
+ <div className="system-xs-regular text-text-secondary">{t('common.humanInputEmailTip', { ns: 'workflow' })}</div>
+ )}
+ {showEmailTip && isEmailDebugMode && (
+ <div className="system-xs-regular text-text-secondary">
+ <Trans
+ i18nKey="common.humanInputEmailTipInDebugMode"
+ ns="workflow"
+ components={{ email: <span className="system-xs-semibold"></span> }}
+ values={{ email }}
+ />
+ </div>
+ )}
+ {showDebugModeTip && <div className="system-xs-medium text-text-warning">{t('common.humanInputWebappTip', { ns: 'workflow' })}</div>}
+ </div>
+ </>
+ )
+}
+
+export default memo(Tips)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/type.ts b/web/app/components/base/chat/chat/answer/human-input-content/type.ts
new file mode 100644
index 00000000000..7fb4082b4ae
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/type.ts
@@ -0,0 +1,31 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
+
+export type ExecutedAction = {
+ id: string
+ title: string
+}
+
+export type UnsubmittedHumanInputContentProps = {
+ formData: HumanInputFormData
+ showEmailTip?: boolean
+ isEmailDebugMode?: boolean
+ showDebugModeTip?: boolean
+ onSubmit?: (formToken: string, data: { inputs: Record<string, string>, action: string }) => Promise<void>
+}
+
+export type SubmittedHumanInputContentProps = {
+ formData: HumanInputFilledFormData
+}
+
+export type HumanInputFormProps = {
+ formData: HumanInputFormData
+ onSubmit?: (formToken: string, data: { inputs: Record<string, string>, action: string }) => Promise<void>
+}
+
+export type ContentItemProps = {
+ content: string
+ formInputFields: FormInputItem[]
+ inputs: Record<string, string>
+ onInputChange: (name: string, value: string) => void
+}
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/unsubmitted.tsx b/web/app/components/base/chat/chat/answer/human-input-content/unsubmitted.tsx
new file mode 100644
index 00000000000..b8b21459239
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/unsubmitted.tsx
@@ -0,0 +1,36 @@
+import type { UnsubmittedHumanInputContentProps } from './type'
+import ExpirationTime from './expiration-time'
+import HumanInputForm from './human-input-form'
+import Tips from './tips'
+
+export const UnsubmittedHumanInputContent = ({
+ formData,
+ showEmailTip = false,
+ isEmailDebugMode = false,
+ showDebugModeTip = false,
+ onSubmit,
+}: UnsubmittedHumanInputContentProps) => {
+ const { expiration_time } = formData
+
+ return (
+ <>
+ {/* Form */}
+ <HumanInputForm
+ formData={formData}
+ onSubmit={onSubmit}
+ />
+ {/* Tips */}
+ {(showEmailTip || showDebugModeTip) && (
+ <Tips
+ showEmailTip={showEmailTip}
+ isEmailDebugMode={isEmailDebugMode}
+ showDebugModeTip={showDebugModeTip}
+ />
+ )}
+ {/* Expiration Time */}
+ {typeof expiration_time === 'number' && (
+ <ExpirationTime expirationTime={expiration_time * 1000} />
+ )}
+ </>
+ )
+}
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/utils.ts b/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
new file mode 100644
index 00000000000..dd35932797f
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
@@ -0,0 +1,64 @@
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { Locale } from '@/i18n-config'
+import dayjs from 'dayjs'
+import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
+import relativeTime from 'dayjs/plugin/relativeTime'
+import utc from 'dayjs/plugin/utc'
+import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
+import 'dayjs/locale/en'
+import 'dayjs/locale/zh-cn'
+import 'dayjs/locale/ja'
+
+dayjs.extend(utc)
+dayjs.extend(relativeTime)
+dayjs.extend(isSameOrAfter)
+
+export const getButtonStyle = (style: UserActionButtonType) => {
+ if (style === UserActionButtonType.Primary)
+ return 'primary'
+ if (style === UserActionButtonType.Default)
+ return 'secondary'
+ if (style === UserActionButtonType.Accent)
+ return 'secondary-accent'
+ if (style === UserActionButtonType.Ghost)
+ return 'ghost'
+}
+
+export const splitByOutputVar = (content: string): string[] => {
+ const outputVarRegex = /(\{\{#\$output\.[^#]+#\}\})/g
+ const parts = content.split(outputVarRegex)
+ return parts.filter(part => part.length > 0)
+}
+
+export const initializeInputs = (formInputs: FormInputItem[], defaultValues: Record<string, string> = {}) => {
+ const initialInputs: Record<string, any> = {}
+ formInputs.forEach((item) => {
+ if (item.type === 'text-input' || item.type === 'paragraph')
+ initialInputs[item.output_variable_name] = item.default.type === 'variable' ? defaultValues[item.output_variable_name] || '' : item.default.value
+ else
+ initialInputs[item.output_variable_name] = undefined
+ })
+ return initialInputs
+}
+
+const localeMap: Record<string, string> = {
+ 'en-US': 'en',
+ 'zh-Hans': 'zh-cn',
+ 'ja-JP': 'ja',
+}
+
+export const getRelativeTime = (
+ utcTimestamp: string | number,
+ locale: Locale = 'en-US',
+) => {
+ const dayjsLocale = localeMap[locale] ?? 'en'
+
+ return dayjs
+ .utc(utcTimestamp)
+ .locale(dayjsLocale)
+ .fromNow()
+}
+
+export const isRelativeTimeSameOrAfter = (utcTimestamp: string | number) => {
+ return dayjs.utc(utcTimestamp).isSameOrAfter(dayjs())
+}
diff --git a/web/app/components/base/chat/chat/answer/human-input-filled-form-list.tsx b/web/app/components/base/chat/chat/answer/human-input-filled-form-list.tsx
new file mode 100644
index 00000000000..4dd82b13a76
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-filled-form-list.tsx
@@ -0,0 +1,32 @@
+import type { HumanInputFilledFormData } from '@/types/workflow'
+import ContentWrapper from './human-input-content/content-wrapper'
+import { SubmittedHumanInputContent } from './human-input-content/submitted'
+
+type HumanInputFilledFormListProps = {
+ humanInputFilledFormDataList: HumanInputFilledFormData[]
+}
+
+const HumanInputFilledFormList = ({
+ humanInputFilledFormDataList,
+}: HumanInputFilledFormListProps) => {
+ return (
+ <div className="mt-2 flex flex-col gap-y-2">
+ {
+ humanInputFilledFormDataList.map(formData => (
+ <ContentWrapper
+ key={formData.node_id}
+ nodeTitle={formData.node_title}
+ showExpandIcon
+ >
+ <SubmittedHumanInputContent
+ key={formData.node_id}
+ formData={formData}
+ />
+ </ContentWrapper>
+ ))
+ }
+ </div>
+ )
+}
+
+export default HumanInputFilledFormList
diff --git a/web/app/components/base/chat/chat/answer/human-input-form-list.tsx b/web/app/components/base/chat/chat/answer/human-input-form-list.tsx
new file mode 100644
index 00000000000..1403bcb6007
--- /dev/null
+++ b/web/app/components/base/chat/chat/answer/human-input-form-list.tsx
@@ -0,0 +1,70 @@
+import type { DeliveryMethod, HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
+import type { Node } from '@/app/components/workflow/types'
+import type { HumanInputFormData } from '@/types/workflow'
+import { useMemo } from 'react'
+import { DeliveryMethodType } from '@/app/components/workflow/nodes/human-input/types'
+import ContentWrapper from './human-input-content/content-wrapper'
+import { UnsubmittedHumanInputContent } from './human-input-content/unsubmitted'
+
+type HumanInputFormListProps = {
+ humanInputFormDataList: HumanInputFormData[]
+ onHumanInputFormSubmit?: (formToken: string, formData: { inputs: Record<string, string>, action: string }) => Promise<void>
+ getHumanInputNodeData?: (nodeID: string) => Node<HumanInputNodeType> | undefined
+}
+
+const HumanInputFormList = ({
+ humanInputFormDataList,
+ onHumanInputFormSubmit,
+ getHumanInputNodeData,
+}: HumanInputFormListProps) => {
+ const deliveryMethodsConfig = useMemo((): Record<string, { showEmailTip: boolean, isEmailDebugMode: boolean, showDebugModeTip: boolean }> => {
+ if (!humanInputFormDataList.length)
+ return {}
+ return humanInputFormDataList.reduce((acc, formData) => {
+ const deliveryMethodsConfig = getHumanInputNodeData?.(formData.node_id)?.data.delivery_methods || []
+ if (!deliveryMethodsConfig.length) {
+ acc[formData.node_id] = {
+ showEmailTip: false,
+ isEmailDebugMode: false,
+ showDebugModeTip: false,
+ }
+ return acc
+ }
+ const isWebappEnabled = deliveryMethodsConfig.some((method: DeliveryMethod) => method.type === DeliveryMethodType.WebApp && method.enabled)
+ const isEmailEnabled = deliveryMethodsConfig.some((method: DeliveryMethod) => method.type === DeliveryMethodType.Email && method.enabled)
+ const isEmailDebugMode = deliveryMethodsConfig.some((method: DeliveryMethod) => method.type === DeliveryMethodType.Email && method.config?.debug_mode)
+ acc[formData.node_id] = {
+ showEmailTip: isEmailEnabled,
+ isEmailDebugMode,
+ showDebugModeTip: !isWebappEnabled,
+ }
+ return acc
+ }, {} as Record<string, { showEmailTip: boolean, isEmailDebugMode: boolean, showDebugModeTip: boolean }>)
+ }, [getHumanInputNodeData, humanInputFormDataList])
+
+ const filteredHumanInputFormDataList = humanInputFormDataList.filter(formData => formData.display_in_ui)
+
+ return (
+ <div className="mt-2 flex flex-col gap-y-2">
+ {
+ filteredHumanInputFormDataList.map(formData => (
+ <ContentWrapper
+ key={formData.form_id}
+ nodeTitle={formData.node_title}
+ >
+ <UnsubmittedHumanInputContent
+ key={formData.form_id}
+ formData={formData}
+ showEmailTip={!!deliveryMethodsConfig[formData.node_id]?.showEmailTip}
+ isEmailDebugMode={!!deliveryMethodsConfig[formData.node_id]?.isEmailDebugMode}
+ showDebugModeTip={!!deliveryMethodsConfig[formData.node_id]?.showDebugModeTip}
+ onSubmit={onHumanInputFormSubmit}
+ />
+ </ContentWrapper>
+ ))
+ }
+ </div>
+ )
+}
+
+export default HumanInputFormList
diff --git a/web/app/components/base/chat/chat/answer/index.tsx b/web/app/components/base/chat/chat/answer/index.tsx
index da46f47c61b..0ea46aa9305 100644
--- a/web/app/components/base/chat/chat/answer/index.tsx
+++ b/web/app/components/base/chat/chat/answer/index.tsx
@@ -16,8 +16,11 @@ import LoadingAnim from '@/app/components/base/chat/chat/loading-anim'
import { FileList } from '@/app/components/base/file-uploader'
import { cn } from '@/utils/classnames'
import ContentSwitch from '../content-switch'
+import { useChatContext } from '../context'
import AgentContent from './agent-content'
import BasicContent from './basic-content'
+import HumanInputFilledFormList from './human-input-filled-form-list'
+import HumanInputFormList from './human-input-form-list'
import More from './more'
import Operation from './operation'
import SuggestedQuestions from './suggested-questions'
@@ -36,6 +39,8 @@ type AnswerProps = {
appData?: AppData
noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void
+ hideAvatar?: boolean
+ onHumanInputFormSubmit?: (formToken: string, formData: any) => Promise<void>
}
const Answer: FC<AnswerProps> = ({
item,
@@ -50,6 +55,8 @@ const Answer: FC<AnswerProps> = ({
appData,
noChatInput,
switchSibling,
+ hideAvatar,
+ onHumanInputFormSubmit,
}) => {
const { t } = useTranslation()
const {
@@ -61,13 +68,22 @@ const Answer: FC<AnswerProps> = ({
workflowProcess,
allFiles,
message_files,
+ humanInputFormDataList,
+ humanInputFilledFormDataList,
} = item
const hasAgentThoughts = !!agent_thoughts?.length
+ const hasHumanInputs = !!humanInputFormDataList?.length || !!humanInputFilledFormDataList?.length
const [containerWidth, setContainerWidth] = useState(0)
const [contentWidth, setContentWidth] = useState(0)
+ const [humanInputFormContainerWidth, setHumanInputFormContainerWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
+ const humanInputFormContainerRef = useRef<HTMLDivElement>(null)
+
+ const {
+ getHumanInputNodeData,
+ } = useChatContext()
const getContainerWidth = () => {
if (containerRef.current)
@@ -87,12 +103,23 @@ const Answer: FC<AnswerProps> = ({
getContentWidth()
}, [responding])
+ const getHumanInputFormContainerWidth = () => {
+ if (humanInputFormContainerRef.current)
+ setHumanInputFormContainerWidth(humanInputFormContainerRef.current?.clientWidth)
+ }
+
+ useEffect(() => {
+ if (hasHumanInputs)
+ getHumanInputFormContainerWidth()
+ }, [hasHumanInputs])
+
// Recalculate contentWidth when content changes (e.g., SVG preview/source toggle)
useEffect(() => {
if (!containerRef.current)
return
const resizeObserver = new ResizeObserver(() => {
getContentWidth()
+ getHumanInputFormContainerWidth()
})
resizeObserver.observe(containerRef.current)
return () => {
@@ -115,115 +142,285 @@ const Answer: FC<AnswerProps> = ({
return (
<div className="mb-2 flex last:mb-0">
- <div className="relative h-10 w-10 shrink-0">
- {answerIcon || <AnswerIcon />}
- {responding && (
- <div className="absolute left-[-3px] top-[-3px] flex h-4 w-4 items-center rounded-full border-[0.5px] border-divider-subtle bg-background-section-burn pl-[6px] shadow-xs">
- <LoadingAnim type="avatar" />
+ {!hideAvatar && (
+ <div className="relative h-10 w-10 shrink-0">
+ {answerIcon || <AnswerIcon />}
+ {responding && (
+ <div className="absolute left-[-3px] top-[-3px] flex h-4 w-4 items-center rounded-full border-[0.5px] border-divider-subtle bg-background-section-burn pl-[6px] shadow-xs">
+ <LoadingAnim type="avatar" />
+ </div>
+ )}
+ </div>
+ )}
+ <div className="chat-answer-container group ml-4 w-0 grow pb-4" ref={containerRef}>
+ {/* Block 1: Workflow Process + Human Input Forms */}
+ {hasHumanInputs && (
+ <div className={cn('group relative pr-10', chatAnswerContainerInner)}>
+ <div
+ ref={humanInputFormContainerRef}
+ className={cn('body-lg-regular relative inline-block w-full max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary')}
+ >
+ {
+ !responding && contentIsEmpty && !hasAgentThoughts && (
+ <Operation
+ hasWorkflowProcess={!!workflowProcess}
+ maxSize={containerWidth - humanInputFormContainerWidth - 4}
+ contentWidth={humanInputFormContainerWidth}
+ item={item}
+ question={question}
+ index={index}
+ showPromptLog={showPromptLog}
+ noChatInput={noChatInput}
+ />
+ )
+ }
+ {/** Render workflow process */}
+ {
+ workflowProcess && (
+ <WorkflowProcessItem
+ data={workflowProcess}
+ item={item}
+ hideProcessDetail={hideProcessDetail}
+ readonly={hideProcessDetail && appData ? !appData.site.show_workflow_steps : undefined}
+ />
+ )
+ }
+ {
+ humanInputFormDataList && humanInputFormDataList.length > 0 && (
+ <HumanInputFormList
+ humanInputFormDataList={humanInputFormDataList}
+ onHumanInputFormSubmit={onHumanInputFormSubmit}
+ getHumanInputNodeData={getHumanInputNodeData}
+ />
+ )
+ }
+ {
+ humanInputFilledFormDataList && humanInputFilledFormDataList.length > 0 && (
+ <HumanInputFilledFormList
+ humanInputFilledFormDataList={humanInputFilledFormDataList}
+ />
+ )
+ }
+ {
+ typeof item.siblingCount === 'number'
+ && item.siblingCount > 1
+ && !responding
+ && contentIsEmpty
+ && !hasAgentThoughts
+ && (
+ <ContentSwitch
+ count={item.siblingCount}
+ currentIndex={item.siblingIndex}
+ prevDisabled={!item.prevSibling}
+ nextDisabled={!item.nextSibling}
+ switchSibling={handleSwitchSibling}
+ />
+ )
+ }
+ </div>
</div>
)}
- </div>
- <div className="chat-answer-container group ml-4 w-0 grow pb-4" ref={containerRef}>
- <div className={cn('group relative pr-10', chatAnswerContainerInner)}>
- <div
- ref={contentRef}
- className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', workflowProcess && 'w-full')}
- >
- {
- !responding && (
- <Operation
- hasWorkflowProcess={!!workflowProcess}
- maxSize={containerWidth - contentWidth - 4}
- contentWidth={contentWidth}
- item={item}
- question={question}
- index={index}
- showPromptLog={showPromptLog}
- noChatInput={noChatInput}
- />
- )
- }
- {/** Render workflow process */}
- {
- workflowProcess && (
- <WorkflowProcessItem
- data={workflowProcess}
- item={item}
- hideProcessDetail={hideProcessDetail}
- readonly={hideProcessDetail && appData ? !appData.site?.show_workflow_steps : undefined}
- />
- )
- }
- {
- responding && contentIsEmpty && !hasAgentThoughts && (
- <div className="flex h-5 w-6 items-center justify-center">
- <LoadingAnim type="text" />
- </div>
- )
- }
- {
- !contentIsEmpty && !hasAgentThoughts && (
- <BasicContent item={item} />
- )
- }
- {
- (hasAgentThoughts) && (
- <AgentContent
- item={item}
- responding={responding}
- content={content}
- />
- )
- }
- {
- !!allFiles?.length && (
- <FileList
- className="my-1"
- files={allFiles}
- showDeleteAction={false}
- showDownloadAction
- canPreview
- />
- )
- }
- {
- !!message_files?.length && (
- <FileList
- className="my-1"
- files={message_files}
- showDeleteAction={false}
- showDownloadAction
- canPreview
- />
- )
- }
- {
- annotation?.id && annotation.authorName && (
- <EditTitle
- className="mt-1"
- title={t('editBy', { ns: 'appAnnotation', author: annotation.authorName })}
- />
- )
- }
- <SuggestedQuestions item={item} />
- {
- !!citation?.length && !responding && (
- <Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
- )
- }
- {
- !!(item.siblingCount && item.siblingCount > 1 && item.siblingIndex !== undefined) && (
- <ContentSwitch
- count={item.siblingCount}
- currentIndex={item.siblingIndex}
- prevDisabled={!item.prevSibling}
- nextDisabled={!item.nextSibling}
- switchSibling={handleSwitchSibling}
- />
- )
- }
+
+ {/* Block 2: Response Content (when human inputs exist) */}
+ {hasHumanInputs && (responding || !contentIsEmpty || hasAgentThoughts) && (
+ <div className={cn('group relative mt-2 pr-10', chatAnswerContainerInner)}>
+ <div className="absolute -top-2 left-6 h-3 w-0.5 bg-chat-answer-human-input-form-divider-bg" />
+ <div
+ ref={contentRef}
+ className="body-lg-regular relative inline-block w-full max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary"
+ >
+ {
+ !responding && (
+ <Operation
+ hasWorkflowProcess={!!workflowProcess}
+ maxSize={containerWidth - contentWidth - 4}
+ contentWidth={contentWidth}
+ item={item}
+ question={question}
+ index={index}
+ showPromptLog={showPromptLog}
+ noChatInput={noChatInput}
+ />
+ )
+ }
+ {
+ responding && contentIsEmpty && !hasAgentThoughts && (
+ <div className="flex h-5 w-6 items-center justify-center">
+ <LoadingAnim type="text" />
+ </div>
+ )
+ }
+ {
+ !contentIsEmpty && !hasAgentThoughts && (
+ <BasicContent item={item} />
+ )
+ }
+ {
+ hasAgentThoughts && (
+ <AgentContent
+ item={item}
+ responding={responding}
+ content={content}
+ />
+ )
+ }
+ {
+ !!allFiles?.length && (
+ <FileList
+ className="my-1"
+ files={allFiles}
+ showDeleteAction={false}
+ showDownloadAction
+ canPreview
+ />
+ )
+ }
+ {
+ !!message_files?.length && (
+ <FileList
+ className="my-1"
+ files={message_files}
+ showDeleteAction={false}
+ showDownloadAction
+ canPreview
+ />
+ )
+ }
+ {
+ annotation?.id && annotation.authorName && (
+ <EditTitle
+ className="mt-1"
+ title={t('editBy', { ns: 'appAnnotation', author: annotation.authorName })}
+ />
+ )
+ }
+ <SuggestedQuestions item={item} />
+ {
+ !!citation?.length && !responding && (
+ <Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
+ )
+ }
+ {
+ typeof item.siblingCount === 'number'
+ && item.siblingCount > 1
+ && (
+ <ContentSwitch
+ count={item.siblingCount}
+ currentIndex={item.siblingIndex}
+ prevDisabled={!item.prevSibling}
+ nextDisabled={!item.nextSibling}
+ switchSibling={handleSwitchSibling}
+ />
+ )
+ }
+ </div>
</div>
- </div>
+ )}
+
+ {/* Original single block layout (when no human inputs) */}
+ {!hasHumanInputs && (
+ <div className={cn('group relative pr-10', chatAnswerContainerInner)}>
+ <div
+ ref={contentRef}
+ className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary', workflowProcess && 'w-full')}
+ >
+ {
+ !responding && (
+ <Operation
+ hasWorkflowProcess={!!workflowProcess}
+ maxSize={containerWidth - contentWidth - 4}
+ contentWidth={contentWidth}
+ item={item}
+ question={question}
+ index={index}
+ showPromptLog={showPromptLog}
+ noChatInput={noChatInput}
+ />
+ )
+ }
+ {/** Render workflow process */}
+ {
+ workflowProcess && (
+ <WorkflowProcessItem
+ data={workflowProcess}
+ item={item}
+ hideProcessDetail={hideProcessDetail}
+ readonly={hideProcessDetail && appData ? !appData.site?.show_workflow_steps : undefined}
+ />
+ )
+ }
+ {
+ responding && contentIsEmpty && !hasAgentThoughts && (
+ <div className="flex h-5 w-6 items-center justify-center">
+ <LoadingAnim type="text" />
+ </div>
+ )
+ }
+ {
+ !contentIsEmpty && !hasAgentThoughts && (
+ <BasicContent item={item} />
+ )
+ }
+ {
+ hasAgentThoughts && (
+ <AgentContent
+ item={item}
+ responding={responding}
+ content={content}
+ />
+ )
+ }
+ {
+ !!allFiles?.length && (
+ <FileList
+ className="my-1"
+ files={allFiles}
+ showDeleteAction={false}
+ showDownloadAction
+ canPreview
+ />
+ )
+ }
+ {
+ !!message_files?.length && (
+ <FileList
+ className="my-1"
+ files={message_files}
+ showDeleteAction={false}
+ showDownloadAction
+ canPreview
+ />
+ )
+ }
+ {
+ annotation?.id && annotation.authorName && (
+ <EditTitle
+ className="mt-1"
+ title={t('editBy', { ns: 'appAnnotation', author: annotation.authorName })}
+ />
+ )
+ }
+ <SuggestedQuestions item={item} />
+ {
+ !!citation?.length && !responding && (
+ <Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
+ )
+ }
+ {
+ typeof item.siblingCount === 'number'
+ && item.siblingCount > 1 && (
+ <ContentSwitch
+ count={item.siblingCount}
+ currentIndex={item.siblingIndex}
+ prevDisabled={!item.prevSibling}
+ nextDisabled={!item.nextSibling}
+ switchSibling={handleSwitchSibling}
+ />
+ )
+ }
+ </div>
+ </div>
+ )}
<More more={more} />
</div>
</div>
diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsx
index e29af5a79cb..4acf1072321 100644
--- a/web/app/components/base/chat/chat/answer/operation.tsx
+++ b/web/app/components/base/chat/chat/answer/operation.tsx
@@ -69,6 +69,7 @@ const Operation: FC<OperationProps> = ({
feedback,
adminFeedback,
agent_thoughts,
+ humanInputFormDataList,
} = item
const [userLocalFeedback, setUserLocalFeedback] = useState(feedback)
const [adminLocalFeedback, setAdminLocalFeedback] = useState(adminFeedback)
@@ -186,7 +187,7 @@ const Operation: FC<OperationProps> = ({
)}
style={(!hasWorkflowProcess && positionRight) ? { left: contentWidth + 8 } : {}}
>
- {shouldShowUserFeedbackBar && (
+ {shouldShowUserFeedbackBar && !humanInputFormDataList?.length && (
<div className={cn(
'ml-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm',
hasUserFeedback ? 'flex' : 'hidden group-hover:flex',
@@ -226,7 +227,7 @@ const Operation: FC<OperationProps> = ({
)}
</div>
)}
- {shouldShowAdminFeedbackBar && (
+ {shouldShowAdminFeedbackBar && !humanInputFormDataList?.length && (
<div className={cn(
'ml-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm',
(hasAdminFeedback || hasUserFeedback) ? 'flex' : 'hidden group-hover:flex',
@@ -305,26 +306,28 @@ const Operation: FC<OperationProps> = ({
)}
{!isOpeningStatement && (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
- {(config?.text_to_speech?.enabled) && (
+ {(config?.text_to_speech?.enabled && !humanInputFormDataList?.length) && (
<NewAudioButton
id={id}
value={content}
voice={config?.text_to_speech?.voice}
/>
)}
- <ActionButton onClick={() => {
- copy(content)
- Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })
- }}
- >
- <RiClipboardLine className="h-4 w-4" />
- </ActionButton>
+ {!humanInputFormDataList?.length && (
+ <ActionButton onClick={() => {
+ copy(content)
+ Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })
+ }}
+ >
+ <RiClipboardLine className="h-4 w-4" />
+ </ActionButton>
+ )}
{!noChatInput && (
<ActionButton onClick={() => onRegenerate?.(item)}>
<RiResetLeftLine className="h-4 w-4" />
</ActionButton>
)}
- {(config?.supportAnnotation && config.annotation_reply?.enabled) && (
+ {config?.supportAnnotation && config.annotation_reply?.enabled && !humanInputFormDataList?.length && (
<AnnotationCtrlButton
appId={config?.appId || ''}
messageId={id}
diff --git a/web/app/components/base/chat/chat/answer/workflow-process.tsx b/web/app/components/base/chat/chat/answer/workflow-process.tsx
index fd8c1daf3e7..65027fd8535 100644
--- a/web/app/components/base/chat/chat/answer/workflow-process.tsx
+++ b/web/app/components/base/chat/chat/answer/workflow-process.tsx
@@ -3,6 +3,7 @@ import {
RiArrowRightSLine,
RiErrorWarningFill,
RiLoader2Line,
+ RiPauseCircleFill,
} from '@remixicon/react'
import {
useEffect,
@@ -34,6 +35,8 @@ const WorkflowProcessItem = ({
const running = data.status === WorkflowRunningStatus.Running
const succeeded = data.status === WorkflowRunningStatus.Succeeded
const failed = data.status === WorkflowRunningStatus.Failed || data.status === WorkflowRunningStatus.Stopped
+ const paused = data.status === WorkflowRunningStatus.Paused
+ const latestNode = data.tracing[data.tracing.length - 1]
useEffect(() => {
setCollapse(!expand)
@@ -50,7 +53,10 @@ const WorkflowProcessItem = ({
running && !collapse && 'bg-background-section-burn',
succeeded && !collapse && 'bg-state-success-hover',
failed && !collapse && 'bg-state-destructive-hover',
- collapse && 'bg-workflow-process-bg',
+ paused && !collapse && 'bg-state-warning-hover',
+ collapse && !failed && !paused && 'bg-workflow-process-bg',
+ collapse && paused && 'bg-workflow-process-paused-bg',
+ collapse && failed && 'bg-workflow-process-failed-bg',
)}
>
<div
@@ -72,8 +78,13 @@ const WorkflowProcessItem = ({
<RiErrorWarningFill className="mr-1 h-3.5 w-3.5 shrink-0 text-text-destructive" />
)
}
+ {
+ paused && (
+ <RiPauseCircleFill className="mr-1 h-3.5 w-3.5 shrink-0 text-text-warning-secondary" />
+ )
+ }
<div className={cn('system-xs-medium text-text-secondary', !collapse && 'grow')}>
- {t('common.workflowProcess', { ns: 'workflow' })}
+ {!collapse ? t('common.workflowProcess', { ns: 'workflow' }) : latestNode?.title}
</div>
<RiArrowRightSLine className={cn('ml-1 h-4 w-4 text-text-tertiary', !collapse && 'rotate-90')} />
</div>
diff --git a/web/app/components/base/chat/chat/context.tsx b/web/app/components/base/chat/chat/context.tsx
index 12d3175d396..7843665ad73 100644
--- a/web/app/components/base/chat/chat/context.tsx
+++ b/web/app/components/base/chat/chat/context.tsx
@@ -16,7 +16,8 @@ export type ChatContextValue = Pick<ChatProps, 'config'
| 'onAnnotationAdded'
| 'onAnnotationRemoved'
| 'disableFeedback'
- | 'onFeedback'> & {
+ | 'onFeedback'
+ | 'getHumanInputNodeData'> & {
readonly?: boolean
}
@@ -45,6 +46,7 @@ export const ChatContextProvider = ({
onAnnotationRemoved,
disableFeedback,
onFeedback,
+ getHumanInputNodeData,
}: ChatContextProviderProps) => {
return (
<ChatContext.Provider value={{
@@ -62,6 +64,7 @@ export const ChatContextProvider = ({
onAnnotationRemoved,
disableFeedback,
onFeedback,
+ getHumanInputNodeData,
}}
>
{children}
diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.ts
index 182aeebdbb1..a154e58bcb5 100644
--- a/web/app/components/base/chat/chat/hooks.ts
+++ b/web/app/components/base/chat/chat/hooks.ts
@@ -8,6 +8,10 @@ import type { InputForm } from './type'
import type AudioPlayer from '@/app/components/base/audio-btn/audio'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { Annotation } from '@/models/log'
+import type {
+ IOnDataMoreInfo,
+ IOtherOptions,
+} from '@/service/base'
import { uniqBy } from 'es-toolkit/compat'
import { noop } from 'es-toolkit/function'
import { produce, setAutoFreeze } from 'immer'
@@ -27,9 +31,12 @@ import {
getProcessedFilesFromResponse,
} from '@/app/components/base/file-uploader/utils'
import { useToastContext } from '@/app/components/base/toast'
-import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { NodeRunningStatus, WorkflowRunningStatus } from '@/app/components/workflow/types'
import useTimestamp from '@/hooks/use-timestamp'
-import { ssePost } from '@/service/base'
+import {
+ sseGet,
+ ssePost,
+} from '@/service/base'
import { TransferMethod } from '@/types/app'
import { getThreadMessages } from '../utils'
import {
@@ -67,6 +74,7 @@ export const useChat = (
const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
const conversationMessagesAbortControllerRef = useRef<AbortController | null>(null)
const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)
+ const workflowEventsAbortControllerRef = useRef<AbortController | null>(null)
const params = useParams()
const pathname = usePathname()
@@ -102,7 +110,7 @@ export const useChat = (
}
}
return ret
- }, [threadMessages, config?.opening_statement, getIntroduction, config?.suggested_questions])
+ }, [threadMessages, config, getIntroduction])
useEffect(() => {
setAutoFreeze(false)
@@ -164,6 +172,8 @@ export const useChat = (
conversationMessagesAbortControllerRef.current.abort()
if (suggestedQuestionsAbortControllerRef.current)
suggestedQuestionsAbortControllerRef.current.abort()
+ if (workflowEventsAbortControllerRef.current)
+ workflowEventsAbortControllerRef.current.abort()
}, [stopChat, handleResponding])
const handleRestart = useCallback((cb?: any) => {
@@ -175,6 +185,379 @@ export const useChat = (
cb?.()
}, [handleStop])
+ const createAudioPlayerManager = useCallback(() => {
+ let ttsUrl = ''
+ let ttsIsPublic = false
+ if (params.token) {
+ ttsUrl = '/text-to-audio'
+ ttsIsPublic = true
+ }
+ else if (params.appId) {
+ if (pathname.search('explore/installed') > -1)
+ ttsUrl = `/installed-apps/${params.appId}/text-to-audio`
+ else
+ ttsUrl = `/apps/${params.appId}/text-to-audio`
+ }
+
+ let player: AudioPlayer | null = null
+ const getOrCreatePlayer = () => {
+ if (!player)
+ player = AudioPlayerManager.getInstance().getAudioPlayer(ttsUrl, ttsIsPublic, uuidV4(), 'none', 'none', noop)
+
+ return player
+ }
+
+ return getOrCreatePlayer
+ }, [params.token, params.appId, pathname])
+
+ const handleResume = useCallback(async (
+ messageId: string,
+ workflowRunId: string,
+ {
+ onGetSuggestedQuestions,
+ onConversationComplete,
+ isPublicAPI,
+ }: SendCallback,
+ ) => {
+ const getOrCreatePlayer = createAudioPlayerManager()
+ // Re-subscribe to workflow events for the specific message
+ const url = `/workflow/${workflowRunId}/events?include_state_snapshot=true`
+
+ const otherOptions: IOtherOptions = {
+ isPublicAPI,
+ getAbortController: (abortController) => {
+ workflowEventsAbortControllerRef.current = abortController
+ },
+ onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: IOnDataMoreInfo) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ const isAgentMode = responseItem.agent_thoughts && responseItem.agent_thoughts.length > 0
+ if (!isAgentMode) {
+ responseItem.content = responseItem.content + message
+ }
+ else {
+ const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
+ if (lastThought)
+ lastThought.thought = lastThought.thought + message
+ }
+ if (messageId)
+ responseItem.id = messageId
+ })
+
+ if (isFirstMessage && newConversationId)
+ conversationId.current = newConversationId
+
+ if (taskId)
+ taskIdRef.current = taskId
+ },
+ async onCompleted(hasError?: boolean) {
+ handleResponding(false)
+
+ if (hasError)
+ return
+
+ if (onConversationComplete)
+ onConversationComplete(conversationId.current)
+
+ if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
+ try {
+ const { data }: any = await onGetSuggestedQuestions(
+ messageId,
+ newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ )
+ setSuggestQuestions(data)
+ }
+ // eslint-disable-next-line unused-imports/no-unused-vars
+ catch (e) {
+ setSuggestQuestions([])
+ }
+ }
+ },
+ onFile(file) {
+ // Convert simple file type to MIME type for non-agent mode
+ // Backend sends: { id, type: "image", belongs_to, url }
+ // Frontend expects: { id, type: "image/png", transferMethod, url, uploadedId, supportFileType, name, size }
+
+ // Determine file type for MIME conversion
+ const fileType = (file as { type?: string }).type || 'image'
+
+ // If file already has transferMethod, use it as base and ensure all required fields exist
+ // Otherwise, create a new complete file object
+ const baseFile = ('transferMethod' in file) ? (file as Partial<FileEntity>) : null
+
+ const convertedFile: FileEntity = {
+ id: baseFile?.id || (file as { id: string }).id,
+ type: baseFile?.type || (fileType === 'image' ? 'image/png' : fileType === 'video' ? 'video/mp4' : fileType === 'audio' ? 'audio/mpeg' : 'application/octet-stream'),
+ transferMethod: (baseFile?.transferMethod as FileEntity['transferMethod']) || (fileType === 'image' ? 'remote_url' : 'local_file'),
+ uploadedId: baseFile?.uploadedId || (file as { id: string }).id,
+ supportFileType: baseFile?.supportFileType || (fileType === 'image' ? 'image' : fileType === 'video' ? 'video' : fileType === 'audio' ? 'audio' : 'document'),
+ progress: baseFile?.progress ?? 100,
+ name: baseFile?.name || `generated_${fileType}.${fileType === 'image' ? 'png' : fileType === 'video' ? 'mp4' : fileType === 'audio' ? 'mp3' : 'bin'}`,
+ url: baseFile?.url || (file as { url?: string }).url,
+ size: baseFile?.size ?? 0, // Generated files don't have a known size
+ }
+ updateChatTreeNode(messageId, (responseItem) => {
+ const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
+ if (lastThought) {
+ responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(lastThought as any).message_files, convertedFile]
+ }
+ else {
+ const currentFiles = (responseItem.message_files as FileEntity[] | undefined) ?? []
+ responseItem.message_files = [...currentFiles, convertedFile]
+ }
+ })
+ },
+ onThought(thought) {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (thought.message_id)
+ responseItem.id = thought.message_id
+ if (thought.conversation_id)
+ responseItem.conversationId = thought.conversation_id
+
+ if (!responseItem.agent_thoughts)
+ responseItem.agent_thoughts = []
+
+ if (responseItem.agent_thoughts.length === 0) {
+ responseItem.agent_thoughts.push(thought)
+ }
+ else {
+ const lastThought = responseItem.agent_thoughts[responseItem.agent_thoughts.length - 1]
+ if (lastThought.id === thought.id) {
+ thought.thought = lastThought.thought
+ thought.message_files = lastThought.message_files
+ responseItem.agent_thoughts[responseItem.agent_thoughts.length - 1] = thought
+ }
+ else {
+ responseItem.agent_thoughts.push(thought)
+ }
+ }
+ })
+ },
+ onMessageEnd: (messageEnd) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (messageEnd.metadata?.annotation_reply) {
+ responseItem.annotation = ({
+ id: messageEnd.metadata.annotation_reply.id,
+ authorName: messageEnd.metadata.annotation_reply.account.name,
+ })
+ return
+ }
+ responseItem.citation = messageEnd.metadata?.retriever_resources || []
+ const processedFilesFromResponse = getProcessedFilesFromResponse(messageEnd.files || [])
+ responseItem.allFiles = uniqBy([...(responseItem.allFiles || []), ...(processedFilesFromResponse || [])], 'id')
+ })
+ },
+ onMessageReplace: (messageReplace) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ responseItem.content = messageReplace.answer
+ })
+ },
+ onError() {
+ handleResponding(false)
+ },
+ onWorkflowStarted: ({ workflow_run_id, task_id }) => {
+ handleResponding(true)
+ hasStopResponded.current = false
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.workflowProcess && responseItem.workflowProcess.tracing.length > 0) {
+ responseItem.workflowProcess.status = WorkflowRunningStatus.Running
+ }
+ else {
+ taskIdRef.current = task_id
+ responseItem.workflow_run_id = workflow_run_id
+ responseItem.workflowProcess = {
+ status: WorkflowRunningStatus.Running,
+ tracing: [],
+ }
+ }
+ })
+ },
+ onWorkflowFinished: ({ data: workflowFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.workflowProcess)
+ responseItem.workflowProcess.status = workflowFinishedData.status as WorkflowRunningStatus
+ })
+ },
+ onIterationStart: ({ data: iterationStartedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+ responseItem.workflowProcess.tracing.push({
+ ...iterationStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ })
+ },
+ onIterationFinish: ({ data: iterationFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess?.tracing)
+ return
+ const tracing = responseItem.workflowProcess.tracing
+ const iterationIndex = tracing.findIndex(item => item.node_id === iterationFinishedData.node_id
+ && (item.execution_metadata?.parallel_id === iterationFinishedData.execution_metadata?.parallel_id || item.parallel_id === iterationFinishedData.execution_metadata?.parallel_id))!
+ if (iterationIndex > -1) {
+ tracing[iterationIndex] = {
+ ...tracing[iterationIndex],
+ ...iterationFinishedData,
+ status: WorkflowRunningStatus.Succeeded,
+ }
+ }
+ })
+ },
+ onNodeStarted: ({ data: nodeStartedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+
+ const currentIndex = responseItem.workflowProcess.tracing.findIndex(item => item.node_id === nodeStartedData.node_id)
+ // if the node is already started, update the node
+ if (currentIndex > -1) {
+ responseItem.workflowProcess.tracing[currentIndex] = {
+ ...nodeStartedData,
+ status: NodeRunningStatus.Running,
+ }
+ }
+ else {
+ if (nodeStartedData.iteration_id)
+ return
+
+ responseItem.workflowProcess.tracing.push({
+ ...nodeStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ }
+ })
+ },
+ onNodeFinished: ({ data: nodeFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess?.tracing)
+ return
+
+ if (nodeFinishedData.iteration_id)
+ return
+
+ const currentIndex = responseItem.workflowProcess.tracing.findIndex((item) => {
+ if (!item.execution_metadata?.parallel_id)
+ return item.id === nodeFinishedData.id
+
+ return item.id === nodeFinishedData.id && (item.execution_metadata?.parallel_id === nodeFinishedData.execution_metadata?.parallel_id)
+ })
+ if (currentIndex > -1)
+ responseItem.workflowProcess.tracing[currentIndex] = nodeFinishedData as any
+ })
+ },
+ onTTSChunk: (messageId: string, audio: string) => {
+ if (!audio || audio === '')
+ return
+ const audioPlayer = getOrCreatePlayer()
+ if (audioPlayer) {
+ audioPlayer.playAudioWithAudio(audio, true)
+ AudioPlayerManager.getInstance().resetMsgId(messageId)
+ }
+ },
+ onTTSEnd: (messageId: string, audio: string) => {
+ const audioPlayer = getOrCreatePlayer()
+ if (audioPlayer)
+ audioPlayer.playAudioWithAudio(audio, false)
+ },
+ onLoopStart: ({ data: loopStartedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+ responseItem.workflowProcess.tracing.push({
+ ...loopStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ })
+ },
+ onLoopFinish: ({ data: loopFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess?.tracing)
+ return
+ const tracing = responseItem.workflowProcess.tracing
+ const loopIndex = tracing.findIndex(item => item.node_id === loopFinishedData.node_id
+ && (item.execution_metadata?.parallel_id === loopFinishedData.execution_metadata?.parallel_id || item.parallel_id === loopFinishedData.execution_metadata?.parallel_id))!
+ if (loopIndex > -1) {
+ tracing[loopIndex] = {
+ ...tracing[loopIndex],
+ ...loopFinishedData,
+ status: WorkflowRunningStatus.Succeeded,
+ }
+ }
+ })
+ },
+ onHumanInputRequired: ({ data: humanInputRequiredData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.humanInputFormDataList) {
+ responseItem.humanInputFormDataList = [humanInputRequiredData]
+ }
+ else {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentFormIndex > -1) {
+ responseItem.humanInputFormDataList[currentFormIndex] = humanInputRequiredData
+ }
+ else {
+ responseItem.humanInputFormDataList.push(humanInputRequiredData)
+ }
+ }
+ if (responseItem.workflowProcess?.tracing) {
+ const currentTracingIndex = responseItem.workflowProcess.tracing.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentTracingIndex > -1)
+ responseItem.workflowProcess.tracing[currentTracingIndex].status = NodeRunningStatus.Paused
+ }
+ })
+ },
+ onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
+ if (currentFormIndex > -1)
+ responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
+ if (!responseItem.humanInputFilledFormDataList) {
+ responseItem.humanInputFilledFormDataList = [humanInputFilledFormData]
+ }
+ else {
+ responseItem.humanInputFilledFormDataList.push(humanInputFilledFormData)
+ }
+ })
+ },
+ onHumanInputFormTimeout: ({ data: humanInputFormTimeoutData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputFormTimeoutData.node_id)
+ responseItem.humanInputFormDataList[currentFormIndex].expiration_time = humanInputFormTimeoutData.expiration_time
+ }
+ })
+ },
+ onWorkflowPaused: ({ data: workflowPausedData }) => {
+ const resumeUrl = `/workflow/${workflowPausedData.workflow_run_id}/events`
+ sseGet(
+ resumeUrl,
+ {},
+ otherOptions,
+ )
+ updateChatTreeNode(messageId, (responseItem) => {
+ responseItem.workflowProcess!.status = WorkflowRunningStatus.Paused
+ })
+ },
+ }
+
+ if (workflowEventsAbortControllerRef.current)
+ workflowEventsAbortControllerRef.current.abort()
+
+ sseGet(
+ url,
+ {},
+ otherOptions,
+ )
+ }, [updateChatTreeNode, handleResponding, createAudioPlayerManager, config?.suggested_questions_after_answer])
+
const updateCurrentQAOnTree = useCallback(({
parentId,
responseItem,
@@ -297,374 +680,462 @@ export const useChat = (
let isAgentMode = false
let hasSetResponseId = false
- let ttsUrl = ''
- let ttsIsPublic = false
- if (params.token) {
- ttsUrl = '/text-to-audio'
- ttsIsPublic = true
- }
- else if (params.appId) {
- if (pathname.search('explore/installed') > -1)
- ttsUrl = `/installed-apps/${params.appId}/text-to-audio`
- else
- ttsUrl = `/apps/${params.appId}/text-to-audio`
- }
- // Lazy initialization: Only create AudioPlayer when TTS is actually needed
- // This prevents opening audio channel unnecessarily
- let player: AudioPlayer | null = null
- const getOrCreatePlayer = () => {
- if (!player)
- player = AudioPlayerManager.getInstance().getAudioPlayer(ttsUrl, ttsIsPublic, uuidV4(), 'none', 'none', noop)
-
- return player
- }
+ const getOrCreatePlayer = createAudioPlayerManager()
- ssePost(
- url,
- {
- body: bodyParams,
+ const otherOptions: IOtherOptions = {
+ isPublicAPI,
+ getAbortController: (abortController) => {
+ workflowEventsAbortControllerRef.current = abortController
},
- {
- isPublicAPI,
- onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
- if (!isAgentMode) {
- responseItem.content = responseItem.content + message
- }
- else {
- const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
- if (lastThought)
- lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
- }
+ onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
+ if (!isAgentMode) {
+ responseItem.content = responseItem.content + message
+ }
+ else {
+ const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
+ if (lastThought)
+ lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
+ }
- if (messageId && !hasSetResponseId) {
- questionItem.id = `question-${messageId}`
- responseItem.id = messageId
- responseItem.parentMessageId = questionItem.id
- hasSetResponseId = true
- }
+ if (messageId && !hasSetResponseId) {
+ questionItem.id = `question-${messageId}`
+ responseItem.id = messageId
+ responseItem.parentMessageId = questionItem.id
+ hasSetResponseId = true
+ }
- if (isFirstMessage && newConversationId)
- conversationId.current = newConversationId
+ if (isFirstMessage && newConversationId)
+ conversationId.current = newConversationId
- taskIdRef.current = taskId
- if (messageId)
- responseItem.id = messageId
+ taskIdRef.current = taskId
+ if (messageId)
+ responseItem.id = messageId
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- async onCompleted(hasError?: boolean) {
- handleResponding(false)
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ async onCompleted(hasError?: boolean) {
+ handleResponding(false)
- if (hasError)
- return
+ if (hasError)
+ return
- if (onConversationComplete)
- onConversationComplete(conversationId.current)
+ if (onConversationComplete)
+ onConversationComplete(conversationId.current)
- if (conversationId.current && !hasStopResponded.current && onGetConversationMessages) {
- const { data }: any = await onGetConversationMessages(
- conversationId.current,
- newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
- )
- const newResponseItem = data.find((item: any) => item.id === responseItem.id)
- if (!newResponseItem)
- return
+ if (conversationId.current && !hasStopResponded.current && onGetConversationMessages) {
+ const { data }: any = await onGetConversationMessages(
+ conversationId.current,
+ newAbortController => conversationMessagesAbortControllerRef.current = newAbortController,
+ )
+ const newResponseItem = data.find((item: any) => item.id === responseItem.id)
+ if (!newResponseItem)
+ return
- const isUseAgentThought = newResponseItem.agent_thoughts?.length > 0 && newResponseItem.agent_thoughts[newResponseItem.agent_thoughts?.length - 1].thought === newResponseItem.answer
- updateChatTreeNode(responseItem.id, {
- content: isUseAgentThought ? '' : newResponseItem.answer,
- log: [
- ...newResponseItem.message,
- ...(newResponseItem.message[newResponseItem.message.length - 1].role !== 'assistant'
- ? [
- {
- role: 'assistant',
- text: newResponseItem.answer,
- files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
- },
- ]
- : []),
- ],
- more: {
- time: formatTime(newResponseItem.created_at, 'hh:mm A'),
- tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
- latency: newResponseItem.provider_response_latency.toFixed(2),
- tokens_per_second: newResponseItem.provider_response_latency > 0 ? (newResponseItem.answer_tokens / newResponseItem.provider_response_latency).toFixed(2) : undefined,
- },
- // for agent log
- conversationId: conversationId.current,
- input: {
- inputs: newResponseItem.inputs,
- query: newResponseItem.query,
- },
- })
- }
- if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
- try {
- const { data }: any = await onGetSuggestedQuestions(
- responseItem.id,
- newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
- )
- setSuggestQuestions(data)
- }
- // eslint-disable-next-line unused-imports/no-unused-vars
- catch (e) {
- setSuggestQuestions([])
- }
+ const isUseAgentThought = newResponseItem.agent_thoughts?.length > 0 && newResponseItem.agent_thoughts[newResponseItem.agent_thoughts?.length - 1].thought === newResponseItem.answer
+ updateChatTreeNode(responseItem.id, {
+ content: isUseAgentThought ? '' : newResponseItem.answer,
+ log: [
+ ...newResponseItem.message,
+ ...(newResponseItem.message[newResponseItem.message.length - 1].role !== 'assistant'
+ ? [
+ {
+ role: 'assistant',
+ text: newResponseItem.answer,
+ files: newResponseItem.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
+ },
+ ]
+ : []),
+ ],
+ more: {
+ time: formatTime(newResponseItem.created_at, 'hh:mm A'),
+ tokens: newResponseItem.answer_tokens + newResponseItem.message_tokens,
+ latency: newResponseItem.provider_response_latency.toFixed(2),
+ tokens_per_second: newResponseItem.provider_response_latency > 0 ? (newResponseItem.answer_tokens / newResponseItem.provider_response_latency).toFixed(2) : undefined,
+ },
+ // for agent log
+ conversationId: conversationId.current,
+ input: {
+ inputs: newResponseItem.inputs,
+ query: newResponseItem.query,
+ },
+ })
+ }
+ if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
+ try {
+ const { data }: any = await onGetSuggestedQuestions(
+ responseItem.id,
+ newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ )
+ setSuggestQuestions(data)
}
- },
- onFile(file) {
- // Convert simple file type to MIME type for non-agent mode
- // Backend sends: { id, type: "image", belongs_to, url }
- // Frontend expects: { id, type: "image/png", transferMethod, url, uploadedId, supportFileType, name, size }
-
- // Determine file type for MIME conversion
- const fileType = (file as { type?: string }).type || 'image'
-
- // If file already has transferMethod, use it as base and ensure all required fields exist
- // Otherwise, create a new complete file object
- const baseFile = ('transferMethod' in file) ? (file as Partial<FileEntity>) : null
-
- const convertedFile: FileEntity = {
- id: baseFile?.id || (file as { id: string }).id,
- type: baseFile?.type || (fileType === 'image' ? 'image/png' : fileType === 'video' ? 'video/mp4' : fileType === 'audio' ? 'audio/mpeg' : 'application/octet-stream'),
- transferMethod: (baseFile?.transferMethod as FileEntity['transferMethod']) || (fileType === 'image' ? 'remote_url' : 'local_file'),
- uploadedId: baseFile?.uploadedId || (file as { id: string }).id,
- supportFileType: baseFile?.supportFileType || (fileType === 'image' ? 'image' : fileType === 'video' ? 'video' : fileType === 'audio' ? 'audio' : 'document'),
- progress: baseFile?.progress ?? 100,
- name: baseFile?.name || `generated_${fileType}.${fileType === 'image' ? 'png' : fileType === 'video' ? 'mp4' : fileType === 'audio' ? 'mp3' : 'bin'}`,
- url: baseFile?.url || (file as { url?: string }).url,
- size: baseFile?.size ?? 0, // Generated files don't have a known size
+ // eslint-disable-next-line unused-imports/no-unused-vars
+ catch (e) {
+ setSuggestQuestions([])
}
+ }
+ },
+ onFile(file) {
+ // Convert simple file type to MIME type for non-agent mode
+ // Backend sends: { id, type: "image", belongs_to, url }
+ // Frontend expects: { id, type: "image/png", transferMethod, url, uploadedId, supportFileType, name, size }
- // For agent mode, add files to the last thought
- const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
- if (lastThought) {
- const thought = lastThought as { message_files?: FileEntity[] }
- responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(thought.message_files ?? []), convertedFile]
- }
- // For non-agent mode, add files directly to responseItem.message_files
- else {
- const currentFiles = (responseItem.message_files as FileEntity[] | undefined) ?? []
- responseItem.message_files = [...currentFiles, convertedFile]
- }
+ // Determine file type for MIME conversion
+ const fileType = (file as { type?: string }).type || 'image'
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onThought(thought) {
- isAgentMode = true
- const response = responseItem as any
- if (thought.message_id && !hasSetResponseId)
- response.id = thought.message_id
- if (thought.conversation_id)
- response.conversationId = thought.conversation_id
+ // If file already has transferMethod, use it as base and ensure all required fields exist
+ // Otherwise, create a new complete file object
+ const baseFile = ('transferMethod' in file) ? (file as Partial<FileEntity>) : null
+
+ const convertedFile: FileEntity = {
+ id: baseFile?.id || (file as { id: string }).id,
+ type: baseFile?.type || (fileType === 'image' ? 'image/png' : fileType === 'video' ? 'video/mp4' : fileType === 'audio' ? 'audio/mpeg' : 'application/octet-stream'),
+ transferMethod: (baseFile?.transferMethod as FileEntity['transferMethod']) || (fileType === 'image' ? 'remote_url' : 'local_file'),
+ uploadedId: baseFile?.uploadedId || (file as { id: string }).id,
+ supportFileType: baseFile?.supportFileType || (fileType === 'image' ? 'image' : fileType === 'video' ? 'video' : fileType === 'audio' ? 'audio' : 'document'),
+ progress: baseFile?.progress ?? 100,
+ name: baseFile?.name || `generated_${fileType}.${fileType === 'image' ? 'png' : fileType === 'video' ? 'mp4' : fileType === 'audio' ? 'mp3' : 'bin'}`,
+ url: baseFile?.url || (file as { url?: string }).url,
+ size: baseFile?.size ?? 0, // Generated files don't have a known size
+ }
+
+ // For agent mode, add files to the last thought
+ const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
+ if (lastThought) {
+ const thought = lastThought as { message_files?: FileEntity[] }
+ responseItem.agent_thoughts![responseItem.agent_thoughts!.length - 1].message_files = [...(thought.message_files ?? []), convertedFile]
+ }
+ // For non-agent mode, add files directly to responseItem.message_files
+ else {
+ const currentFiles = (responseItem.message_files as FileEntity[] | undefined) ?? []
+ responseItem.message_files = [...currentFiles, convertedFile]
+ }
+
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onThought(thought) {
+ isAgentMode = true
+ const response = responseItem as any
+ if (thought.message_id && !hasSetResponseId)
+ response.id = thought.message_id
+ if (thought.conversation_id)
+ response.conversationId = thought.conversation_id
- if (response.agent_thoughts.length === 0) {
- response.agent_thoughts.push(thought)
+ if (response.agent_thoughts.length === 0) {
+ response.agent_thoughts.push(thought)
+ }
+ else {
+ const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
+ // thought changed but still the same thought, so update.
+ if (lastThought.id === thought.id) {
+ thought.thought = lastThought.thought
+ thought.message_files = lastThought.message_files
+ responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
}
else {
- const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
- // thought changed but still the same thought, so update.
- if (lastThought.id === thought.id) {
- thought.thought = lastThought.thought
- thought.message_files = lastThought.message_files
- responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
- }
- else {
- responseItem.agent_thoughts!.push(thought)
- }
+ responseItem.agent_thoughts!.push(thought)
}
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onMessageEnd: (messageEnd) => {
- if (messageEnd.metadata?.annotation_reply) {
- responseItem.id = messageEnd.id
- responseItem.annotation = ({
- id: messageEnd.metadata.annotation_reply.id,
- authorName: messageEnd.metadata.annotation_reply.account.name,
- })
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- return
- }
- responseItem.citation = messageEnd.metadata?.retriever_resources || []
- const processedFilesFromResponse = getProcessedFilesFromResponse(messageEnd.files || [])
- responseItem.allFiles = uniqBy([...(responseItem.allFiles || []), ...(processedFilesFromResponse || [])], 'id')
-
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onMessageEnd: (messageEnd) => {
+ if (messageEnd.metadata?.annotation_reply) {
+ responseItem.id = messageEnd.id
+ responseItem.annotation = ({
+ id: messageEnd.metadata.annotation_reply.id,
+ authorName: messageEnd.metadata.annotation_reply.account.name,
})
- },
- onMessageReplace: (messageReplace) => {
- responseItem.content = messageReplace.answer
- },
- onError() {
- handleResponding(false)
updateCurrentQAOnTree({
placeholderQuestionId,
questionItem,
responseItem,
parentId: data.parent_message_id,
})
- },
- onWorkflowStarted: ({ workflow_run_id, task_id }) => {
+ return
+ }
+ responseItem.citation = messageEnd.metadata?.retriever_resources || []
+ const processedFilesFromResponse = getProcessedFilesFromResponse(messageEnd.files || [])
+ responseItem.allFiles = uniqBy([...(responseItem.allFiles || []), ...(processedFilesFromResponse || [])], 'id')
+
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onMessageReplace: (messageReplace) => {
+ responseItem.content = messageReplace.answer
+ },
+ onError() {
+ handleResponding(false)
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onWorkflowStarted: ({ workflow_run_id, task_id, conversation_id, message_id }) => {
+ // If there are no streaming messages, we still need to set the conversation_id to avoid create a new conversation when regeneration in chat-flow.
+ if (conversation_id) {
+ conversationId.current = conversation_id
+ }
+ if (message_id && !hasSetResponseId) {
+ questionItem.id = `question-${message_id}`
+ responseItem.id = message_id
+ responseItem.parentMessageId = questionItem.id
+ hasSetResponseId = true
+ }
+
+ if (responseItem.workflowProcess && responseItem.workflowProcess.tracing.length > 0) {
+ responseItem.workflowProcess.status = WorkflowRunningStatus.Running
+ }
+ else {
taskIdRef.current = task_id
responseItem.workflow_run_id = workflow_run_id
responseItem.workflowProcess = {
status: WorkflowRunningStatus.Running,
tracing: [],
}
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onWorkflowFinished: ({ data: workflowFinishedData }) => {
- responseItem.workflowProcess!.status = workflowFinishedData.status as WorkflowRunningStatus
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onIterationStart: ({ data: iterationStartedData }) => {
- responseItem.workflowProcess!.tracing!.push({
- ...iterationStartedData,
- status: WorkflowRunningStatus.Running,
- })
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onIterationFinish: ({ data: iterationFinishedData }) => {
- const tracing = responseItem.workflowProcess!.tracing!
- const iterationIndex = tracing.findIndex(item => item.node_id === iterationFinishedData.node_id
- && (item.execution_metadata?.parallel_id === iterationFinishedData.execution_metadata?.parallel_id || item.parallel_id === iterationFinishedData.execution_metadata?.parallel_id))!
- tracing[iterationIndex] = {
- ...tracing[iterationIndex],
- ...iterationFinishedData,
- status: WorkflowRunningStatus.Succeeded,
- }
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onWorkflowFinished: ({ data: workflowFinishedData }) => {
+ responseItem.workflowProcess!.status = workflowFinishedData.status as WorkflowRunningStatus
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onIterationStart: ({ data: iterationStartedData }) => {
+ responseItem.workflowProcess!.tracing!.push({
+ ...iterationStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onIterationFinish: ({ data: iterationFinishedData }) => {
+ const tracing = responseItem.workflowProcess!.tracing!
+ const iterationIndex = tracing.findIndex(item => item.node_id === iterationFinishedData.node_id
+ && (item.execution_metadata?.parallel_id === iterationFinishedData.execution_metadata?.parallel_id || item.parallel_id === iterationFinishedData.execution_metadata?.parallel_id))!
+ tracing[iterationIndex] = {
+ ...tracing[iterationIndex],
+ ...iterationFinishedData,
+ status: WorkflowRunningStatus.Succeeded,
+ }
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onNodeStarted: ({ data: nodeStartedData }) => {
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onNodeStarted: ({ data: nodeStartedData }) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+
+ const currentIndex = responseItem.workflowProcess.tracing.findIndex(item => item.node_id === nodeStartedData.node_id)
+ if (currentIndex > -1) {
+ responseItem.workflowProcess.tracing[currentIndex] = {
+ ...nodeStartedData,
+ status: NodeRunningStatus.Running,
+ }
+ }
+ else {
if (nodeStartedData.iteration_id)
return
if (data.loop_id)
return
- responseItem.workflowProcess!.tracing!.push({
+ responseItem.workflowProcess.tracing.push({
...nodeStartedData,
status: WorkflowRunningStatus.Running,
})
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onNodeFinished: ({ data: nodeFinishedData }) => {
- if (nodeFinishedData.iteration_id)
- return
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onNodeFinished: ({ data: nodeFinishedData }) => {
+ if (nodeFinishedData.iteration_id)
+ return
- if (data.loop_id)
- return
+ if (data.loop_id)
+ return
- const currentIndex = responseItem.workflowProcess!.tracing!.findIndex((item) => {
- if (!item.execution_metadata?.parallel_id)
- return item.node_id === nodeFinishedData.node_id
+ const currentIndex = responseItem.workflowProcess!.tracing!.findIndex((item) => {
+ if (!item.execution_metadata?.parallel_id)
+ return item.id === nodeFinishedData.id
- return item.node_id === nodeFinishedData.node_id && (item.execution_metadata?.parallel_id === nodeFinishedData.execution_metadata?.parallel_id)
- })
- responseItem.workflowProcess!.tracing[currentIndex] = nodeFinishedData as any
+ return item.id === nodeFinishedData.id && (item.execution_metadata?.parallel_id === nodeFinishedData.execution_metadata?.parallel_id)
+ })
+ responseItem.workflowProcess!.tracing[currentIndex] = nodeFinishedData as any
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onTTSChunk: (messageId: string, audio: string) => {
- if (!audio || audio === '')
- return
- const audioPlayer = getOrCreatePlayer()
- if (audioPlayer) {
- audioPlayer.playAudioWithAudio(audio, true)
- AudioPlayerManager.getInstance().resetMsgId(messageId)
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onTTSChunk: (messageId: string, audio: string) => {
+ if (!audio || audio === '')
+ return
+ const audioPlayer = getOrCreatePlayer()
+ if (audioPlayer) {
+ audioPlayer.playAudioWithAudio(audio, true)
+ AudioPlayerManager.getInstance().resetMsgId(messageId)
+ }
+ },
+ onTTSEnd: (messageId: string, audio: string) => {
+ const audioPlayer = getOrCreatePlayer()
+ if (audioPlayer)
+ audioPlayer.playAudioWithAudio(audio, false)
+ },
+ onLoopStart: ({ data: loopStartedData }) => {
+ responseItem.workflowProcess!.tracing!.push({
+ ...loopStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onLoopFinish: ({ data: loopFinishedData }) => {
+ const tracing = responseItem.workflowProcess!.tracing!
+ const loopIndex = tracing.findIndex(item => item.node_id === loopFinishedData.node_id
+ && (item.execution_metadata?.parallel_id === loopFinishedData.execution_metadata?.parallel_id || item.parallel_id === loopFinishedData.execution_metadata?.parallel_id))!
+ tracing[loopIndex] = {
+ ...tracing[loopIndex],
+ ...loopFinishedData,
+ status: WorkflowRunningStatus.Succeeded,
+ }
+
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onHumanInputRequired: ({ data: humanInputRequiredData }) => {
+ if (!responseItem.humanInputFormDataList) {
+ responseItem.humanInputFormDataList = [humanInputRequiredData]
+ }
+ else {
+ const currentFormIndex = responseItem.humanInputFormDataList!.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentFormIndex > -1) {
+ responseItem.humanInputFormDataList[currentFormIndex] = humanInputRequiredData
}
- },
- onTTSEnd: (messageId: string, audio: string) => {
- const audioPlayer = getOrCreatePlayer()
- if (audioPlayer)
- audioPlayer.playAudioWithAudio(audio, false)
- },
- onLoopStart: ({ data: loopStartedData }) => {
- responseItem.workflowProcess!.tracing!.push({
- ...loopStartedData,
- status: WorkflowRunningStatus.Running,
- })
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: data.parent_message_id,
- })
- },
- onLoopFinish: ({ data: loopFinishedData }) => {
- const tracing = responseItem.workflowProcess!.tracing!
- const loopIndex = tracing.findIndex(item => item.node_id === loopFinishedData.node_id
- && (item.execution_metadata?.parallel_id === loopFinishedData.execution_metadata?.parallel_id || item.parallel_id === loopFinishedData.execution_metadata?.parallel_id))!
- tracing[loopIndex] = {
- ...tracing[loopIndex],
- ...loopFinishedData,
- status: WorkflowRunningStatus.Succeeded,
+ else {
+ responseItem.humanInputFormDataList.push(humanInputRequiredData)
}
-
+ }
+ const currentTracingIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentTracingIndex > -1) {
+ responseItem.workflowProcess!.tracing[currentTracingIndex].status = NodeRunningStatus.Paused
updateCurrentQAOnTree({
placeholderQuestionId,
questionItem,
responseItem,
parentId: data.parent_message_id,
})
- },
+ }
+ },
+ onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList!.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
+ responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
+ if (!responseItem.humanInputFilledFormDataList) {
+ responseItem.humanInputFilledFormDataList = [humanInputFilledFormData]
+ }
+ else {
+ responseItem.humanInputFilledFormDataList.push(humanInputFilledFormData)
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onHumanInputFormTimeout: ({ data: humanInputFormTimeoutData }) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList!.findIndex(item => item.node_id === humanInputFormTimeoutData.node_id)
+ responseItem.humanInputFormDataList[currentFormIndex].expiration_time = humanInputFormTimeoutData.expiration_time
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ onWorkflowPaused: ({ data: workflowPausedData }) => {
+ const url = `/workflow/${workflowPausedData.workflow_run_id}/events`
+ sseGet(
+ url,
+ {},
+ otherOptions,
+ )
+ responseItem.workflowProcess!.status = WorkflowRunningStatus.Paused
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: data.parent_message_id,
+ })
+ },
+ }
+
+ // Abort the previous workflow events SSE request
+ if (workflowEventsAbortControllerRef.current)
+ workflowEventsAbortControllerRef.current.abort()
+
+ ssePost(
+ url,
+ {
+ body: bodyParams,
},
+ otherOptions,
)
return true
}, [
@@ -677,9 +1148,7 @@ export const useChat = (
notify,
handleResponding,
formatTime,
- params.token,
- params.appId,
- pathname,
+ createAudioPlayerManager,
formSettings,
])
@@ -736,6 +1205,36 @@ export const useChat = (
})
}, [chatList, updateChatTreeNode])
+ const handleSwitchSibling = useCallback((
+ siblingMessageId: string,
+ callbacks: SendCallback,
+ ) => {
+ setTargetMessageId(siblingMessageId)
+
+ // Helper to find message in tree
+ const findMessageInTree = (nodes: ChatItemInTree[], targetId: string): ChatItemInTree | undefined => {
+ for (const node of nodes) {
+ if (node.id === targetId)
+ return node
+ if (node.children) {
+ const found = findMessageInTree(node.children, targetId)
+ if (found)
+ return found
+ }
+ }
+ return undefined
+ }
+
+ const targetMessage = findMessageInTree(chatTreeRef.current, siblingMessageId)
+ if (targetMessage?.workflow_run_id && targetMessage.humanInputFormDataList && targetMessage.humanInputFormDataList.length > 0) {
+ handleResume(
+ targetMessage.id,
+ targetMessage.workflow_run_id,
+ callbacks,
+ )
+ }
+ }, [setTargetMessageId, handleResume])
+
useEffect(() => {
if (clearChatList)
handleRestart(() => clearChatListCallback?.(false))
@@ -744,10 +1243,11 @@ export const useChat = (
return {
chatList,
setTargetMessageId,
- conversationId: conversationId.current,
isResponding,
setIsResponding,
handleSend,
+ handleResume,
+ handleSwitchSibling,
suggestedQuestions,
handleRestart,
handleStop,
diff --git a/web/app/components/base/chat/chat/index.tsx b/web/app/components/base/chat/chat/index.tsx
index 5422ee8e4fa..e9669ba3f8c 100644
--- a/web/app/components/base/chat/chat/index.tsx
+++ b/web/app/components/base/chat/chat/index.tsx
@@ -75,6 +75,9 @@ export type ChatProps = {
noSpacing?: boolean
inputDisabled?: boolean
sidebarCollapseState?: boolean
+ hideAvatar?: boolean
+ onHumanInputFormSubmit?: (formToken: string, formData: any) => Promise<void>
+ getHumanInputNodeData?: (nodeID: string) => any
}
const Chat: FC<ChatProps> = ({
@@ -116,6 +119,9 @@ const Chat: FC<ChatProps> = ({
noSpacing,
inputDisabled,
sidebarCollapseState,
+ hideAvatar,
+ onHumanInputFormSubmit,
+ getHumanInputNodeData,
}) => {
const { t } = useTranslation()
const { currentLogItem, setCurrentLogItem, showPromptLogModal, setShowPromptLogModal, showAgentLogModal, setShowAgentLogModal } = useAppStore(useShallow(state => ({
@@ -265,6 +271,7 @@ const Chat: FC<ChatProps> = ({
onAnnotationRemoved={onAnnotationRemoved}
disableFeedback={disableFeedback}
onFeedback={onFeedback}
+ getHumanInputNodeData={getHumanInputNodeData}
>
<div className={cn('relative h-full', isTryApp && 'flex flex-col')}>
<div
@@ -295,6 +302,8 @@ const Chat: FC<ChatProps> = ({
hideProcessDetail={hideProcessDetail}
noChatInput={noChatInput}
switchSibling={switchSibling}
+ hideAvatar={hideAvatar}
+ onHumanInputFormSubmit={onHumanInputFormSubmit}
/>
)
}
@@ -306,6 +315,7 @@ const Chat: FC<ChatProps> = ({
theme={themeBuilder?.theme}
enableEdit={config?.questionEditEnable}
switchSibling={switchSibling}
+ hideAvatar={hideAvatar}
/>
)
})
diff --git a/web/app/components/base/chat/chat/question.tsx b/web/app/components/base/chat/chat/question.tsx
index 73f1b5cd93d..ff7571ef6e0 100644
--- a/web/app/components/base/chat/chat/question.tsx
+++ b/web/app/components/base/chat/chat/question.tsx
@@ -32,6 +32,7 @@ type QuestionProps = {
theme: Theme | null | undefined
enableEdit?: boolean
switchSibling?: (siblingMessageId: string) => void
+ hideAvatar?: boolean
}
const Question: FC<QuestionProps> = ({
@@ -40,6 +41,7 @@ const Question: FC<QuestionProps> = ({
theme,
enableEdit = true,
switchSibling,
+ hideAvatar,
}) => {
const { t } = useTranslation()
@@ -174,15 +176,17 @@ const Question: FC<QuestionProps> = ({
</div>
<div className="mt-1 h-[18px]" />
</div>
- <div className="h-10 w-10 shrink-0">
- {
- questionIcon || (
- <div className="h-full w-full rounded-full border-[0.5px] border-black/5">
- <User className="h-full w-full" />
- </div>
- )
- }
- </div>
+ {!hideAvatar && (
+ <div className="h-10 w-10 shrink-0">
+ {
+ questionIcon || (
+ <div className="h-full w-full rounded-full border-[0.5px] border-black/5">
+ <User className="h-full w-full" />
+ </div>
+ )
+ }
+ </div>
+ )}
</div>
)
}
diff --git a/web/app/components/base/chat/chat/type.ts b/web/app/components/base/chat/chat/type.ts
index 291b0ae0646..7bd4de5b058 100644
--- a/web/app/components/base/chat/chat/type.ts
+++ b/web/app/components/base/chat/chat/type.ts
@@ -2,7 +2,11 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { InputVarType } from '@/app/components/workflow/types'
import type { Annotation, MessageRating } from '@/models/log'
-import type { FileResponse } from '@/types/workflow'
+import type {
+ FileResponse,
+ HumanInputFilledFormData,
+ HumanInputFormData,
+} from '@/types/workflow'
export type MessageMore = {
time: string
@@ -64,6 +68,19 @@ export type CitationItem = {
word_count: number
}
+export type ExtraContent
+ = {
+ type: 'human_input'
+ submitted: false
+ form_definition: HumanInputFormData
+ workflow_run_id: string
+ }
+ | {
+ type: 'human_input'
+ submitted: true
+ form_submission_data: HumanInputFilledFormData
+ }
+
export type IChatItem = {
id: string
content: string
@@ -104,6 +121,10 @@ export type IChatItem = {
siblingIndex?: number
prevSibling?: string
nextSibling?: string
+ // for human input
+ humanInputFormDataList?: HumanInputFormData[]
+ humanInputFilledFormDataList?: HumanInputFilledFormData[]
+ extra_contents?: ExtraContent[]
}
export type Metadata = {
diff --git a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
index 5d40d8da560..b781eae918d 100644
--- a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
@@ -2,6 +2,7 @@ import type { FileEntity } from '../../file-uploader/types'
import type {
ChatConfig,
ChatItem,
+ ChatItemInTree,
OnSend,
} from '../types'
import { useCallback, useEffect, useMemo, useState } from 'react'
@@ -17,7 +18,9 @@ import {
fetchSuggestedQuestions,
getUrl,
stopChatMessageResponding,
+ submitHumanInputForm,
} from '@/service/share'
+import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import { TransferMethod } from '@/types/app'
import { cn } from '@/utils/classnames'
import Avatar from '../../avatar'
@@ -70,9 +73,9 @@ const ChatWrapper = () => {
}, [appParams, currentConversationItem?.introduction])
const {
chatList,
- setTargetMessageId,
handleSend,
handleStop,
+ handleSwitchSibling,
isResponding: respondingState,
suggestedQuestions,
} = useChat(
@@ -130,6 +133,40 @@ const ChatWrapper = () => {
setIsResponding(respondingState)
}, [respondingState, setIsResponding])
+ // Resume paused workflows when chat history is loaded
+ useEffect(() => {
+ if (!appPrevChatList || appPrevChatList.length === 0)
+ return
+
+ // Find the last answer item with workflow_run_id that needs resumption (DFS - find deepest first)
+ let lastPausedNode: ChatItemInTree | undefined
+ const findLastPausedWorkflow = (nodes: ChatItemInTree[]) => {
+ nodes.forEach((node) => {
+ // DFS: recurse to children first
+ if (node.children && node.children.length > 0)
+ findLastPausedWorkflow(node.children)
+
+ // Track the last node with humanInputFormDataList
+ if (node.isAnswer && node.workflow_run_id && node.humanInputFormDataList && node.humanInputFormDataList.length > 0)
+ lastPausedNode = node
+ })
+ }
+
+ findLastPausedWorkflow(appPrevChatList)
+
+ // Only resume the last paused workflow
+ if (lastPausedNode) {
+ handleSwitchSibling(
+ lastPausedNode.id,
+ {
+ onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, appSourceType, appId),
+ onConversationComplete: currentConversationId ? undefined : handleNewConversationCompleted,
+ isPublicAPI: appSourceType === AppSourceType.webApp,
+ },
+ )
+ }
+ }, [])
+
const doSend: OnSend = useCallback((message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {
const data: any = {
query: message,
@@ -147,7 +184,7 @@ const ChatWrapper = () => {
isPublicAPI: appSourceType === AppSourceType.webApp,
},
)
- }, [currentConversationId, currentConversationInputs, newConversationInputs, chatList, handleSend, isInstalledApp, appId, handleNewConversationCompleted])
+ }, [currentConversationId, currentConversationInputs, newConversationInputs, chatList, handleSend, appSourceType, appId, handleNewConversationCompleted])
const doRegenerate = useCallback((chatItem: ChatItem, editedQuestion?: { message: string, files?: FileEntity[] }) => {
const question = editedQuestion ? chatItem : chatList.find(item => item.id === chatItem.parentMessageId)!
@@ -155,6 +192,14 @@ const ChatWrapper = () => {
doSend(editedQuestion ? editedQuestion.message : question.content, editedQuestion ? editedQuestion.files : question.message_files, true, isValidGeneratedAnswer(parentAnswer) ? parentAnswer : null)
}, [chatList, doSend])
+ const doSwitchSibling = useCallback((siblingMessageId: string) => {
+ handleSwitchSibling(siblingMessageId, {
+ onGetSuggestedQuestions: responseItemId => fetchSuggestedQuestions(responseItemId, appSourceType, appId),
+ onConversationComplete: currentConversationId ? undefined : handleNewConversationCompleted,
+ isPublicAPI: appSourceType === AppSourceType.webApp,
+ })
+ }, [handleSwitchSibling, appSourceType, appId, currentConversationId, handleNewConversationCompleted])
+
const messageList = useMemo(() => {
if (currentConversationId || chatList.length > 1)
return chatList
@@ -178,6 +223,13 @@ const ChatWrapper = () => {
}
}, [inputsForms.length, isMobile, currentConversationId, collapsed, allInputsHidden])
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: any) => {
+ if (isInstalledApp)
+ await submitHumanInputFormService(formToken, formData)
+ else
+ await submitHumanInputForm(formToken, formData)
+ }, [isInstalledApp])
+
const welcome = useMemo(() => {
const welcomeMessage = chatList.find(item => item.isOpeningStatement)
if (respondingState)
@@ -223,7 +275,7 @@ const ChatWrapper = () => {
</div>
</div>
)
- }, [appData?.site, chatList, collapsed, currentConversationId, inputsForms.length, respondingState, allInputsHidden])
+ }, [chatList, respondingState, currentConversationId, collapsed, inputsForms.length, allInputsHidden, appData?.site, isMobile])
const answerIcon = isDify()
? <LogoAvatar className="relative shrink-0" />
@@ -253,6 +305,7 @@ const ChatWrapper = () => {
inputsForm={inputsForms}
onRegenerate={doRegenerate}
onStopResponding={handleStop}
+ onHumanInputFormSubmit={handleSubmitHumanInputForm}
chatNode={(
<>
{chatNode}
@@ -266,7 +319,7 @@ const ChatWrapper = () => {
answerIcon={answerIcon}
hideProcessDetail
themeBuilder={themeBuilder}
- switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)}
+ switchSibling={doSwitchSibling}
inputDisabled={inputDisabled}
questionIcon={
initUserVariables?.avatar_url
diff --git a/web/app/components/base/chat/types.ts b/web/app/components/base/chat/types.ts
index e12c6fca547..1502a32e928 100644
--- a/web/app/components/base/chat/types.ts
+++ b/web/app/components/base/chat/types.ts
@@ -5,7 +5,7 @@ import type {
ModelConfig,
VisionSettings,
} from '@/types/app'
-import type { NodeTracing } from '@/types/workflow'
+import type { HumanInputFilledFormData, HumanInputFormData, NodeTracing } from '@/types/workflow'
export type {
Inputs,
@@ -67,6 +67,8 @@ export type WorkflowProcess = {
expand?: boolean // for UI
resultText?: string
files?: FileEntity[]
+ humanInputFormDataList?: HumanInputFormData[]
+ humanInputFilledFormDataList?: HumanInputFilledFormData[]
}
export type ChatItem = IChatItem & {
diff --git a/web/app/components/base/icons/assets/public/other/slack.svg b/web/app/components/base/icons/assets/public/other/slack.svg
new file mode 100644
index 00000000000..656c4c2326a
--- /dev/null
+++ b/web/app/components/base/icons/assets/public/other/slack.svg
@@ -0,0 +1,6 @@
+<svg width="27" height="27" viewBox="0 0 27 27" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path fill-rule="evenodd" clip-rule="evenodd" d="M9.625 0C9.27992 0.000320434 8.93828 0.0686147 8.6196 0.200983C8.30091 0.333351 8.01142 0.527199 7.76766 0.771458C7.5239 1.01572 7.33064 1.3056 7.19893 1.62456C7.06721 1.94351 6.99962 2.28529 7 2.63037C6.99968 2.97541 7.06732 3.31714 7.19907 3.63603C7.33081 3.95493 7.52408 4.24476 7.76783 4.48897C8.01159 4.73317 8.30105 4.92698 8.61971 5.05932C8.93836 5.19165 9.27996 5.25993 9.625 5.26025H12.25V2.63037C12.2504 2.28529 12.1828 1.94351 12.0511 1.62456C11.9194 1.3056 11.7261 1.01572 11.4823 0.771458C11.2386 0.527199 10.9491 0.333351 10.6304 0.200983C10.3117 0.0686147 9.97008 0.000320434 9.625 0ZM9.625 7.01416H2.625C2.27996 7.01448 1.93836 7.08276 1.61971 7.21509C1.30106 7.34743 1.01159 7.54124 0.767835 7.78544C0.524081 8.02965 0.330814 8.31948 0.199069 8.63838C0.0673241 8.95728 -0.000319124 9.299 1.63476e-06 9.64404C-0.000383292 9.98912 0.0672126 10.3309 0.198929 10.6499C0.330645 10.9688 0.523902 11.2587 0.767662 11.503C1.01142 11.7472 1.30091 11.9411 1.6196 12.0734C1.93828 12.2058 2.27992 12.2741 2.625 12.2744H9.625C9.97008 12.2741 10.3117 12.2058 10.6304 12.0734C10.9491 11.9411 11.2386 11.7472 11.4823 11.503C11.7261 11.2587 11.9194 10.9688 12.0511 10.6499C12.1828 10.3309 12.2504 9.98912 12.25 9.64404C12.2503 9.299 12.1827 8.95728 12.0509 8.63838C11.9192 8.31948 11.7259 8.02965 11.4822 7.78544C11.2384 7.54124 10.9489 7.34743 10.6303 7.21509C10.3116 7.08276 9.97004 7.01448 9.625 7.01416Z" fill="#44BEDF"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M26.25 9.64404C26.2503 9.299 26.1827 8.95728 26.0509 8.63838C25.9192 8.31948 25.7259 8.02965 25.4822 7.78544C25.2384 7.54124 24.9489 7.34743 24.6303 7.21509C24.3116 7.08276 23.97 7.01448 23.625 7.01416C23.28 7.01448 22.9384 7.08276 22.6197 7.21509C22.3011 7.34743 22.0116 7.54124 21.7678 7.78544C21.5241 8.02965 21.3308 8.31948 21.1991 8.63838C21.0673 8.95728 20.9997 9.299 21 9.64404V12.2744H23.625C23.9701 12.2741 24.3117 12.2058 24.6304 12.0734C24.9491 11.9411 25.2386 11.7472 25.4823 11.503C25.7261 11.2587 25.9194 10.9688 26.0511 10.6499C26.1828 10.3309 26.2504 9.98912 26.25 9.64404ZM19.25 9.64404V2.63037C19.2504 2.28529 19.1828 1.94351 19.0511 1.62456C18.9194 1.3056 18.7261 1.01572 18.4823 0.771458C18.2386 0.527199 17.9491 0.333351 17.6304 0.200983C17.3117 0.0686147 16.9701 0.000320434 16.625 0C16.2799 0.000320434 15.9383 0.0686147 15.6196 0.200983C15.3009 0.333351 15.0114 0.527199 14.7677 0.771458C14.5239 1.01572 14.3306 1.3056 14.1989 1.62456C14.0672 1.94351 13.9996 2.28529 14 2.63037V9.64404C13.9996 9.98912 14.0672 10.3309 14.1989 10.6499C14.3306 10.9688 14.5239 11.2587 14.7677 11.503C15.0114 11.7472 15.3009 11.9411 15.6196 12.0734C15.9383 12.2058 16.2799 12.2741 16.625 12.2744C16.9701 12.2741 17.3117 12.2058 17.6304 12.0734C17.9491 11.9411 18.2386 11.7472 18.4823 11.503C18.7261 11.2587 18.9194 10.9688 19.0511 10.6499C19.1828 10.3309 19.2504 9.98912 19.25 9.64404Z" fill="#2EB67D"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M16.625 26.302C16.9701 26.3017 17.3117 26.2334 17.6304 26.101C17.9491 25.9686 18.2386 25.7748 18.4823 25.5305C18.7261 25.2863 18.9194 24.9964 19.0511 24.6774C19.1828 24.3585 19.2504 24.0167 19.25 23.6716C19.2503 23.3266 19.1827 22.9849 19.0509 22.666C18.9192 22.3471 18.7259 22.0572 18.4822 21.813C18.2384 21.5688 17.9489 21.375 17.6303 21.2427C17.3116 21.1103 16.97 21.0421 16.625 21.0417H14V23.6716C13.9996 24.0167 14.0672 24.3585 14.1989 24.6774C14.3306 24.9964 14.5239 25.2863 14.7677 25.5305C15.0114 25.7748 15.3009 25.9686 15.6196 26.101C15.9383 26.2334 16.2799 26.3017 16.625 26.302ZM16.625 19.2878H23.625C23.97 19.2875 24.3116 19.2192 24.6303 19.0869C24.9489 18.9546 25.2384 18.7608 25.4822 18.5166C25.7259 18.2723 25.9192 17.9825 26.0509 17.6636C26.1827 17.3447 26.2503 17.003 26.25 16.658C26.2504 16.3129 26.1828 15.9711 26.0511 15.6521C25.9194 15.3332 25.7261 15.0433 25.4823 14.799C25.2386 14.5548 24.9491 14.3609 24.6304 14.2286C24.3117 14.0962 23.9701 14.0279 23.625 14.0276H16.625C16.2799 14.0279 15.9383 14.0962 15.6196 14.2286C15.3009 14.3609 15.0114 14.5548 14.7677 14.799C14.5239 15.0433 14.3306 15.3332 14.1989 15.6521C14.0672 15.9711 13.9996 16.3129 14 16.658C13.9997 17.003 14.0673 17.3447 14.1991 17.6636C14.3308 17.9825 14.5241 18.2723 14.7678 18.5166C15.0116 18.7608 15.3011 18.9546 15.6197 19.0869C15.9384 19.2192 16.28 19.2875 16.625 19.2878Z" fill="#ECB22E"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M2.22485e-06 16.658C-0.000318534 17.003 0.0673247 17.3447 0.19907 17.6636C0.330815 17.9825 0.524081 18.2723 0.767835 18.5166C1.01159 18.7608 1.30106 18.9546 1.61971 19.0869C1.93836 19.2192 2.27996 19.2875 2.625 19.2878C2.97004 19.2875 3.31164 19.2192 3.63029 19.0869C3.94895 18.9546 4.23841 18.7608 4.48217 18.5166C4.72592 18.2723 4.91919 17.9825 5.05093 17.6636C5.18268 17.3447 5.25032 17.003 5.25 16.658V14.0276H2.625C2.27988 14.0279 1.9382 14.0962 1.61948 14.2286C1.30077 14.361 1.01126 14.5549 0.76749 14.7992C0.523723 15.0435 0.330477 15.3335 0.198789 15.6525C0.0671016 15.9715 -0.000446885 16.3128 2.22485e-06 16.658ZM7 16.658V23.6716C6.99962 24.0167 7.06721 24.3585 7.19893 24.6774C7.33064 24.9964 7.5239 25.2863 7.76766 25.5305C8.01142 25.7748 8.30091 25.9686 8.6196 26.101C8.93828 26.2334 9.27992 26.3017 9.625 26.302C9.97008 26.3017 10.3117 26.2334 10.6304 26.101C10.9491 25.9686 11.2386 25.7748 11.4823 25.5305C11.7261 25.2863 11.9194 24.9964 12.0511 24.6774C12.1828 24.3585 12.2504 24.0167 12.25 23.6716V16.6584C12.2504 16.3134 12.1828 15.9716 12.0511 15.6526C11.9194 15.3337 11.7261 15.0438 11.4823 14.7995C11.2386 14.5553 10.9491 14.3614 10.6304 14.2291C10.3117 14.0967 9.97008 14.0284 9.625 14.0281C9.27992 14.0284 8.93828 14.0967 8.6196 14.2291C8.30091 14.3614 8.01142 14.5553 7.76766 14.7995C7.5239 15.0438 7.33064 15.3337 7.19893 15.6526C7.06721 15.9716 6.99962 16.3129 7 16.658Z" fill="#E01E5A"/>
+</svg>
diff --git a/web/app/components/base/icons/assets/public/other/teams.svg b/web/app/components/base/icons/assets/public/other/teams.svg
new file mode 100644
index 00000000000..cdcc6a62420
--- /dev/null
+++ b/web/app/components/base/icons/assets/public/other/teams.svg
@@ -0,0 +1,19 @@
+<svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_20307_29670)">
+<path opacity="0.1" d="M9.33332 11.8067V20.4167C9.33204 21.432 9.57619 22.4327 10.045 23.3333H15.8783C16.2912 23.305 16.6807 23.1312 16.9776 22.8428C17.2745 22.5545 17.4596 22.1702 17.5 21.7583V10.5H17.1733H10.64C10.2934 10.5 9.96108 10.6377 9.71603 10.8827C9.47098 11.1278 9.33332 11.4601 9.33332 11.8067Z" fill="black"/>
+<path opacity="0.1" d="M16.135 7H12.635C12.8805 7.78672 13.3726 8.47355 14.0386 8.9589C14.7047 9.44425 15.5093 9.70234 16.3333 9.695C16.7301 9.68885 17.1235 9.62197 17.5 9.49667V8.33C17.488 7.97504 17.3392 7.63847 17.0849 7.39061C16.8305 7.14276 16.4902 7.00281 16.135 7Z" fill="black"/>
+<path d="M26.6817 10.5H20.8484L19.2267 11.8183V18.34C19.2846 19.4628 19.7715 20.5204 20.5867 21.2946C21.4019 22.0689 22.4833 22.5005 23.6075 22.5005C24.7318 22.5005 25.8131 22.0689 26.6283 21.2946C27.4436 20.5204 27.9304 19.4628 27.9884 18.34V11.8183C27.9899 11.6458 27.9572 11.4746 27.8923 11.3147C27.8273 11.1548 27.7313 11.0094 27.6098 10.8868C27.4883 10.7643 27.3437 10.667 27.1844 10.6006C27.0251 10.5342 26.8543 10.5 26.6817 10.5Z" fill="#5059C9"/>
+<path d="M23.9167 9.33333C25.5275 9.33333 26.8333 8.0275 26.8333 6.41667C26.8333 4.80584 25.5275 3.5 23.9167 3.5C22.3058 3.5 21 4.80584 21 6.41667C21 8.0275 22.3058 9.33333 23.9167 9.33333Z" fill="#5059C9"/>
+<path d="M10.64 10.5H20.86C21.2065 10.5 21.5389 10.6377 21.7839 10.8827C22.029 11.1278 22.1666 11.4601 22.1666 11.8067V20.4167C22.1666 22.1185 21.4906 23.7506 20.2872 24.9539C19.0839 26.1573 17.4518 26.8333 15.75 26.8333C14.0482 26.8333 12.4161 26.1573 11.2127 24.9539C10.0094 23.7506 9.33331 22.1185 9.33331 20.4167V11.8067C9.33331 11.4601 9.47098 11.1278 9.71603 10.8827C9.96107 10.6377 10.2934 10.5 10.64 10.5Z" fill="#7B83EB"/>
+<path d="M16.3333 9.69477C18.4661 9.69477 20.195 7.96584 20.195 5.8331C20.195 3.70036 18.4661 1.97144 16.3333 1.97144C14.2006 1.97144 12.4717 3.70036 12.4717 5.8331C12.4717 7.96584 14.2006 9.69477 16.3333 9.69477Z" fill="#7B83EB"/>
+<path opacity="0.5" d="M9.33332 11.8067V20.4167C9.33204 21.432 9.57619 22.4327 10.045 23.3333H15.8783C16.2912 23.305 16.6807 23.1312 16.9776 22.8428C17.2745 22.5545 17.4596 22.1702 17.5 21.7583V10.5H17.1733H10.64C10.2934 10.5 9.96108 10.6377 9.71603 10.8827C9.47098 11.1278 9.33332 11.4601 9.33332 11.8067Z" fill="black"/>
+<path opacity="0.5" d="M16.135 7H12.635C12.8805 7.78672 13.3726 8.47355 14.0386 8.9589C14.7047 9.44425 15.5093 9.70234 16.3333 9.695C16.7301 9.68885 17.1235 9.62197 17.5 9.49667V8.33C17.488 7.97504 17.3392 7.63847 17.0849 7.39061C16.8305 7.14276 16.4902 7.00281 16.135 7Z" fill="black"/>
+<path d="M14.9683 5.83325H1.365C0.611131 5.83325 0 6.44438 0 7.19825V20.8016C0 21.5555 0.611131 22.1666 1.365 22.1666H14.9683C15.7222 22.1666 16.3333 21.5555 16.3333 20.8016V7.19825C16.3333 6.44438 15.7222 5.83325 14.9683 5.83325Z" fill="#4B53BC"/>
+<path d="M11.8767 11.1766H9.08833V18.6666H7.25666V11.1766H4.45667V9.33325H11.8767V11.1766Z" fill="white"/>
+</g>
+<defs>
+<clipPath id="clip0_20307_29670">
+<rect width="28" height="28" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/app/components/base/icons/assets/vender/workflow/human-in-loop.svg b/web/app/components/base/icons/assets/vender/workflow/human-in-loop.svg
new file mode 100644
index 00000000000..07efc8ecc6b
--- /dev/null
+++ b/web/app/components/base/icons/assets/vender/workflow/human-in-loop.svg
@@ -0,0 +1,5 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M3.66634 2.66675C3.66634 2.29856 3.36787 2.00008 2.99967 2.00008C2.63149 2.00008 2.33301 2.29855 2.33301 2.66675L3.66634 2.66675ZM2.99967 5.33341H2.33301C2.33301 5.51023 2.40325 5.6798 2.52827 5.80482C2.65329 5.92984 2.82286 6.00008 2.99967 6.00008V5.33341ZM5.66641 6.00008C6.03459 6.00008 6.33307 5.7016 6.33307 5.33341C6.33307 4.96523 6.03459 4.66675 5.66641 4.66675L5.66641 6.00008ZM2.41183 5.01659C2.23816 5.34125 2.36056 5.74523 2.68522 5.91889C3.00988 6.09256 3.41385 5.97016 3.58752 5.6455L2.41183 5.01659ZM3.03395 8.58915C2.99109 8.22348 2.6599 7.96175 2.29421 8.00461C1.92853 8.04748 1.66682 8.37868 1.70967 8.74435L3.03395 8.58915ZM12.0439 5.05931C12.2607 5.3569 12.6777 5.42238 12.9753 5.20557C13.2729 4.98876 13.3383 4.57176 13.1215 4.27417L12.0439 5.05931ZM5.02145 13.5907C5.34627 13.7641 5.75013 13.6413 5.92349 13.3165C6.09685 12.9917 5.97407 12.5878 5.64925 12.4145L5.02145 13.5907ZM2.33301 2.66675L2.33301 5.33341H3.66634L3.66634 2.66675L2.33301 2.66675ZM2.99967 6.00008L5.66641 6.00008L5.66641 4.66675H2.99967L2.99967 6.00008ZM3.58752 5.6455C4.43045 4.06972 6.09066 3.00008 7.99968 3.00008V1.66675C5.57951 1.66675 3.47747 3.02445 2.41183 5.01659L3.58752 5.6455ZM7.99968 3.00008C9.66128 3.00008 11.1336 3.80991 12.0439 5.05931L13.1215 4.27417C11.9711 2.69513 10.1055 1.66675 7.99968 1.66675V3.00008ZM5.64925 12.4145C4.23557 11.6599 3.22828 10.2474 3.03395 8.58915L1.70967 8.74435C1.95639 10.8495 3.23403 12.6367 5.02145 13.5907L5.64925 12.4145Z" fill="white"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M13.1946 8.13826C12.9027 7.84637 12.4294 7.84638 12.1375 8.13829L9.11842 11.1574C9.01642 11.2594 8.95025 11.3917 8.92985 11.5345C8.92985 11.5345 8.92985 11.5345 8.92985 11.5345L8.78508 12.5479L9.79846 12.4031C9.94127 12.3827 10.0736 12.3165 10.1756 12.2145L13.1947 9.19548C13.4866 8.90359 13.4866 8.43027 13.1946 8.13826C13.1947 8.13827 13.1946 8.13825 13.1946 8.13826ZM11.1947 7.19548C12.0073 6.38286 13.3249 6.38286 14.1375 7.19548C14.95 8.00814 14.9501 9.32565 14.1375 10.1383L11.1184 13.1574C10.8124 13.4633 10.4154 13.6618 9.98703 13.723L8.09369 13.9935C7.88596 14.0232 7.67639 13.9533 7.52801 13.805C7.37963 13.6566 7.30977 13.447 7.33945 13.2393L7.60991 11.3459C7.67111 10.9175 7.86961 10.5205 8.17561 10.2145L11.1947 7.19548Z" fill="white"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M12.528 10.8048L10.528 8.80482L11.4708 7.86201L13.4708 9.86201L12.528 10.8048Z" fill="white"/>
+</svg>
diff --git a/web/app/components/base/icons/src/public/other/Slack.json b/web/app/components/base/icons/src/public/other/Slack.json
new file mode 100644
index 00000000000..e83673ed311
--- /dev/null
+++ b/web/app/components/base/icons/src/public/other/Slack.json
@@ -0,0 +1,61 @@
+{
+ "icon": {
+ "type": "element",
+ "isRootNode": true,
+ "name": "svg",
+ "attributes": {
+ "width": "27",
+ "height": "27",
+ "viewBox": "0 0 27 27",
+ "fill": "none",
+ "xmlns": "http://www.w3.org/2000/svg"
+ },
+ "children": [
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "fill-rule": "evenodd",
+ "clip-rule": "evenodd",
+ "d": "M9.625 0C9.27992 0.000320434 8.93828 0.0686147 8.6196 0.200983C8.30091 0.333351 8.01142 0.527199 7.76766 0.771458C7.5239 1.01572 7.33064 1.3056 7.19893 1.62456C7.06721 1.94351 6.99962 2.28529 7 2.63037C6.99968 2.97541 7.06732 3.31714 7.19907 3.63603C7.33081 3.95493 7.52408 4.24476 7.76783 4.48897C8.01159 4.73317 8.30105 4.92698 8.61971 5.05932C8.93836 5.19165 9.27996 5.25993 9.625 5.26025H12.25V2.63037C12.2504 2.28529 12.1828 1.94351 12.0511 1.62456C11.9194 1.3056 11.7261 1.01572 11.4823 0.771458C11.2386 0.527199 10.9491 0.333351 10.6304 0.200983C10.3117 0.0686147 9.97008 0.000320434 9.625 0ZM9.625 7.01416H2.625C2.27996 7.01448 1.93836 7.08276 1.61971 7.21509C1.30106 7.34743 1.01159 7.54124 0.767835 7.78544C0.524081 8.02965 0.330814 8.31948 0.199069 8.63838C0.0673241 8.95728 -0.000319124 9.299 1.63476e-06 9.64404C-0.000383292 9.98912 0.0672126 10.3309 0.198929 10.6499C0.330645 10.9688 0.523902 11.2587 0.767662 11.503C1.01142 11.7472 1.30091 11.9411 1.6196 12.0734C1.93828 12.2058 2.27992 12.2741 2.625 12.2744H9.625C9.97008 12.2741 10.3117 12.2058 10.6304 12.0734C10.9491 11.9411 11.2386 11.7472 11.4823 11.503C11.7261 11.2587 11.9194 10.9688 12.0511 10.6499C12.1828 10.3309 12.2504 9.98912 12.25 9.64404C12.2503 9.299 12.1827 8.95728 12.0509 8.63838C11.9192 8.31948 11.7259 8.02965 11.4822 7.78544C11.2384 7.54124 10.9489 7.34743 10.6303 7.21509C10.3116 7.08276 9.97004 7.01448 9.625 7.01416Z",
+ "fill": "#44BEDF"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "fill-rule": "evenodd",
+ "clip-rule": "evenodd",
+ "d": "M26.25 9.64404C26.2503 9.299 26.1827 8.95728 26.0509 8.63838C25.9192 8.31948 25.7259 8.02965 25.4822 7.78544C25.2384 7.54124 24.9489 7.34743 24.6303 7.21509C24.3116 7.08276 23.97 7.01448 23.625 7.01416C23.28 7.01448 22.9384 7.08276 22.6197 7.21509C22.3011 7.34743 22.0116 7.54124 21.7678 7.78544C21.5241 8.02965 21.3308 8.31948 21.1991 8.63838C21.0673 8.95728 20.9997 9.299 21 9.64404V12.2744H23.625C23.9701 12.2741 24.3117 12.2058 24.6304 12.0734C24.9491 11.9411 25.2386 11.7472 25.4823 11.503C25.7261 11.2587 25.9194 10.9688 26.0511 10.6499C26.1828 10.3309 26.2504 9.98912 26.25 9.64404ZM19.25 9.64404V2.63037C19.2504 2.28529 19.1828 1.94351 19.0511 1.62456C18.9194 1.3056 18.7261 1.01572 18.4823 0.771458C18.2386 0.527199 17.9491 0.333351 17.6304 0.200983C17.3117 0.0686147 16.9701 0.000320434 16.625 0C16.2799 0.000320434 15.9383 0.0686147 15.6196 0.200983C15.3009 0.333351 15.0114 0.527199 14.7677 0.771458C14.5239 1.01572 14.3306 1.3056 14.1989 1.62456C14.0672 1.94351 13.9996 2.28529 14 2.63037V9.64404C13.9996 9.98912 14.0672 10.3309 14.1989 10.6499C14.3306 10.9688 14.5239 11.2587 14.7677 11.503C15.0114 11.7472 15.3009 11.9411 15.6196 12.0734C15.9383 12.2058 16.2799 12.2741 16.625 12.2744C16.9701 12.2741 17.3117 12.2058 17.6304 12.0734C17.9491 11.9411 18.2386 11.7472 18.4823 11.503C18.7261 11.2587 18.9194 10.9688 19.0511 10.6499C19.1828 10.3309 19.2504 9.98912 19.25 9.64404Z",
+ "fill": "#2EB67D"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "fill-rule": "evenodd",
+ "clip-rule": "evenodd",
+ "d": "M16.625 26.302C16.9701 26.3017 17.3117 26.2334 17.6304 26.101C17.9491 25.9686 18.2386 25.7748 18.4823 25.5305C18.7261 25.2863 18.9194 24.9964 19.0511 24.6774C19.1828 24.3585 19.2504 24.0167 19.25 23.6716C19.2503 23.3266 19.1827 22.9849 19.0509 22.666C18.9192 22.3471 18.7259 22.0572 18.4822 21.813C18.2384 21.5688 17.9489 21.375 17.6303 21.2427C17.3116 21.1103 16.97 21.0421 16.625 21.0417H14V23.6716C13.9996 24.0167 14.0672 24.3585 14.1989 24.6774C14.3306 24.9964 14.5239 25.2863 14.7677 25.5305C15.0114 25.7748 15.3009 25.9686 15.6196 26.101C15.9383 26.2334 16.2799 26.3017 16.625 26.302ZM16.625 19.2878H23.625C23.97 19.2875 24.3116 19.2192 24.6303 19.0869C24.9489 18.9546 25.2384 18.7608 25.4822 18.5166C25.7259 18.2723 25.9192 17.9825 26.0509 17.6636C26.1827 17.3447 26.2503 17.003 26.25 16.658C26.2504 16.3129 26.1828 15.9711 26.0511 15.6521C25.9194 15.3332 25.7261 15.0433 25.4823 14.799C25.2386 14.5548 24.9491 14.3609 24.6304 14.2286C24.3117 14.0962 23.9701 14.0279 23.625 14.0276H16.625C16.2799 14.0279 15.9383 14.0962 15.6196 14.2286C15.3009 14.3609 15.0114 14.5548 14.7677 14.799C14.5239 15.0433 14.3306 15.3332 14.1989 15.6521C14.0672 15.9711 13.9996 16.3129 14 16.658C13.9997 17.003 14.0673 17.3447 14.1991 17.6636C14.3308 17.9825 14.5241 18.2723 14.7678 18.5166C15.0116 18.7608 15.3011 18.9546 15.6197 19.0869C15.9384 19.2192 16.28 19.2875 16.625 19.2878Z",
+ "fill": "#ECB22E"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "fill-rule": "evenodd",
+ "clip-rule": "evenodd",
+ "d": "M2.22485e-06 16.658C-0.000318534 17.003 0.0673247 17.3447 0.19907 17.6636C0.330815 17.9825 0.524081 18.2723 0.767835 18.5166C1.01159 18.7608 1.30106 18.9546 1.61971 19.0869C1.93836 19.2192 2.27996 19.2875 2.625 19.2878C2.97004 19.2875 3.31164 19.2192 3.63029 19.0869C3.94895 18.9546 4.23841 18.7608 4.48217 18.5166C4.72592 18.2723 4.91919 17.9825 5.05093 17.6636C5.18268 17.3447 5.25032 17.003 5.25 16.658V14.0276H2.625C2.27988 14.0279 1.9382 14.0962 1.61948 14.2286C1.30077 14.361 1.01126 14.5549 0.76749 14.7992C0.523723 15.0435 0.330477 15.3335 0.198789 15.6525C0.0671016 15.9715 -0.000446885 16.3128 2.22485e-06 16.658ZM7 16.658V23.6716C6.99962 24.0167 7.06721 24.3585 7.19893 24.6774C7.33064 24.9964 7.5239 25.2863 7.76766 25.5305C8.01142 25.7748 8.30091 25.9686 8.6196 26.101C8.93828 26.2334 9.27992 26.3017 9.625 26.302C9.97008 26.3017 10.3117 26.2334 10.6304 26.101C10.9491 25.9686 11.2386 25.7748 11.4823 25.5305C11.7261 25.2863 11.9194 24.9964 12.0511 24.6774C12.1828 24.3585 12.2504 24.0167 12.25 23.6716V16.6584C12.2504 16.3134 12.1828 15.9716 12.0511 15.6526C11.9194 15.3337 11.7261 15.0438 11.4823 14.7995C11.2386 14.5553 10.9491 14.3614 10.6304 14.2291C10.3117 14.0967 9.97008 14.0284 9.625 14.0281C9.27992 14.0284 8.93828 14.0967 8.6196 14.2291C8.30091 14.3614 8.01142 14.5553 7.76766 14.7995C7.5239 15.0438 7.33064 15.3337 7.19893 15.6526C7.06721 15.9716 6.99962 16.3129 7 16.658Z",
+ "fill": "#E01E5A"
+ },
+ "children": []
+ }
+ ]
+ },
+ "name": "Slack"
+}
diff --git a/web/app/components/base/icons/src/public/other/Slack.tsx b/web/app/components/base/icons/src/public/other/Slack.tsx
new file mode 100644
index 00000000000..3150598cdbb
--- /dev/null
+++ b/web/app/components/base/icons/src/public/other/Slack.tsx
@@ -0,0 +1,20 @@
+// GENERATE BY script
+// DON NOT EDIT IT MANUALLY
+
+import type { IconData } from '@/app/components/base/icons/IconBase'
+import * as React from 'react'
+import IconBase from '@/app/components/base/icons/IconBase'
+import data from './Slack.json'
+
+const Icon = (
+ {
+ ref,
+ ...props
+ }: React.SVGProps<SVGSVGElement> & {
+ ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
+ },
+) => <IconBase {...props} ref={ref} data={data as IconData} />
+
+Icon.displayName = 'Slack'
+
+export default Icon
diff --git a/web/app/components/base/icons/src/public/other/Teams.json b/web/app/components/base/icons/src/public/other/Teams.json
new file mode 100644
index 00000000000..aa9afa22405
--- /dev/null
+++ b/web/app/components/base/icons/src/public/other/Teams.json
@@ -0,0 +1,146 @@
+{
+ "icon": {
+ "type": "element",
+ "isRootNode": true,
+ "name": "svg",
+ "attributes": {
+ "width": "28",
+ "height": "28",
+ "viewBox": "0 0 28 28",
+ "fill": "none",
+ "xmlns": "http://www.w3.org/2000/svg"
+ },
+ "children": [
+ {
+ "type": "element",
+ "name": "g",
+ "attributes": {
+ "clip-path": "url(#clip0_20307_29670)"
+ },
+ "children": [
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "opacity": "0.1",
+ "d": "M9.33332 11.8067V20.4167C9.33204 21.432 9.57619 22.4327 10.045 23.3333H15.8783C16.2912 23.305 16.6807 23.1312 16.9776 22.8428C17.2745 22.5545 17.4596 22.1702 17.5 21.7583V10.5H17.1733H10.64C10.2934 10.5 9.96108 10.6377 9.71603 10.8827C9.47098 11.1278 9.33332 11.4601 9.33332 11.8067Z",
+ "fill": "black"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "opacity": "0.1",
+ "d": "M16.135 7H12.635C12.8805 7.78672 13.3726 8.47355 14.0386 8.9589C14.7047 9.44425 15.5093 9.70234 16.3333 9.695C16.7301 9.68885 17.1235 9.62197 17.5 9.49667V8.33C17.488 7.97504 17.3392 7.63847 17.0849 7.39061C16.8305 7.14276 16.4902 7.00281 16.135 7Z",
+ "fill": "black"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M26.6817 10.5H20.8484L19.2267 11.8183V18.34C19.2846 19.4628 19.7715 20.5204 20.5867 21.2946C21.4019 22.0689 22.4833 22.5005 23.6075 22.5005C24.7318 22.5005 25.8131 22.0689 26.6283 21.2946C27.4436 20.5204 27.9304 19.4628 27.9884 18.34V11.8183C27.9899 11.6458 27.9572 11.4746 27.8923 11.3147C27.8273 11.1548 27.7313 11.0094 27.6098 10.8868C27.4883 10.7643 27.3437 10.667 27.1844 10.6006C27.0251 10.5342 26.8543 10.5 26.6817 10.5Z",
+ "fill": "#5059C9"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M23.9167 9.33333C25.5275 9.33333 26.8333 8.0275 26.8333 6.41667C26.8333 4.80584 25.5275 3.5 23.9167 3.5C22.3058 3.5 21 4.80584 21 6.41667C21 8.0275 22.3058 9.33333 23.9167 9.33333Z",
+ "fill": "#5059C9"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M10.64 10.5H20.86C21.2065 10.5 21.5389 10.6377 21.7839 10.8827C22.029 11.1278 22.1666 11.4601 22.1666 11.8067V20.4167C22.1666 22.1185 21.4906 23.7506 20.2872 24.9539C19.0839 26.1573 17.4518 26.8333 15.75 26.8333C14.0482 26.8333 12.4161 26.1573 11.2127 24.9539C10.0094 23.7506 9.33331 22.1185 9.33331 20.4167V11.8067C9.33331 11.4601 9.47098 11.1278 9.71603 10.8827C9.96107 10.6377 10.2934 10.5 10.64 10.5Z",
+ "fill": "#7B83EB"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M16.3333 9.69477C18.4661 9.69477 20.195 7.96584 20.195 5.8331C20.195 3.70036 18.4661 1.97144 16.3333 1.97144C14.2006 1.97144 12.4717 3.70036 12.4717 5.8331C12.4717 7.96584 14.2006 9.69477 16.3333 9.69477Z",
+ "fill": "#7B83EB"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "opacity": "0.5",
+ "d": "M9.33332 11.8067V20.4167C9.33204 21.432 9.57619 22.4327 10.045 23.3333H15.8783C16.2912 23.305 16.6807 23.1312 16.9776 22.8428C17.2745 22.5545 17.4596 22.1702 17.5 21.7583V10.5H17.1733H10.64C10.2934 10.5 9.96108 10.6377 9.71603 10.8827C9.47098 11.1278 9.33332 11.4601 9.33332 11.8067Z",
+ "fill": "black"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "opacity": "0.5",
+ "d": "M16.135 7H12.635C12.8805 7.78672 13.3726 8.47355 14.0386 8.9589C14.7047 9.44425 15.5093 9.70234 16.3333 9.695C16.7301 9.68885 17.1235 9.62197 17.5 9.49667V8.33C17.488 7.97504 17.3392 7.63847 17.0849 7.39061C16.8305 7.14276 16.4902 7.00281 16.135 7Z",
+ "fill": "black"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M14.9683 5.83325H1.365C0.611131 5.83325 0 6.44438 0 7.19825V20.8016C0 21.5555 0.611131 22.1666 1.365 22.1666H14.9683C15.7222 22.1666 16.3333 21.5555 16.3333 20.8016V7.19825C16.3333 6.44438 15.7222 5.83325 14.9683 5.83325Z",
+ "fill": "#4B53BC"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M11.8767 11.1766H9.08833V18.6666H7.25666V11.1766H4.45667V9.33325H11.8767V11.1766Z",
+ "fill": "white"
+ },
+ "children": []
+ }
+ ]
+ },
+ {
+ "type": "element",
+ "name": "defs",
+ "attributes": {},
+ "children": [
+ {
+ "type": "element",
+ "name": "clipPath",
+ "attributes": {
+ "id": "clip0_20307_29670"
+ },
+ "children": [
+ {
+ "type": "element",
+ "name": "rect",
+ "attributes": {
+ "width": "28",
+ "height": "28",
+ "fill": "white"
+ },
+ "children": []
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ "name": "Teams"
+}
diff --git a/web/app/components/base/icons/src/public/other/Teams.tsx b/web/app/components/base/icons/src/public/other/Teams.tsx
new file mode 100644
index 00000000000..4559b50793b
--- /dev/null
+++ b/web/app/components/base/icons/src/public/other/Teams.tsx
@@ -0,0 +1,20 @@
+// GENERATE BY script
+// DON NOT EDIT IT MANUALLY
+
+import type { IconData } from '@/app/components/base/icons/IconBase'
+import * as React from 'react'
+import IconBase from '@/app/components/base/icons/IconBase'
+import data from './Teams.json'
+
+const Icon = (
+ {
+ ref,
+ ...props
+ }: React.SVGProps<SVGSVGElement> & {
+ ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>
+ },
+) => <IconBase {...props} ref={ref} data={data as IconData} />
+
+Icon.displayName = 'Teams'
+
+export default Icon
diff --git a/web/app/components/base/icons/src/public/other/index.ts b/web/app/components/base/icons/src/public/other/index.ts
index 71887f11cce..10987368fb5 100644
--- a/web/app/components/base/icons/src/public/other/index.ts
+++ b/web/app/components/base/icons/src/public/other/index.ts
@@ -2,3 +2,5 @@ export { default as DefaultToolIcon } from './DefaultToolIcon'
export { default as Icon3Dots } from './Icon3Dots'
export { default as Message3Fill } from './Message3Fill'
export { default as RowStruct } from './RowStruct'
+export { default as Slack } from './Slack'
+export { default as Teams } from './Teams'
diff --git a/web/app/components/base/icons/src/vender/workflow/HumanInLoop.json b/web/app/components/base/icons/src/vender/workflow/HumanInLoop.json
new file mode 100644
index 00000000000..f6612414a5b
--- /dev/null
+++ b/web/app/components/base/icons/src/vender/workflow/HumanInLoop.json
@@ -0,0 +1,48 @@
+{
+ "icon": {
+ "type": "element",
+ "isRootNode": true,
+ "name": "svg",
+ "attributes": {
+ "width": "16",
+ "height": "16",
+ "viewBox": "0 0 16 16",
+ "fill": "none",
+ "xmlns": "http://www.w3.org/2000/svg"
+ },
+ "children": [
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "d": "M3.66634 2.66675C3.66634 2.29856 3.36787 2.00008 2.99967 2.00008C2.63149 2.00008 2.33301 2.29855 2.33301 2.66675L3.66634 2.66675ZM2.99967 5.33341H2.33301C2.33301 5.51023 2.40325 5.6798 2.52827 5.80482C2.65329 5.92984 2.82286 6.00008 2.99967 6.00008V5.33341ZM5.66641 6.00008C6.03459 6.00008 6.33307 5.7016 6.33307 5.33341C6.33307 4.96523 6.03459 4.66675 5.66641 4.66675L5.66641 6.00008ZM2.41183 5.01659C2.23816 5.34125 2.36056 5.74523 2.68522 5.91889C3.00988 6.09256 3.41385 5.97016 3.58752 5.6455L2.41183 5.01659ZM3.03395 8.58915C2.99109 8.22348 2.6599 7.96175 2.29421 8.00461C1.92853 8.04748 1.66682 8.37868 1.70967 8.74435L3.03395 8.58915ZM12.0439 5.05931C12.2607 5.3569 12.6777 5.42238 12.9753 5.20557C13.2729 4.98876 13.3383 4.57176 13.1215 4.27417L12.0439 5.05931ZM5.02145 13.5907C5.34627 13.7641 5.75013 13.6413 5.92349 13.3165C6.09685 12.9917 5.97407 12.5878 5.64925 12.4145L5.02145 13.5907ZM2.33301 2.66675L2.33301 5.33341H3.66634L3.66634 2.66675L2.33301 2.66675ZM2.99967 6.00008L5.66641 6.00008L5.66641 4.66675H2.99967L2.99967 6.00008ZM3.58752 5.6455C4.43045 4.06972 6.09066 3.00008 7.99968 3.00008V1.66675C5.57951 1.66675 3.47747 3.02445 2.41183 5.01659L3.58752 5.6455ZM7.99968 3.00008C9.66128 3.00008 11.1336 3.80991 12.0439 5.05931L13.1215 4.27417C11.9711 2.69513 10.1055 1.66675 7.99968 1.66675V3.00008ZM5.64925 12.4145C4.23557 11.6599 3.22828 10.2474 3.03395 8.58915L1.70967 8.74435C1.95639 10.8495 3.23403 12.6367 5.02145 13.5907L5.64925 12.4145Z",
+ "fill": "currentColor"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "fill-rule": "evenodd",
+ "clip-rule": "evenodd",
+ "d": "M13.1946 8.13826C12.9027 7.84637 12.4294 7.84638 12.1375 8.13829L9.11842 11.1574C9.01642 11.2594 8.95025 11.3917 8.92985 11.5345C8.92985 11.5345 8.92985 11.5345 8.92985 11.5345L8.78508 12.5479L9.79846 12.4031C9.94127 12.3827 10.0736 12.3165 10.1756 12.2145L13.1947 9.19548C13.4866 8.90359 13.4866 8.43027 13.1946 8.13826C13.1947 8.13827 13.1946 8.13825 13.1946 8.13826ZM11.1947 7.19548C12.0073 6.38286 13.3249 6.38286 14.1375 7.19548C14.95 8.00814 14.9501 9.32565 14.1375 10.1383L11.1184 13.1574C10.8124 13.4633 10.4154 13.6618 9.98703 13.723L8.09369 13.9935C7.88596 14.0232 7.67639 13.9533 7.52801 13.805C7.37963 13.6566 7.30977 13.447 7.33945 13.2393L7.60991 11.3459C7.67111 10.9175 7.86961 10.5205 8.17561 10.2145L11.1947 7.19548Z",
+ "fill": "currentColor"
+ },
+ "children": []
+ },
+ {
+ "type": "element",
+ "name": "path",
+ "attributes": {
+ "fill-rule": "evenodd",
+ "clip-rule": "evenodd",
+ "d": "M12.528 10.8048L10.528 8.80482L11.4708 7.86201L13.4708 9.86201L12.528 10.8048Z",
+ "fill": "currentColor"
+ },
+ "children": []
+ }
+ ]
+ },
+ "name": "HumanInLoop"
+}
diff --git a/web/app/components/base/icons/src/vender/workflow/HumanInLoop.tsx b/web/app/components/base/icons/src/vender/workflow/HumanInLoop.tsx
new file mode 100644
index 00000000000..a94daf432aa
--- /dev/null
+++ b/web/app/components/base/icons/src/vender/workflow/HumanInLoop.tsx
@@ -0,0 +1,20 @@
+// GENERATE BY script
+// DON NOT EDIT IT MANUALLY
+
+import type { IconData } from '@/app/components/base/icons/IconBase'
+import * as React from 'react'
+import IconBase from '@/app/components/base/icons/IconBase'
+import data from './HumanInLoop.json'
+
+const Icon = (
+ {
+ ref,
+ ...props
+ }: React.SVGProps<SVGSVGElement> & {
+ ref?: React.RefObject<React.MutableRefObject<HTMLOrSVGElement>>
+ },
+) => <IconBase {...props} ref={ref} data={data as IconData} />
+
+Icon.displayName = 'HumanInLoop'
+
+export default Icon
diff --git a/web/app/components/base/icons/src/vender/workflow/index.ts b/web/app/components/base/icons/src/vender/workflow/index.ts
index ec8dce100da..c21e865a091 100644
--- a/web/app/components/base/icons/src/vender/workflow/index.ts
+++ b/web/app/components/base/icons/src/vender/workflow/index.ts
@@ -10,6 +10,7 @@ export { default as DocsExtractor } from './DocsExtractor'
export { default as End } from './End'
export { default as Home } from './Home'
export { default as Http } from './Http'
+export { default as HumanInLoop } from './HumanInLoop'
export { default as IfElse } from './IfElse'
export { default as Iteration } from './Iteration'
export { default as IterationStart } from './IterationStart'
diff --git a/web/app/components/base/markdown/index.tsx b/web/app/components/base/markdown/index.tsx
index c487b205508..8b6728f2460 100644
--- a/web/app/components/base/markdown/index.tsx
+++ b/web/app/components/base/markdown/index.tsx
@@ -18,7 +18,7 @@ export type MarkdownProps = {
content: string
className?: string
pluginInfo?: SimplePluginInfo
-} & Pick<ReactMarkdownWrapperProps, 'customComponents' | 'customDisallowedElements'>
+} & Pick<ReactMarkdownWrapperProps, 'customComponents' | 'customDisallowedElements' | 'rehypePlugins'>
export const Markdown = (props: MarkdownProps) => {
const { customComponents = {}, pluginInfo } = props
@@ -29,7 +29,13 @@ export const Markdown = (props: MarkdownProps) => {
return (
<div className={cn('markdown-body', '!text-text-primary', props.className)}>
- <ReactMarkdown pluginInfo={pluginInfo} latexContent={latexContent} customComponents={customComponents} customDisallowedElements={props.customDisallowedElements} />
+ <ReactMarkdown
+ pluginInfo={pluginInfo}
+ latexContent={latexContent}
+ customComponents={customComponents}
+ customDisallowedElements={props.customDisallowedElements}
+ rehypePlugins={props.rehypePlugins}
+ />
</div>
)
}
diff --git a/web/app/components/base/markdown/react-markdown-wrapper.tsx b/web/app/components/base/markdown/react-markdown-wrapper.tsx
index ed9e93e8b33..a3693a561a8 100644
--- a/web/app/components/base/markdown/react-markdown-wrapper.tsx
+++ b/web/app/components/base/markdown/react-markdown-wrapper.tsx
@@ -22,6 +22,7 @@ export type ReactMarkdownWrapperProps = {
customDisallowedElements?: string[]
customComponents?: Record<string, React.ComponentType<any>>
pluginInfo?: SimplePluginInfo
+ rehypePlugins?: any// js: PluggableList[]
}
export const ReactMarkdownWrapper: FC<ReactMarkdownWrapperProps> = (props) => {
@@ -55,6 +56,7 @@ export const ReactMarkdownWrapper: FC<ReactMarkdownWrapperProps> = (props) => {
tree.children.forEach(iterate)
}
},
+ ...(props.rehypePlugins || []),
]}
urlTransform={customUrlTransform}
disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body', ...(props.customDisallowedElements || [])]}
diff --git a/web/app/components/base/prompt-editor/constants.tsx b/web/app/components/base/prompt-editor/constants.tsx
index d6b8e9fcb45..2dcc62706a4 100644
--- a/web/app/components/base/prompt-editor/constants.tsx
+++ b/web/app/components/base/prompt-editor/constants.tsx
@@ -4,6 +4,7 @@ import { SupportUploadFileTypes } from '../../workflow/types'
export const CONTEXT_PLACEHOLDER_TEXT = '{{#context#}}'
export const HISTORY_PLACEHOLDER_TEXT = '{{#histories#}}'
export const QUERY_PLACEHOLDER_TEXT = '{{#query#}}'
+export const REQUEST_URL_PLACEHOLDER_TEXT = '{{#url#}}'
export const CURRENT_PLACEHOLDER_TEXT = '{{#current#}}'
export const ERROR_MESSAGE_PLACEHOLDER_TEXT = '{{#error_message#}}'
export const LAST_RUN_PLACEHOLDER_TEXT = '{{#last_run#}}'
@@ -30,6 +31,12 @@ export const checkHasQueryBlock = (text: string) => {
return text.includes(QUERY_PLACEHOLDER_TEXT)
}
+export const checkHasRequestURLBlock = (text: string) => {
+ if (!text)
+ return false
+ return text.includes(REQUEST_URL_PLACEHOLDER_TEXT)
+}
+
/*
* {{#1711617514996.name#}} => [1711617514996, name]
* {{#1711617514996.sys.query#}} => [sys, query]
diff --git a/web/app/components/base/prompt-editor/index.tsx b/web/app/components/base/prompt-editor/index.tsx
index 99e3a3325ca..6f1d40f6eb1 100644
--- a/web/app/components/base/prompt-editor/index.tsx
+++ b/web/app/components/base/prompt-editor/index.tsx
@@ -2,16 +2,20 @@
import type {
EditorState,
+ LexicalCommand,
} from 'lexical'
import type { FC } from 'react'
+import type { Hotkey } from './plugins/shortcuts-popup-plugin'
import type {
ContextBlockType,
CurrentBlockType,
ErrorMessageBlockType,
ExternalToolBlockType,
HistoryBlockType,
+ HITLInputBlockType,
LastRunBlockType,
QueryBlockType,
+ RequestURLBlockType,
VariableBlockType,
WorkflowVariableBlockType,
} from './types'
@@ -27,7 +31,7 @@ import {
TextNode,
} from 'lexical'
import * as React from 'react'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { cn } from '@/utils/classnames'
import {
@@ -46,17 +50,23 @@ import {
CurrentBlockReplacementBlock,
} from './plugins/current-block'
import { CustomTextNode } from './plugins/custom-text/node'
+import DraggableBlockPlugin from './plugins/draggable-plugin'
import {
ErrorMessageBlock,
ErrorMessageBlockNode,
ErrorMessageBlockReplacementBlock,
} from './plugins/error-message-block'
-
import {
HistoryBlock,
HistoryBlockNode,
HistoryBlockReplacementBlock,
} from './plugins/history-block'
+
+import {
+ HITLInputBlock,
+ HITLInputBlockReplacementBlock,
+ HITLInputNode,
+} from './plugins/hitl-input-block'
import {
LastRunBlock,
LastRunBlockNode,
@@ -70,6 +80,12 @@ import {
QueryBlockNode,
QueryBlockReplacementBlock,
} from './plugins/query-block'
+import {
+ RequestURLBlock,
+ RequestURLBlockNode,
+ RequestURLBlockReplacementBlock,
+} from './plugins/request-url-block'
+import ShortcutsPopupPlugin from './plugins/shortcuts-popup-plugin'
import UpdateBlock from './plugins/update-block'
import VariableBlock from './plugins/variable-block'
import VariableValueBlock from './plugins/variable-value-block'
@@ -96,14 +112,17 @@ export type PromptEditorProps = {
onFocus?: () => void
contextBlock?: ContextBlockType
queryBlock?: QueryBlockType
+ requestURLBlock?: RequestURLBlockType
historyBlock?: HistoryBlockType
variableBlock?: VariableBlockType
externalToolBlock?: ExternalToolBlockType
workflowVariableBlock?: WorkflowVariableBlockType
+ hitlInputBlock?: HITLInputBlockType
currentBlock?: CurrentBlockType
errorMessageBlock?: ErrorMessageBlockType
lastRunBlock?: LastRunBlockType
isSupportFileVar?: boolean
+ shortcutPopups?: Array<{ hotkey: Hotkey, Popup: React.ComponentType<{ onClose: () => void, onInsert: (command: LexicalCommand<unknown>, params: any[]) => void }> }>
}
const PromptEditor: FC<PromptEditorProps> = ({
@@ -121,14 +140,17 @@ const PromptEditor: FC<PromptEditorProps> = ({
onFocus,
contextBlock,
queryBlock,
+ requestURLBlock,
historyBlock,
variableBlock,
externalToolBlock,
workflowVariableBlock,
+ hitlInputBlock,
currentBlock,
errorMessageBlock,
lastRunBlock,
isSupportFileVar,
+ shortcutPopups = [],
}) => {
const { eventEmitter } = useEventEmitterContextContext()
const initialConfig = {
@@ -143,8 +165,10 @@ const PromptEditor: FC<PromptEditorProps> = ({
ContextBlockNode,
HistoryBlockNode,
QueryBlockNode,
+ RequestURLBlockNode,
WorkflowVariableBlockNode,
VariableValueBlockNode,
+ HITLInputNode,
CurrentBlockNode,
ErrorMessageBlockNode,
LastRunBlockNode, // LastRunBlockNode is used for error message block replacement
@@ -176,9 +200,16 @@ const PromptEditor: FC<PromptEditorProps> = ({
} as any)
}, [eventEmitter, historyBlock?.history])
+ const [floatingAnchorElem, setFloatingAnchorElem] = useState(null)
+
+ const onRef = (_floatingAnchorElem: any) => {
+ if (_floatingAnchorElem !== null)
+ setFloatingAnchorElem(_floatingAnchorElem)
+ }
+
return (
<LexicalComposer initialConfig={{ ...initialConfig, editable }}>
- <div className={cn('relative', wrapperClassName)}>
+ <div className={cn('relative', wrapperClassName)} ref={onRef}>
<RichTextPlugin
contentEditable={(
<ContentEditable
@@ -199,11 +230,17 @@ const PromptEditor: FC<PromptEditorProps> = ({
)}
ErrorBoundary={LexicalErrorBoundary}
/>
+ {shortcutPopups?.map(({ hotkey, Popup }, idx) => (
+ <ShortcutsPopupPlugin key={idx} hotkey={hotkey}>
+ {(closePortal, onInsert) => <Popup onClose={closePortal} onInsert={onInsert} />}
+ </ShortcutsPopupPlugin>
+ ))}
<ComponentPickerBlock
triggerString="/"
contextBlock={contextBlock}
historyBlock={historyBlock}
queryBlock={queryBlock}
+ requestURLBlock={requestURLBlock}
variableBlock={variableBlock}
externalToolBlock={externalToolBlock}
workflowVariableBlock={workflowVariableBlock}
@@ -217,6 +254,7 @@ const PromptEditor: FC<PromptEditorProps> = ({
contextBlock={contextBlock}
historyBlock={historyBlock}
queryBlock={queryBlock}
+ requestURLBlock={requestURLBlock}
variableBlock={variableBlock}
externalToolBlock={externalToolBlock}
workflowVariableBlock={workflowVariableBlock}
@@ -265,6 +303,14 @@ const PromptEditor: FC<PromptEditorProps> = ({
</>
)
}
+ {
+ hitlInputBlock?.show && (
+ <>
+ <HITLInputBlock {...hitlInputBlock} />
+ <HITLInputBlockReplacementBlock {...hitlInputBlock} />
+ </>
+ )
+ }
{
currentBlock?.show && (
<>
@@ -273,6 +319,14 @@ const PromptEditor: FC<PromptEditorProps> = ({
</>
)
}
+ {
+ requestURLBlock?.show && (
+ <>
+ <RequestURLBlock {...requestURLBlock} />
+ <RequestURLBlockReplacementBlock {...requestURLBlock} />
+ </>
+ )
+ }
{
errorMessageBlock?.show && (
<>
@@ -298,6 +352,9 @@ const PromptEditor: FC<PromptEditorProps> = ({
<OnBlurBlock onBlur={onBlur} onFocus={onFocus} />
<UpdateBlock instanceId={instanceId} />
<HistoryPlugin />
+ {floatingAnchorElem && (
+ <DraggableBlockPlugin anchorElem={floatingAnchorElem} />
+ )}
{/* <TreeView /> */}
</div>
</LexicalComposer>
diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/hooks.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/hooks.tsx
index 8855d948df4..247a4a782c6 100644
--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/hooks.tsx
+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/hooks.tsx
@@ -6,10 +6,12 @@ import type {
HistoryBlockType,
LastRunBlockType,
QueryBlockType,
+ RequestURLBlockType,
VariableBlockType,
WorkflowVariableBlockType,
} from '../../types'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { RiGlobalLine } from '@remixicon/react'
import { $insertNodes } from 'lexical'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -27,6 +29,7 @@ import { INSERT_CONTEXT_BLOCK_COMMAND } from '../context-block'
import { $createCustomTextNode } from '../custom-text/node'
import { INSERT_HISTORY_BLOCK_COMMAND } from '../history-block'
import { INSERT_QUERY_BLOCK_COMMAND } from '../query-block'
+import { INSERT_REQUEST_URL_BLOCK_COMMAND } from '../request-url-block'
import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '../variable-block'
import { PickerBlockMenuOption } from './menu'
import { PromptMenuItem } from './prompt-option'
@@ -36,6 +39,7 @@ export const usePromptOptions = (
contextBlock?: ContextBlockType,
queryBlock?: QueryBlockType,
historyBlock?: HistoryBlockType,
+ requestURLBlock?: RequestURLBlockType,
) => {
const { t } = useTranslation()
const [editor] = useLexicalComposerContext()
@@ -91,6 +95,30 @@ export const usePromptOptions = (
)
}
+ if (requestURLBlock?.show) {
+ promptOptions.push(new PickerBlockMenuOption({
+ key: t('promptEditor.requestURL.item.title', { ns: 'common' }),
+ group: 'request URL',
+ render: ({ isSelected, onSelect, onSetHighlight }) => {
+ return (
+ <PromptMenuItem
+ title={t('promptEditor.requestURL.item.title', { ns: 'common' })}
+ icon={<RiGlobalLine className="h-4 w-4 text-util-colors-violet-violet-600" />}
+ disabled={!requestURLBlock.selectable}
+ isSelected={isSelected}
+ onClick={onSelect}
+ onMouseEnter={onSetHighlight}
+ />
+ )
+ },
+ onSelect: () => {
+ if (!requestURLBlock?.selectable)
+ return
+ editor.dispatchCommand(INSERT_REQUEST_URL_BLOCK_COMMAND, undefined)
+ },
+ }))
+ }
+
if (historyBlock?.show) {
promptOptions.push(
new PickerBlockMenuOption({
@@ -272,12 +300,13 @@ export const useOptions = (
variableBlock?: VariableBlockType,
externalToolBlockType?: ExternalToolBlockType,
workflowVariableBlockType?: WorkflowVariableBlockType,
+ requestURLBlock?: RequestURLBlockType,
currentBlockType?: CurrentBlockType,
errorMessageBlockType?: ErrorMessageBlockType,
lastRunBlockType?: LastRunBlockType,
queryString?: string,
) => {
- const promptOptions = usePromptOptions(contextBlock, queryBlock, historyBlock)
+ const promptOptions = usePromptOptions(contextBlock, queryBlock, historyBlock, requestURLBlock)
const variableOptions = useVariableOptions(variableBlock, queryString)
const externalToolOptions = useExternalToolOptions(externalToolBlockType, queryString)
diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
index 728ae21a709..8001a2755b6 100644
--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
@@ -8,6 +8,7 @@ import type {
HistoryBlockType,
LastRunBlockType,
QueryBlockType,
+ RequestURLBlockType,
VariableBlockType,
WorkflowVariableBlockType,
} from '../../types'
@@ -44,6 +45,7 @@ type ComponentPickerProps = {
triggerString: string
contextBlock?: ContextBlockType
queryBlock?: QueryBlockType
+ requestURLBlock?: RequestURLBlockType
historyBlock?: HistoryBlockType
variableBlock?: VariableBlockType
externalToolBlock?: ExternalToolBlockType
@@ -57,6 +59,7 @@ const ComponentPicker = ({
triggerString,
contextBlock,
queryBlock,
+ requestURLBlock,
historyBlock,
variableBlock,
externalToolBlock,
@@ -100,6 +103,7 @@ const ComponentPicker = ({
variableBlock,
externalToolBlock,
workflowVariableBlock,
+ requestURLBlock,
currentBlock,
errorMessageBlock,
lastRunBlock,
diff --git a/web/app/components/base/prompt-editor/plugins/draggable-plugin/index.tsx b/web/app/components/base/prompt-editor/plugins/draggable-plugin/index.tsx
new file mode 100644
index 00000000000..68daed47618
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/draggable-plugin/index.tsx
@@ -0,0 +1,86 @@
+import type { JSX } from 'react'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { DraggableBlockPlugin_EXPERIMENTAL } from '@lexical/react/LexicalDraggableBlockPlugin'
+import { RiDraggable } from '@remixicon/react'
+import { useEffect, useRef, useState } from 'react'
+import { cn } from '@/utils/classnames'
+
+const DRAGGABLE_BLOCK_MENU_CLASSNAME = 'draggable-block-menu'
+
+function isOnMenu(element: HTMLElement): boolean {
+ return !!element.closest(`.${DRAGGABLE_BLOCK_MENU_CLASSNAME}`)
+}
+
+const SUPPORT_DRAG_CLASS = 'support-drag'
+function checkSupportDrag(element: Element | null): boolean {
+ if (!element)
+ return false
+
+ if (element.classList.contains(SUPPORT_DRAG_CLASS))
+ return true
+
+ if (element.querySelector(`.${SUPPORT_DRAG_CLASS}`))
+ return true
+
+ return !!(element.closest(`.${SUPPORT_DRAG_CLASS}`))
+}
+
+export default function DraggableBlockPlugin({
+ anchorElem = document.body,
+}: {
+ anchorElem?: HTMLElement
+}): JSX.Element {
+ const menuRef = useRef<HTMLDivElement>(null)
+ const targetLineRef = useRef<HTMLDivElement>(null)
+ const [, setDraggableElement] = useState<HTMLElement | null>(
+ null,
+ )
+ const [editor] = useLexicalComposerContext()
+
+ const [isSupportDrag, setIsSupportDrag] = useState(false)
+
+ useEffect(() => {
+ const root = editor.getRootElement()
+ if (!root)
+ return
+
+ const onMove = (e: MouseEvent) => {
+ const isSupportDrag = checkSupportDrag(e.target as Element)
+ setIsSupportDrag(isSupportDrag)
+ }
+
+ root.addEventListener('mousemove', onMove)
+ return () => root.removeEventListener('mousemove', onMove)
+ }, [editor])
+
+ return (
+ <DraggableBlockPlugin_EXPERIMENTAL
+ anchorElem={anchorElem}
+ menuRef={menuRef as any}
+ targetLineRef={targetLineRef as any}
+ menuComponent={
+ isSupportDrag
+ ? (
+ <div ref={menuRef} className={cn(DRAGGABLE_BLOCK_MENU_CLASSNAME, 'absolute right-2.5 top-4 cursor-grab opacity-0 will-change-transform active:cursor-move')}>
+ <RiDraggable className="size-3.5 text-text-tertiary" />
+ </div>
+ )
+ : null
+ }
+ targetLineComponent={(
+ <div
+ ref={targetLineRef}
+ className="pointer-events-none absolute left-[-21px] top-0 opacity-0 will-change-transform"
+ // style={{ width: 500 }} // width not worked here
+ >
+ <div
+ className="absolute -right-10 left-0 top-0 h-[2px] bg-text-accent-secondary"
+ >
+ </div>
+ </div>
+ )}
+ isOnMenu={isOnMenu}
+ onElementChanged={setDraggableElement}
+ />
+ )
+}
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
new file mode 100644
index 00000000000..736f6bafe9d
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
@@ -0,0 +1,170 @@
+'use client'
+import type { FC } from 'react'
+import type { WorkflowNodesMap } from '../workflow-variable-block/node'
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { Type } from '@/app/components/workflow/nodes/llm/types'
+import type { ValueSelector, Var } from '@/app/components/workflow/types'
+import { RiDeleteBinLine, RiEditLine } from '@remixicon/react'
+import { useBoolean } from 'ahooks'
+import * as React from 'react'
+import { useCallback, useEffect, useMemo, useRef } from 'react'
+import { InputVarType } from '@/app/components/workflow/types'
+import ActionButton from '../../../action-button'
+import { VariableX } from '../../../icons/src/vender/workflow'
+import Modal from '../../../modal'
+import InputField from './input-field'
+import VariableBlock from './variable-block'
+
+type HITLInputComponentUIProps = {
+ nodeId: string
+ varName: string
+ formInput?: FormInputItem
+ onChange: (input: FormInputItem) => void
+ onRename: (payload: FormInputItem, oldName: string) => void
+ onRemove: (varName: string) => void
+ workflowNodesMap: WorkflowNodesMap
+ environmentVariables?: Var[]
+ conversationVariables?: Var[]
+ ragVariables?: Var[]
+ getVarType?: (payload: {
+ nodeId: string
+ valueSelector: ValueSelector
+ }) => Type
+ readonly?: boolean
+}
+
+const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
+ nodeId,
+ varName,
+ formInput = {
+ type: InputVarType.paragraph,
+ output_variable_name: varName,
+ default: {
+ type: 'constant',
+ selector: [],
+ value: '',
+ },
+ },
+ onChange,
+ onRename,
+ onRemove,
+ workflowNodesMap = {},
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+}) => {
+ const [isShowEditModal, {
+ setTrue: showEditModal,
+ setFalse: hideEditModal,
+ }] = useBoolean(false)
+
+ // Lexical delegate the click make it unable to add click by the method of react
+ const editBtnRef = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ const editBtn = editBtnRef.current
+ if (editBtn)
+ editBtn.addEventListener('click', showEditModal)
+
+ return () => {
+ if (editBtn)
+ editBtn.removeEventListener('click', showEditModal)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ const removeBtnRef = useRef<HTMLDivElement>(null)
+ useEffect(() => {
+ const removeBtn = removeBtnRef.current
+ const removeHandler = () => onRemove(varName)
+ if (removeBtn)
+ removeBtn.addEventListener('click', removeHandler)
+
+ return () => {
+ if (removeBtn)
+ removeBtn.removeEventListener('click', removeHandler)
+ }
+ }, [onRemove, varName])
+
+ const handleChange = useCallback((newPayload: FormInputItem) => {
+ if (varName === newPayload.output_variable_name)
+ onChange(newPayload)
+ else
+ onRename(newPayload, varName)
+ hideEditModal()
+ }, [hideEditModal, onChange, onRename, varName])
+
+ const isDefaultValueVariable = useMemo(() => {
+ return formInput.default?.type === 'variable'
+ }, [formInput.default?.type])
+
+ return (
+ <div
+ className="group relative flex h-8 w-full select-none items-center rounded-[8px] border-[1.5px] border-components-input-border-active bg-background-default-hover pl-1.5 pr-0.5"
+ >
+ <div className="absolute left-2.5 top-[-12px]">
+ <div className="absolute bottom-1 h-[1.5px] w-full bg-background-default-subtle"></div>
+ <div className="relative flex items-center space-x-0.5 px-1 text-text-accent-light-mode-only">
+ <VariableX className="size-3" />
+ <div className="system-xs-medium">{varName}</div>
+ </div>
+ </div>
+
+ <div className="flex w-full items-center gap-x-0.5 pr-5">
+ <div className="min-w-0 grow">
+ {/* Default Value Info */}
+ {isDefaultValueVariable && (
+ <VariableBlock
+ variables={formInput.default?.selector}
+ workflowNodesMap={workflowNodesMap}
+ getVarType={getVarType}
+ environmentVariables={environmentVariables}
+ conversationVariables={conversationVariables}
+ ragVariables={ragVariables}
+ />
+ )}
+ {!isDefaultValueVariable && (
+ <div className="system-xs-medium max-w-full truncate text-components-input-text-filled">{formInput.default?.value}</div>
+ )}
+ </div>
+
+ {/* Actions */}
+ {!readonly && (
+ <div className="hidden h-full shrink-0 items-center space-x-1 group-hover:flex">
+ <div className="flex h-full items-center" ref={editBtnRef}>
+ <ActionButton size="s">
+ <RiEditLine className="size-4 text-text-tertiary" />
+ </ActionButton>
+ </div>
+
+ <div className="flex h-full items-center" ref={removeBtnRef}>
+ <ActionButton size="s">
+ <RiDeleteBinLine className="size-4 text-text-tertiary" />
+ </ActionButton>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {isShowEditModal && (
+ <Modal
+ isShow
+ onClose={hideEditModal}
+ wrapperClassName="z-[999]"
+ className="max-w-[372px] !p-0"
+ >
+ <InputField
+ nodeId={nodeId}
+ isEdit
+ payload={formInput}
+ onChange={handleChange}
+ onCancel={hideEditModal}
+ />
+ </Modal>
+ )}
+ </div>
+ )
+}
+
+export default React.memo(HITLInputComponentUI)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx
new file mode 100644
index 00000000000..df4147fc33c
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component.tsx
@@ -0,0 +1,86 @@
+import type { FC } from 'react'
+import type { WorkflowNodesMap } from '../workflow-variable-block/node'
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { Type } from '@/app/components/workflow/nodes/llm/types'
+import type { ValueSelector, Var } from '@/app/components/workflow/types'
+import { produce } from 'immer'
+import { useCallback } from 'react'
+import { useSelectOrDelete } from '../../hooks'
+import { DELETE_HITL_INPUT_BLOCK_COMMAND } from './'
+import ComponentUi from './component-ui'
+
+type HITLInputComponentProps = {
+ nodeKey: string
+ nodeId: string
+ varName: string
+ formInputs?: FormInputItem[]
+ onChange: (inputs: FormInputItem[]) => void
+ onRename: (payload: FormInputItem, oldName: string) => void
+ onRemove: (varName: string) => void
+ workflowNodesMap: WorkflowNodesMap
+ environmentVariables?: Var[]
+ conversationVariables?: Var[]
+ ragVariables?: Var[]
+ getVarType?: (payload: {
+ nodeId: string
+ valueSelector: ValueSelector
+ }) => Type
+ readonly?: boolean
+}
+
+const HITLInputComponent: FC<HITLInputComponentProps> = ({
+ nodeKey,
+ nodeId,
+ varName,
+ formInputs = [],
+ onChange,
+ onRename,
+ onRemove,
+ workflowNodesMap = {},
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+}) => {
+ const [ref] = useSelectOrDelete(nodeKey, DELETE_HITL_INPUT_BLOCK_COMMAND)
+ const payload = formInputs.find(item => item.output_variable_name === varName)
+
+ const handleChange = useCallback((newPayload: FormInputItem) => {
+ if (!payload) {
+ onChange([...formInputs, newPayload])
+ return
+ }
+ if (payload?.output_variable_name !== newPayload.output_variable_name) {
+ onChange(produce(formInputs, (draft) => {
+ draft.splice(draft.findIndex(item => item.output_variable_name === payload?.output_variable_name), 1, newPayload)
+ }))
+ return
+ }
+ onChange(formInputs.map(item => item.output_variable_name === varName ? newPayload : item))
+ }, [formInputs, onChange, payload, varName])
+
+ return (
+ <div
+ ref={ref}
+ className="w-full pb-1 pt-3"
+ >
+ <ComponentUi
+ nodeId={nodeId}
+ varName={varName}
+ formInput={payload}
+ onChange={handleChange}
+ onRename={onRename}
+ onRemove={onRemove}
+ workflowNodesMap={workflowNodesMap}
+ getVarType={getVarType}
+ environmentVariables={environmentVariables}
+ conversationVariables={conversationVariables}
+ ragVariables={ragVariables}
+ readonly={readonly}
+ />
+ </div>
+ )
+}
+
+export default HITLInputComponent
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx
new file mode 100644
index 00000000000..cd1515c57df
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx
@@ -0,0 +1,89 @@
+import type { TextNode } from 'lexical'
+import type { HITLInputBlockType } from '../../types'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { mergeRegister } from '@lexical/utils'
+import { $applyNodeReplacement } from 'lexical'
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useMemo,
+} from 'react'
+import { HITL_INPUT_REG } from '@/config'
+import { decoratorTransform } from '../../utils'
+import { CustomTextNode } from '../custom-text/node'
+import { $createHITLInputNode, HITLInputNode } from './node'
+
+const REGEX = new RegExp(HITL_INPUT_REG)
+
+const HITLInputReplacementBlock = ({
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ workflowNodesMap,
+ getVarType,
+ variables,
+ readonly,
+}: HITLInputBlockType) => {
+ const [editor] = useLexicalComposerContext()
+
+ const environmentVariables = useMemo(() => variables?.find(o => o.nodeId === 'env')?.vars || [], [variables])
+ const conversationVariables = useMemo(() => variables?.find(o => o.nodeId === 'conversation')?.vars || [], [variables])
+ const ragVariables = useMemo(() => variables?.reduce<any[]>((acc, curr) => {
+ if (curr.nodeId === 'rag')
+ acc.push(...curr.vars)
+ else
+ acc.push(...curr.vars.filter(v => v.isRagVariable))
+ return acc
+ }, []), [variables])
+
+ useEffect(() => {
+ if (!editor.hasNodes([HITLInputNode]))
+ throw new Error('HITLInputNodePlugin: HITLInputNode not registered on editor')
+ }, [editor])
+
+ const createHITLInputBlockNode = useCallback((textNode: TextNode): HITLInputNode => {
+ const varName = textNode.getTextContent().split('.')[1].replace(/#\}\}$/, '')
+ return $applyNodeReplacement($createHITLInputNode(
+ varName,
+ nodeId,
+ formInputs || [],
+ onFormInputsChange!,
+ onFormInputItemRename,
+ onFormInputItemRemove!,
+ workflowNodesMap,
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+ ))
+ }, [nodeId, formInputs, onFormInputsChange, onFormInputItemRename, onFormInputItemRemove, workflowNodesMap, getVarType, environmentVariables, conversationVariables, ragVariables, readonly])
+
+ const getMatch = useCallback((text: string) => {
+ const matchArr = REGEX.exec(text)
+
+ if (matchArr === null)
+ return null
+
+ const startOffset = matchArr.index
+ const endOffset = startOffset + matchArr[0].length
+ return {
+ end: endOffset,
+ start: startOffset,
+ }
+ }, [])
+
+ useEffect(() => {
+ REGEX.lastIndex = 0
+ return mergeRegister(
+ editor.registerNodeTransform(CustomTextNode, textNode => decoratorTransform(textNode, getMatch, createHITLInputBlockNode)),
+ )
+ }, [])
+
+ return null
+}
+
+export default memo(HITLInputReplacementBlock)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx
new file mode 100644
index 00000000000..49b0e3d150f
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/index.tsx
@@ -0,0 +1,106 @@
+import type { HITLInputBlockType } from '../../types'
+import type {
+ HITLNodeProps,
+} from './node'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { mergeRegister } from '@lexical/utils'
+import {
+ $insertNodes,
+ COMMAND_PRIORITY_EDITOR,
+ createCommand,
+} from 'lexical'
+import {
+ memo,
+ useEffect,
+} from 'react'
+import { CustomTextNode } from '../custom-text/node'
+import {
+ $createHITLInputNode,
+ HITLInputNode,
+} from './node'
+
+export const INSERT_HITL_INPUT_BLOCK_COMMAND = createCommand('INSERT_HITL_INPUT_BLOCK_COMMAND')
+export const DELETE_HITL_INPUT_BLOCK_COMMAND = createCommand('DELETE_HITL_INPUT_BLOCK_COMMAND')
+export const UPDATE_WORKFLOW_NODES_MAP = createCommand('UPDATE_WORKFLOW_NODES_MAP')
+
+export type HITLInputProps = {
+ onInsert?: () => void
+ onDelete?: () => void
+}
+const HITLInputBlock = memo(({
+ onInsert,
+ onDelete,
+ workflowNodesMap,
+ getVarType,
+ readonly,
+}: HITLInputBlockType) => {
+ const [editor] = useLexicalComposerContext()
+
+ useEffect(() => {
+ editor.update(() => {
+ editor.dispatchCommand(UPDATE_WORKFLOW_NODES_MAP, workflowNodesMap)
+ })
+ }, [editor, workflowNodesMap])
+
+ useEffect(() => {
+ if (!editor.hasNodes([HITLInputNode]))
+ throw new Error('HITLInputBlockPlugin: HITLInputBlock not registered on editor')
+ return mergeRegister(
+ editor.registerCommand(
+ INSERT_HITL_INPUT_BLOCK_COMMAND,
+ (nodeProps: HITLNodeProps) => {
+ const {
+ variableName,
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ } = nodeProps
+ const currentHITLNode = $createHITLInputNode(
+ variableName,
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ workflowNodesMap,
+ getVarType,
+ undefined,
+ undefined,
+ undefined,
+ readonly,
+ )
+ const prev = new CustomTextNode('\n')
+ $insertNodes([prev])
+ $insertNodes([currentHITLNode])
+ const next = new CustomTextNode('\n')
+ $insertNodes([next])
+ if (onInsert)
+ onInsert()
+
+ return true
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
+ editor.registerCommand(
+ DELETE_HITL_INPUT_BLOCK_COMMAND,
+ () => {
+ if (onDelete)
+ onDelete()
+
+ return true
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
+ )
+ }, [editor, onInsert, onDelete])
+
+ return null
+})
+
+HITLInputBlock.displayName = 'HITLInputBlock'
+
+export { HITLInputBlock }
+export { default as HITLInputBlockReplacementBlock } from './hitl-input-block-replacement-block'
+export { HITLInputNode } from './node'
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
new file mode 100644
index 00000000000..06f7e1db7ad
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
@@ -0,0 +1,153 @@
+import type { FormInputItem, FormInputItemDefault } from '@/app/components/workflow/nodes/human-input/types'
+import type { ValueSelector } from '@/app/components/workflow/types'
+import { produce } from 'immer'
+import * as React from 'react'
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Input from '@/app/components/base/input'
+import { InputVarType } from '@/app/components/workflow/types'
+import { getKeyboardKeyNameBySystem } from '@/app/components/workflow/utils'
+import Button from '../../../button'
+import PrePopulate from './pre-populate'
+
+const i18nPrefix = 'nodes.humanInput.insertInputField'
+
+type InputFieldProps = {
+ nodeId: string
+ isEdit: boolean
+ payload?: FormInputItem
+ onChange: (newPayload: FormInputItem) => void
+ onCancel: () => void
+}
+const defaultPayload: FormInputItem = {
+ type: InputVarType.paragraph,
+ output_variable_name: '',
+ default: { type: 'constant', selector: [], value: '' },
+}
+const InputField: React.FC<InputFieldProps> = ({
+ nodeId,
+ isEdit,
+ payload,
+ onChange,
+ onCancel,
+}) => {
+ const { t } = useTranslation()
+ const [tempPayload, setTempPayload] = useState(payload || defaultPayload)
+ const nameValid = useMemo(() => {
+ const name = tempPayload.output_variable_name.trim()
+ if (!name)
+ return false
+ if (name.includes(' '))
+ return false
+ return /^[a-z_]\w{0,29}$/.test(name)
+ }, [tempPayload.output_variable_name])
+ const handleSave = useCallback(() => {
+ if (!nameValid)
+ return
+ onChange(tempPayload)
+ }, [nameValid, onChange, tempPayload])
+ const defaultValueConfig = tempPayload.default
+ const handleDefaultValueChange = useCallback((key: keyof FormInputItemDefault) => {
+ return (value: ValueSelector | string) => {
+ const nextValue = produce(tempPayload, (draft) => {
+ if (!draft.default)
+ draft.default = { type: 'constant', selector: [], value: '' }
+ if (key === 'selector') {
+ draft.default.type = 'variable'
+ draft.default.selector = value as ValueSelector
+ }
+ else if (key === 'value') {
+ draft.default.type = 'constant'
+ draft.default.value = value as string
+ }
+ else if (key === 'type') {
+ draft.default.type = value as 'constant' | 'variable'
+ }
+ })
+ setTempPayload(nextValue)
+ }
+ }, [tempPayload])
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
+ e.preventDefault()
+ handleSave()
+ }
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown)
+ }
+ }, [handleSave])
+
+ return (
+ <div className="w-[372px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 shadow-lg backdrop-blur-[5px]">
+ <div className="system-md-semibold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'workflow' })}</div>
+ <div className="mt-3">
+ <div className="system-xs-medium text-text-secondary">
+ {t(`${i18nPrefix}.saveResponseAs`, { ns: 'workflow' })}
+ <span className="system-xs-regular relative text-text-destructive-secondary">*</span>
+ </div>
+ <Input
+ className="mt-1.5"
+ placeholder={t(`${i18nPrefix}.saveResponseAsPlaceholder`, { ns: 'workflow' })}
+ value={tempPayload.output_variable_name}
+ onChange={(e) => {
+ setTempPayload(prev => ({ ...prev, output_variable_name: e.target.value }))
+ }}
+ autoFocus
+ />
+ {tempPayload.output_variable_name && !nameValid && (
+ <div className="system-xs-regular mt-1 px-1 text-text-destructive-secondary">
+ {t(`${i18nPrefix}.variableNameInvalid`, { ns: 'workflow' })}
+ </div>
+ )}
+ </div>
+ <div className="mt-4">
+ <div className="system-xs-medium mb-1.5 text-text-secondary">
+ {t(`${i18nPrefix}.prePopulateField`, { ns: 'workflow' })}
+ </div>
+ <PrePopulate
+ isVariable={defaultValueConfig?.type === 'variable'}
+ onIsVariableChange={(isVariable) => {
+ handleDefaultValueChange('type')(isVariable ? 'variable' : 'constant')
+ }}
+ nodeId={nodeId}
+ valueSelector={defaultValueConfig?.selector}
+ onValueSelectorChange={handleDefaultValueChange('selector')}
+ value={defaultValueConfig?.value}
+ onValueChange={handleDefaultValueChange('value')}
+ />
+ </div>
+ <div className="mt-4 flex justify-end space-x-2">
+ <Button onClick={onCancel}>{t('operation.cancel', { ns: 'common' })}</Button>
+ {isEdit
+ ? (
+ <Button
+ variant="primary"
+ onClick={handleSave}
+ disabled={!nameValid}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ )
+ : (
+ <Button
+ className="flex"
+ variant="primary"
+ disabled={!nameValid}
+ onClick={handleSave}
+ >
+ <span className="mr-1">{t(`${i18nPrefix}.insert`, { ns: 'workflow' })}</span>
+ <span className="system-kbd mr-0.5 flex h-4 items-center rounded-[4px] bg-components-kbd-bg-white px-1">{getKeyboardKeyNameBySystem('ctrl')}</span>
+ <span className=" system-kbd flex h-4 items-center rounded-[4px] bg-components-kbd-bg-white px-1">↩︎</span>
+ </Button>
+ )}
+
+ </div>
+ </div>
+ )
+}
+
+export default InputField
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx
new file mode 100644
index 00000000000..bf3c44acf3e
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/node.tsx
@@ -0,0 +1,272 @@
+import type { LexicalNode, NodeKey, SerializedLexicalNode } from 'lexical'
+import type { GetVarType } from '../../types'
+import type { WorkflowNodesMap } from '../workflow-variable-block/node'
+import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
+import type { Var } from '@/app/components/workflow/types'
+import { DecoratorNode } from 'lexical'
+import HILTInputBlockComponent from './component'
+
+export type HITLNodeProps = {
+ variableName: string
+ nodeId: string
+ formInputs: FormInputItem[]
+ onFormInputsChange: (inputs: FormInputItem[]) => void
+ onFormInputItemRename: (payload: FormInputItem, oldName: string) => void
+ onFormInputItemRemove: (varName: string) => void
+ workflowNodesMap: WorkflowNodesMap
+ getVarType?: GetVarType
+ environmentVariables?: Var[]
+ conversationVariables?: Var[]
+ ragVariables?: Var[]
+ readonly?: boolean
+}
+
+export type SerializedNode = SerializedLexicalNode & HITLNodeProps
+
+export class HITLInputNode extends DecoratorNode<React.JSX.Element> {
+ __variableName: string
+ __nodeId: string
+ __formInputs?: FormInputItem[]
+ __onFormInputsChange: (inputs: FormInputItem[]) => void
+ __onFormInputItemRename: (payload: FormInputItem, oldName: string) => void
+ __onFormInputItemRemove: (varName: string) => void
+ __workflowNodesMap: WorkflowNodesMap
+ __getVarType?: GetVarType
+ __environmentVariables?: Var[]
+ __conversationVariables?: Var[]
+ __ragVariables?: Var[]
+ __readonly?: boolean
+
+ isIsolated(): boolean {
+ return true // This is necessary for drag-and-drop to work correctly
+ }
+
+ isTopLevel(): boolean {
+ return true // This is necessary for drag-and-drop to work correctly
+ }
+
+ static getType(): string {
+ return 'hitl-input-block'
+ }
+
+ getVariableName(): string {
+ const self = this.getLatest()
+ return self.__variableName
+ }
+
+ getNodeId(): string {
+ const self = this.getLatest()
+ return self.__nodeId
+ }
+
+ getFormInputs(): FormInputItem[] {
+ const self = this.getLatest()
+ return self.__formInputs || []
+ }
+
+ getOnFormInputsChange(): (inputs: FormInputItem[]) => void {
+ const self = this.getLatest()
+ return self.__onFormInputsChange
+ }
+
+ getOnFormInputItemRename(): (payload: FormInputItem, oldName: string) => void {
+ const self = this.getLatest()
+ return self.__onFormInputItemRename
+ }
+
+ getOnFormInputItemRemove(): (varName: string) => void {
+ const self = this.getLatest()
+ return self.__onFormInputItemRemove
+ }
+
+ getWorkflowNodesMap(): WorkflowNodesMap {
+ const self = this.getLatest()
+ return self.__workflowNodesMap
+ }
+
+ getGetVarType(): GetVarType | undefined {
+ const self = this.getLatest()
+ return self.__getVarType
+ }
+
+ getEnvironmentVariables(): Var[] {
+ const self = this.getLatest()
+ return self.__environmentVariables || []
+ }
+
+ getConversationVariables(): Var[] {
+ const self = this.getLatest()
+ return self.__conversationVariables || []
+ }
+
+ getRagVariables(): Var[] {
+ const self = this.getLatest()
+ return self.__ragVariables || []
+ }
+
+ getReadonly(): boolean {
+ const self = this.getLatest()
+ return self.__readonly || false
+ }
+
+ static clone(node: HITLInputNode): HITLInputNode {
+ return new HITLInputNode(
+ node.__variableName,
+ node.__nodeId,
+ node.__formInputs || [],
+ node.__onFormInputsChange,
+ node.__onFormInputItemRename,
+ node.__onFormInputItemRemove,
+ node.__workflowNodesMap,
+ node.__getVarType,
+ node.__environmentVariables,
+ node.__conversationVariables,
+ node.__ragVariables,
+ node.__readonly,
+ node.__key,
+ )
+ }
+
+ isInline(): boolean {
+ return true
+ }
+
+ constructor(
+ varName: string,
+ nodeId: string,
+ formInputs: FormInputItem[],
+ onFormInputsChange: (inputs: FormInputItem[]) => void,
+ onFormInputItemRename: (payload: FormInputItem, oldName: string) => void,
+ onFormInputItemRemove: (varName: string) => void,
+ workflowNodesMap: WorkflowNodesMap,
+ getVarType?: GetVarType,
+ environmentVariables?: Var[],
+ conversationVariables?: Var[],
+ ragVariables?: Var[],
+ readonly?: boolean,
+ key?: NodeKey,
+ ) {
+ super(key)
+
+ this.__variableName = varName
+ this.__nodeId = nodeId
+ this.__formInputs = formInputs
+ this.__onFormInputsChange = onFormInputsChange
+ this.__onFormInputItemRename = onFormInputItemRename
+ this.__onFormInputItemRemove = onFormInputItemRemove
+ this.__workflowNodesMap = workflowNodesMap
+ this.__getVarType = getVarType
+ this.__environmentVariables = environmentVariables
+ this.__conversationVariables = conversationVariables
+ this.__ragVariables = ragVariables
+ this.__readonly = readonly
+ }
+
+ createDOM(): HTMLElement {
+ const div = document.createElement('div')
+ div.classList.add('inline-flex', 'w-[calc(100%-1px)]', 'items-center', 'align-middle', 'support-drag')
+ return div
+ }
+
+ updateDOM(): false {
+ return false
+ }
+
+ decorate(): React.JSX.Element {
+ return (
+ <HILTInputBlockComponent
+ nodeKey={this.getKey()}
+ varName={this.getVariableName()}
+ nodeId={this.getNodeId()}
+ formInputs={this.getFormInputs()}
+ onChange={this.getOnFormInputsChange()}
+ onRename={this.getOnFormInputItemRename()}
+ onRemove={this.getOnFormInputItemRemove()}
+ workflowNodesMap={this.getWorkflowNodesMap()}
+ getVarType={this.getGetVarType()}
+ environmentVariables={this.getEnvironmentVariables()}
+ conversationVariables={this.getConversationVariables()}
+ ragVariables={this.getRagVariables()}
+ readonly={this.getReadonly()}
+ />
+ )
+ }
+
+ static importJSON(serializedNode: SerializedNode): HITLInputNode {
+ const node = $createHITLInputNode(
+ serializedNode.variableName,
+ serializedNode.nodeId,
+ serializedNode.formInputs,
+ serializedNode.onFormInputsChange,
+ serializedNode.onFormInputItemRename,
+ serializedNode.onFormInputItemRemove,
+ serializedNode.workflowNodesMap,
+ serializedNode.getVarType,
+ serializedNode.environmentVariables,
+ serializedNode.conversationVariables,
+ serializedNode.ragVariables,
+ serializedNode.readonly,
+ )
+
+ return node
+ }
+
+ exportJSON(): SerializedNode {
+ return {
+ type: 'hitl-input-block',
+ version: 1,
+ variableName: this.getVariableName(),
+ nodeId: this.getNodeId(),
+ formInputs: this.getFormInputs(),
+ onFormInputsChange: this.getOnFormInputsChange(),
+ onFormInputItemRename: this.getOnFormInputItemRename(),
+ onFormInputItemRemove: this.getOnFormInputItemRemove(),
+ workflowNodesMap: this.getWorkflowNodesMap(),
+ getVarType: this.getGetVarType(),
+ environmentVariables: this.getEnvironmentVariables(),
+ conversationVariables: this.getConversationVariables(),
+ ragVariables: this.getRagVariables(),
+ readonly: this.getReadonly(),
+ }
+ }
+
+ getTextContent(): string {
+ return `{{#$output.${this.getVariableName()}#}}`
+ }
+}
+
+export function $createHITLInputNode(
+ variableName: string,
+ nodeId: string,
+ formInputs: FormInputItem[],
+ onFormInputsChange: (inputs: FormInputItem[]) => void,
+ onFormInputItemRename: (payload: FormInputItem, oldName: string) => void,
+ onFormInputItemRemove: (varName: string) => void,
+ workflowNodesMap: WorkflowNodesMap,
+ getVarType?: GetVarType,
+ environmentVariables?: Var[],
+ conversationVariables?: Var[],
+ ragVariables?: Var[],
+ readonly?: boolean,
+): HITLInputNode {
+ return new HITLInputNode(
+ variableName,
+ nodeId,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ workflowNodesMap,
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+ readonly,
+ )
+}
+
+export function $isHITLInputNode(
+ node: HITLInputNode | LexicalNode | null | undefined,
+): node is HITLInputNode {
+ return node instanceof HITLInputNode
+}
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
new file mode 100644
index 00000000000..bbcf5485b97
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
@@ -0,0 +1,148 @@
+'use client'
+import type { FC } from 'react'
+import type { ValueSelector, Var } from '@/app/components/workflow/types'
+import * as React from 'react'
+import { useCallback, useEffect, useState } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
+import { VarType } from '@/app/components/workflow/types'
+import { cn } from '@/utils/classnames'
+import Textarea from '../../../textarea'
+import TagLabel from './tag-label'
+import TypeSwitch from './type-switch'
+
+type Props = {
+ isVariable?: boolean
+ onIsVariableChange?: (isVariable: boolean) => void
+ nodeId: string
+ valueSelector?: ValueSelector
+ onValueSelectorChange?: (valueSelector: ValueSelector | string) => void
+ value?: string
+ onValueChange?: (value: string) => void
+}
+
+const i18nPrefix = 'nodes.humanInput.insertInputField'
+
+type PlaceholderProps = {
+ varPickerProps: {
+ nodeId: string
+ value: ValueSelector
+ onChange: (valueSelector: ValueSelector | string) => void
+ readonly: boolean
+ zIndex: number
+ filterVar: (varPayload: Var) => boolean
+ isJustShowValue?: boolean
+ }
+ onTypeClick: (isVariable: boolean) => void
+}
+const Placeholder = ({
+ varPickerProps,
+ onTypeClick,
+}: PlaceholderProps) => {
+ const { t } = useTranslation()
+ return (
+ <div className="system-sm-regular mt-1 h-[80px] rounded-lg bg-components-input-bg-normal px-3 pt-2 text-text-tertiary">
+ <div className="flex flex-wrap items-center leading-5">
+ <Trans
+ i18nKey={`${i18nPrefix}.prePopulateFieldPlaceholder`}
+ ns="workflow"
+ components={{
+ staticContent: <TagLabel type="edit" className="mx-1" onClick={() => onTypeClick(false)}>{t(`${i18nPrefix}.staticContent`, { ns: 'workflow' })}</TagLabel>,
+ variable: (
+ <VarReferencePicker
+ {...varPickerProps}
+ trigger={
+ <TagLabel type="variable" className="mx-1">{t(`${i18nPrefix}.variable`, { ns: 'workflow' })}</TagLabel>
+ }
+ />
+ ),
+ }}
+ />
+ </div>
+ </div>
+ )
+}
+
+const PrePopulate: FC<Props> = ({
+ isVariable = false,
+ onIsVariableChange,
+ nodeId,
+ valueSelector,
+ onValueSelectorChange,
+ value,
+ onValueChange,
+}) => {
+ const [onPlaceholderClicked, setOnPlaceholderClicked] = useState(false)
+ const handleTypeChange = useCallback((isVar: boolean) => {
+ setOnPlaceholderClicked(true)
+ onIsVariableChange?.(isVar)
+ }, [onIsVariableChange])
+
+ const [isFocus, setIsFocus] = useState(false)
+
+ const varPickerProps = {
+ nodeId,
+ value: valueSelector || [],
+ onChange: onValueSelectorChange!,
+ readonly: false,
+ zIndex: 1000000, // bigger than shortcut plugin popup
+ filterVar: (varPayload: Var) => {
+ return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
+ },
+ }
+
+ const isShowPlaceholder = !onPlaceholderClicked && (isVariable ? (!valueSelector || valueSelector.length === 0) : !value)
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Tab' && !onPlaceholderClicked) {
+ e.preventDefault()
+ setOnPlaceholderClicked(true)
+ }
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown)
+ }
+ }, [onPlaceholderClicked, setOnPlaceholderClicked])
+
+ if (isShowPlaceholder)
+ return <Placeholder varPickerProps={varPickerProps} onTypeClick={handleTypeChange} />
+
+ if (isVariable) {
+ return (
+ <div className="relative h-[80px] rounded-lg border border-transparent bg-components-input-bg-normal px-3 pt-2">
+ <VarReferencePicker
+ {...varPickerProps}
+ isJustShowValue
+ />
+ <TypeSwitch
+ className="absolute bottom-1 left-1.5"
+ isVariable={isVariable}
+ onIsVariableChange={handleTypeChange}
+ />
+ </div>
+ )
+ }
+ return (
+ <div className={cn('relative min-h-[80px] rounded-lg border border-transparent bg-components-input-bg-normal pb-1', isFocus && 'border-components-input-border-active bg-components-input-bg-active shadow-xs')}>
+ <Textarea
+ value={value || ''}
+ className="h-[43px] min-h-[43px] rounded-none border-none bg-transparent px-3 hover:bg-transparent focus:bg-transparent focus:shadow-none"
+ onChange={e => onValueChange?.(e.target.value)}
+ onFocus={() => {
+ setOnPlaceholderClicked(true)
+ setIsFocus(true)
+ }}
+ onBlur={() => setIsFocus(false)}
+ autoFocus
+ />
+ <TypeSwitch
+ className="absolute bottom-1 left-1.5"
+ isVariable={isVariable}
+ onIsVariableChange={handleTypeChange}
+ />
+ </div>
+ )
+}
+export default React.memo(PrePopulate)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx
new file mode 100644
index 00000000000..c414db866d6
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx
@@ -0,0 +1,32 @@
+'use client'
+import type { FC } from 'react'
+import { RiEditLine } from '@remixicon/react'
+import * as React from 'react'
+import { cn } from '@/utils/classnames'
+import { Variable02 } from '../../../icons/src/vender/solid/development'
+
+type Props = {
+ type: 'edit' | 'variable'
+ children: string
+ className?: string
+ onClick?: () => void
+}
+
+const TagLabel: FC<Props> = ({
+ type,
+ children,
+ className,
+ onClick,
+}) => {
+ const Icon = type === 'edit' ? RiEditLine : Variable02
+ return (
+ <div
+ className={cn('inline-flex h-5 cursor-pointer items-center space-x-1 rounded-md bg-components-button-secondary-bg px-1 text-text-accent', className)}
+ onClick={onClick}
+ >
+ <Icon className="size-3.5" />
+ <div className="system-xs-medium ">{children}</div>
+ </div>
+ )
+}
+export default React.memo(TagLabel)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/type-switch.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/type-switch.tsx
new file mode 100644
index 00000000000..667f0605e84
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/type-switch.tsx
@@ -0,0 +1,27 @@
+'use client'
+import type { FC } from 'react'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import { cn } from '@/utils/classnames'
+import { Variable02 } from '../../../icons/src/vender/solid/development'
+
+type Props = {
+ className?: string
+ isVariable?: boolean
+ onIsVariableChange?: (isVariable: boolean) => void
+}
+
+const TypeSwitch: FC<Props> = ({
+ className,
+ isVariable,
+ onIsVariableChange,
+}) => {
+ const { t } = useTranslation()
+ return (
+ <div className={cn('inline-flex h-6 cursor-pointer select-none items-center space-x-1 rounded-md pl-1.5 pr-2 text-text-tertiary hover:bg-components-button-ghost-bg-hover', className)} onClick={() => onIsVariableChange?.(!isVariable)}>
+ <Variable02 className="size-3.5" />
+ <div className="system-xs-medium">{t(`nodes.humanInput.insertInputField.${isVariable ? 'useConstantInstead' : 'useVarInstead'}`, { ns: 'workflow' })}</div>
+ </div>
+ )
+}
+export default React.memo(TypeSwitch)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/variable-block.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/variable-block.tsx
new file mode 100644
index 00000000000..b1374b994f3
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/variable-block.tsx
@@ -0,0 +1,148 @@
+import type { WorkflowNodesMap } from '../workflow-variable-block/node'
+import type { ValueSelector, Var } from '@/app/components/workflow/types'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { mergeRegister } from '@lexical/utils'
+import {
+ COMMAND_PRIORITY_EDITOR,
+} from 'lexical'
+import {
+ memo,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/app/components/base/tooltip'
+import {
+ isConversationVar,
+ isENV,
+ isGlobalVar,
+ isRagVariableVar,
+ isSystemVar,
+} from '@/app/components/workflow/nodes/_base/components/variable/utils'
+import VarFullPathPanel from '@/app/components/workflow/nodes/_base/components/variable/var-full-path-panel'
+import {
+ VariableLabelInEditor,
+} from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
+import { Type } from '@/app/components/workflow/nodes/llm/types'
+import { isExceptionVariable } from '@/app/components/workflow/utils'
+import { UPDATE_WORKFLOW_NODES_MAP } from '../workflow-variable-block'
+import { HITLInputNode } from './node'
+
+type HITLInputVariableBlockComponentProps = {
+ variables: string[]
+ workflowNodesMap: WorkflowNodesMap
+ environmentVariables?: Var[]
+ conversationVariables?: Var[]
+ ragVariables?: Var[]
+ getVarType?: (payload: {
+ nodeId: string
+ valueSelector: ValueSelector
+ }) => Type
+}
+
+const HITLInputVariableBlockComponent = ({
+ variables,
+ workflowNodesMap = {},
+ getVarType,
+ environmentVariables,
+ conversationVariables,
+ ragVariables,
+}: HITLInputVariableBlockComponentProps) => {
+ const { t } = useTranslation()
+ const [editor] = useLexicalComposerContext()
+ const variablesLength = variables.length
+ const isRagVar = isRagVariableVar(variables)
+ const isShowAPart = variablesLength > 2 && !isRagVar
+ const varName = (
+ () => {
+ const isSystem = isSystemVar(variables)
+ const varName = variables[variablesLength - 1]
+ return `${isSystem ? 'sys.' : ''}${varName}`
+ }
+ )()
+ const [localWorkflowNodesMap, setLocalWorkflowNodesMap] = useState<WorkflowNodesMap>(workflowNodesMap)
+ const node = localWorkflowNodesMap![variables[isRagVar ? 1 : 0]]
+
+ const isException = isExceptionVariable(varName, node?.type)
+ const variableValid = useMemo(() => {
+ let variableValid = true
+ const isEnv = isENV(variables)
+ const isChatVar = isConversationVar(variables)
+ const isGlobal = isGlobalVar(variables)
+ if (isGlobal)
+ return true
+
+ if (isEnv) {
+ if (environmentVariables)
+ variableValid = environmentVariables.some(v => v.variable === `${variables?.[0] ?? ''}.${variables?.[1] ?? ''}`)
+ }
+ else if (isChatVar) {
+ if (conversationVariables)
+ variableValid = conversationVariables.some(v => v.variable === `${variables?.[0] ?? ''}.${variables?.[1] ?? ''}`)
+ }
+ else if (isRagVar) {
+ if (ragVariables)
+ variableValid = ragVariables.some(v => v.variable === `${variables?.[0] ?? ''}.${variables?.[1] ?? ''}.${variables?.[2] ?? ''}`)
+ }
+ else {
+ variableValid = !!node
+ }
+ return variableValid
+ }, [variables, node, environmentVariables, conversationVariables, isRagVar, ragVariables])
+
+ useEffect(() => {
+ if (!editor.hasNodes([HITLInputNode]))
+ throw new Error('HITLInputNodePlugin: HITLInputNode not registered on editor')
+
+ return mergeRegister(
+ editor.registerCommand(
+ UPDATE_WORKFLOW_NODES_MAP,
+ (workflowNodesMap: WorkflowNodesMap) => {
+ setLocalWorkflowNodesMap(workflowNodesMap)
+
+ return true
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
+ )
+ }, [editor])
+
+ const Item = (
+ <VariableLabelInEditor
+ nodeType={node?.type}
+ nodeTitle={node?.title}
+ variables={variables}
+ isExceptionVariable={isException}
+ errorMsg={!variableValid ? t('errorMsg.invalidVariable', { ns: 'workflow' }) : undefined}
+ notShowFullPath={isShowAPart}
+ />
+ )
+
+ if (!node)
+ return Item
+
+ return (
+ <Tooltip
+ noDecoration
+ popupContent={(
+ <VarFullPathPanel
+ nodeName={node.title}
+ path={variables.slice(1)}
+ varType={getVarType
+ ? getVarType({
+ nodeId: variables[0],
+ valueSelector: variables,
+ })
+ : Type.string}
+ nodeType={node?.type}
+ />
+ )}
+ disabled={!isShowAPart}
+ >
+ <div>{Item}</div>
+ </Tooltip>
+ )
+}
+
+export default memo(HITLInputVariableBlockComponent)
diff --git a/web/app/components/base/prompt-editor/plugins/request-url-block/component.tsx b/web/app/components/base/prompt-editor/plugins/request-url-block/component.tsx
new file mode 100644
index 00000000000..80b5ef94da3
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/request-url-block/component.tsx
@@ -0,0 +1,33 @@
+import type { FC } from 'react'
+import { RiGlobalLine } from '@remixicon/react'
+import { useTranslation } from 'react-i18next'
+
+import { cn } from '@/utils/classnames'
+import { useSelectOrDelete } from '../../hooks'
+import { DELETE_REQUEST_URL_BLOCK_COMMAND } from './index'
+
+type RequestURLBlockComponentProps = {
+ nodeKey: string
+}
+
+const RequestURLBlockComponent: FC<RequestURLBlockComponentProps> = ({
+ nodeKey,
+}) => {
+ const { t } = useTranslation()
+ const [ref, isSelected] = useSelectOrDelete(nodeKey, DELETE_REQUEST_URL_BLOCK_COMMAND)
+
+ return (
+ <div
+ className={cn(
+ 'group/wrap relative mx-0.5 flex h-[18px] select-none items-center rounded-[5px] border border-components-panel-border-subtle bg-components-badge-white-to-dark px-1 hover:border-[#7839ee]',
+ isSelected && '!border-[#7839ee] hover:!border-[#7839ee]',
+ )}
+ ref={ref}
+ >
+ <RiGlobalLine className="mr-0.5 h-3.5 w-3.5 text-util-colors-violet-violet-600" />
+ <div className="system-xs-medium text-util-colors-violet-violet-600">{t('promptEditor.requestURL.item.title', { ns: 'common' })}</div>
+ </div>
+ )
+}
+
+export default RequestURLBlockComponent
diff --git a/web/app/components/base/prompt-editor/plugins/request-url-block/index.tsx b/web/app/components/base/prompt-editor/plugins/request-url-block/index.tsx
new file mode 100644
index 00000000000..8f41f449b62
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/request-url-block/index.tsx
@@ -0,0 +1,64 @@
+import type { RequestURLBlockType } from '../../types'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { mergeRegister } from '@lexical/utils'
+import {
+ $insertNodes,
+ COMMAND_PRIORITY_EDITOR,
+ createCommand,
+} from 'lexical'
+import {
+ memo,
+ useEffect,
+} from 'react'
+import {
+ $createRequestURLBlockNode,
+ RequestURLBlockNode,
+} from './node'
+
+export const INSERT_REQUEST_URL_BLOCK_COMMAND = createCommand('INSERT_REQUEST_URL_BLOCK_COMMAND')
+export const DELETE_REQUEST_URL_BLOCK_COMMAND = createCommand('DELETE_REQUEST_URL_BLOCK_COMMAND')
+
+const RequestURLBlock = memo(({
+ onInsert,
+ onDelete,
+}: RequestURLBlockType) => {
+ const [editor] = useLexicalComposerContext()
+
+ useEffect(() => {
+ if (!editor.hasNodes([RequestURLBlockNode]))
+ throw new Error('RequestURLBlockPlugin: RequestURLBlock not registered on editor')
+
+ return mergeRegister(
+ editor.registerCommand(
+ INSERT_REQUEST_URL_BLOCK_COMMAND,
+ () => {
+ const contextBlockNode = $createRequestURLBlockNode()
+
+ $insertNodes([contextBlockNode])
+ if (onInsert)
+ onInsert()
+
+ return true
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
+ editor.registerCommand(
+ DELETE_REQUEST_URL_BLOCK_COMMAND,
+ () => {
+ if (onDelete)
+ onDelete()
+
+ return true
+ },
+ COMMAND_PRIORITY_EDITOR,
+ ),
+ )
+ }, [editor, onInsert, onDelete])
+
+ return null
+})
+RequestURLBlock.displayName = 'RequestURLBlock'
+
+export { RequestURLBlock }
+export { RequestURLBlockNode } from './node'
+export { default as RequestURLBlockReplacementBlock } from './request-url-block-replacement-block'
diff --git a/web/app/components/base/prompt-editor/plugins/request-url-block/node.tsx b/web/app/components/base/prompt-editor/plugins/request-url-block/node.tsx
new file mode 100644
index 00000000000..b1e74aa3a6d
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/request-url-block/node.tsx
@@ -0,0 +1,59 @@
+import type { LexicalNode, SerializedLexicalNode } from 'lexical'
+import { DecoratorNode } from 'lexical'
+import RequestURLBlockComponent from './component'
+
+export type SerializedNode = SerializedLexicalNode
+
+export class RequestURLBlockNode extends DecoratorNode<React.JSX.Element> {
+ static getType(): string {
+ return 'request-url-block'
+ }
+
+ static clone(node: RequestURLBlockNode): RequestURLBlockNode {
+ return new RequestURLBlockNode(node.__key)
+ }
+
+ isInline(): boolean {
+ return true
+ }
+
+ createDOM(): HTMLElement {
+ const div = document.createElement('div')
+ div.classList.add('inline-flex', 'items-center', 'align-middle')
+ return div
+ }
+
+ updateDOM(): false {
+ return false
+ }
+
+ decorate(): React.JSX.Element {
+ return <RequestURLBlockComponent nodeKey={this.getKey()} />
+ }
+
+ static importJSON(): RequestURLBlockNode {
+ const node = $createRequestURLBlockNode()
+
+ return node
+ }
+
+ exportJSON(): SerializedNode {
+ return {
+ type: 'request-url-block',
+ version: 1,
+ }
+ }
+
+ getTextContent(): string {
+ return '{{#url#}}'
+ }
+}
+export function $createRequestURLBlockNode(): RequestURLBlockNode {
+ return new RequestURLBlockNode()
+}
+
+export function $isRequestURLBlockNode(
+ node: RequestURLBlockNode | LexicalNode | null | undefined,
+): node is RequestURLBlockNode {
+ return node instanceof RequestURLBlockNode
+}
diff --git a/web/app/components/base/prompt-editor/plugins/request-url-block/request-url-block-replacement-block.tsx b/web/app/components/base/prompt-editor/plugins/request-url-block/request-url-block-replacement-block.tsx
new file mode 100644
index 00000000000..7cac5d0e190
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/request-url-block/request-url-block-replacement-block.tsx
@@ -0,0 +1,60 @@
+import type { RequestURLBlockType } from '../../types'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { mergeRegister } from '@lexical/utils'
+import { $applyNodeReplacement } from 'lexical'
+import {
+ memo,
+ useCallback,
+ useEffect,
+} from 'react'
+import { REQUEST_URL_PLACEHOLDER_TEXT } from '../../constants'
+import { decoratorTransform } from '../../utils'
+import { CustomTextNode } from '../custom-text/node'
+import {
+ $createRequestURLBlockNode,
+ RequestURLBlockNode,
+} from '../request-url-block/node'
+
+const REGEX = new RegExp(REQUEST_URL_PLACEHOLDER_TEXT)
+
+const RequestURLBlockReplacementBlock = ({
+ onInsert,
+}: RequestURLBlockType) => {
+ const [editor] = useLexicalComposerContext()
+
+ useEffect(() => {
+ if (!editor.hasNodes([RequestURLBlockNode]))
+ throw new Error('RequestURLBlockNodePlugin: RequestURLBlockNode not registered on editor')
+ }, [editor])
+
+ const createRequestURLBlockNode = useCallback((): RequestURLBlockNode => {
+ if (onInsert)
+ onInsert()
+ return $applyNodeReplacement($createRequestURLBlockNode())
+ }, [onInsert])
+
+ const getMatch = useCallback((text: string) => {
+ const matchArr = REGEX.exec(text)
+
+ if (matchArr === null)
+ return null
+
+ const startOffset = matchArr.index
+ const endOffset = startOffset + REQUEST_URL_PLACEHOLDER_TEXT.length
+ return {
+ end: endOffset,
+ start: startOffset,
+ }
+ }, [])
+
+ useEffect(() => {
+ REGEX.lastIndex = 0
+ return mergeRegister(
+ editor.registerNodeTransform(CustomTextNode, textNode => decoratorTransform(textNode, getMatch, createRequestURLBlockNode)),
+ )
+ }, [])
+
+ return null
+}
+
+export default memo(RequestURLBlockReplacementBlock)
diff --git a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.spec.tsx b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.spec.tsx
new file mode 100644
index 00000000000..ad449701873
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.spec.tsx
@@ -0,0 +1,134 @@
+import { LexicalComposer } from '@lexical/react/LexicalComposer'
+import { ContentEditable } from '@lexical/react/LexicalContentEditable'
+import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'
+import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import * as React from 'react'
+import { useState } from 'react'
+import ShortcutsPopupPlugin, { SHORTCUTS_EMPTY_CONTENT } from './index'
+import '@testing-library/jest-dom'
+
+// Mock Range.getClientRects and getBoundingClientRect for JSDOM
+const mockDOMRect = {
+ x: 100,
+ y: 100,
+ width: 100,
+ height: 20,
+ top: 100,
+ right: 200,
+ bottom: 120,
+ left: 100,
+ toJSON: () => ({}),
+}
+
+beforeAll(() => {
+ // Mock getClientRects on Range prototype
+ Range.prototype.getClientRects = vi.fn(() => {
+ const rectList = [mockDOMRect] as unknown as DOMRectList
+ Object.defineProperty(rectList, 'length', { value: 1 })
+ Object.defineProperty(rectList, 'item', { value: (index: number) => index === 0 ? mockDOMRect : null })
+ return rectList
+ })
+
+ // Mock getBoundingClientRect on Range prototype
+ Range.prototype.getBoundingClientRect = vi.fn(() => mockDOMRect as DOMRect)
+})
+
+const CONTAINER_ID = 'host'
+const CONTENT_EDITABLE_ID = 'ce'
+
+const MinimalEditor: React.FC<{
+ withContainer?: boolean
+}> = ({ withContainer = true }) => {
+ const initialConfig = {
+ namespace: 'shortcuts-popup-plugin-test',
+ onError: (e: Error) => {
+ throw e
+ },
+ }
+ const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null)
+
+ return (
+ <LexicalComposer initialConfig={initialConfig}>
+ <div data-testid={CONTAINER_ID} className="relative" ref={withContainer ? setContainerEl : undefined}>
+ <RichTextPlugin
+ contentEditable={<ContentEditable data-testid={CONTENT_EDITABLE_ID} />}
+ placeholder={null}
+ ErrorBoundary={LexicalErrorBoundary}
+ />
+ <ShortcutsPopupPlugin
+ container={withContainer ? containerEl : undefined}
+ />
+ </div>
+ </LexicalComposer>
+ )
+}
+
+describe('ShortcutsPopupPlugin', () => {
+ it('opens on hotkey when editor is focused', async () => {
+ render(<MinimalEditor />)
+ const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
+ ce.focus()
+
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true }) // 模拟 Ctrl+/
+ expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
+ })
+
+ it('does not open when editor is not focused', async () => {
+ render(<MinimalEditor />)
+ // 未聚焦
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ await waitFor(() => {
+ expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
+ })
+ })
+
+ it('closes on Escape', async () => {
+ render(<MinimalEditor />)
+ const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
+ ce.focus()
+
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
+
+ fireEvent.keyDown(document, { key: 'Escape' })
+ await waitFor(() => {
+ expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
+ })
+ })
+
+ it('closes on click outside', async () => {
+ render(<MinimalEditor />)
+ const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
+ ce.focus()
+
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
+
+ fireEvent.mouseDown(ce)
+ await waitFor(() => {
+ expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
+ })
+ })
+
+ it('portals into provided container when container is set', async () => {
+ render(<MinimalEditor withContainer />)
+ const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
+ const host = screen.getByTestId(CONTAINER_ID)
+ ce.focus()
+
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ const portalContent = await screen.findByText(SHORTCUTS_EMPTY_CONTENT)
+ expect(host).toContainElement(portalContent)
+ })
+
+ it('falls back to document.body when container is not provided', async () => {
+ render(<MinimalEditor withContainer={false} />)
+ const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
+ ce.focus()
+
+ fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ const portalContent = await screen.findByText(SHORTCUTS_EMPTY_CONTENT)
+ expect(document.body).toContainElement(portalContent)
+ })
+})
diff --git a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
new file mode 100644
index 00000000000..bf559193ec2
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
@@ -0,0 +1,305 @@
+import type { LexicalCommand } from 'lexical'
+import {
+ autoUpdate,
+ flip,
+ offset,
+ shift,
+ size,
+ useFloating,
+} from '@floating-ui/react'
+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import {
+ $getSelection,
+ $isRangeSelection,
+} from 'lexical'
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
+import { createPortal } from 'react-dom'
+import { cn } from '@/utils/classnames'
+
+export const SHORTCUTS_EMPTY_CONTENT = 'shortcuts_empty_content'
+
+// Hotkey can be:
+// - string: 'mod+/'
+// - string[]: ['mod', '/']
+// - string[][]: [['mod', '/'], ['mod', 'shift', '/']] (any combo matches)
+// - function: custom matcher
+export type Hotkey = string | string[] | string[][] | ((e: KeyboardEvent) => boolean)
+
+type ShortcutPopupPluginProps = {
+ hotkey?: Hotkey
+ children?: React.ReactNode | ((close: () => void, onInsert: (command: LexicalCommand<unknown>, params: any[]) => void) => React.ReactNode)
+ className?: string
+ container?: Element | null
+ onOpen?: () => void
+ onClose?: () => void
+}
+
+const META_ALIASES = new Set(['meta', 'cmd', 'command'])
+const CTRL_ALIASES = new Set(['ctrl'])
+const ALT_ALIASES = new Set(['alt', 'option'])
+const SHIFT_ALIASES = new Set(['shift'])
+
+function matchHotkey(event: KeyboardEvent, hotkey?: Hotkey) {
+ if (!hotkey)
+ return false
+
+ if (typeof hotkey === 'function')
+ return hotkey(event)
+
+ const matchCombo = (tokens: string[]) => {
+ const parts = tokens.map(t => t.toLowerCase().trim()).filter(Boolean)
+ let expectedKey: string | null = null
+
+ let needMod = false
+ let needCtrl = false
+ let needMeta = false
+ let needAlt = false
+ let needShift = false
+
+ for (const p of parts) {
+ if (p === 'mod') {
+ needMod = true
+ continue
+ }
+ if (CTRL_ALIASES.has(p)) {
+ needCtrl = true
+ continue
+ }
+ if (META_ALIASES.has(p)) {
+ needMeta = true
+ continue
+ }
+ if (ALT_ALIASES.has(p)) {
+ needAlt = true
+ continue
+ }
+ if (SHIFT_ALIASES.has(p)) {
+ needShift = true
+ continue
+ }
+ expectedKey = p
+ }
+
+ if (needMod && !(event.metaKey || event.ctrlKey))
+ return false
+ if (needCtrl && !event.ctrlKey)
+ return false
+ if (needMeta && !event.metaKey)
+ return false
+ if (needAlt && !event.altKey)
+ return false
+ if (needShift && !event.shiftKey)
+ return false
+
+ if (expectedKey) {
+ const k = event.key.toLowerCase()
+ const normalized = k === ' ' ? 'space' : k
+ if (normalized !== expectedKey)
+ return false
+ }
+
+ return true
+ }
+
+ if (Array.isArray(hotkey)) {
+ const isNested = hotkey.length > 0 && Array.isArray((hotkey as unknown[])[0])
+ if (isNested) {
+ const combos = hotkey as string[][]
+ return combos.some(tokens => matchCombo(tokens))
+ }
+ else {
+ const tokens = hotkey as string[]
+ return matchCombo(tokens)
+ }
+ }
+
+ const tokensFromString = hotkey
+ .toLowerCase()
+ .split('+')
+ .map(t => t.trim())
+ .filter(Boolean)
+ return matchCombo(tokensFromString)
+}
+
+export default function ShortcutsPopupPlugin({
+ hotkey = 'mod+/',
+ children,
+ className,
+ container,
+ onOpen,
+ onClose,
+}: ShortcutPopupPluginProps): React.ReactPortal | null {
+ const [editor] = useLexicalComposerContext()
+ const [open, setOpen] = useState(false)
+ const portalRef = useRef<HTMLDivElement | null>(null)
+ const lastSelectionRef = useRef<Range | null>(null)
+
+ const containerEl = useMemo(() => container ?? (typeof document !== 'undefined' ? document.body : null), [container])
+ const useContainer = !!containerEl && containerEl !== document.body
+
+ const { refs, floatingStyles, isPositioned } = useFloating({
+ placement: 'bottom-start',
+ middleware: [
+ offset(0), // fix hide cursor
+ shift({
+ padding: 8,
+ altBoundary: true,
+ }),
+ flip(),
+ size({
+ apply({ availableWidth, availableHeight, elements }) {
+ Object.assign(elements.floating.style, {
+ maxWidth: `${Math.min(400, availableWidth)}px`,
+ maxHeight: `${Math.min(300, availableHeight)}px`,
+ overflow: 'auto',
+ })
+ },
+ padding: 8,
+ }),
+ ],
+ whileElementsMounted: autoUpdate,
+ })
+
+ useEffect(() => {
+ return editor.registerUpdateListener(({ editorState }) => {
+ editorState.read(() => {
+ const selection = $getSelection()
+ if ($isRangeSelection(selection)) {
+ const domSelection = window.getSelection()
+ if (domSelection && domSelection.rangeCount > 0)
+ lastSelectionRef.current = domSelection.getRangeAt(0).cloneRange()
+ }
+ })
+ })
+ }, [editor])
+
+ const isEditorFocused = useCallback(() => {
+ const root = editor.getRootElement()
+ if (!root)
+ return false
+ return root.contains(document.activeElement)
+ }, [editor])
+
+ const openPortal = useCallback(() => {
+ const domSelection = window.getSelection()
+ let range: Range | null = null
+ if (domSelection && domSelection.rangeCount > 0)
+ range = domSelection.getRangeAt(0).cloneRange()
+ else
+ range = lastSelectionRef.current
+
+ if (range) {
+ const rects = range.getClientRects()
+ let rect: DOMRect | null = null
+
+ if (rects && rects.length)
+ rect = rects[rects.length - 1]
+
+ else
+ rect = range.getBoundingClientRect()
+
+ if (rect.width === 0 && rect.height === 0) {
+ const root = editor.getRootElement()
+ if (root) {
+ const sc = range.startContainer
+ const node = sc.nodeType === Node.ELEMENT_NODE
+ ? sc as Element
+ : (sc.parentElement || root)
+
+ rect = node.getBoundingClientRect()
+
+ if (rect.width === 0 && rect.height === 0)
+ rect = root.getBoundingClientRect()
+ }
+ }
+
+ if (rect && !(rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0)) {
+ const virtualEl = {
+ getBoundingClientRect() {
+ return rect!
+ },
+ }
+ refs.setReference(virtualEl as Element)
+ }
+ }
+
+ setOpen(true)
+ onOpen?.()
+ }, [onOpen])
+
+ const closePortal = useCallback(() => {
+ setOpen(false)
+ onClose?.()
+ }, [onClose])
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (open && event.key === 'Escape') {
+ event.stopPropagation()
+ event.preventDefault()
+ closePortal()
+ return
+ }
+
+ if (!isEditorFocused())
+ return
+
+ if (matchHotkey(event, hotkey)) {
+ event.preventDefault()
+ openPortal()
+ }
+ }
+
+ document.addEventListener('keydown', handleKeyDown, true)
+ return () => document.removeEventListener('keydown', handleKeyDown, true)
+ }, [hotkey, open, isEditorFocused, openPortal, closePortal])
+
+ useEffect(() => {
+ if (!open)
+ return
+
+ const onMouseDown = (e: MouseEvent) => {
+ if (!portalRef.current)
+ return
+ if (!portalRef.current.contains(e.target as Node))
+ closePortal()
+ }
+ document.addEventListener('mousedown', onMouseDown, false)
+ return () => document.removeEventListener('mousedown', onMouseDown, false)
+ }, [open, closePortal])
+
+ const handleInsert = useCallback((command: LexicalCommand<unknown>, params: any) => {
+ editor.dispatchCommand(command, params)
+ closePortal()
+ }, [editor, closePortal])
+
+ if (!open || !containerEl)
+ return null
+
+ return createPortal(
+ <div
+ ref={(node) => {
+ portalRef.current = node
+ refs.setFloating(node)
+ }}
+ className={cn(
+ useContainer ? '' : 'z-[999999]',
+ 'absolute rounded-xl bg-components-panel-bg-blur shadow-lg',
+ className,
+ )}
+ style={{
+ ...floatingStyles,
+ visibility: isPositioned ? 'visible' : 'hidden',
+ }}
+ >
+ {typeof children === 'function' ? children(closePortal, handleInsert) : (children ?? SHORTCUTS_EMPTY_CONTENT)}
+ </div>,
+ containerEl,
+ )
+}
diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx
index 615fa837e1e..573c97f4650 100644
--- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx
+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/workflow-variable-block-replacement-block.tsx
@@ -40,7 +40,7 @@ const WorkflowVariableBlockReplacementBlock = ({
const nodePathString = textNode.getTextContent().slice(3, -3)
return $applyNodeReplacement($createWorkflowVariableBlockNode(nodePathString.split('.'), workflowNodesMap, getVarType, variables?.find(o => o.nodeId === 'env')?.vars || [], variables?.find(o => o.nodeId === 'conversation')?.vars || [], ragVariables))
- }, [onInsert, workflowNodesMap, getVarType, variables])
+ }, [onInsert, workflowNodesMap, getVarType, variables, ragVariables])
const getMatch = useCallback((text: string) => {
const matchArr = REGEX.exec(text)
diff --git a/web/app/components/base/prompt-editor/types.ts b/web/app/components/base/prompt-editor/types.ts
index 875f9eab076..99221ffebdb 100644
--- a/web/app/components/base/prompt-editor/types.ts
+++ b/web/app/components/base/prompt-editor/types.ts
@@ -1,4 +1,5 @@
import type { GeneratorType } from '../../app/configuration/config/automatic/types'
+import type { FormInputItem } from '../../workflow/nodes/human-input/types'
import type { Type } from '../../workflow/nodes/llm/types'
import type { Dataset } from './plugins/context-block'
import type { RoleName } from './plugins/history-block'
@@ -46,6 +47,13 @@ export type HistoryBlockType = {
onEditRole?: () => void
}
+export type RequestURLBlockType = {
+ show?: boolean
+ selectable?: boolean
+ onInsert?: () => void
+ onDelete?: () => void
+}
+
export type VariableBlockType = {
show?: boolean
variables?: Option[]
@@ -73,6 +81,21 @@ export type WorkflowVariableBlockType = {
onManageInputField?: () => void
}
+export type HITLInputBlockType = {
+ show?: boolean
+ nodeId: string
+ formInputs?: FormInputItem[]
+ variables?: NodeOutPutVar[]
+ workflowNodesMap?: Record<string, Pick<Node['data'], 'title' | 'type' | 'height' | 'width' | 'position'>>
+ getVarType?: GetVarType
+ onFormInputsChange?: (inputs: FormInputItem[]) => void
+ onFormInputItemRemove: (varName: string) => void
+ onFormInputItemRename: (payload: FormInputItem, oldName: string) => void
+ onInsert?: () => void
+ onDelete?: () => void
+ readonly?: boolean
+}
+
export type MenuTextMatch = {
leadOffset: number
matchingString: string
diff --git a/web/app/components/billing/plan/index.spec.tsx b/web/app/components/billing/plan/index.spec.tsx
index fb1800653e8..db22b47db4a 100644
--- a/web/app/components/billing/plan/index.spec.tsx
+++ b/web/app/components/billing/plan/index.spec.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { EDUCATION_VERIFYING_LOCALSTORAGE_ITEM } from '@/app/education-apply/constants'
import { Plan } from '../type'
import PlanComp from './index'
@@ -188,7 +188,9 @@ describe('PlanComp', () => {
expect(lastCall.onCancel).toBeDefined()
// Call onConfirm to close modal
- lastCall.onConfirm()
- lastCall.onCancel()
+ act(() => {
+ lastCall.onConfirm()
+ lastCall.onCancel()
+ })
})
})
diff --git a/web/app/components/billing/type.ts b/web/app/components/billing/type.ts
index 1522de63b28..e3eb8b67996 100644
--- a/web/app/components/billing/type.ts
+++ b/web/app/components/billing/type.ts
@@ -118,6 +118,7 @@ export type CurrentPlanInfoBackend = {
knowledge_pipeline: {
publish_enabled: boolean
}
+ human_input_email_delivery_enabled: boolean
}
export type SubscriptionItem = {
diff --git a/web/app/components/billing/utils/index.spec.ts b/web/app/components/billing/utils/index.spec.ts
index 03a159c18a8..d85155d6ff1 100644
--- a/web/app/components/billing/utils/index.spec.ts
+++ b/web/app/components/billing/utils/index.spec.ts
@@ -94,6 +94,7 @@ describe('billing utils', () => {
knowledge_pipeline: {
publish_enabled: false,
},
+ human_input_email_delivery_enabled: false,
...overrides,
})
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/common-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/common-modal.spec.tsx
index 543d3deebc1..35539a2144c 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/common-modal.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/common-modal.spec.tsx
@@ -1247,6 +1247,10 @@ describe('CommonCreateModal', () => {
const input = screen.getByTestId('form-field-webhook_url')
fireEvent.change(input, { target: { value: 'https://example.com/webhook' } })
+ await waitFor(() => {
+ expect(mockUpdateBuilder).toHaveBeenCalled()
+ })
+
await waitFor(() => {
expect(mockToastNotify).toHaveBeenCalledWith({
type: 'error',
diff --git a/web/app/components/rag-pipeline/components/index.spec.tsx b/web/app/components/rag-pipeline/components/index.spec.tsx
index 827fe124a75..e17f07303d9 100644
--- a/web/app/components/rag-pipeline/components/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/index.spec.tsx
@@ -295,6 +295,8 @@ vi.mock('@/utils/var', () => ({
// Mock provider context
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => createMockProviderContextValue(),
+ useProviderContextSelector: <T,>(selector: (state: ReturnType<typeof createMockProviderContextValue>) => T): T =>
+ selector(createMockProviderContextValue()),
}))
// Mock WorkflowWithInnerContext
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx
index 1a7a7422c15..4f3465a9205 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/index.spec.tsx
@@ -141,6 +141,8 @@ vi.mock('@/context/modal-context', () => ({
let mockProviderContextValue = createMockProviderContextValue()
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => mockProviderContextValue,
+ useProviderContextSelector: <T,>(selector: (s: ReturnType<typeof createMockProviderContextValue>) => T): T =>
+ selector(mockProviderContextValue),
}))
// Mock event emitter context
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx
index 86cd15db974..2a01218ee65 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.spec.tsx
@@ -131,6 +131,8 @@ vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
isAllowPublishAsCustomKnowledgePipelineTemplate: mockIsAllowPublishAsCustomKnowledgePipelineTemplate(),
}),
+ useProviderContextSelector: <T,>(selector: (s: { isAllowPublishAsCustomKnowledgePipelineTemplate: boolean }) => T): T =>
+ selector({ isAllowPublishAsCustomKnowledgePipelineTemplate: mockIsAllowPublishAsCustomKnowledgePipelineTemplate() }),
}))
// Mock toast context
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
index c66b293d8a8..2dd56b4277b 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
@@ -37,7 +37,7 @@ import { getKeyboardKeyCodeBySystem } from '@/app/components/workflow/utils'
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
import { useDocLink } from '@/context/i18n'
import { useModalContextSelector } from '@/context/modal-context'
-import { useProviderContext } from '@/context/provider-context'
+import { useProviderContextSelector } from '@/context/provider-context'
import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'
@@ -68,7 +68,7 @@ const Popup = () => {
const { mutateAsync: publishWorkflow } = usePublishWorkflow()
const { notify } = useToastContext()
const workflowStore = useWorkflowStore()
- const { isAllowPublishAsCustomKnowledgePipelineTemplate } = useProviderContext()
+ const isAllowPublishAsCustomKnowledgePipelineTemplate = useProviderContextSelector(s => s.isAllowPublishAsCustomKnowledgePipelineTemplate)
const setShowPricingModal = useModalContextSelector(s => s.setShowPricingModal)
const apiReferenceUrl = useDatasetApiAccessUrl()
@@ -152,7 +152,7 @@ const Popup = () => {
if (confirmVisible)
hideConfirm()
}
- }, [handleCheckBeforePublish, publishWorkflow, pipelineId, notify, t, workflowStore, mutateDatasetRes, invalidPublishedPipelineInfo, showConfirm, publishedAt, confirmVisible, hidePublishing, showPublishing, hideConfirm, publishing])
+ }, [publishing, handleCheckBeforePublish, publishedAt, confirmVisible, showPublishing, publishWorkflow, pipelineId, datasetId, showConfirm, notify, t, workflowStore, mutateDatasetRes, invalidPublishedPipelineInfo, invalidDatasetList, hidePublishing, hideConfirm])
useKeyPress(`${getKeyboardKeyCodeBySystem('ctrl')}.shift.p`, (e) => {
e.preventDefault()
@@ -207,15 +207,7 @@ const Popup = () => {
hidePublishingAsCustomizedPipeline()
hidePublishAsKnowledgePipelineModal()
}
- }, [
- pipelineId,
- publishAsCustomizedPipeline,
- showPublishingAsCustomizedPipeline,
- hidePublishingAsCustomizedPipeline,
- hidePublishAsKnowledgePipelineModal,
- notify,
- t,
- ])
+ }, [showPublishingAsCustomizedPipeline, publishAsCustomizedPipeline, pipelineId, notify, t, invalidCustomizedTemplateList, hidePublishingAsCustomizedPipeline, hidePublishAsKnowledgePipelineModal])
const handleClickPublishAsKnowledgePipeline = useCallback(() => {
if (!isAllowPublishAsCustomKnowledgePipelineTemplate)
diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.spec.ts b/web/app/components/rag-pipeline/hooks/use-DSL.spec.ts
index 0f235516e0a..1b258058db4 100644
--- a/web/app/components/rag-pipeline/hooks/use-DSL.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/use-DSL.spec.ts
@@ -67,6 +67,12 @@ vi.mock('@/service/workflow', () => ({
fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),
}))
+// Mock download utility
+const mockDownloadBlob = vi.fn()
+vi.mock('@/utils/download', () => ({
+ downloadBlob: (options: { data: Blob, fileName: string }) => mockDownloadBlob(options),
+}))
+
// Mock workflow constants
vi.mock('@/app/components/workflow/constants', () => ({
DSL_EXPORT_CHECK: 'DSL_EXPORT_CHECK',
@@ -77,33 +83,9 @@ vi.mock('@/app/components/workflow/constants', () => ({
// ============================================================================
describe('useDSL', () => {
- let mockLink: { href: string, download: string, click: ReturnType<typeof vi.fn> }
- let originalCreateElement: typeof document.createElement
- let mockCreateObjectURL: ReturnType<typeof vi.spyOn>
- let mockRevokeObjectURL: ReturnType<typeof vi.spyOn>
-
beforeEach(() => {
vi.clearAllMocks()
- // Create a proper mock link element
- mockLink = {
- href: '',
- download: '',
- click: vi.fn(),
- }
-
- // Save original and mock selectively - only intercept 'a' elements
- originalCreateElement = document.createElement.bind(document)
- document.createElement = vi.fn((tagName: string) => {
- if (tagName === 'a') {
- return mockLink as unknown as HTMLElement
- }
- return originalCreateElement(tagName)
- }) as typeof document.createElement
-
- mockCreateObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:test-url')
- mockRevokeObjectURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
-
// Default store state
mockWorkflowStoreGetState.mockReturnValue({
pipelineId: 'test-pipeline-id',
@@ -118,9 +100,6 @@ describe('useDSL', () => {
})
afterEach(() => {
- document.createElement = originalCreateElement
- mockCreateObjectURL.mockRestore()
- mockRevokeObjectURL.mockRestore()
vi.clearAllMocks()
})
@@ -187,9 +166,10 @@ describe('useDSL', () => {
await result.current.handleExportDSL()
})
- expect(document.createElement).toHaveBeenCalledWith('a')
- expect(mockCreateObjectURL).toHaveBeenCalled()
- expect(mockRevokeObjectURL).toHaveBeenCalledWith('blob:test-url')
+ expect(mockDownloadBlob).toHaveBeenCalled()
+ const callArg = mockDownloadBlob.mock.calls[0][0]
+ expect(callArg.data).toBeInstanceOf(Blob)
+ expect(callArg.fileName).toBe('Test Knowledge Base.pipeline')
})
it('should use correct file extension for download', async () => {
@@ -199,17 +179,23 @@ describe('useDSL', () => {
await result.current.handleExportDSL()
})
- expect(mockLink.download).toBe('Test Knowledge Base.pipeline')
+ expect(mockDownloadBlob).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fileName: 'Test Knowledge Base.pipeline',
+ }),
+ )
})
- it('should trigger download click', async () => {
+ it('should trigger download with yaml blob', async () => {
const { result } = renderHook(() => useDSL())
await act(async () => {
await result.current.handleExportDSL()
})
- expect(mockLink.click).toHaveBeenCalled()
+ expect(mockDownloadBlob).toHaveBeenCalled()
+ const callArg = mockDownloadBlob.mock.calls[0][0]
+ expect(callArg.data.type).toBe('application/yaml')
})
it('should show error notification on export failure', async () => {
diff --git a/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts b/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts
index 3720ef388b1..eaadf471062 100644
--- a/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts
+++ b/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts
@@ -13,7 +13,8 @@ export const useAvailableNodesMetaData = () => {
const docLink = useDocLink()
const mergedNodesMetaData = useMemo(() => [
- ...WORKFLOW_COMMON_NODES,
+ // RAG pipeline doesn't support human-input node temporarily
+ ...WORKFLOW_COMMON_NODES.filter(node => node.metaData.type !== BlockEnum.HumanInput),
{
...dataSourceDefault,
defaultValue: {
@@ -47,7 +48,7 @@ export const useAvailableNodesMetaData = () => {
title,
},
}
- }), [mergedNodesMetaData, t])
+ }), [helpLinkUri, mergedNodesMetaData, t])
const availableNodesMetaDataMap = useMemo(() => availableNodesMetaData.reduce((acc, node) => {
acc![node.metaData.type] = node
diff --git a/web/app/components/rag-pipeline/hooks/use-configs-map.ts b/web/app/components/rag-pipeline/hooks/use-configs-map.ts
index aa76dbf6ca3..99c42923495 100644
--- a/web/app/components/rag-pipeline/hooks/use-configs-map.ts
+++ b/web/app/components/rag-pipeline/hooks/use-configs-map.ts
@@ -20,5 +20,5 @@ export const useConfigsMap = () => {
fileUploadConfig,
},
}
- }, [pipelineId])
+ }, [fileUploadConfig, pipelineId])
}
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
index 1f53262482d..dc2a234d1e3 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
@@ -1,7 +1,7 @@
import type { IOtherOptions } from '@/service/base'
import type { VersionHistory } from '@/types/workflow'
import { produce } from 'immer'
-import { useCallback } from 'react'
+import { useCallback, useRef } from 'react'
import {
useReactFlow,
useStoreApi,
@@ -42,6 +42,8 @@ export const usePipelineRun = () => {
handleWorkflowTextReplace,
} = useWorkflowRunEvent()
+ const abortControllerRef = useRef<AbortController | null>(null)
+
const handleBackupDraft = useCallback(() => {
const {
getNodes,
@@ -154,12 +156,18 @@ export const usePipelineRun = () => {
resultText: '',
})
+ abortControllerRef.current?.abort()
+ abortControllerRef.current = null
+
ssePost(
url,
{
body: params,
},
{
+ getAbortController: (controller: AbortController) => {
+ abortControllerRef.current = controller
+ },
onWorkflowStarted: (params) => {
handleWorkflowStarted(params)
@@ -267,31 +275,17 @@ export const usePipelineRun = () => {
...restCallback,
},
)
- }, [
- store,
- workflowStore,
- doSyncWorkflowDraft,
- handleWorkflowStarted,
- handleWorkflowFinished,
- handleWorkflowFailed,
- handleWorkflowNodeStarted,
- handleWorkflowNodeFinished,
- handleWorkflowNodeIterationStarted,
- handleWorkflowNodeIterationNext,
- handleWorkflowNodeIterationFinished,
- handleWorkflowNodeLoopStarted,
- handleWorkflowNodeLoopNext,
- handleWorkflowNodeLoopFinished,
- handleWorkflowNodeRetry,
- handleWorkflowTextChunk,
- handleWorkflowTextReplace,
- handleWorkflowAgentLog,
- ])
+ }, [store, doSyncWorkflowDraft, workflowStore, handleWorkflowStarted, handleWorkflowFinished, fetchInspectVars, invalidAllLastRun, handleWorkflowFailed, handleWorkflowNodeStarted, handleWorkflowNodeFinished, handleWorkflowNodeIterationStarted, handleWorkflowNodeIterationNext, handleWorkflowNodeIterationFinished, handleWorkflowNodeLoopStarted, handleWorkflowNodeLoopNext, handleWorkflowNodeLoopFinished, handleWorkflowNodeRetry, handleWorkflowAgentLog, handleWorkflowTextChunk, handleWorkflowTextReplace])
const handleStopRun = useCallback((taskId: string) => {
const { pipelineId } = workflowStore.getState()
stopWorkflowRun(`/rag/pipelines/${pipelineId}/workflow-runs/tasks/${taskId}/stop`)
+
+ if (abortControllerRef.current)
+ abortControllerRef.current.abort()
+
+ abortControllerRef.current = null
}, [workflowStore])
const handleRestoreFromPublishedWorkflow = useCallback((publishedWorkflow: VersionHistory) => {
diff --git a/web/app/components/share/text-generation/result/content.spec.tsx b/web/app/components/share/text-generation/result/content.spec.tsx
deleted file mode 100644
index 242ae7aa5f3..00000000000
--- a/web/app/components/share/text-generation/result/content.spec.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import type { FeedbackType } from '@/app/components/base/chat/chat/type'
-import { cleanup, render, screen } from '@testing-library/react'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import Result from './content'
-
-// Only mock react-i18next for translations
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}))
-
-// Mock copy-to-clipboard for the Header component
-vi.mock('copy-to-clipboard', () => ({
- default: vi.fn(() => true),
-}))
-
-// Mock the format function from service/base
-vi.mock('@/service/base', () => ({
- format: (content: string) => content.replace(/\n/g, '<br>'),
-}))
-
-afterEach(() => {
- cleanup()
-})
-
-describe('Result (content)', () => {
- const mockOnFeedback = vi.fn()
-
- const defaultProps = {
- content: 'Test content here',
- showFeedback: true,
- feedback: { rating: null } as FeedbackType,
- onFeedback: mockOnFeedback,
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- describe('rendering', () => {
- it('should render the Header component', () => {
- render(<Result {...defaultProps} />)
-
- // Header renders the result title
- expect(screen.getByText('generation.resultTitle')).toBeInTheDocument()
- })
-
- it('should render content', () => {
- render(<Result {...defaultProps} />)
-
- expect(screen.getByText('Test content here')).toBeInTheDocument()
- })
-
- it('should render formatted content with line breaks', () => {
- render(
- <Result
- {...defaultProps}
- content={'Line 1\nLine 2'}
- />,
- )
-
- // The format function converts \n to <br>
- const contentDiv = document.querySelector('[class*="overflow-scroll"]')
- expect(contentDiv?.innerHTML).toContain('Line 1<br>Line 2')
- })
-
- it('should have max height style', () => {
- render(<Result {...defaultProps} />)
-
- const contentDiv = document.querySelector('[class*="overflow-scroll"]')
- expect(contentDiv).toHaveStyle({ maxHeight: '70vh' })
- })
-
- it('should render with empty content', () => {
- render(
- <Result
- {...defaultProps}
- content=""
- />,
- )
-
- expect(screen.getByText('generation.resultTitle')).toBeInTheDocument()
- })
-
- it('should render with HTML content safely', () => {
- render(
- <Result
- {...defaultProps}
- content="<script>alert('xss')</script>"
- />,
- )
-
- // Content is rendered via dangerouslySetInnerHTML
- const contentDiv = document.querySelector('[class*="overflow-scroll"]')
- expect(contentDiv).toBeInTheDocument()
- })
- })
-
- describe('feedback props', () => {
- it('should pass showFeedback to Header', () => {
- render(
- <Result
- {...defaultProps}
- showFeedback={false}
- />,
- )
-
- // Feedback buttons should not be visible
- const feedbackArea = document.querySelector('[class*="space-x-1 rounded-lg border"]')
- expect(feedbackArea).not.toBeInTheDocument()
- })
-
- it('should pass feedback to Header', () => {
- render(
- <Result
- {...defaultProps}
- feedback={{ rating: 'like' }}
- />,
- )
-
- // Like button should be highlighted
- const likeButton = document.querySelector('[class*="primary"]')
- expect(likeButton).toBeInTheDocument()
- })
- })
-
- describe('memoization', () => {
- it('should be wrapped with React.memo', () => {
- expect((Result as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))
- })
- })
-})
diff --git a/web/app/components/share/text-generation/result/content.tsx b/web/app/components/share/text-generation/result/content.tsx
deleted file mode 100644
index 01161d6dcd0..00000000000
--- a/web/app/components/share/text-generation/result/content.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { FC } from 'react'
-import type { FeedbackType } from '@/app/components/base/chat/chat/type'
-import * as React from 'react'
-import { format } from '@/service/base'
-import Header from './header'
-
-export type IResultProps = {
- content: string
- showFeedback: boolean
- feedback: FeedbackType
- onFeedback: (feedback: FeedbackType) => void
-}
-const Result: FC<IResultProps> = ({
- content,
- showFeedback,
- feedback,
- onFeedback,
-}) => {
- return (
- <div className="h-max basis-3/4">
- <Header result={content} showFeedback={showFeedback} feedback={feedback} onFeedback={onFeedback} />
- <div
- className="mt-4 flex w-full overflow-scroll text-sm font-normal leading-5 text-gray-900"
- style={{
- maxHeight: '70vh',
- }}
- dangerouslySetInnerHTML={{
- __html: format(content),
- }}
- >
- </div>
- </div>
- )
-}
-export default React.memo(Result)
diff --git a/web/app/components/share/text-generation/result/header.spec.tsx b/web/app/components/share/text-generation/result/header.spec.tsx
deleted file mode 100644
index b2ef0fadc4f..00000000000
--- a/web/app/components/share/text-generation/result/header.spec.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import type { FeedbackType } from '@/app/components/base/chat/chat/type'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import Header from './header'
-
-// Only mock react-i18next for translations
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}))
-
-// Mock copy-to-clipboard
-const mockCopy = vi.fn((_text: string) => true)
-vi.mock('copy-to-clipboard', () => ({
- default: (text: string) => mockCopy(text),
-}))
-
-afterEach(() => {
- cleanup()
-})
-
-describe('Header', () => {
- const mockOnFeedback = vi.fn()
-
- const defaultProps = {
- result: 'Test result content',
- showFeedback: true,
- feedback: { rating: null } as FeedbackType,
- onFeedback: mockOnFeedback,
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- describe('rendering', () => {
- it('should render the result title', () => {
- render(<Header {...defaultProps} />)
-
- expect(screen.getByText('generation.resultTitle')).toBeInTheDocument()
- })
-
- it('should render the copy button', () => {
- render(<Header {...defaultProps} />)
-
- expect(screen.getByText('generation.copy')).toBeInTheDocument()
- })
- })
-
- describe('copy functionality', () => {
- it('should copy result when copy button is clicked', () => {
- render(<Header {...defaultProps} />)
-
- const copyButton = screen.getByText('generation.copy').closest('button')
- fireEvent.click(copyButton!)
-
- expect(mockCopy).toHaveBeenCalledWith('Test result content')
- })
- })
-
- describe('feedback buttons when showFeedback is true', () => {
- it('should show feedback buttons when no rating is given', () => {
- render(<Header {...defaultProps} />)
-
- // Should show both thumbs up and down buttons
- const buttons = document.querySelectorAll('[class*="cursor-pointer"]')
- expect(buttons.length).toBeGreaterThan(0)
- })
-
- it('should show like button highlighted when rating is like', () => {
- render(
- <Header
- {...defaultProps}
- feedback={{ rating: 'like' }}
- />,
- )
-
- // Should show the undo button for like
- const likeButton = document.querySelector('[class*="primary"]')
- expect(likeButton).toBeInTheDocument()
- })
-
- it('should show dislike button highlighted when rating is dislike', () => {
- render(
- <Header
- {...defaultProps}
- feedback={{ rating: 'dislike' }}
- />,
- )
-
- // Should show the undo button for dislike
- const dislikeButton = document.querySelector('[class*="red"]')
- expect(dislikeButton).toBeInTheDocument()
- })
-
- it('should call onFeedback with like when thumbs up is clicked', () => {
- render(<Header {...defaultProps} />)
-
- // Find the thumbs up button (first one in the feedback area)
- const thumbButtons = document.querySelectorAll('[class*="cursor-pointer"]')
- const thumbsUp = Array.from(thumbButtons).find(btn =>
- btn.className.includes('rounded-md') && !btn.className.includes('primary'),
- )
-
- if (thumbsUp) {
- fireEvent.click(thumbsUp)
- expect(mockOnFeedback).toHaveBeenCalledWith({ rating: 'like' })
- }
- })
-
- it('should call onFeedback with dislike when thumbs down is clicked', () => {
- render(<Header {...defaultProps} />)
-
- // Find the thumbs down button
- const thumbButtons = document.querySelectorAll('[class*="cursor-pointer"]')
- const thumbsDown = Array.from(thumbButtons).pop()
-
- if (thumbsDown) {
- fireEvent.click(thumbsDown)
- expect(mockOnFeedback).toHaveBeenCalledWith({ rating: 'dislike' })
- }
- })
-
- it('should call onFeedback with null when undo like is clicked', () => {
- render(
- <Header
- {...defaultProps}
- feedback={{ rating: 'like' }}
- />,
- )
-
- // When liked, clicking the like button again should undo it (has bg-primary-100 class)
- const likeButton = document.querySelector('[class*="bg-primary-100"]')
- expect(likeButton).toBeInTheDocument()
- fireEvent.click(likeButton!)
- expect(mockOnFeedback).toHaveBeenCalledWith({ rating: null })
- })
-
- it('should call onFeedback with null when undo dislike is clicked', () => {
- render(
- <Header
- {...defaultProps}
- feedback={{ rating: 'dislike' }}
- />,
- )
-
- // When disliked, clicking the dislike button again should undo it (has bg-red-100 class)
- const dislikeButton = document.querySelector('[class*="bg-red-100"]')
- expect(dislikeButton).toBeInTheDocument()
- fireEvent.click(dislikeButton!)
- expect(mockOnFeedback).toHaveBeenCalledWith({ rating: null })
- })
- })
-
- describe('feedback buttons when showFeedback is false', () => {
- it('should not show feedback buttons', () => {
- render(
- <Header
- {...defaultProps}
- showFeedback={false}
- />,
- )
-
- // Should not show feedback area buttons (only copy button)
- const feedbackArea = document.querySelector('[class*="space-x-1 rounded-lg border"]')
- expect(feedbackArea).not.toBeInTheDocument()
- })
- })
-
- describe('memoization', () => {
- it('should be wrapped with React.memo', () => {
- expect((Header as unknown as { $$typeof: symbol }).$$typeof).toBe(Symbol.for('react.memo'))
- })
- })
-})
diff --git a/web/app/components/share/text-generation/result/header.tsx b/web/app/components/share/text-generation/result/header.tsx
deleted file mode 100644
index 250a46f088e..00000000000
--- a/web/app/components/share/text-generation/result/header.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import type { FeedbackType } from '@/app/components/base/chat/chat/type'
-import { ClipboardDocumentIcon, HandThumbDownIcon, HandThumbUpIcon } from '@heroicons/react/24/outline'
-import copy from 'copy-to-clipboard'
-import * as React from 'react'
-import { useTranslation } from 'react-i18next'
-import Button from '@/app/components/base/button'
-import Toast from '@/app/components/base/toast'
-import Tooltip from '@/app/components/base/tooltip'
-
-type IResultHeaderProps = {
- result: string
- showFeedback: boolean
- feedback: FeedbackType
- onFeedback: (feedback: FeedbackType) => void
-}
-
-const Header: FC<IResultHeaderProps> = ({
- feedback,
- showFeedback,
- onFeedback,
- result,
-}) => {
- const { t } = useTranslation()
- return (
- <div className="flex w-full items-center justify-between ">
- <div className="text-2xl font-normal leading-4 text-gray-800">{t('generation.resultTitle', { ns: 'share' })}</div>
- <div className="flex items-center space-x-2">
- <Button
- className="h-7 p-[2px] pr-2"
- onClick={() => {
- copy(result)
- Toast.notify({ type: 'success', message: 'copied' })
- }}
- >
- <>
- <ClipboardDocumentIcon className="mr-1 h-3 w-4 text-gray-500" />
- <span className="text-xs leading-3 text-gray-500">{t('generation.copy', { ns: 'share' })}</span>
- </>
- </Button>
-
- {showFeedback && feedback.rating && feedback.rating === 'like' && (
- <Tooltip
- popupContent="Undo Great Rating"
- >
- <div
- onClick={() => {
- onFeedback({
- rating: null,
- })
- }}
- className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md border border-primary-200 bg-primary-100 !text-primary-600 hover:border-primary-300 hover:bg-primary-200"
- >
- <HandThumbUpIcon width={16} height={16} />
- </div>
- </Tooltip>
- )}
-
- {showFeedback && feedback.rating && feedback.rating === 'dislike' && (
- <Tooltip
- popupContent="Undo Undesirable Response"
- >
- <div
- onClick={() => {
- onFeedback({
- rating: null,
- })
- }}
- className="flex h-7 w-7 cursor-pointer items-center justify-center rounded-md border border-red-200 bg-red-100 !text-red-600 hover:border-red-300 hover:bg-red-200"
- >
- <HandThumbDownIcon width={16} height={16} />
- </div>
- </Tooltip>
- )}
-
- {showFeedback && !feedback.rating && (
- <div className="flex space-x-1 rounded-lg border border-gray-200 p-[1px]">
- <Tooltip
- popupContent="Great Rating"
- needsDelay={false}
- >
- <div
- onClick={() => {
- onFeedback({
- rating: 'like',
- })
- }}
- className="flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-gray-100"
- >
- <HandThumbUpIcon width={16} height={16} />
- </div>
- </Tooltip>
- <Tooltip
- popupContent="Undesirable Response"
- needsDelay={false}
- >
- <div
- onClick={() => {
- onFeedback({
- rating: 'dislike',
- })
- }}
- className="flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-gray-100"
- >
- <HandThumbDownIcon width={16} height={16} />
- </div>
- </Tooltip>
- </div>
- )}
- </div>
-
- </div>
- )
-}
-
-export default React.memo(Header)
diff --git a/web/app/components/share/text-generation/result/index.tsx b/web/app/components/share/text-generation/result/index.tsx
index fe518c6d259..05e6e30dcff 100644
--- a/web/app/components/share/text-generation/result/index.tsx
+++ b/web/app/components/share/text-generation/result/index.tsx
@@ -5,7 +5,9 @@ import type { WorkflowProcess } from '@/app/components/base/chat/types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { PromptConfig } from '@/models/debug'
import type { SiteInfo } from '@/models/share'
-import type { AppSourceType } from '@/service/share'
+import type {
+ IOtherOptions,
+} from '@/service/base'
import type { VisionFile, VisionSettings } from '@/types/app'
import { RiLoader2Line } from '@remixicon/react'
import { useBoolean } from 'ahooks'
@@ -25,7 +27,17 @@ import Toast from '@/app/components/base/toast'
import NoData from '@/app/components/share/text-generation/no-data'
import { NodeRunningStatus, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { TEXT_GENERATION_TIMEOUT_MS } from '@/config'
-import { sendCompletionMessage, sendWorkflowMessage, stopChatMessageResponding, stopWorkflowMessage, updateFeedback } from '@/service/share'
+import {
+ sseGet,
+} from '@/service/base'
+import {
+ AppSourceType,
+ sendCompletionMessage,
+ sendWorkflowMessage,
+ stopChatMessageResponding,
+ stopWorkflowMessage,
+ updateFeedback,
+} from '@/service/share'
import { TransferMethod } from '@/types/app'
import { sleep } from '@/utils'
import { formatBooleanInputs } from '@/utils/model-config'
@@ -93,10 +105,10 @@ const Result: FC<IResultProps> = ({
const getCompletionRes = () => completionResRef.current
const [workflowProcessData, doSetWorkflowProcessData] = useState<WorkflowProcess>()
const workflowProcessDataRef = useRef<WorkflowProcess | undefined>(undefined)
- const setWorkflowProcessData = (data: WorkflowProcess) => {
+ const setWorkflowProcessData = useCallback((data: WorkflowProcess | undefined) => {
workflowProcessDataRef.current = data
doSetWorkflowProcessData(data)
- }
+ }, [])
const getWorkflowProcessData = () => workflowProcessDataRef.current
const [currentTaskId, setCurrentTaskId] = useState<string | null>(null)
const [isStopping, setIsStopping] = useState(false)
@@ -157,7 +169,7 @@ const Result: FC<IResultProps> = ({
finally {
setIsStopping(false)
}
- }, [appId, currentTaskId, appSourceType, appId, isStopping, isWorkflow, notify])
+ }, [appId, currentTaskId, appSourceType, isStopping, isWorkflow, notify])
useEffect(() => {
if (!onRunControlChange)
@@ -257,6 +269,7 @@ const Result: FC<IResultProps> = ({
rating: null,
})
setCompletionRes('')
+ setWorkflowProcessData(undefined)
resetRunState()
let res: string[] = []
@@ -281,10 +294,17 @@ const Result: FC<IResultProps> = ({
})()
if (isWorkflow) {
- sendWorkflowMessage(
- data,
- {
- onWorkflowStarted: ({ workflow_run_id, task_id }) => {
+ const otherOptions: IOtherOptions = {
+ isPublicAPI: appSourceType === AppSourceType.webApp,
+ onWorkflowStarted: ({ workflow_run_id, task_id }) => {
+ const workflowProcessData = getWorkflowProcessData()
+ if (workflowProcessData && workflowProcessData.tracing.length > 0) {
+ setWorkflowProcessData(produce(workflowProcessData, (draft) => {
+ draft.expand = true
+ draft.status = WorkflowRunningStatus.Running
+ }))
+ }
+ else {
tempMessageId = workflow_run_id
setCurrentTaskId(task_id || null)
setIsStopping(false)
@@ -294,178 +314,258 @@ const Result: FC<IResultProps> = ({
expand: false,
resultText: '',
})
- },
- onIterationStart: ({ data }) => {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.expand = true
- draft.tracing!.push({
- ...data,
- status: NodeRunningStatus.Running,
- expand: true,
- })
- }))
- },
- onIterationNext: () => {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.expand = true
- const iterations = draft.tracing.find(item => item.node_id === data.node_id
- && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
- iterations?.details!.push([])
- }))
- },
- onIterationFinish: ({ data }) => {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.expand = true
- const iterationsIndex = draft.tracing.findIndex(item => item.node_id === data.node_id
- && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
- draft.tracing[iterationsIndex] = {
- ...data,
- expand: !!data.error,
+ }
+ },
+ onIterationStart: ({ data }) => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = true
+ draft.tracing!.push({
+ ...data,
+ status: NodeRunningStatus.Running,
+ expand: true,
+ })
+ }))
+ },
+ onIterationNext: () => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = true
+ const iterations = draft.tracing.find(item => item.node_id === data.node_id
+ && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
+ iterations?.details!.push([])
+ }))
+ },
+ onIterationFinish: ({ data }) => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = true
+ const iterationsIndex = draft.tracing.findIndex(item => item.node_id === data.node_id
+ && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
+ draft.tracing[iterationsIndex] = {
+ ...data,
+ expand: !!data.error,
+ }
+ }))
+ },
+ onLoopStart: ({ data }) => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = true
+ draft.tracing!.push({
+ ...data,
+ status: NodeRunningStatus.Running,
+ expand: true,
+ })
+ }))
+ },
+ onLoopNext: () => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = true
+ const loops = draft.tracing.find(item => item.node_id === data.node_id
+ && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
+ loops?.details!.push([])
+ }))
+ },
+ onLoopFinish: ({ data }) => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = true
+ const loopsIndex = draft.tracing.findIndex(item => item.node_id === data.node_id
+ && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
+ draft.tracing[loopsIndex] = {
+ ...data,
+ expand: !!data.error,
+ }
+ }))
+ },
+ onNodeStarted: ({ data }) => {
+ if (data.iteration_id)
+ return
+
+ if (data.loop_id)
+ return
+ const workflowProcessData = getWorkflowProcessData()
+ setWorkflowProcessData(produce(workflowProcessData!, (draft) => {
+ if (draft.tracing.length > 0) {
+ const currentIndex = draft.tracing.findIndex(item => item.node_id === data.node_id)
+ if (currentIndex > -1) {
+ draft.expand = true
+ draft.tracing![currentIndex] = {
+ ...data,
+ status: NodeRunningStatus.Running,
+ expand: true,
+ }
}
- }))
- },
- onLoopStart: ({ data }) => {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ else {
+ draft.expand = true
+ draft.tracing.push({
+ ...data,
+ status: NodeRunningStatus.Running,
+ expand: true,
+ })
+ }
+ }
+ else {
draft.expand = true
draft.tracing!.push({
...data,
status: NodeRunningStatus.Running,
expand: true,
})
- }))
- },
- onLoopNext: () => {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.expand = true
- const loops = draft.tracing.find(item => item.node_id === data.node_id
- && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
- loops?.details!.push([])
- }))
- },
- onLoopFinish: ({ data }) => {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.expand = true
- const loopsIndex = draft.tracing.findIndex(item => item.node_id === data.node_id
- && (item.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || item.parallel_id === data.execution_metadata?.parallel_id))!
- draft.tracing[loopsIndex] = {
+ }
+ }))
+ },
+ onNodeFinished: ({ data }) => {
+ if (data.iteration_id)
+ return
+
+ if (data.loop_id)
+ return
+
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id
+ && (trace.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || trace.parallel_id === data.execution_metadata?.parallel_id))
+ if (currentIndex > -1 && draft.tracing) {
+ draft.tracing[currentIndex] = {
+ ...(draft.tracing[currentIndex].extras
+ ? { extras: draft.tracing[currentIndex].extras }
+ : {}),
...data,
expand: !!data.error,
}
- }))
- },
- onNodeStarted: ({ data }) => {
- if (data.iteration_id)
- return
-
- if (data.loop_id)
+ }
+ }))
+ },
+ onWorkflowFinished: ({ data }) => {
+ if (isTimeout) {
+ notify({ type: 'warning', message: t('warningMessage.timeoutExceeded', { ns: 'appDebug' }) })
+ return
+ }
+ const workflowStatus = data.status as WorkflowRunningStatus | undefined
+ const markNodesStopped = (traces?: WorkflowProcess['tracing']) => {
+ if (!traces)
return
-
+ const markTrace = (trace: WorkflowProcess['tracing'][number]) => {
+ if ([NodeRunningStatus.Running, NodeRunningStatus.Waiting].includes(trace.status as NodeRunningStatus))
+ trace.status = NodeRunningStatus.Stopped
+ trace.details?.forEach(detailGroup => detailGroup.forEach(markTrace))
+ trace.retryDetail?.forEach(markTrace)
+ trace.parallelDetail?.children?.forEach(markTrace)
+ }
+ traces.forEach(markTrace)
+ }
+ if (workflowStatus === WorkflowRunningStatus.Stopped) {
setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.expand = true
- draft.tracing!.push({
- ...data,
- status: NodeRunningStatus.Running,
- expand: true,
- })
+ draft.status = WorkflowRunningStatus.Stopped
+ markNodesStopped(draft.tracing)
}))
- },
- onNodeFinished: ({ data }) => {
- if (data.iteration_id)
- return
-
- if (data.loop_id)
- return
-
+ setRespondingFalse()
+ resetRunState()
+ onCompleted(getCompletionRes(), taskId, false)
+ isEnd = true
+ return
+ }
+ if (data.error) {
+ notify({ type: 'error', message: data.error })
setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id
- && (trace.execution_metadata?.parallel_id === data.execution_metadata?.parallel_id || trace.parallel_id === data.execution_metadata?.parallel_id))
- if (currentIndex > -1 && draft.tracing) {
- draft.tracing[currentIndex] = {
- ...(draft.tracing[currentIndex].extras
- ? { extras: draft.tracing[currentIndex].extras }
- : {}),
- ...data,
- expand: !!data.error,
- }
- }
+ draft.status = WorkflowRunningStatus.Failed
+ markNodesStopped(draft.tracing)
}))
- },
- onWorkflowFinished: ({ data }) => {
- if (isTimeout) {
- notify({ type: 'warning', message: t('warningMessage.timeoutExceeded', { ns: 'appDebug' }) })
- return
+ setRespondingFalse()
+ resetRunState()
+ onCompleted(getCompletionRes(), taskId, false)
+ isEnd = true
+ return
+ }
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.status = WorkflowRunningStatus.Succeeded
+ draft.files = getFilesInLogs(data.outputs || []) as any[]
+ }))
+ if (!data.outputs) {
+ setCompletionRes('')
+ }
+ else {
+ setCompletionRes(data.outputs)
+ const isStringOutput = Object.keys(data.outputs).length === 1 && typeof data.outputs[Object.keys(data.outputs)[0]] === 'string'
+ if (isStringOutput) {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.resultText = data.outputs[Object.keys(data.outputs)[0]]
+ }))
+ }
+ }
+ setRespondingFalse()
+ resetRunState()
+ setMessageId(tempMessageId)
+ onCompleted(getCompletionRes(), taskId, true)
+ isEnd = true
+ },
+ onTextChunk: (params) => {
+ const { data: { text } } = params
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.resultText += text
+ }))
+ },
+ onTextReplace: (params) => {
+ const { data: { text } } = params
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.resultText = text
+ }))
+ },
+ onHumanInputRequired: ({ data: humanInputRequiredData }) => {
+ const workflowProcessData = getWorkflowProcessData()
+ setWorkflowProcessData(produce(workflowProcessData!, (draft) => {
+ if (!draft.humanInputFormDataList) {
+ draft.humanInputFormDataList = [humanInputRequiredData]
}
- const workflowStatus = data.status as WorkflowRunningStatus | undefined
- const markNodesStopped = (traces?: WorkflowProcess['tracing']) => {
- if (!traces)
- return
- const markTrace = (trace: WorkflowProcess['tracing'][number]) => {
- if ([NodeRunningStatus.Running, NodeRunningStatus.Waiting].includes(trace.status as NodeRunningStatus))
- trace.status = NodeRunningStatus.Stopped
- trace.details?.forEach(detailGroup => detailGroup.forEach(markTrace))
- trace.retryDetail?.forEach(markTrace)
- trace.parallelDetail?.children?.forEach(markTrace)
+ else {
+ const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentFormIndex > -1) {
+ draft.humanInputFormDataList[currentFormIndex] = humanInputRequiredData
+ }
+ else {
+ draft.humanInputFormDataList.push(humanInputRequiredData)
}
- traces.forEach(markTrace)
}
- if (workflowStatus === WorkflowRunningStatus.Stopped) {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.status = WorkflowRunningStatus.Stopped
- markNodesStopped(draft.tracing)
- }))
- setRespondingFalse()
- resetRunState()
- onCompleted(getCompletionRes(), taskId, false)
- isEnd = true
- return
+ const currentIndex = draft.tracing!.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentIndex > -1) {
+ draft.tracing![currentIndex].status = NodeRunningStatus.Paused
}
- if (data.error) {
- notify({ type: 'error', message: data.error })
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.status = WorkflowRunningStatus.Failed
- markNodesStopped(draft.tracing)
- }))
- setRespondingFalse()
- resetRunState()
- onCompleted(getCompletionRes(), taskId, false)
- isEnd = true
- return
+ }))
+ },
+ onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ if (draft.humanInputFormDataList?.length) {
+ const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
+ draft.humanInputFormDataList.splice(currentFormIndex, 1)
}
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.status = WorkflowRunningStatus.Succeeded
- draft.files = getFilesInLogs(data.outputs || []) as any[]
- }))
- if (!data.outputs) {
- setCompletionRes('')
+ if (!draft.humanInputFilledFormDataList) {
+ draft.humanInputFilledFormDataList = [humanInputFilledFormData]
}
else {
- setCompletionRes(data.outputs)
- const isStringOutput = Object.keys(data.outputs).length === 1 && typeof data.outputs[Object.keys(data.outputs)[0]] === 'string'
- if (isStringOutput) {
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.resultText = data.outputs[Object.keys(data.outputs)[0]]
- }))
- }
+ draft.humanInputFilledFormDataList.push(humanInputFilledFormData)
}
- setRespondingFalse()
- resetRunState()
- setMessageId(tempMessageId)
- onCompleted(getCompletionRes(), taskId, true)
- isEnd = true
- },
- onTextChunk: (params) => {
- const { data: { text } } = params
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.resultText += text
- }))
- },
- onTextReplace: (params) => {
- const { data: { text } } = params
- setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
- draft.resultText = text
- }))
- },
+ }))
+ },
+ onHumanInputFormTimeout: ({ data: humanInputFormTimeoutData }) => {
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ if (draft.humanInputFormDataList?.length) {
+ const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === humanInputFormTimeoutData.node_id)
+ draft.humanInputFormDataList[currentFormIndex].expiration_time = humanInputFormTimeoutData.expiration_time
+ }
+ }))
},
+ onWorkflowPaused: ({ data: workflowPausedData }) => {
+ const url = `/workflow/${workflowPausedData.workflow_run_id}/events`
+ sseGet(
+ url,
+ {},
+ otherOptions,
+ )
+ setWorkflowProcessData(produce(getWorkflowProcessData()!, (draft) => {
+ draft.expand = false
+ draft.status = WorkflowRunningStatus.Paused
+ }))
+ },
+ }
+ sendWorkflowMessage(
+ data,
+ otherOptions,
appSourceType,
appId,
).catch((error) => {
@@ -562,7 +662,8 @@ const Result: FC<IResultProps> = ({
isMobile={isMobile}
appSourceType={appSourceType}
installedAppId={appId}
- isLoading={isCallBatchAPI ? (!completionRes && isResponding) : false}
+ // isLoading={isCallBatchAPI ? (!completionRes && isResponding) : false}
+ isLoading={false}
taskId={isCallBatchAPI ? ((taskId as number) < 10 ? `0${taskId}` : `${taskId}`) : undefined}
controlClearMoreLikeThis={controlClearMoreLikeThis}
isShowTextToSpeech={isShowTextToSpeech}
diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx
index 466220b6115..d58eb6c669f 100644
--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx
+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx
@@ -111,6 +111,10 @@ const FeaturesTrigger = () => {
return isFetchedPlan && plan.type === Plan.sandbox && entryCount > 2
}, [nodes, plan.type, isFetchedPlan])
+ const hasHumanInputNode = useMemo(() => {
+ return nodes.some(node => node.data.type === BlockEnum.HumanInput)
+ }, [nodes])
+
const resetWorkflowVersionHistory = useResetWorkflowVersionHistory()
const invalidateAppTriggers = useInvalidateAppTriggers()
@@ -171,7 +175,7 @@ const FeaturesTrigger = () => {
else {
throw new Error('Checklist failed')
}
- }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, notify, appID, t, updatePublishedWorkflow, updateAppDetail, workflowStore, resetWorkflowVersionHistory, invalidateAppTriggers])
+ }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, notify, appID, t, updatePublishedWorkflow, updateAppDetail, workflowStore, resetWorkflowVersionHistory, invalidateAppTriggers, hasUserInputNode])
const onPublisherToggle = useCallback((state: boolean) => {
if (state)
@@ -214,6 +218,7 @@ const FeaturesTrigger = () => {
hasTriggerNode,
startNodeLimitExceeded,
publishDisabled: !hasWorkflowNodes || startNodeLimitExceeded,
+ hasHumanInputNode,
}}
/>
</>
diff --git a/web/app/components/workflow-app/hooks/use-workflow-run.ts b/web/app/components/workflow-app/hooks/use-workflow-run.ts
index 49c5d20dde5..ef6d7731a4d 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-run.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-run.ts
@@ -21,7 +21,7 @@ import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-
import { useWorkflowRunEvent } from '@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event'
import { useWorkflowStore } from '@/app/components/workflow/store'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
-import { handleStream, post, ssePost } from '@/service/base'
+import { handleStream, post, sseGet, ssePost } from '@/service/base'
import { ContentType } from '@/service/fetch'
import { useInvalidAllLastRun } from '@/service/use-workflow'
import { stopWorkflowRun } from '@/service/workflow'
@@ -79,6 +79,9 @@ export const useWorkflowRun = () => {
handleWorkflowFailed,
handleWorkflowNodeStarted,
handleWorkflowNodeFinished,
+ handleWorkflowNodeHumanInputRequired,
+ handleWorkflowNodeHumanInputFormFilled,
+ handleWorkflowNodeHumanInputFormTimeout,
handleWorkflowNodeIterationStarted,
handleWorkflowNodeIterationNext,
handleWorkflowNodeIterationFinished,
@@ -89,6 +92,7 @@ export const useWorkflowRun = () => {
handleWorkflowAgentLog,
handleWorkflowTextChunk,
handleWorkflowTextReplace,
+ handleWorkflowPaused,
} = useWorkflowRunEvent()
const handleBackupDraft = useCallback(() => {
@@ -176,6 +180,10 @@ export const useWorkflowRun = () => {
onNodeRetry,
onAgentLog,
onError,
+ onWorkflowPaused,
+ onHumanInputRequired,
+ onHumanInputFormFilled,
+ onHumanInputFormTimeout,
onCompleted,
...restCallback
} = callback || {}
@@ -372,12 +380,6 @@ export const useWorkflowRun = () => {
const baseSseOptions: IOtherOptions = {
...restCallback,
onWorkflowStarted: (params) => {
- const state = workflowStore.getState()
- if (state.workflowRunningData) {
- state.setWorkflowRunningData(produce(state.workflowRunningData, (draft) => {
- draft.resultText = ''
- }))
- }
handleWorkflowStarted(params)
if (onWorkflowStarted)
@@ -492,6 +494,32 @@ export const useWorkflowRun = () => {
if (audioPlayer)
audioPlayer.playAudioWithAudio(audio, false)
},
+ onWorkflowPaused: (params) => {
+ handleWorkflowPaused()
+ if (onWorkflowPaused)
+ onWorkflowPaused(params)
+ const url = `/workflow/${params.workflow_run_id}/events`
+ sseGet(
+ url,
+ {},
+ baseSseOptions,
+ )
+ },
+ onHumanInputRequired: (params) => {
+ handleWorkflowNodeHumanInputRequired(params)
+ if (onHumanInputRequired)
+ onHumanInputRequired(params)
+ },
+ onHumanInputFormFilled: (params) => {
+ handleWorkflowNodeHumanInputFormFilled(params)
+ if (onHumanInputFormFilled)
+ onHumanInputFormFilled(params)
+ },
+ onHumanInputFormTimeout: (params) => {
+ handleWorkflowNodeHumanInputFormTimeout(params)
+ if (onHumanInputFormTimeout)
+ onHumanInputFormTimeout(params)
+ },
onError: wrappedOnError,
onCompleted: wrappedOnCompleted,
}
@@ -604,6 +632,10 @@ export const useWorkflowRun = () => {
baseSseOptions.onTTSEnd,
baseSseOptions.onTextReplace,
baseSseOptions.onAgentLog,
+ baseSseOptions.onHumanInputRequired,
+ baseSseOptions.onHumanInputFormFilled,
+ baseSseOptions.onHumanInputFormTimeout,
+ baseSseOptions.onWorkflowPaused,
baseSseOptions.onDataSourceNodeProcessing,
baseSseOptions.onDataSourceNodeCompleted,
baseSseOptions.onDataSourceNodeError,
@@ -655,19 +687,157 @@ export const useWorkflowRun = () => {
return
}
+ const finalCallbacks: IOtherOptions = {
+ ...baseSseOptions,
+ getAbortController: (controller: AbortController) => {
+ abortControllerRef.current = controller
+ },
+ onWorkflowFinished: (params) => {
+ handleWorkflowFinished(params)
+
+ if (onWorkflowFinished)
+ onWorkflowFinished(params)
+ if (isInWorkflowDebug) {
+ fetchInspectVars({})
+ invalidAllLastRun()
+ }
+ },
+ onError: (params) => {
+ handleWorkflowFailed()
+
+ if (onError)
+ onError(params)
+ },
+ onNodeStarted: (params) => {
+ handleWorkflowNodeStarted(
+ params,
+ {
+ clientWidth,
+ clientHeight,
+ },
+ )
+
+ if (onNodeStarted)
+ onNodeStarted(params)
+ },
+ onNodeFinished: (params) => {
+ handleWorkflowNodeFinished(params)
+
+ if (onNodeFinished)
+ onNodeFinished(params)
+ },
+ onIterationStart: (params) => {
+ handleWorkflowNodeIterationStarted(
+ params,
+ {
+ clientWidth,
+ clientHeight,
+ },
+ )
+
+ if (onIterationStart)
+ onIterationStart(params)
+ },
+ onIterationNext: (params) => {
+ handleWorkflowNodeIterationNext(params)
+
+ if (onIterationNext)
+ onIterationNext(params)
+ },
+ onIterationFinish: (params) => {
+ handleWorkflowNodeIterationFinished(params)
+
+ if (onIterationFinish)
+ onIterationFinish(params)
+ },
+ onLoopStart: (params) => {
+ handleWorkflowNodeLoopStarted(
+ params,
+ {
+ clientWidth,
+ clientHeight,
+ },
+ )
+
+ if (onLoopStart)
+ onLoopStart(params)
+ },
+ onLoopNext: (params) => {
+ handleWorkflowNodeLoopNext(params)
+
+ if (onLoopNext)
+ onLoopNext(params)
+ },
+ onLoopFinish: (params) => {
+ handleWorkflowNodeLoopFinished(params)
+
+ if (onLoopFinish)
+ onLoopFinish(params)
+ },
+ onNodeRetry: (params) => {
+ handleWorkflowNodeRetry(params)
+
+ if (onNodeRetry)
+ onNodeRetry(params)
+ },
+ onAgentLog: (params) => {
+ handleWorkflowAgentLog(params)
+
+ if (onAgentLog)
+ onAgentLog(params)
+ },
+ onTextChunk: (params) => {
+ handleWorkflowTextChunk(params)
+ },
+ onTextReplace: (params) => {
+ handleWorkflowTextReplace(params)
+ },
+ onTTSChunk: (messageId: string, audio: string) => {
+ if (!audio || audio === '')
+ return
+ player?.playAudioWithAudio(audio, true)
+ AudioPlayerManager.getInstance().resetMsgId(messageId)
+ },
+ onTTSEnd: (messageId: string, audio: string) => {
+ player?.playAudioWithAudio(audio, false)
+ },
+ onWorkflowPaused: (params) => {
+ handleWorkflowPaused()
+ if (onWorkflowPaused)
+ onWorkflowPaused(params)
+ const url = `/workflow/${params.workflow_run_id}/events`
+ sseGet(
+ url,
+ {},
+ finalCallbacks,
+ )
+ },
+ onHumanInputRequired: (params) => {
+ handleWorkflowNodeHumanInputRequired(params)
+ if (onHumanInputRequired)
+ onHumanInputRequired(params)
+ },
+ onHumanInputFormFilled: (params) => {
+ handleWorkflowNodeHumanInputFormFilled(params)
+ if (onHumanInputFormFilled)
+ onHumanInputFormFilled(params)
+ },
+ onHumanInputFormTimeout: (params) => {
+ handleWorkflowNodeHumanInputFormTimeout(params)
+ if (onHumanInputFormTimeout)
+ onHumanInputFormTimeout(params)
+ },
+ ...restCallback,
+ }
+
ssePost(
url,
{
body: requestBody,
},
- {
- ...baseSseOptions,
- getAbortController: (controller: AbortController) => {
- abortControllerRef.current = controller
- },
- },
+ finalCallbacks,
)
- }, [store, doSyncWorkflowDraft, workflowStore, pathname, handleWorkflowStarted, handleWorkflowFinished, fetchInspectVars, invalidAllLastRun, handleWorkflowFailed, handleWorkflowNodeStarted, handleWorkflowNodeFinished, handleWorkflowNodeIterationStarted, handleWorkflowNodeIterationNext, handleWorkflowNodeIterationFinished, handleWorkflowNodeLoopStarted, handleWorkflowNodeLoopNext, handleWorkflowNodeLoopFinished, handleWorkflowNodeRetry, handleWorkflowAgentLog, handleWorkflowTextChunk, handleWorkflowTextReplace])
+ }, [store, doSyncWorkflowDraft, workflowStore, pathname, handleWorkflowFailed, flowId, handleWorkflowStarted, handleWorkflowFinished, fetchInspectVars, invalidAllLastRun, handleWorkflowNodeStarted, handleWorkflowNodeFinished, handleWorkflowNodeIterationStarted, handleWorkflowNodeIterationNext, handleWorkflowNodeIterationFinished, handleWorkflowNodeLoopStarted, handleWorkflowNodeLoopNext, handleWorkflowNodeLoopFinished, handleWorkflowNodeRetry, handleWorkflowAgentLog, handleWorkflowTextChunk, handleWorkflowTextReplace, handleWorkflowPaused, handleWorkflowNodeHumanInputRequired, handleWorkflowNodeHumanInputFormFilled, handleWorkflowNodeHumanInputFormTimeout])
const handleStopRun = useCallback((taskId: string) => {
const setStoppedState = () => {
diff --git a/web/app/components/workflow/block-icon.tsx b/web/app/components/workflow/block-icon.tsx
index 32b06d475ff..f12812af787 100644
--- a/web/app/components/workflow/block-icon.tsx
+++ b/web/app/components/workflow/block-icon.tsx
@@ -11,6 +11,7 @@ import {
End,
Home,
Http,
+ HumanInLoop,
IfElse,
Iteration,
KnowledgeBase,
@@ -71,6 +72,7 @@ const DEFAULT_ICON_MAP: Record<BlockEnum, React.ComponentType<{ className: strin
[BlockEnum.TriggerSchedule]: Schedule,
[BlockEnum.TriggerWebhook]: WebhookLine,
[BlockEnum.TriggerPlugin]: VariableX,
+ [BlockEnum.HumanInput]: HumanInLoop,
}
const getIcon = (type: BlockEnum, className: string) => {
@@ -102,6 +104,7 @@ const ICON_CONTAINER_BG_COLOR_MAP: Record<string, string> = {
[BlockEnum.DocExtractor]: 'bg-util-colors-green-green-500',
[BlockEnum.ListFilter]: 'bg-util-colors-cyan-cyan-500',
[BlockEnum.Agent]: 'bg-util-colors-indigo-indigo-500',
+ [BlockEnum.HumanInput]: 'bg-util-colors-cyan-cyan-500',
[BlockEnum.KnowledgeBase]: 'bg-util-colors-warning-warning-500',
[BlockEnum.DataSource]: 'bg-components-icon-bg-midnight-solid',
[BlockEnum.TriggerSchedule]: 'bg-util-colors-violet-violet-500',
diff --git a/web/app/components/workflow/constants.ts b/web/app/components/workflow/constants.ts
index 4d95db7fcfe..ed9a072824e 100644
--- a/web/app/components/workflow/constants.ts
+++ b/web/app/components/workflow/constants.ts
@@ -128,6 +128,7 @@ export const SUPPORT_OUTPUT_VARS_NODE = [
BlockEnum.ListFilter,
BlockEnum.Agent,
BlockEnum.DataSource,
+ BlockEnum.HumanInput,
]
export const AGENT_OUTPUT_STRUCT: Var[] = [
@@ -211,6 +212,17 @@ export const TOOL_OUTPUT_STRUCT: Var[] = [
},
]
+export const HUMAN_INPUT_OUTPUT_STRUCT: Var[] = [
+ {
+ variable: '__action_id',
+ type: VarType.string,
+ },
+ {
+ variable: '__rendered_content',
+ type: VarType.string,
+ },
+]
+
export const PARAMETER_EXTRACTOR_COMMON_STRUCT: Var[] = [
{
variable: '__is_success',
diff --git a/web/app/components/workflow/constants/node.ts b/web/app/components/workflow/constants/node.ts
index 5de95127524..4d67f278c25 100644
--- a/web/app/components/workflow/constants/node.ts
+++ b/web/app/components/workflow/constants/node.ts
@@ -5,12 +5,13 @@ import codeDefault from '@/app/components/workflow/nodes/code/default'
import documentExtractorDefault from '@/app/components/workflow/nodes/document-extractor/default'
import httpRequestDefault from '@/app/components/workflow/nodes/http/default'
+import humanInputDefault from '@/app/components/workflow/nodes/human-input/default'
import ifElseDefault from '@/app/components/workflow/nodes/if-else/default'
import iterationStartDefault from '@/app/components/workflow/nodes/iteration-start/default'
import iterationDefault from '@/app/components/workflow/nodes/iteration/default'
import knowledgeRetrievalDefault from '@/app/components/workflow/nodes/knowledge-retrieval/default'
-import listOperatorDefault from '@/app/components/workflow/nodes/list-operator/default'
+import listOperatorDefault from '@/app/components/workflow/nodes/list-operator/default'
import llmDefault from '@/app/components/workflow/nodes/llm/default'
import loopEndDefault from '@/app/components/workflow/nodes/loop-end/default'
import loopStartDefault from '@/app/components/workflow/nodes/loop-start/default'
@@ -41,4 +42,5 @@ export const WORKFLOW_COMMON_NODES = [
httpRequestDefault,
listOperatorDefault,
toolDefault,
+ humanInputDefault,
]
diff --git a/web/app/components/workflow/header/run-mode.tsx b/web/app/components/workflow/header/run-mode.tsx
index 74bc5bc80a0..63c48ff0dca 100644
--- a/web/app/components/workflow/header/run-mode.tsx
+++ b/web/app/components/workflow/header/run-mode.tsx
@@ -32,7 +32,7 @@ const RunMode = ({
handleWorkflowRunAllTriggersInWorkflow,
} = useWorkflowStartRun()
const { handleStopRun } = useWorkflowRun()
- const { validateBeforeRun, warningNodes } = useWorkflowRunValidation()
+ const { warningNodes } = useWorkflowRunValidation()
const workflowRunningData = useStore(s => s.workflowRunningData)
const isListening = useStore(s => s.isListening)
@@ -98,14 +98,7 @@ const RunMode = ({
// Placeholder for trigger-specific execution logic for schedule, webhook, plugin types
console.log('TODO: Handle trigger execution for type:', option.type, 'nodeId:', option.nodeId)
}
- }, [
- validateBeforeRun,
- handleWorkflowStartRunInWorkflow,
- handleWorkflowTriggerScheduleRunInWorkflow,
- handleWorkflowTriggerWebhookRunInWorkflow,
- handleWorkflowTriggerPluginRunInWorkflow,
- handleWorkflowRunAllTriggersInWorkflow,
- ])
+ }, [warningNodes, notify, t, handleWorkflowStartRunInWorkflow, handleWorkflowTriggerScheduleRunInWorkflow, handleWorkflowTriggerWebhookRunInWorkflow, handleWorkflowTriggerPluginRunInWorkflow, handleWorkflowRunAllTriggersInWorkflow])
const { eventEmitter } = useEventEmitterContextContext()
eventEmitter?.useSubscription((v: any) => {
diff --git a/web/app/components/workflow/hooks/use-available-blocks.ts b/web/app/components/workflow/hooks/use-available-blocks.ts
index 4969cb9d89d..3d92142b106 100644
--- a/web/app/components/workflow/hooks/use-available-blocks.ts
+++ b/web/app/components/workflow/hooks/use-available-blocks.ts
@@ -6,7 +6,7 @@ import { BlockEnum } from '../types'
import { useNodesMetaData } from './use-nodes-meta-data'
const availableBlocksFilter = (nodeType: BlockEnum, inContainer?: boolean) => {
- if (inContainer && (nodeType === BlockEnum.Iteration || nodeType === BlockEnum.Loop || nodeType === BlockEnum.End || nodeType === BlockEnum.DataSource || nodeType === BlockEnum.KnowledgeBase))
+ if (inContainer && (nodeType === BlockEnum.Iteration || nodeType === BlockEnum.Loop || nodeType === BlockEnum.End || nodeType === BlockEnum.DataSource || nodeType === BlockEnum.KnowledgeBase || nodeType === BlockEnum.HumanInput))
return false
if (!inContainer && nodeType === BlockEnum.LoopEnd)
diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.ts
index 5a9e4dacb7c..642179aed7f 100644
--- a/web/app/components/workflow/hooks/use-checklist.ts
+++ b/web/app/components/workflow/hooks/use-checklist.ts
@@ -249,7 +249,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {
})
return list
- }, [nodes, nodesExtraData, edges, buildInTools, customTools, workflowTools, language, dataSourceList, getToolIcon, strategyProviders, getCheckData, t, map, shouldCheckStartNode])
+ }, [nodes, edges, shouldCheckStartNode, nodesExtraData, buildInTools, customTools, workflowTools, language, dataSourceList, triggerPlugins, getToolIcon, strategyProviders, getCheckData, t, map])
return needWarningNodes
}
@@ -419,7 +419,7 @@ export const useChecklistBeforePublish = () => {
}
return true
- }, [store, notify, t, language, nodesExtraData, strategyProviders, updateDatasetsDetail, getCheckData, workflowStore, buildInTools, customTools, workflowTools, shouldCheckStartNode])
+ }, [store, workflowStore, getNodesAvailableVarList, shouldCheckStartNode, nodesExtraData, notify, t, updateDatasetsDetail, buildInTools, customTools, workflowTools, language, getCheckData, strategyProviders])
return {
handleCheckBeforePublish,
diff --git a/web/app/components/workflow/hooks/use-edges-interactions.ts b/web/app/components/workflow/hooks/use-edges-interactions.ts
index 5104b47ef4a..0e911c3de89 100644
--- a/web/app/components/workflow/hooks/use-edges-interactions.ts
+++ b/web/app/components/workflow/hooks/use-edges-interactions.ts
@@ -151,11 +151,65 @@ export const useEdgesInteractions = () => {
setEdges(newEdges)
}, [store, getNodesReadOnly])
+ const handleEdgeSourceHandleChange = useCallback((nodeId: string, oldHandleId: string, newHandleId: string) => {
+ if (getNodesReadOnly())
+ return
+
+ const { getNodes, setNodes, edges, setEdges } = store.getState()
+ const nodes = getNodes()
+
+ // Find edges connected to the old handle
+ const affectedEdges = edges.filter(
+ edge => edge.source === nodeId && edge.sourceHandle === oldHandleId,
+ )
+
+ if (affectedEdges.length === 0)
+ return
+
+ // Update node metadata: remove old handle, add new handle
+ const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(
+ [
+ ...affectedEdges.map(edge => ({ type: 'remove', edge })),
+ ...affectedEdges.map(edge => ({
+ type: 'add',
+ edge: { ...edge, sourceHandle: newHandleId },
+ })),
+ ],
+ nodes,
+ )
+
+ const newNodes = produce(nodes, (draft: Node[]) => {
+ draft.forEach((node) => {
+ if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {
+ node.data = {
+ ...node.data,
+ ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],
+ }
+ }
+ })
+ })
+ setNodes(newNodes)
+
+ // Update edges to use new sourceHandle and regenerate edge IDs
+ const newEdges = produce(edges, (draft) => {
+ draft.forEach((edge) => {
+ if (edge.source === nodeId && edge.sourceHandle === oldHandleId) {
+ edge.sourceHandle = newHandleId
+ edge.id = `${edge.source}-${newHandleId}-${edge.target}-${edge.targetHandle}`
+ }
+ })
+ })
+ setEdges(newEdges)
+ handleSyncWorkflowDraft()
+ saveStateToHistory(WorkflowHistoryEvent.EdgeSourceHandleChange)
+ }, [getNodesReadOnly, store, handleSyncWorkflowDraft, saveStateToHistory])
+
return {
handleEdgeEnter,
handleEdgeLeave,
handleEdgeDeleteByDeleteBranch,
handleEdgeDelete,
handleEdgesChange,
+ handleEdgeSourceHandleChange,
}
}
diff --git a/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts b/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts
index 54c2c77d0d3..f013402cd3e 100644
--- a/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts
+++ b/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts
@@ -2,7 +2,7 @@ import type { Node, ToolWithProvider } from '@/app/components/workflow/types'
import type { SchemaTypeDefinition } from '@/service/use-common'
import type { FlowType } from '@/types/common'
import type { NodeWithVar, VarInInspect } from '@/types/workflow'
-import { useCallback } from 'react'
+import { useCallback, useMemo } from 'react'
import { useStoreApi } from 'reactflow'
import { useNodesInteractionsWithoutSync } from '@/app/components/workflow/hooks/use-nodes-interactions-without-sync'
import { useStore, useWorkflowStore } from '@/app/components/workflow/store'
@@ -14,7 +14,7 @@ import {
} from '@/service/use-tools'
import { useInvalidateConversationVarValues, useInvalidateSysVarValues } from '@/service/use-workflow'
import { fetchAllInspectVars } from '@/service/workflow'
-import useMatchSchemaType, { getMatchedSchemaType } from '../nodes/_base/components/variable/use-match-schema-type'
+import useMatchSchemaType from '../nodes/_base/components/variable/use-match-schema-type'
import { toNodeOutputVars } from '../nodes/_base/components/variable/utils'
type Params = {
@@ -37,15 +37,18 @@ export const useSetWorkflowVarsWithValue = ({
const { data: workflowTools } = useAllWorkflowTools()
const { data: mcpTools } = useAllMCPTools()
const dataSourceList = useStore(s => s.dataSourceList)
- const allPluginInfoList = {
- buildInTools: buildInTools || [],
- customTools: customTools || [],
- workflowTools: workflowTools || [],
- mcpTools: mcpTools || [],
- dataSourceList: dataSourceList || [],
- }
- const setInspectVarsToStore = (inspectVars: VarInInspect[], passedInAllPluginInfoList?: Record<string, ToolWithProvider[]>, passedInSchemaTypeDefinitions?: SchemaTypeDefinition[]) => {
+ const allPluginInfoList = useMemo(() => {
+ return {
+ buildInTools: buildInTools || [],
+ customTools: customTools || [],
+ workflowTools: workflowTools || [],
+ mcpTools: mcpTools || [],
+ dataSourceList: dataSourceList || [],
+ }
+ }, [buildInTools, customTools, workflowTools, mcpTools, dataSourceList])
+
+ const setInspectVarsToStore = useCallback((inspectVars: VarInInspect[], passedInAllPluginInfoList?: Record<string, ToolWithProvider[]>, passedInSchemaTypeDefinitions?: SchemaTypeDefinition[]) => {
const { setNodesWithInspectVars } = workflowStore.getState()
const { getNodes } = store.getState()
@@ -95,7 +98,7 @@ export const useSetWorkflowVarsWithValue = ({
return nodeWithVar
})
setNodesWithInspectVars(res)
- }
+ }, [workflowStore, store, allPluginInfoList, schemaTypeDefinitions])
const fetchInspectVars = useCallback(async (params: {
passInVars?: boolean
@@ -109,7 +112,8 @@ export const useSetWorkflowVarsWithValue = ({
const data = passInVars ? vars! : await fetchAllInspectVars(flowType, flowId)
setInspectVarsToStore(data, passedInAllPluginInfoList, passedInSchemaTypeDefinitions)
handleCancelAllNodeSuccessStatus() // to make sure clear node output show the unset status
- }, [invalidateConversationVarValues, invalidateSysVarValues, flowType, flowId, setInspectVarsToStore, handleCancelAllNodeSuccessStatus, schemaTypeDefinitions, getMatchedSchemaType])
+ }, [invalidateConversationVarValues, invalidateSysVarValues, flowType, flowId, setInspectVarsToStore, handleCancelAllNodeSuccessStatus])
+
return {
fetchInspectVars,
}
diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.ts
index 8277e7dac8a..4635baa7870 100644
--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts
+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts
@@ -299,6 +299,7 @@ export const useNodesInteractions = () => {
|| connectingNode.data.type === BlockEnum.VariableAggregator)
&& node.data.type !== BlockEnum.IfElse
&& node.data.type !== BlockEnum.QuestionClassifier
+ && node.data.type !== BlockEnum.HumanInput
) {
n.data._isEntering = true
}
@@ -1017,6 +1018,7 @@ export const useNodesInteractions = () => {
if (
nodeType !== BlockEnum.IfElse
&& nodeType !== BlockEnum.QuestionClassifier
+ && nodeType !== BlockEnum.HumanInput
) {
newNode.data._connectedSourceHandleIds = [sourceHandle]
}
@@ -1053,6 +1055,7 @@ export const useNodesInteractions = () => {
if (
nodeType !== BlockEnum.IfElse
&& nodeType !== BlockEnum.QuestionClassifier
+ && nodeType !== BlockEnum.HumanInput
&& nodeType !== BlockEnum.LoopEnd
) {
newEdge = {
@@ -1244,6 +1247,7 @@ export const useNodesInteractions = () => {
if (
nodeType !== BlockEnum.IfElse
&& nodeType !== BlockEnum.QuestionClassifier
+ && nodeType !== BlockEnum.HumanInput
&& nodeType !== BlockEnum.LoopEnd
) {
newNextEdge = {
diff --git a/web/app/components/workflow/hooks/use-workflow-history.ts b/web/app/components/workflow/hooks/use-workflow-history.ts
index 17270bea632..7feaec9709a 100644
--- a/web/app/components/workflow/hooks/use-workflow-history.ts
+++ b/web/app/components/workflow/hooks/use-workflow-history.ts
@@ -27,6 +27,7 @@ export const WorkflowHistoryEvent = {
NodeDelete: 'NodeDelete',
EdgeDelete: 'EdgeDelete',
EdgeDeleteByDeleteBranch: 'EdgeDeleteByDeleteBranch',
+ EdgeSourceHandleChange: 'EdgeSourceHandleChange',
NodeAdd: 'NodeAdd',
NodeResize: 'NodeResize',
NoteAdd: 'NoteAdd',
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/index.ts b/web/app/components/workflow/hooks/use-workflow-run-event/index.ts
index 3f31b423ad8..43486873339 100644
--- a/web/app/components/workflow/hooks/use-workflow-run-event/index.ts
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/index.ts
@@ -2,6 +2,9 @@ export * from './use-workflow-agent-log'
export * from './use-workflow-failed'
export * from './use-workflow-finished'
export * from './use-workflow-node-finished'
+export * from './use-workflow-node-human-input-form-filled'
+export * from './use-workflow-node-human-input-form-timeout'
+export * from './use-workflow-node-human-input-required'
export * from './use-workflow-node-iteration-finished'
export * from './use-workflow-node-iteration-next'
export * from './use-workflow-node-iteration-started'
@@ -10,6 +13,7 @@ export * from './use-workflow-node-loop-next'
export * from './use-workflow-node-loop-started'
export * from './use-workflow-node-retry'
export * from './use-workflow-node-started'
+export * from './use-workflow-paused'
export * from './use-workflow-started'
export * from './use-workflow-text-chunk'
export * from './use-workflow-text-replace'
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-finished.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-finished.ts
index cf0d9bcef1e..6768273f204 100644
--- a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-finished.ts
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-finished.ts
@@ -49,6 +49,8 @@ export const useWorkflowNodeFinished = () => {
if (data.node_type === BlockEnum.QuestionClassifier)
currentNode.data._runningBranchId = data?.outputs?.class_id
+ if (data.node_type === BlockEnum.HumanInput)
+ currentNode.data._runningBranchId = data?.outputs?.__action_id
}
})
setNodes(newNodes)
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-form-filled.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-form-filled.ts
new file mode 100644
index 00000000000..f3750b69961
--- /dev/null
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-form-filled.ts
@@ -0,0 +1,34 @@
+import type { HumanInputFormFilledResponse } from '@/types/workflow'
+import { produce } from 'immer'
+import { useCallback } from 'react'
+import { useWorkflowStore } from '@/app/components/workflow/store'
+
+export const useWorkflowNodeHumanInputFormFilled = () => {
+ const workflowStore = useWorkflowStore()
+
+ const handleWorkflowNodeHumanInputFormFilled = useCallback((params: HumanInputFormFilledResponse) => {
+ const { data } = params
+ const {
+ workflowRunningData,
+ setWorkflowRunningData,
+ } = workflowStore.getState()
+
+ const newWorkflowRunningData = produce(workflowRunningData!, (draft) => {
+ if (draft.humanInputFormDataList?.length) {
+ const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
+ draft.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
+ if (!draft.humanInputFilledFormDataList) {
+ draft.humanInputFilledFormDataList = [data]
+ }
+ else {
+ draft.humanInputFilledFormDataList.push(data)
+ }
+ })
+ setWorkflowRunningData(newWorkflowRunningData)
+ }, [workflowStore])
+
+ return {
+ handleWorkflowNodeHumanInputFormFilled,
+ }
+}
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-form-timeout.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-form-timeout.ts
new file mode 100644
index 00000000000..d3016eeb1da
--- /dev/null
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-form-timeout.ts
@@ -0,0 +1,28 @@
+import type { HumanInputFormTimeoutResponse } from '@/types/workflow'
+import { produce } from 'immer'
+import { useCallback } from 'react'
+import { useWorkflowStore } from '@/app/components/workflow/store'
+
+export const useWorkflowNodeHumanInputFormTimeout = () => {
+ const workflowStore = useWorkflowStore()
+
+ const handleWorkflowNodeHumanInputFormTimeout = useCallback((params: HumanInputFormTimeoutResponse) => {
+ const { data } = params
+ const {
+ workflowRunningData,
+ setWorkflowRunningData,
+ } = workflowStore.getState()
+
+ const newWorkflowRunningData = produce(workflowRunningData!, (draft) => {
+ if (draft.humanInputFormDataList?.length) {
+ const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
+ draft.humanInputFormDataList[currentFormIndex].expiration_time = data.expiration_time
+ }
+ })
+ setWorkflowRunningData(newWorkflowRunningData)
+ }, [workflowStore])
+
+ return {
+ handleWorkflowNodeHumanInputFormTimeout,
+ }
+}
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-required.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-required.ts
new file mode 100644
index 00000000000..87f82c69f20
--- /dev/null
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-human-input-required.ts
@@ -0,0 +1,60 @@
+import type { HumanInputRequiredResponse } from '@/types/workflow'
+import { produce } from 'immer'
+import { useCallback } from 'react'
+import {
+ useStoreApi,
+} from 'reactflow'
+import { useWorkflowStore } from '@/app/components/workflow/store'
+import { NodeRunningStatus } from '@/app/components/workflow/types'
+
+export const useWorkflowNodeHumanInputRequired = () => {
+ const store = useStoreApi()
+ const workflowStore = useWorkflowStore()
+
+ // Notice: Human input required !== Workflow Paused
+ const handleWorkflowNodeHumanInputRequired = useCallback((params: HumanInputRequiredResponse) => {
+ const { data } = params
+ const {
+ workflowRunningData,
+ setWorkflowRunningData,
+ } = workflowStore.getState()
+
+ const newWorkflowRunningData = produce(workflowRunningData!, (draft) => {
+ if (!draft.humanInputFormDataList) {
+ draft.humanInputFormDataList = [data]
+ }
+ else {
+ const currentFormIndex = draft.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
+ if (currentFormIndex > -1) {
+ draft.humanInputFormDataList[currentFormIndex] = data
+ }
+ else {
+ draft.humanInputFormDataList.push(data)
+ }
+ }
+ const currentIndex = draft.tracing!.findIndex(item => item.node_id === data.node_id)
+ if (currentIndex > -1) {
+ draft.tracing![currentIndex] = {
+ ...draft.tracing![currentIndex],
+ status: NodeRunningStatus.Paused,
+ }
+ }
+ })
+ setWorkflowRunningData(newWorkflowRunningData)
+
+ const {
+ getNodes,
+ setNodes,
+ } = store.getState()
+ const nodes = getNodes()
+ const currentNodeIndex = nodes.findIndex(node => node.id === data.node_id)
+ const newNodes = produce(nodes, (draft) => {
+ draft[currentNodeIndex].data._runningStatus = NodeRunningStatus.Paused
+ })
+ setNodes(newNodes)
+ }, [store, workflowStore])
+
+ return {
+ handleWorkflowNodeHumanInputRequired,
+ }
+}
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-started.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-started.ts
index 03c7387d389..01f60e12e9b 100644
--- a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-started.ts
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-node-started.ts
@@ -33,12 +33,23 @@ export const useWorkflowNodeStarted = () => {
transform,
} = store.getState()
const nodes = getNodes()
- setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
- draft.tracing!.push({
- ...data,
- status: NodeRunningStatus.Running,
- })
- }))
+ const currentIndex = workflowRunningData?.tracing?.findIndex(item => item.node_id === data.node_id)
+ if (currentIndex && currentIndex > -1) {
+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
+ draft.tracing![currentIndex] = {
+ ...data,
+ status: NodeRunningStatus.Running,
+ }
+ }))
+ }
+ else {
+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
+ draft.tracing!.push({
+ ...data,
+ status: NodeRunningStatus.Running,
+ })
+ }))
+ }
const {
setViewport,
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-paused.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-paused.ts
new file mode 100644
index 00000000000..fc85d3d459b
--- /dev/null
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-paused.ts
@@ -0,0 +1,26 @@
+import { produce } from 'immer'
+import { useCallback } from 'react'
+import { useWorkflowStore } from '@/app/components/workflow/store'
+import { WorkflowRunningStatus } from '@/app/components/workflow/types'
+
+export const useWorkflowPaused = () => {
+ const workflowStore = useWorkflowStore()
+
+ const handleWorkflowPaused = useCallback(() => {
+ const {
+ workflowRunningData,
+ setWorkflowRunningData,
+ } = workflowStore.getState()
+
+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
+ draft.result = {
+ ...draft.result,
+ status: WorkflowRunningStatus.Paused,
+ }
+ }))
+ }, [workflowStore])
+
+ return {
+ handleWorkflowPaused,
+ }
+}
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event.ts
index 64883076cdc..bf8fd319a2d 100644
--- a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event.ts
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event.ts
@@ -3,6 +3,9 @@ import {
useWorkflowFailed,
useWorkflowFinished,
useWorkflowNodeFinished,
+ useWorkflowNodeHumanInputFormFilled,
+ useWorkflowNodeHumanInputFormTimeout,
+ useWorkflowNodeHumanInputRequired,
useWorkflowNodeIterationFinished,
useWorkflowNodeIterationNext,
useWorkflowNodeIterationStarted,
@@ -11,6 +14,7 @@ import {
useWorkflowNodeLoopStarted,
useWorkflowNodeRetry,
useWorkflowNodeStarted,
+ useWorkflowPaused,
useWorkflowStarted,
useWorkflowTextChunk,
useWorkflowTextReplace,
@@ -32,6 +36,10 @@ export const useWorkflowRunEvent = () => {
const { handleWorkflowTextChunk } = useWorkflowTextChunk()
const { handleWorkflowTextReplace } = useWorkflowTextReplace()
const { handleWorkflowAgentLog } = useWorkflowAgentLog()
+ const { handleWorkflowPaused } = useWorkflowPaused()
+ const { handleWorkflowNodeHumanInputRequired } = useWorkflowNodeHumanInputRequired()
+ const { handleWorkflowNodeHumanInputFormFilled } = useWorkflowNodeHumanInputFormFilled()
+ const { handleWorkflowNodeHumanInputFormTimeout } = useWorkflowNodeHumanInputFormTimeout()
return {
handleWorkflowStarted,
@@ -49,5 +57,9 @@ export const useWorkflowRunEvent = () => {
handleWorkflowTextChunk,
handleWorkflowTextReplace,
handleWorkflowAgentLog,
+ handleWorkflowPaused,
+ handleWorkflowNodeHumanInputFormFilled,
+ handleWorkflowNodeHumanInputRequired,
+ handleWorkflowNodeHumanInputFormTimeout,
}
}
diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-started.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-started.ts
index 16ad9766077..fa9109c4608 100644
--- a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-started.ts
+++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-started.ts
@@ -22,6 +22,15 @@ export const useWorkflowStarted = () => {
edges,
setEdges,
} = store.getState()
+ if (workflowRunningData?.result?.status === WorkflowRunningStatus.Paused) {
+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
+ draft.result = {
+ ...draft.result,
+ status: WorkflowRunningStatus.Running,
+ }
+ }))
+ return
+ }
setIterParallelLogMap(new Map())
setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
draft.task_id = task_id
@@ -30,6 +39,7 @@ export const useWorkflowStarted = () => {
...data,
status: WorkflowRunningStatus.Running,
}
+ draft.resultText = ''
}))
const nodes = getNodes()
const newNodes = produce(nodes, (draft) => {
diff --git a/web/app/components/workflow/hooks/use-workflow-variables.ts b/web/app/components/workflow/hooks/use-workflow-variables.ts
index d6a5b8bdd16..8a975d80ec0 100644
--- a/web/app/components/workflow/hooks/use-workflow-variables.ts
+++ b/web/app/components/workflow/hooks/use-workflow-variables.ts
@@ -116,7 +116,7 @@ export const useWorkflowVariables = () => {
schemaTypeDefinitions,
preferSchemaType,
})
- }, [workflowStore, getVarType, schemaTypeDefinitions, buildInTools, customTools, workflowTools, mcpTools])
+ }, [workflowStore, schemaTypeDefinitions, buildInTools, customTools, workflowTools, mcpTools])
return {
getNodeAvailableVars,
diff --git a/web/app/components/workflow/hooks/use-workflow.ts b/web/app/components/workflow/hooks/use-workflow.ts
index 990c8c950d2..0c6aa7466e1 100644
--- a/web/app/components/workflow/hooks/use-workflow.ts
+++ b/web/app/components/workflow/hooks/use-workflow.ts
@@ -479,11 +479,21 @@ export const useNodesReadOnly = () => {
isRestoring,
} = workflowStore.getState()
- return !!(workflowRunningData?.result.status === WorkflowRunningStatus.Running || historyWorkflowData || isRestoring)
+ return !!(
+ workflowRunningData?.result.status === WorkflowRunningStatus.Running
+ || workflowRunningData?.result.status === WorkflowRunningStatus.Paused
+ || historyWorkflowData
+ || isRestoring
+ )
}, [workflowStore])
return {
- nodesReadOnly: !!(workflowRunningData?.result.status === WorkflowRunningStatus.Running || historyWorkflowData || isRestoring),
+ nodesReadOnly: !!(
+ workflowRunningData?.result.status === WorkflowRunningStatus.Running
+ || workflowRunningData?.result.status === WorkflowRunningStatus.Paused
+ || historyWorkflowData
+ || isRestoring
+ ),
getNodesReadOnly,
}
}
diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx
index 3eef34bd7b5..d66d47cc1f5 100644
--- a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx
+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx
@@ -82,7 +82,7 @@ const FormItem: FC<Props> = ({
<div className="p-[1px]">
<VarBlockIcon type={nodeType || BlockEnum.Start} />
</div>
- <div className="mx-0.5 max-w-[150px] truncate text-xs font-medium text-gray-700" title={nodeName}>
+ <div className="mx-0.5 max-w-[150px] truncate text-xs font-medium text-text-secondary" title={nodeName}>
{nodeName}
</div>
<Line3 className="mr-0.5"></Line3>
diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx
index 8967b76f6c4..4b7f65bcc16 100644
--- a/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx
+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/index.tsx
@@ -3,7 +3,8 @@ import type { FC } from 'react'
import type { Props as FormProps } from './form'
import type { Emoji } from '@/app/components/tools/types'
import type { SpecialResultPanelProps } from '@/app/components/workflow/run/special-result-panel'
-import type { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
+import type { NodeRunningStatus } from '@/app/components/workflow/types'
+import type { HumanInputFormData } from '@/types/workflow'
import * as React from 'react'
import { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
@@ -11,7 +12,8 @@ import Button from '@/app/components/base/button'
import { getProcessedFiles } from '@/app/components/base/file-uploader/utils'
import Toast from '@/app/components/base/toast'
import Split from '@/app/components/workflow/nodes/_base/components/split'
-import { InputVarType } from '@/app/components/workflow/types'
+import SingleRunForm from '@/app/components/workflow/nodes/human-input/components/single-run-form'
+import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
import { TransferMethod } from '@/types/app'
import { cn } from '@/utils/classnames'
import Form from './form'
@@ -31,6 +33,12 @@ export type BeforeRunFormProps = {
showSpecialResultPanel?: boolean
existVarValuesInForms: Record<string, any>[]
filteredExistVarForms: FormProps[]
+ showGeneratedForm?: boolean
+ handleShowGeneratedForm?: (data: Record<string, any>) => void
+ handleHideGeneratedForm?: () => void
+ formData?: HumanInputFormData
+ handleSubmitHumanInputForm?: (data: any) => Promise<void>
+ handleAfterHumanInputStepRun?: () => void
} & Partial<SpecialResultPanelProps>
function formatValue(value: string | any, type: InputVarType) {
@@ -62,14 +70,24 @@ function formatValue(value: string | any, type: InputVarType) {
}
const BeforeRunForm: FC<BeforeRunFormProps> = ({
nodeName,
+ nodeType,
onHide,
onRun,
forms,
filteredExistVarForms,
existVarValuesInForms,
+ showGeneratedForm = false,
+ handleShowGeneratedForm,
+ handleHideGeneratedForm,
+ formData,
+ handleSubmitHumanInputForm,
+ handleAfterHumanInputStepRun,
}) => {
const { t } = useTranslation()
+ const isHumanInput = nodeType === BlockEnum.HumanInput
+ const showBackButton = filteredExistVarForms.length > 0
+
const isFileLoaded = (() => {
if (!forms || forms.length === 0)
return true
@@ -84,7 +102,8 @@ const BeforeRunForm: FC<BeforeRunFormProps> = ({
return true
})()
- const handleRun = () => {
+
+ const handleRunOrGenerateForm = () => {
let errMsg = ''
forms.forEach((form, i) => {
const existVarValuesInForm = existVarValuesInForms[i]
@@ -135,19 +154,30 @@ const BeforeRunForm: FC<BeforeRunFormProps> = ({
return
}
- onRun(submitData)
+ if (isHumanInput)
+ handleShowGeneratedForm?.(submitData)
+ else
+ onRun(submitData)
}
+
+ const handleHumanInputFormSubmit = async (data: any) => {
+ await handleSubmitHumanInputForm?.(data)
+ handleAfterHumanInputStepRun?.()
+ }
+
const hasRun = useRef(false)
useEffect(() => {
// React 18 run twice in dev mode
if (hasRun.current)
return
hasRun.current = true
- if (filteredExistVarForms.length === 0)
+ if (filteredExistVarForms.length === 0 && !isHumanInput)
onRun({})
- }, [filteredExistVarForms, onRun])
+ if (filteredExistVarForms.length === 0 && isHumanInput)
+ handleShowGeneratedForm?.({})
+ }, [filteredExistVarForms, handleShowGeneratedForm, isHumanInput, onRun])
- if (filteredExistVarForms.length === 0)
+ if (filteredExistVarForms.length === 0 && !isHumanInput)
return null
return (
@@ -156,23 +186,43 @@ const BeforeRunForm: FC<BeforeRunFormProps> = ({
onHide={onHide}
>
<div className="h-0 grow overflow-y-auto pb-4">
- <div className="mt-3 space-y-4 px-4">
- {filteredExistVarForms.map((form, index) => (
- <div key={index}>
- <Form
- key={index}
- className={cn(index < forms.length - 1 && 'mb-4')}
- {...form}
- />
- {index < forms.length - 1 && <Split />}
- </div>
- ))}
- </div>
- <div className="mt-4 flex justify-between space-x-2 px-4">
- <Button disabled={!isFileLoaded} variant="primary" className="w-0 grow space-x-2" onClick={handleRun}>
- <div>{t(`${i18nPrefix}.startRun`, { ns: 'workflow' })}</div>
- </Button>
- </div>
+ {!showGeneratedForm && (
+ <div className="mt-3 space-y-4 px-4">
+ {filteredExistVarForms.map((form, index) => (
+ <div key={index}>
+ <Form
+ key={index}
+ className={cn(index < forms.length - 1 && 'mb-4')}
+ {...form}
+ />
+ {index < forms.length - 1 && <Split />}
+ </div>
+ ))}
+ </div>
+ )}
+ {showGeneratedForm && formData && (
+ <SingleRunForm
+ nodeName={nodeName}
+ showBackButton={showBackButton}
+ handleBack={handleHideGeneratedForm}
+ data={formData}
+ onSubmit={handleHumanInputFormSubmit}
+ />
+ )}
+ {!showGeneratedForm && (
+ <div className="mt-4 flex justify-between space-x-2 px-4">
+ {!isHumanInput && (
+ <Button disabled={!isFileLoaded} variant="primary" className="w-0 grow space-x-2" onClick={handleRunOrGenerateForm}>
+ <div>{t(`${i18nPrefix}.startRun`, { ns: 'workflow' })}</div>
+ </Button>
+ )}
+ {isHumanInput && (
+ <Button disabled={!isFileLoaded} variant="primary" className="w-0 grow space-x-2" onClick={handleRunOrGenerateForm}>
+ <div>{t('nodes.humanInput.singleRun.button', { ns: 'workflow' })}</div>
+ </Button>
+ )}
+ </div>
+ )}
</div>
</PanelWrap>
)
diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
index 2f83945dc2d..867221ea317 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
@@ -15,6 +15,7 @@ import type { QuestionClassifierNodeType } from '../../../question-classifier/ty
import type { TemplateTransformNodeType } from '../../../template-transform/types'
import type { ToolNodeType } from '../../../tool/types'
import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'
+import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
import type { CaseItem, Condition } from '@/app/components/workflow/nodes/if-else/types'
import type { Field as StructField } from '@/app/components/workflow/nodes/llm/types'
import type { StartNodeType } from '@/app/components/workflow/nodes/start/types'
@@ -41,6 +42,7 @@ import {
FILE_STRUCT,
getGlobalVars,
HTTP_REQUEST_OUTPUT_STRUCT,
+ HUMAN_INPUT_OUTPUT_STRUCT,
KNOWLEDGE_RETRIEVAL_OUTPUT_STRUCT,
LLM_OUTPUT_STRUCT,
PARAMETER_EXTRACTOR_COMMON_STRUCT,
@@ -50,6 +52,7 @@ import {
TOOL_OUTPUT_STRUCT,
} from '@/app/components/workflow/constants'
import DataSourceNodeDefault from '@/app/components/workflow/nodes/data-source/default'
+import HumanInputNodeDefault from '@/app/components/workflow/nodes/human-input/default'
import ToolNodeDefault from '@/app/components/workflow/nodes/tool/default'
import PluginTriggerNodeDefault from '@/app/components/workflow/nodes/trigger-plugin/default'
import {
@@ -630,6 +633,17 @@ const formatItem = (
break
}
+ case BlockEnum.HumanInput: {
+ const outputSchema = HumanInputNodeDefault.getOutputVars?.(
+ data as HumanInputNodeType,
+ allPluginInfoList,
+ [],
+ { schemaTypeDefinitions },
+ ) || []
+ res.vars = [...outputSchema, ...HUMAN_INPUT_OUTPUT_STRUCT]
+ break
+ }
+
case 'env': {
res.vars = data.envList.map((env: EnvironmentVariable) => {
return {
@@ -1487,6 +1501,13 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {
res = valueSelectors
break
}
+
+ case BlockEnum.HumanInput: {
+ const payload = data as HumanInputNodeType
+ const formContent = payload.form_content
+ res = matchNotSystemVars([formContent])
+ break
+ }
}
return res || []
}
@@ -1585,6 +1606,11 @@ export const getNodeUsedVarPassToServerKey = (
res = 'query'
break
}
+
+ case BlockEnum.HumanInput: {
+ res = `#${valueSelector.join('.')}#`
+ break
+ }
}
return res
}
@@ -1921,6 +1947,15 @@ export const updateNodeVars = (
payload.variable = newVarSelector
break
}
+ case BlockEnum.HumanInput: {
+ const payload = data as HumanInputNodeType
+ payload.form_content = replaceOldVarInText(
+ payload.form_content,
+ oldVarSelector,
+ newVarSelector,
+ )
+ break
+ }
}
})
return newNode
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx
index 6dfcbaf4d81..8ff42bc5c41 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx
@@ -71,6 +71,8 @@ type Props = {
availableNodes?: Node[]
availableVars?: NodeOutPutVar[]
isAddBtnTrigger?: boolean
+ trigger?: React.ReactNode
+ isJustShowValue?: boolean
schema?: Partial<CredentialFormSchema>
valueTypePlaceHolder?: string
isInTable?: boolean
@@ -103,6 +105,8 @@ const VarReferencePicker: FC<Props> = ({
isFilterFileVar,
availableNodes: passedInAvailableNodes,
availableVars: passedInAvailableVars,
+ trigger,
+ isJustShowValue,
isAddBtnTrigger,
schema,
valueTypePlaceHolder,
@@ -423,204 +427,207 @@ const VarReferencePicker: FC<Props> = ({
onOpenChange={setOpen}
placement={isAddBtnTrigger ? 'bottom-end' : 'bottom-start'}
>
- <WrapElem
- onClick={() => {
- if (readonly)
- return
- if (!isConstant)
- setOpen(!open)
- else
- setControlFocus(Date.now())
- }}
- className="group/picker-trigger-wrap relative !flex"
- >
- <>
- {isAddBtnTrigger
- ? (
- <div>
- <AddButton onClick={noop}></AddButton>
- </div>
- )
- : (
- <div ref={!isSupportConstantValue ? triggerRef : null} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'group/wrap relative flex h-8 w-full items-center', !isSupportConstantValue && 'rounded-lg bg-components-input-bg-normal p-1', isInTable && 'border-none bg-transparent', readonly && 'bg-components-input-bg-disabled')}>
- {isSupportConstantValue
- ? (
- <div
- onClick={(e) => {
- e.stopPropagation()
- setOpen(false)
- setControlFocus(Date.now())
- }}
- className="mr-1 flex h-full items-center space-x-1"
- >
- <TypeSelector
- noLeft
- trigger={(
- <div className="radius-md flex h-8 items-center bg-components-input-bg-normal px-2">
- <div className="system-sm-regular mr-1 text-components-input-text-filled">{varKindTypes.find(item => item.value === varKindType)?.label}</div>
- <RiArrowDownSLine className="h-4 w-4 text-text-quaternary" />
- </div>
- )}
- popupClassName="top-8"
+ {!!trigger && <PortalToFollowElemTrigger onClick={() => setOpen(!open)}>{trigger}</PortalToFollowElemTrigger>}
+ {!trigger && (
+ <WrapElem
+ onClick={() => {
+ if (readonly)
+ return
+ if (!isConstant)
+ setOpen(!open)
+ else
+ setControlFocus(Date.now())
+ }}
+ className="group/picker-trigger-wrap relative !flex"
+ >
+ <>
+ {isAddBtnTrigger
+ ? (
+ <div>
+ <AddButton onClick={noop}></AddButton>
+ </div>
+ )
+ : (
+ <div ref={!isSupportConstantValue ? triggerRef : null} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'group/wrap relative flex h-8 w-full items-center', !isSupportConstantValue && 'rounded-lg bg-components-input-bg-normal p-1', isInTable && 'border-none bg-transparent', readonly && 'bg-components-input-bg-disabled', isJustShowValue && 'h-6 bg-transparent p-0')}>
+ {isSupportConstantValue
+ ? (
+ <div
+ onClick={(e) => {
+ e.stopPropagation()
+ setOpen(false)
+ setControlFocus(Date.now())
+ }}
+ className="mr-1 flex h-full items-center space-x-1"
+ >
+ <TypeSelector
+ noLeft
+ trigger={(
+ <div className="radius-md flex h-8 items-center bg-components-input-bg-normal px-2">
+ <div className="system-sm-regular mr-1 text-components-input-text-filled">{varKindTypes.find(item => item.value === varKindType)?.label}</div>
+ <RiArrowDownSLine className="h-4 w-4 text-text-quaternary" />
+ </div>
+ )}
+ popupClassName="top-8"
+ readonly={readonly}
+ value={varKindType}
+ options={varKindTypes}
+ onChange={handleVarKindTypeChange}
+ showChecked
+ />
+ </div>
+ )
+ : (!hasValue && (
+ <div className="ml-1.5 mr-1">
+ <Variable02 className={`h-4 w-4 ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'}`} />
+ </div>
+ ))}
+ {isConstant
+ ? (
+ <ConstantField
+ value={value as string}
+ onChange={onChange as ((value: string | number, varKindType: VarKindType, varInfo?: Var) => void)}
+ schema={schemaWithDynamicSelect as CredentialFormSchema}
readonly={readonly}
- value={varKindType}
- options={varKindTypes}
- onChange={handleVarKindTypeChange}
- showChecked
+ isLoading={isLoading}
/>
- </div>
- )
- : (!hasValue && (
- <div className="ml-1.5 mr-1">
- <Variable02 className={`h-4 w-4 ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'}`} />
- </div>
- ))}
- {isConstant
- ? (
- <ConstantField
- value={value as string}
- onChange={onChange as ((value: string | number, varKindType: VarKindType, varInfo?: Var) => void)}
- schema={schemaWithDynamicSelect as CredentialFormSchema}
- readonly={readonly}
- isLoading={isLoading}
- />
- )
- : (
- <VarPickerWrap
- onClick={() => {
- if (readonly)
- return
- if (!isConstant)
- setOpen(!open)
- else
- setControlFocus(Date.now())
- }}
- className="h-full grow"
- >
- <div ref={isSupportConstantValue ? triggerRef : null} className={cn('h-full', isSupportConstantValue && 'flex items-center rounded-lg bg-components-panel-bg py-1 pl-1')}>
- <Tooltip noDecoration={isShowAPart} popupContent={tooltipPopup}>
- <div className={cn('h-full items-center rounded-[5px] px-1.5', hasValue ? 'inline-flex bg-components-badge-white-to-dark' : 'flex')}>
- {hasValue
- ? (
- <>
- {isShowNodeName && !isEnv && !isChatVar && !isGlobal && !isRagVar && (
- <div
- className="flex items-center"
- onClick={(e) => {
- if (e.metaKey || e.ctrlKey) {
- e.stopPropagation()
- handleVariableJump(outputVarNode?.id)
- }
- }}
- >
- <div className="h-3 px-[1px]">
- {outputVarNode?.type && (
- <VarBlockIcon
- className="!text-text-primary"
- type={outputVarNode.type}
- />
- )}
+ )
+ : (
+ <VarPickerWrap
+ onClick={() => {
+ if (readonly)
+ return
+ if (!isConstant)
+ setOpen(!open)
+ else
+ setControlFocus(Date.now())
+ }}
+ className="h-full grow"
+ >
+ <div ref={isSupportConstantValue ? triggerRef : null} className={cn('h-full', isSupportConstantValue && 'flex items-center rounded-lg bg-components-panel-bg py-1 pl-1')}>
+ <Tooltip noDecoration={isShowAPart} popupContent={tooltipPopup}>
+ <div className={cn('h-full items-center rounded-[5px] px-1.5', hasValue ? 'inline-flex bg-components-badge-white-to-dark' : 'flex')}>
+ {hasValue
+ ? (
+ <>
+ {isShowNodeName && !isEnv && !isChatVar && !isGlobal && !isRagVar && (
+ <div
+ className="flex items-center"
+ onClick={(e) => {
+ if (e.metaKey || e.ctrlKey) {
+ e.stopPropagation()
+ handleVariableJump(outputVarNode?.id)
+ }
+ }}
+ >
+ <div className="h-3 px-[1px]">
+ {outputVarNode?.type && (
+ <VarBlockIcon
+ className="!text-text-primary"
+ type={outputVarNode.type}
+ />
+ )}
+ </div>
+ <div
+ className="mx-0.5 truncate text-xs font-medium text-text-secondary"
+ title={outputVarNode?.title}
+ style={{
+ maxWidth: maxNodeNameWidth,
+ }}
+ >
+ {outputVarNode?.title}
+ </div>
+ <Line3 className="mr-0.5"></Line3>
+ </div>
+ )}
+ {isShowAPart && (
+ <div className="flex items-center">
+ <RiMoreLine className="h-3 w-3 text-text-secondary" />
+ <Line3 className="mr-0.5 text-divider-deep"></Line3>
</div>
+ )}
+ <div className="flex items-center text-text-accent">
+ {isLoading && <RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />}
+ <VariableIconWithColor
+ variables={value as ValueSelector}
+ variableCategory={variableCategory}
+ isExceptionVariable={isException}
+ />
<div
- className="mx-0.5 truncate text-xs font-medium text-text-secondary"
- title={outputVarNode?.title}
+ className={cn('ml-0.5 truncate text-xs font-medium', isEnv && '!text-text-secondary', isChatVar && 'text-util-colors-teal-teal-700', isException && 'text-text-warning', isGlobal && 'text-util-colors-orange-orange-600')}
+ title={varName}
style={{
- maxWidth: maxNodeNameWidth,
+ maxWidth: maxVarNameWidth,
}}
>
- {outputVarNode?.title}
+ {varName}
</div>
- <Line3 className="mr-0.5"></Line3>
- </div>
- )}
- {isShowAPart && (
- <div className="flex items-center">
- <RiMoreLine className="h-3 w-3 text-text-secondary" />
- <Line3 className="mr-0.5 text-divider-deep"></Line3>
</div>
- )}
- <div className="flex items-center text-text-accent">
- {isLoading && <RiLoader4Line className="h-3.5 w-3.5 animate-spin text-text-secondary" />}
- <VariableIconWithColor
- variables={value as ValueSelector}
- variableCategory={variableCategory}
- isExceptionVariable={isException}
- />
<div
- className={cn('ml-0.5 truncate text-xs font-medium', isEnv && '!text-text-secondary', isChatVar && 'text-util-colors-teal-teal-700', isException && 'text-text-warning', isGlobal && 'text-util-colors-orange-orange-600')}
- title={varName}
+ className="system-xs-regular ml-0.5 truncate text-center capitalize text-text-tertiary"
+ title={type}
style={{
- maxWidth: maxVarNameWidth,
+ maxWidth: maxTypeWidth,
}}
>
- {varName}
+ {type}
</div>
+ {!isValidVar && <RiErrorWarningFill className="ml-0.5 h-3 w-3 text-text-destructive" />}
+ </>
+ )
+ : (
+ <div className={`overflow-hidden ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'} system-sm-regular text-ellipsis`}>
+ {isLoading
+ ? (
+ <div className="flex items-center">
+ <RiLoader4Line className="mr-1 h-3.5 w-3.5 animate-spin text-text-secondary" />
+ <span>{placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })}</span>
+ </div>
+ )
+ : (
+ placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })
+ )}
</div>
- <div
- className="system-xs-regular ml-0.5 truncate text-center capitalize text-text-tertiary"
- title={type}
- style={{
- maxWidth: maxTypeWidth,
- }}
- >
- {type}
- </div>
- {!isValidVar && <RiErrorWarningFill className="ml-0.5 h-3 w-3 text-text-destructive" />}
- </>
- )
- : (
- <div className={`overflow-hidden ${readonly ? 'text-components-input-text-disabled' : 'text-components-input-text-placeholder'} system-sm-regular text-ellipsis`}>
- {isLoading
- ? (
- <div className="flex items-center">
- <RiLoader4Line className="mr-1 h-3.5 w-3.5 animate-spin text-text-secondary" />
- <span>{placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })}</span>
- </div>
- )
- : (
- placeholder ?? t('common.setVarValuePlaceholder', { ns: 'workflow' })
- )}
- </div>
- )}
- </div>
- </Tooltip>
- </div>
-
- </VarPickerWrap>
- )}
- {(hasValue && !readonly && !isInTable) && (
- <div
- className="group invisible absolute right-1 top-[50%] h-5 translate-y-[-50%] cursor-pointer rounded-md p-1 hover:bg-state-base-hover group-hover/wrap:visible"
- onClick={handleClearVar}
- >
- <RiCloseLine className="h-3.5 w-3.5 text-text-tertiary group-hover:text-text-secondary" />
- </div>
- )}
- {!hasValue && valueTypePlaceHolder && (
- <Badge
- className=" absolute right-1 top-[50%] translate-y-[-50%] capitalize"
- text={valueTypePlaceHolder}
- uppercase={false}
- />
- )}
- </div>
- )}
- {!readonly && isInTable && (
- <RemoveButton
- className="absolute right-1 top-0.5 hidden group-hover/picker-trigger-wrap:block"
- onClick={() => onRemove?.()}
- />
- )}
-
- {!hasValue && typePlaceHolder && (
- <Badge
- className="absolute right-2 top-1.5"
- text={typePlaceHolder}
- uppercase={false}
- />
- )}
- </>
- </WrapElem>
+ )}
+ </div>
+ </Tooltip>
+ </div>
+
+ </VarPickerWrap>
+ )}
+ {(hasValue && !readonly && !isInTable && !isJustShowValue) && (
+ <div
+ className="group invisible absolute right-1 top-[50%] h-5 translate-y-[-50%] cursor-pointer rounded-md p-1 hover:bg-state-base-hover group-hover/wrap:visible"
+ onClick={handleClearVar}
+ >
+ <RiCloseLine className="h-3.5 w-3.5 text-text-tertiary group-hover:text-text-secondary" />
+ </div>
+ )}
+ {!hasValue && valueTypePlaceHolder && (
+ <Badge
+ className=" absolute right-1 top-[50%] translate-y-[-50%] capitalize"
+ text={valueTypePlaceHolder}
+ uppercase={false}
+ />
+ )}
+ </div>
+ )}
+ {!readonly && isInTable && (
+ <RemoveButton
+ className="absolute right-1 top-0.5 hidden group-hover/picker-trigger-wrap:block"
+ onClick={() => onRemove?.()}
+ />
+ )}
+
+ {!hasValue && typePlaceHolder && (
+ <Badge
+ className="absolute right-2 top-1.5"
+ text={typePlaceHolder}
+ uppercase={false}
+ />
+ )}
+ </>
+ </WrapElem>
+ )}
<PortalToFollowElemContent
style={{
zIndex: zIndex || 100,
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx
index d44f560e08e..34d2b5e4f93 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx
@@ -149,6 +149,7 @@ const Item: FC<ItemProps> = ({
}, [isHovering])
const handleChosen = (e: React.MouseEvent) => {
e.stopPropagation()
+ e.nativeEvent.stopImmediatePropagation()
if (!isSupportFileVar && isFile)
return
@@ -189,7 +190,11 @@ const Item: FC<ItemProps> = ({
className,
)}
onClick={handleChosen}
- onMouseDown={e => e.preventDefault()}
+ onMouseDown={(e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ e.nativeEvent.stopImmediatePropagation()
+ }}
>
<div className="flex w-0 grow items-center">
{!isFlat && (
diff --git a/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx b/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx
index 032746ad5bd..18d563ca01c 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx
@@ -27,7 +27,7 @@ const VariableLabel = ({
rightSlot,
}: VariablePayload) => {
const varColorClassName = useVarColor(variables, isExceptionVariable)
- const isHideNodeLabel = !(isENV(variables) || isConversationVar(variables) || isGlobalVar(variables) || isRagVariableVar(variables))
+ const isShowNodeLabel = !(isENV(variables) || isConversationVar(variables) || isGlobalVar(variables) || isRagVariableVar(variables))
return (
<div
className={cn(
@@ -37,7 +37,7 @@ const VariableLabel = ({
onClick={onClick}
ref={ref}
>
- { isHideNodeLabel && (
+ {isShowNodeLabel && (
<VariableNodeLabel
nodeType={nodeType}
nodeTitle={nodeTitle}
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx
index c834f29ab38..57fea139f2b 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx
@@ -324,7 +324,7 @@ const BasePanel: FC<BasePanelProps> = ({
const currentDataSource = useMemo(() => {
if (data.type === BlockEnum.DataSource && data.provider_type !== DataSourceClassification.localFile)
return dataSourceList?.find(item => item.plugin_id === data.plugin_id)
- }, [dataSourceList, data.provider_id, data.type, data.provider_type])
+ }, [data.type, data.provider_type, data.plugin_id, dataSourceList])
const handleAuthorizationItemClick = useCallback((credential_id: string) => {
handleNodeDataUpdateWithSyncDraft({
@@ -445,6 +445,7 @@ const BasePanel: FC<BasePanelProps> = ({
{...passedLogParams}
existVarValuesInForms={getExistVarValuesInForms(singleRunParams?.forms as any)}
filteredExistVarForms={getFilteredExistVarForms(singleRunParams?.forms as any)}
+ handleAfterHumanInputStepRun={handleAfterCustomSingleRun}
/>
)}
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts
index 0de98db0329..dcbf392a8f7 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts
@@ -15,6 +15,7 @@ import useVariableAssignerSingleRunFormParams from '@/app/components/workflow/no
import useCodeSingleRunFormParams from '@/app/components/workflow/nodes/code/use-single-run-form-params'
import useDocExtractorSingleRunFormParams from '@/app/components/workflow/nodes/document-extractor/use-single-run-form-params'
import useHttpRequestSingleRunFormParams from '@/app/components/workflow/nodes/http/use-single-run-form-params'
+import useHumanInputSingleRunFormParams from '@/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params'
import useIfElseSingleRunFormParams from '@/app/components/workflow/nodes/if-else/use-single-run-form-params'
import useIterationSingleRunFormParams from '@/app/components/workflow/nodes/iteration/use-single-run-form-params'
import useKnowledgeBaseSingleRunFormParams from '@/app/components/workflow/nodes/knowledge-base/use-single-run-form-params'
@@ -22,15 +23,16 @@ import useKnowledgeRetrievalSingleRunFormParams from '@/app/components/workflow/
import useLLMSingleRunFormParams from '@/app/components/workflow/nodes/llm/use-single-run-form-params'
import useLoopSingleRunFormParams from '@/app/components/workflow/nodes/loop/use-single-run-form-params'
import useParameterExtractorSingleRunFormParams from '@/app/components/workflow/nodes/parameter-extractor/use-single-run-form-params'
-import useQuestionClassifierSingleRunFormParams from '@/app/components/workflow/nodes/question-classifier/use-single-run-form-params'
+import useQuestionClassifierSingleRunFormParams from '@/app/components/workflow/nodes/question-classifier/use-single-run-form-params'
import useStartSingleRunFormParams from '@/app/components/workflow/nodes/start/use-single-run-form-params'
import useTemplateTransformSingleRunFormParams from '@/app/components/workflow/nodes/template-transform/use-single-run-form-params'
-import useToolGetDataForCheckMore from '@/app/components/workflow/nodes/tool/use-get-data-for-check-more'
+import useToolGetDataForCheckMore from '@/app/components/workflow/nodes/tool/use-get-data-for-check-more'
import useToolSingleRunFormParams from '@/app/components/workflow/nodes/tool/use-single-run-form-params'
import useTriggerPluginGetDataForCheckMore from '@/app/components/workflow/nodes/trigger-plugin/use-check-params'
import useVariableAggregatorSingleRunFormParams from '@/app/components/workflow/nodes/variable-assigner/use-single-run-form-params'
+
import { useStore, useWorkflowStore } from '@/app/components/workflow/store'
import { BlockEnum } from '@/app/components/workflow/types'
import { isSupportCustomRunForm } from '@/app/components/workflow/utils'
@@ -63,6 +65,7 @@ const singleRunFormParamsHooks: Record<BlockEnum, any> = {
[BlockEnum.IterationStart]: undefined,
[BlockEnum.LoopStart]: undefined,
[BlockEnum.LoopEnd]: undefined,
+ [BlockEnum.HumanInput]: useHumanInputSingleRunFormParams,
[BlockEnum.DataSource]: undefined,
[BlockEnum.DataSourceEmpty]: undefined,
[BlockEnum.TriggerWebhook]: undefined,
@@ -100,6 +103,7 @@ const getDataForCheckMoreHooks: Record<BlockEnum, any> = {
[BlockEnum.Assigner]: undefined,
[BlockEnum.LoopStart]: undefined,
[BlockEnum.LoopEnd]: undefined,
+ [BlockEnum.HumanInput]: undefined,
[BlockEnum.DataSource]: undefined,
[BlockEnum.DataSourceEmpty]: undefined,
[BlockEnum.KnowledgeBase]: undefined,
@@ -129,6 +133,7 @@ const useLastRun = <T>({
const isLoopNode = blockType === BlockEnum.Loop
const isAggregatorNode = blockType === BlockEnum.VariableAggregator
const isCustomRunNode = isSupportCustomRunForm(blockType)
+ const isHumanInputNode = blockType === BlockEnum.HumanInput
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
const {
getData: getDataForCheckMore,
@@ -338,7 +343,7 @@ const useLastRun = <T>({
return
if (blockType === BlockEnum.TriggerWebhook || blockType === BlockEnum.TriggerPlugin || blockType === BlockEnum.TriggerSchedule)
setShowVariableInspectPanel(true)
- if (isCustomRunNode) {
+ if (isCustomRunNode || isHumanInputNode) {
showSingleRun()
return
}
diff --git a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts
index d2d7b6b6d99..06843eacef6 100644
--- a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts
+++ b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts
@@ -24,6 +24,7 @@ import Assigner from '@/app/components/workflow/nodes/assigner/default'
import CodeDefault from '@/app/components/workflow/nodes/code/default'
import DocumentExtractorDefault from '@/app/components/workflow/nodes/document-extractor/default'
import HTTPDefault from '@/app/components/workflow/nodes/http/default'
+import HumanInputDefault from '@/app/components/workflow/nodes/human-input/default'
import IfElseDefault from '@/app/components/workflow/nodes/if-else/default'
import IterationDefault from '@/app/components/workflow/nodes/iteration/default'
import KnowledgeRetrievalDefault from '@/app/components/workflow/nodes/knowledge-retrieval/default'
@@ -69,6 +70,7 @@ const { checkValid: checkParameterExtractorValid } = ParameterExtractorDefault
const { checkValid: checkIterationValid } = IterationDefault
const { checkValid: checkDocumentExtractorValid } = DocumentExtractorDefault
const { checkValid: checkLoopValid } = LoopDefault
+const { checkValid: checkHumanInputValid } = HumanInputDefault
// eslint-disable-next-line ts/no-unsafe-function-type
const checkValidFns: Partial<Record<BlockEnum, Function>> = {
@@ -86,6 +88,7 @@ const checkValidFns: Partial<Record<BlockEnum, Function>> = {
[BlockEnum.Iteration]: checkIterationValid,
[BlockEnum.DocExtractor]: checkDocumentExtractorValid,
[BlockEnum.Loop]: checkLoopValid,
+ [BlockEnum.HumanInput]: checkHumanInputValid,
}
type RequestError = {
@@ -313,20 +316,7 @@ const useOneStepRun = <T>({
invalidateSysVarValues()
invalidateConversationVarValues() // loop, iteration, variable assigner node can update the conversation variables, but to simple the logic(some nodes may also can update in the future), all nodes refresh.
}
- }, [
- isRunAfterSingleRun,
- runningStatus,
- flowId,
- id,
- store,
- appendNodeInspectVars,
- updateNodeInspectRunningState,
- invalidLastRun,
- isStartNode,
- isTriggerNode,
- invalidateSysVarValues,
- invalidateConversationVarValues,
- ])
+ }, [isRunAfterSingleRun, runningStatus, flowType, flowId, id, store, appendNodeInspectVars, updateNodeInspectRunningState, invalidLastRun, isStartNode, isTriggerNode, invalidateSysVarValues, invalidateConversationVarValues])
const { handleNodeDataUpdate }: { handleNodeDataUpdate: (data: any) => void } = useNodeDataUpdate()
const setNodeRunning = () => {
diff --git a/web/app/components/workflow/nodes/_base/node.tsx b/web/app/components/workflow/nodes/_base/node.tsx
index 47f5028054c..dbecd2d817d 100644
--- a/web/app/components/workflow/nodes/_base/node.tsx
+++ b/web/app/components/workflow/nodes/_base/node.tsx
@@ -9,6 +9,7 @@ import {
RiCheckboxCircleFill,
RiErrorWarningFill,
RiLoader2Line,
+ RiPauseCircleFill,
} from '@remixicon/react'
import {
cloneElement,
@@ -107,7 +108,7 @@ const BaseNode: FC<BaseNodeProps> = ({
showExceptionBorder,
} = useMemo(() => {
return {
- showRunningBorder: data._runningStatus === NodeRunningStatus.Running && !showSelectedBorder,
+ showRunningBorder: (data._runningStatus === NodeRunningStatus.Running || data._runningStatus === NodeRunningStatus.Paused) && !showSelectedBorder,
showSuccessBorder: (data._runningStatus === NodeRunningStatus.Succeeded || hasVarValue) && !showSelectedBorder,
showFailedBorder: data._runningStatus === NodeRunningStatus.Failed && !showSelectedBorder,
showExceptionBorder: data._runningStatus === NodeRunningStatus.Exception && !showSelectedBorder,
@@ -221,7 +222,7 @@ const BaseNode: FC<BaseNodeProps> = ({
)
}
{
- data.type !== BlockEnum.IfElse && data.type !== BlockEnum.QuestionClassifier && !data._isCandidate && (
+ data.type !== BlockEnum.IfElse && data.type !== BlockEnum.QuestionClassifier && data.type !== BlockEnum.HumanInput && !data._isCandidate && (
<NodeSourceHandle
id={id}
data={data}
@@ -287,15 +288,27 @@ const BaseNode: FC<BaseNodeProps> = ({
!!(data.type === BlockEnum.Loop && data._loopIndex) && LoopIndex
}
{
- isLoading
- ? <RiLoader2Line className="h-3.5 w-3.5 animate-spin text-text-accent" />
- : data._runningStatus === NodeRunningStatus.Failed
- ? <RiErrorWarningFill className="h-3.5 w-3.5 text-text-destructive" />
- : data._runningStatus === NodeRunningStatus.Exception
- ? <RiAlertFill className="h-3.5 w-3.5 text-text-warning-secondary" />
- : (data._runningStatus === NodeRunningStatus.Succeeded || hasVarValue)
- ? <RiCheckboxCircleFill className="h-3.5 w-3.5 text-text-success" />
- : null
+ isLoading && <RiLoader2Line className="h-3.5 w-3.5 animate-spin text-text-accent" />
+ }
+ {
+ !isLoading && data._runningStatus === NodeRunningStatus.Failed && (
+ <RiErrorWarningFill className="h-3.5 w-3.5 text-text-destructive" />
+ )
+ }
+ {
+ !isLoading && data._runningStatus === NodeRunningStatus.Exception && (
+ <RiAlertFill className="h-3.5 w-3.5 text-text-warning-secondary" />
+ )
+ }
+ {
+ !isLoading && (data._runningStatus === NodeRunningStatus.Succeeded || hasVarValue) && (
+ <RiCheckboxCircleFill className="h-3.5 w-3.5 text-text-success" />
+ )
+ }
+ {
+ !isLoading && data._runningStatus === NodeRunningStatus.Paused && (
+ <RiPauseCircleFill className="h-3.5 w-3.5 text-text-warning-secondary" />
+ )
}
</div>
{
diff --git a/web/app/components/workflow/nodes/components.ts b/web/app/components/workflow/nodes/components.ts
index 87c0066d150..ec1e4422bf9 100644
--- a/web/app/components/workflow/nodes/components.ts
+++ b/web/app/components/workflow/nodes/components.ts
@@ -16,6 +16,8 @@ import EndNode from './end/node'
import EndPanel from './end/panel'
import HttpNode from './http/node'
import HttpPanel from './http/panel'
+import HumanInputNode from './human-input/node'
+import HumanInputPanel from './human-input/panel'
import IfElseNode from './if-else/node'
import IfElsePanel from './if-else/panel'
import IterationNode from './iteration/node'
@@ -72,6 +74,7 @@ export const NodeComponentMap: Record<string, ComponentType<any>> = {
[BlockEnum.Agent]: AgentNode,
[BlockEnum.DataSource]: DataSourceNode,
[BlockEnum.KnowledgeBase]: KnowledgeBaseNode,
+ [BlockEnum.HumanInput]: HumanInputNode,
[BlockEnum.TriggerSchedule]: TriggerScheduleNode,
[BlockEnum.TriggerWebhook]: TriggerWebhookNode,
[BlockEnum.TriggerPlugin]: TriggerPluginNode,
@@ -100,6 +103,7 @@ export const PanelComponentMap: Record<string, ComponentType<any>> = {
[BlockEnum.Agent]: AgentPanel,
[BlockEnum.DataSource]: DataSourcePanel,
[BlockEnum.KnowledgeBase]: KnowledgeBasePanel,
+ [BlockEnum.HumanInput]: HumanInputPanel,
[BlockEnum.TriggerSchedule]: TriggerSchedulePanel,
[BlockEnum.TriggerWebhook]: TriggerWebhookPanel,
[BlockEnum.TriggerPlugin]: TriggerPluginPanel,
diff --git a/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx b/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx
new file mode 100644
index 00000000000..35049f683b2
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/add-input-field.tsx
@@ -0,0 +1,27 @@
+'use client'
+import type { FC } from 'react'
+import type { FormInputItem } from '../types'
+import * as React from 'react'
+import InputField from '@/app/components/base/prompt-editor/plugins/hitl-input-block/input-field'
+
+type Props = {
+ nodeId: string
+ onSave: (newPayload: FormInputItem) => void
+ onCancel: () => void
+}
+
+const AddInputField: FC<Props> = ({
+ nodeId,
+ onSave,
+ onCancel,
+}) => {
+ return (
+ <InputField
+ nodeId={nodeId}
+ isEdit={false}
+ onChange={onSave}
+ onCancel={onCancel}
+ />
+ )
+}
+export default React.memo(AddInputField)
diff --git a/web/app/components/workflow/nodes/human-input/components/button-style-dropdown.tsx b/web/app/components/workflow/nodes/human-input/components/button-style-dropdown.tsx
new file mode 100644
index 00000000000..d3896049b50
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/button-style-dropdown.tsx
@@ -0,0 +1,111 @@
+import type { FC } from 'react'
+import {
+ RiFontSize,
+} from '@remixicon/react'
+import * as React from 'react'
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import {
+ PortalToFollowElem,
+ PortalToFollowElemContent,
+ PortalToFollowElemTrigger,
+} from '@/app/components/base/portal-to-follow-elem'
+import { cn } from '@/utils/classnames'
+import { UserActionButtonType } from '../types'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ text: string
+ data: UserActionButtonType
+ onChange: (state: UserActionButtonType) => void
+ readonly?: boolean
+}
+
+const ButtonStyleDropdown: FC<Props> = ({
+ text = 'Button Text',
+ data,
+ onChange,
+ readonly,
+}) => {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const currentStyle = useMemo(() => {
+ switch (data) {
+ case UserActionButtonType.Primary:
+ return 'primary'
+ case UserActionButtonType.Default:
+ return 'secondary'
+ case UserActionButtonType.Accent:
+ return 'secondary-accent'
+ default:
+ return 'ghost'
+ }
+ }, [data])
+
+ return (
+ <PortalToFollowElem
+ open={open && !readonly}
+ onOpenChange={setOpen}
+ placement="bottom-end"
+ offset={{
+ mainAxis: 4,
+ crossAxis: 44,
+ }}
+ >
+ <PortalToFollowElemTrigger onClick={() => !readonly && setOpen(v => !v)}>
+ <div className={cn('flex items-center justify-center rounded-lg bg-components-button-tertiary-bg p-1', !readonly && 'cursor-pointer hover:bg-components-button-tertiary-bg-hover', open && 'bg-components-button-tertiary-bg-hover')}>
+ <Button size="small" className="pointer-events-none px-1" variant={currentStyle}>
+ <RiFontSize className="h-4 w-4" />
+ </Button>
+ </div>
+ </PortalToFollowElemTrigger>
+ <PortalToFollowElemContent style={{ zIndex: 1000 }}>
+ <div className="rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-4 shadow-lg backdrop-blur-sm">
+ <div className="system-md-medium text-text-primary">{t(`${i18nPrefix}.userActions.chooseStyle`, { ns: 'workflow' })}</div>
+ <div className="mt-2 flex w-[324px] flex-wrap gap-1">
+ <div
+ className={cn(
+ 'box-border flex h-[80px] w-[160px] cursor-pointer items-center justify-center rounded-lg border-[1.5px] border-transparent bg-background-section hover:bg-background-section-burn',
+ data === UserActionButtonType.Primary && 'border-components-option-card-option-selected-border',
+ )}
+ onClick={() => onChange(UserActionButtonType.Primary)}
+ >
+ <Button variant="primary" className="pointer-events-none">{text}</Button>
+ </div>
+ <div
+ className={cn(
+ 'box-border flex h-[80px] w-[160px] cursor-pointer items-center justify-center rounded-lg border-[1.5px] border-transparent bg-background-section hover:bg-background-section-burn',
+ data === UserActionButtonType.Default && 'border-components-option-card-option-selected-border',
+ )}
+ onClick={() => onChange(UserActionButtonType.Default)}
+ >
+ <Button variant="secondary" className="pointer-events-none">{text}</Button>
+ </div>
+ <div
+ className={cn(
+ 'box-border flex h-[80px] w-[160px] cursor-pointer items-center justify-center rounded-lg border-[1.5px] border-transparent bg-background-section hover:bg-background-section-burn',
+ data === UserActionButtonType.Accent && 'border-components-option-card-option-selected-border',
+ )}
+ onClick={() => onChange(UserActionButtonType.Accent)}
+ >
+ <Button variant="secondary-accent" className="pointer-events-none">{text}</Button>
+ </div>
+ <div
+ className={cn(
+ 'box-border flex h-[80px] w-[160px] cursor-pointer items-center justify-center rounded-lg border-[1.5px] border-transparent bg-background-section hover:bg-background-section-burn',
+ data === UserActionButtonType.Ghost && 'border-components-option-card-option-selected-border',
+ )}
+ onClick={() => onChange(UserActionButtonType.Ghost)}
+ >
+ <Button variant="ghost" className="pointer-events-none">{text}</Button>
+ </div>
+ </div>
+ </div>
+ </PortalToFollowElemContent>
+ </PortalToFollowElem>
+ )
+}
+
+export default ButtonStyleDropdown
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx
new file mode 100644
index 00000000000..4ca1c282902
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/email-configure-modal.tsx
@@ -0,0 +1,176 @@
+import type { EmailConfig } from '../../types'
+import type {
+ Node,
+ NodeOutPutVar,
+} from '@/app/components/workflow/types'
+import { RiBugLine, RiCloseLine } from '@remixicon/react'
+import { noop } from 'es-toolkit/compat'
+import { memo, useCallback, useState } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import Divider from '@/app/components/base/divider'
+import Input from '@/app/components/base/input'
+import Modal from '@/app/components/base/modal'
+import Switch from '@/app/components/base/switch'
+import Toast from '@/app/components/base/toast'
+import { useSelector as useAppContextWithSelector } from '@/context/app-context'
+import MailBodyInput from './mail-body-input'
+import Recipient from './recipient'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type EmailConfigureModalProps = {
+ isShow: boolean
+ onClose: () => void
+ onConfirm: (data: EmailConfig) => void
+ config?: EmailConfig
+ nodesOutputVars?: NodeOutPutVar[]
+ availableNodes?: Node[]
+}
+
+const EmailConfigureModal = ({
+ isShow,
+ onClose,
+ onConfirm,
+ config,
+ nodesOutputVars = [],
+ availableNodes = [],
+}: EmailConfigureModalProps) => {
+ const { t } = useTranslation()
+ const email = useAppContextWithSelector(s => s.userProfile.email)
+ const [recipients, setRecipients] = useState(config?.recipients || { whole_workspace: false, items: [] })
+ const [subject, setSubject] = useState(config?.subject || '')
+ const [body, setBody] = useState(config?.body || '{{#url#}}')
+ const [debugMode, setDebugMode] = useState(config?.debug_mode || false)
+
+ const checkValidConfig = useCallback(() => {
+ if (!subject.trim()) {
+ Toast.notify({
+ type: 'error',
+ message: 'subject is required',
+ })
+ return false
+ }
+ if (!body.trim()) {
+ Toast.notify({
+ type: 'error',
+ message: 'body is required',
+ })
+ return false
+ }
+ if (!/\{\{#url#\}\}/.test(body.trim())) {
+ Toast.notify({
+ type: 'error',
+ message: `body must contain one ${t('promptEditor.requestURL.item.title', { ns: 'common' })}`,
+ })
+ return false
+ }
+ if (!recipients || (recipients.items.length === 0 && !recipients.whole_workspace)) {
+ Toast.notify({
+ type: 'error',
+ message: 'recipients is required',
+ })
+ return false
+ }
+ return true
+ }, [recipients, subject, body, t])
+
+ const handleConfirm = useCallback(() => {
+ if (!checkValidConfig())
+ return
+ onConfirm({
+ recipients,
+ subject,
+ body,
+ debug_mode: debugMode,
+ })
+ }, [checkValidConfig, onConfirm, recipients, subject, body, debugMode])
+
+ return (
+ <Modal
+ isShow={isShow}
+ onClose={noop}
+ className="relative !max-w-[720px] !p-0"
+ >
+ <div className="absolute right-5 top-5 cursor-pointer p-1.5" onClick={onClose}>
+ <RiCloseLine className="h-5 w-5 text-text-tertiary" />
+ </div>
+ <div className="space-y-1 p-6 pb-3">
+ <div className="title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.title`, { ns: 'workflow' })}</div>
+ <div className="system-xs-regular text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.description`, { ns: 'workflow' })}</div>
+ </div>
+ <div className="space-y-5 px-6 py-3">
+ <div>
+ <div className="system-sm-medium mb-1 flex h-6 items-center text-text-secondary">
+ {t(`${i18nPrefix}.deliveryMethod.emailConfigure.subject`, { ns: 'workflow' })}
+ </div>
+ <Input
+ className="w-full"
+ value={subject}
+ onChange={e => setSubject(e.target.value)}
+ placeholder={t(`${i18nPrefix}.deliveryMethod.emailConfigure.subjectPlaceholder`, { ns: 'workflow' })}
+ />
+ </div>
+ <div>
+ <div className="system-sm-medium mb-1 flex h-6 items-center text-text-secondary">
+ {t(`${i18nPrefix}.deliveryMethod.emailConfigure.body`, { ns: 'workflow' })}
+ </div>
+ <MailBodyInput
+ value={body}
+ onChange={setBody}
+ nodesOutputVars={nodesOutputVars}
+ availableNodes={availableNodes}
+ />
+ </div>
+ <div>
+ <div className="system-sm-medium mb-1 flex h-6 items-center text-text-secondary">
+ {t(`${i18nPrefix}.deliveryMethod.emailConfigure.recipient`, { ns: 'workflow' })}
+ </div>
+ <Recipient
+ data={recipients}
+ onChange={setRecipients}
+ />
+ </div>
+ <Divider className="!my-0 !mt-5 !h-px" />
+ <div className="flex items-start justify-between gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-3 pl-2.5 shadow-xs">
+ <div className="rounded-[4px] border border-divider-regular bg-components-icon-bg-orange-dark-solid p-0.5">
+ <RiBugLine className="h-3.5 w-3.5 text-text-primary-on-surface" />
+ </div>
+ <div className="grow space-y-1">
+ <div className="system-sm-medium text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.debugMode`, { ns: 'workflow' })}</div>
+ <div className="body-xs-regular text-text-tertiary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailConfigure.debugModeTip1`}
+ ns="workflow"
+ components={{ email: <span className="body-md-medium text-text-primary">{email}</span> }}
+ values={{ email }}
+ />
+ <div>{t(`${i18nPrefix}.deliveryMethod.emailConfigure.debugModeTip2`, { ns: 'workflow' })}</div>
+ </div>
+ </div>
+ <Switch
+ defaultValue={debugMode}
+ onChange={checked => setDebugMode(checked)}
+ />
+ </div>
+ </div>
+ <div className="flex flex-row-reverse gap-2 p-6 pt-5">
+ <Button
+ variant="primary"
+ className="w-[72px]"
+ onClick={handleConfirm}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ <Button
+ className="w-[72px]"
+ onClick={onClose}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ </div>
+ </Modal>
+ )
+}
+
+export default memo(EmailConfigureModal)
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/index.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/index.tsx
new file mode 100644
index 00000000000..62a0ba0d8b3
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/index.tsx
@@ -0,0 +1,119 @@
+import type { DeliveryMethod, DeliveryMethodType, FormInputItem } from '../../types'
+import type {
+ Node,
+ NodeOutPutVar,
+} from '@/app/components/workflow/types'
+import { produce } from 'immer'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/app/components/base/tooltip'
+import { useNodesSyncDraft } from '@/app/components/workflow/hooks'
+import MethodItem from './method-item'
+import MethodSelector from './method-selector'
+import UpgradeModal from './upgrade-modal'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ nodeId: string
+ value: DeliveryMethod[]
+ nodesOutputVars?: NodeOutPutVar[]
+ availableNodes?: Node[]
+ formContent?: string
+ formInputs?: FormInputItem[]
+ onChange: (value: DeliveryMethod[]) => void
+ readonly?: boolean
+}
+
+const DeliveryMethodForm: React.FC<Props> = ({
+ nodeId,
+ value,
+ nodesOutputVars,
+ availableNodes,
+ formContent,
+ formInputs,
+ onChange,
+ readonly,
+}) => {
+ const { t } = useTranslation()
+ const { handleSyncWorkflowDraft } = useNodesSyncDraft()
+
+ const handleMethodChange = (target: DeliveryMethod) => {
+ const newMethods = produce(value, (draft) => {
+ const index = draft.findIndex(method => method.type === target.type)
+ if (index !== -1)
+ draft[index] = target
+ })
+ onChange(newMethods)
+ handleSyncWorkflowDraft(true, true)
+ }
+
+ const handleMethodAdd = (newMethod: DeliveryMethod) => {
+ const newMethods = [...value, newMethod]
+ onChange(newMethods)
+ }
+
+ const handleMethodDelete = (type: DeliveryMethodType) => {
+ const newMethods = value.filter(method => method.type !== type)
+ onChange(newMethods)
+ }
+
+ const [showUpgradeModal, setShowUpgradeModal] = React.useState(false)
+ const handleShowUpgradeModal = () => {
+ setShowUpgradeModal(true)
+ }
+ const handleCloseUpgradeModal = () => {
+ setShowUpgradeModal(false)
+ }
+
+ return (
+ <div className="px-4 py-2">
+ <div className="mb-1 flex items-center justify-between">
+ <div className="flex items-center gap-0.5">
+ <div className="system-sm-semibold-uppercase text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.title`, { ns: 'workflow' })}</div>
+ <Tooltip
+ popupContent={t(`${i18nPrefix}.deliveryMethod.tooltip`, { ns: 'workflow' })}
+ />
+ </div>
+ {!readonly && (
+ <div className="flex items-center px-1">
+ <MethodSelector
+ data={value}
+ onAdd={handleMethodAdd}
+ onShowUpgradeTip={handleShowUpgradeModal}
+ />
+ </div>
+ )}
+ </div>
+ {!value.length && (
+ <div className="system-xs-regular flex items-center justify-center rounded-[10px] bg-background-section p-3 text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.emptyTip`, { ns: 'workflow' })}</div>
+ )}
+ {value.length > 0 && (
+ <div className="space-y-1">
+ {value.map(method => (
+ <MethodItem
+ nodeId={nodeId}
+ method={method}
+ key={method.id}
+ onChange={handleMethodChange}
+ onDelete={handleMethodDelete}
+ nodesOutputVars={nodesOutputVars}
+ availableNodes={availableNodes}
+ formContent={formContent}
+ formInputs={formInputs}
+ readonly={readonly}
+ />
+ ))}
+ </div>
+ )}
+ {showUpgradeModal && (
+ <UpgradeModal
+ isShow={showUpgradeModal}
+ onClose={handleCloseUpgradeModal}
+ />
+ )}
+ </div>
+ )
+}
+
+export default DeliveryMethodForm
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/mail-body-input.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/mail-body-input.tsx
new file mode 100644
index 00000000000..8e127d932e3
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/mail-body-input.tsx
@@ -0,0 +1,65 @@
+import type {
+ Node,
+ NodeOutPutVar,
+} from '@/app/components/workflow/types'
+import { useTranslation } from 'react-i18next'
+import PromptEditor from '@/app/components/base/prompt-editor'
+import Placeholder from '@/app/components/workflow/nodes/tool/components/mixed-variable-text-input/placeholder'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { cn } from '@/utils/classnames'
+
+type MailBodyInputProps = {
+ readOnly?: boolean
+ nodesOutputVars?: NodeOutPutVar[]
+ availableNodes?: Node[]
+ value?: string
+ onChange?: (text: string) => void
+}
+
+const MailBodyInput = ({
+ readOnly = false,
+ nodesOutputVars,
+ availableNodes = [],
+ value = '',
+ onChange,
+}: MailBodyInputProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <PromptEditor
+ wrapperClassName={cn(
+ 'w-full rounded-lg border border-transparent bg-components-input-bg-normal px-2 py-1',
+ 'hover:border-components-input-border-hover hover:bg-components-input-bg-hover',
+ 'focus-within:border-components-input-border-active focus-within:bg-components-input-bg-active focus-within:shadow-xs',
+ )}
+ className="caret:text-text-accent min-h-[128px]"
+ editable={!readOnly}
+ value={value}
+ requestURLBlock={{
+ show: true,
+ selectable: true,
+ }}
+ workflowVariableBlock={{
+ show: true,
+ variables: nodesOutputVars || [],
+ workflowNodesMap: availableNodes.reduce((acc, node) => {
+ acc[node.id] = {
+ title: node.data.title,
+ type: node.data.type,
+ }
+ if (node.data.type === BlockEnum.Start) {
+ acc.sys = {
+ title: t('blocks.start', { ns: 'workflow' }),
+ type: BlockEnum.Start,
+ }
+ }
+ return acc
+ }, {} as Record<string, Pick<Node['data'], 'title' | 'type'>>),
+ }}
+ placeholder={<Placeholder hideBadge />}
+ onChange={onChange}
+ />
+ )
+}
+
+export default MailBodyInput
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/method-item.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/method-item.tsx
new file mode 100644
index 00000000000..bea2f8cb354
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/method-item.tsx
@@ -0,0 +1,212 @@
+import type { FC } from 'react'
+import type { DeliveryMethod, EmailConfig, FormInputItem } from '../../types'
+import type {
+ Node,
+ NodeOutPutVar,
+} from '@/app/components/workflow/types'
+import {
+ RiDeleteBinLine,
+ RiEqualizer2Line,
+ RiMailSendFill,
+ RiRobot2Fill,
+ RiSendPlane2Line,
+} from '@remixicon/react'
+import { useCallback, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
+import Badge from '@/app/components/base/badge/index'
+import Button from '@/app/components/base/button'
+import Switch from '@/app/components/base/switch'
+import Tooltip from '@/app/components/base/tooltip'
+import Indicator from '@/app/components/header/indicator'
+import { useSelector as useAppContextWithSelector } from '@/context/app-context'
+import { cn } from '@/utils/classnames'
+import { DeliveryMethodType } from '../../types'
+import EmailConfigureModal from './email-configure-modal'
+import TestEmailSender from './test-email-sender'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type DeliveryMethodItemProps = {
+ nodeId: string
+ method: DeliveryMethod
+ nodesOutputVars?: NodeOutPutVar[]
+ availableNodes?: Node[]
+ formContent?: string
+ formInputs?: FormInputItem[]
+ onChange: (method: DeliveryMethod) => void
+ onDelete: (type: DeliveryMethodType) => void
+ readonly?: boolean
+}
+
+const DeliveryMethodItem: FC<DeliveryMethodItemProps> = ({
+ nodeId,
+ method,
+ nodesOutputVars,
+ availableNodes,
+ formContent,
+ formInputs,
+ onChange,
+ onDelete,
+ readonly,
+}) => {
+ const { t } = useTranslation()
+ const email = useAppContextWithSelector(s => s.userProfile.email)
+ const [isHovering, setIsHovering] = useState(false)
+ const [showEmailModal, setShowEmailModal] = useState(false)
+ const [showTestEmailModal, setShowTestEmailModal] = useState(false)
+
+ const handleEnableStatusChange = (enabled: boolean) => {
+ onChange({
+ ...method,
+ enabled,
+ })
+ }
+
+ const handleConfigChange = (config: EmailConfig) => {
+ onChange({
+ ...method,
+ config,
+ })
+ }
+
+ const emailSenderTooltipContent = useMemo(() => {
+ if (method.type !== DeliveryMethodType.Email) {
+ return ''
+ }
+ if (method.config?.debug_mode) {
+ return t(`${i18nPrefix}.deliveryMethod.emailSender.testSendTipInDebugMode`, { ns: 'workflow', email })
+ }
+ return t(`${i18nPrefix}.deliveryMethod.emailSender.testSendTip`, { ns: 'workflow' })
+ }, [method.type, method.config?.debug_mode, t, email])
+
+ const jumpToEmailConfigModal = useCallback(() => {
+ setShowTestEmailModal(false)
+ setShowEmailModal(true)
+ }, [])
+
+ return (
+ <>
+ <div
+ className={cn(
+ 'group flex h-8 items-center justify-between rounded-lg border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg pl-1.5 pr-2 shadow-xs hover:bg-components-panel-on-panel-item-bg-hover hover:shadow-sm',
+ isHovering && 'border-state-destructive-border bg-state-destructive-hover hover:bg-state-destructive-hover',
+ )}
+ >
+ <div className="flex items-center gap-1.5">
+ {method.type === DeliveryMethodType.WebApp && (
+ <div className="rounded-[4px] border border-divider-regular bg-components-icon-bg-indigo-solid p-0.5">
+ <RiRobot2Fill className="h-3.5 w-3.5 text-text-primary-on-surface" />
+ </div>
+ )}
+ {method.type === DeliveryMethodType.Email && (
+ <div className="rounded-[4px] border border-divider-regular bg-components-icon-bg-blue-solid p-0.5">
+ <RiMailSendFill className="h-3.5 w-3.5 text-text-primary-on-surface" />
+ </div>
+ )}
+ <div className="system-xs-medium capitalize text-text-secondary">{method.type}</div>
+ {method.type === DeliveryMethodType.Email
+ && (method.config as EmailConfig)?.debug_mode
+ && <Badge size="s" className="!px-1 !py-0.5">DEBUG</Badge>}
+ </div>
+ <div className="flex items-center gap-1">
+ {!readonly && (
+ <div className="hidden items-end gap-1 group-hover:flex">
+ {method.type === DeliveryMethodType.Email && method.config && (
+ <>
+ <Tooltip
+ popupContent={emailSenderTooltipContent}
+ asChild={false}
+ needsDelay={false}
+ >
+ <ActionButton
+ onClick={() => {
+ setShowTestEmailModal(true)
+ }}
+ >
+ <RiSendPlane2Line className="h-4 w-4" />
+ </ActionButton>
+ </Tooltip>
+ <Tooltip
+ popupContent={t('common.configure', { ns: 'workflow' })}
+ asChild={false}
+ needsDelay={false}
+ >
+ <ActionButton onClick={() => setShowEmailModal(true)}>
+ <RiEqualizer2Line className="h-4 w-4" />
+ </ActionButton>
+
+ </Tooltip>
+ </>
+ )}
+ <Tooltip
+ popupContent={t('operation.remove', { ns: 'common' })}
+ asChild={false}
+ needsDelay={false}
+ >
+ <div
+ onMouseEnter={() => setIsHovering(true)}
+ onMouseLeave={() => setIsHovering(false)}
+ >
+ <ActionButton
+ state={isHovering ? ActionButtonState.Destructive : ActionButtonState.Default}
+ onClick={() => onDelete(method.type)}
+ >
+ <RiDeleteBinLine className="h-4 w-4" />
+ </ActionButton>
+ </div>
+ </Tooltip>
+ </div>
+ )}
+ {(method.config || method.type === DeliveryMethodType.WebApp) && (
+ <Switch
+ defaultValue={method.enabled}
+ onChange={handleEnableStatusChange}
+ disabled={readonly}
+ />
+ )}
+ {method.type === DeliveryMethodType.Email && !method.config && (
+ <Button
+ className="-mr-1"
+ size="small"
+ onClick={() => setShowEmailModal(true)}
+ disabled={readonly}
+ >
+ {t(`${i18nPrefix}.deliveryMethod.notConfigured`, { ns: 'workflow' })}
+ <Indicator color="orange" className="ml-1" />
+ </Button>
+ )}
+ </div>
+ </div>
+ {showEmailModal && (
+ <EmailConfigureModal
+ isShow={showEmailModal}
+ config={method.config as EmailConfig}
+ nodesOutputVars={nodesOutputVars}
+ availableNodes={availableNodes}
+ onClose={() => setShowEmailModal(false)}
+ onConfirm={(data) => {
+ handleConfigChange(data)
+ setShowEmailModal(false)
+ }}
+ />
+ )}
+ {showTestEmailModal && (
+ <TestEmailSender
+ nodeId={nodeId}
+ deliveryId={method.id}
+ isShow={showTestEmailModal}
+ config={method.config as EmailConfig}
+ formContent={formContent}
+ formInputs={formInputs}
+ nodesOutputVars={nodesOutputVars}
+ availableNodes={availableNodes}
+ onClose={() => setShowTestEmailModal(false)}
+ jumpToEmailConfigModal={jumpToEmailConfigModal}
+ />
+ )}
+ </>
+ )
+}
+
+export default DeliveryMethodItem
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsx
new file mode 100644
index 00000000000..3c3c0ddba2d
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/method-selector.tsx
@@ -0,0 +1,222 @@
+'use client'
+import type { FC } from 'react'
+import type { DeliveryMethod } from '../../types'
+import {
+ RiAddLine,
+ RiDiscordFill,
+ RiLightbulbFlashFill,
+ RiMailSendFill,
+ RiRobot2Fill,
+} from '@remixicon/react'
+import { memo, useCallback, useMemo, useRef, useState } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import { v4 as uuid4 } from 'uuid'
+import ActionButton from '@/app/components/base/action-button'
+import Badge from '@/app/components/base/badge'
+import { Slack, Teams } from '@/app/components/base/icons/src/public/other'
+import {
+ PortalToFollowElem,
+ PortalToFollowElemContent,
+ PortalToFollowElemTrigger,
+} from '@/app/components/base/portal-to-follow-elem'
+import useWorkflowNodes from '@/app/components/workflow/store/workflow/use-nodes'
+import { isTriggerWorkflow } from '@/app/components/workflow/utils/workflow-entry'
+import { IS_CE_EDITION } from '@/config'
+import { useProviderContextSelector } from '@/context/provider-context'
+import { cn } from '@/utils/classnames'
+import { DeliveryMethodType } from '../../types'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type MethodSelectorProps = {
+ data: DeliveryMethod[]
+ onAdd: (method: DeliveryMethod) => void
+ onShowUpgradeTip: () => void
+}
+
+const MethodSelector: FC<MethodSelectorProps> = ({
+ data,
+ onAdd,
+ onShowUpgradeTip,
+}) => {
+ const { t } = useTranslation()
+ const [open, doSetOpen] = useState(false)
+ const humanInputEmailDeliveryEnabled = useProviderContextSelector(s => s.humanInputEmailDeliveryEnabled)
+ const openRef = useRef(open)
+ const nodes = useWorkflowNodes()
+
+ const setOpen = useCallback((v: boolean) => {
+ doSetOpen(v)
+ openRef.current = v
+ }, [doSetOpen])
+
+ const handleTrigger = useCallback(() => {
+ setOpen(!openRef.current)
+ }, [setOpen])
+
+ const webAppDeliveryInfo = useMemo(() => {
+ const isTriggerMode = isTriggerWorkflow(nodes)
+ return {
+ disabled: isTriggerMode || data.some(method => method.type === DeliveryMethodType.WebApp),
+ added: data.some(method => method.type === DeliveryMethodType.WebApp),
+ isTriggerMode,
+ }
+ }, [data, nodes])
+
+ const emailDeliveryInfo = useMemo(() => {
+ return {
+ noPermission: !humanInputEmailDeliveryEnabled,
+ added: data.some(method => method.type === DeliveryMethodType.Email),
+ }
+ }, [data, humanInputEmailDeliveryEnabled])
+
+ return (
+ <PortalToFollowElem
+ open={open}
+ onOpenChange={setOpen}
+ placement="bottom-end"
+ offset={{
+ mainAxis: 4,
+ crossAxis: 12,
+ }}
+ >
+ <PortalToFollowElemTrigger onClick={handleTrigger}>
+ <div>
+ <ActionButton className={cn(open && 'bg-state-base-hover')}>
+ <RiAddLine className="h-4 w-4" />
+ </ActionButton>
+ </div>
+ </PortalToFollowElemTrigger>
+ <PortalToFollowElemContent className="z-50">
+ <div className="w-[360px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
+ <div className="p-1">
+ <div
+ className={cn('relative flex cursor-pointer items-center gap-1 rounded-lg p-1 pl-3 hover:bg-state-base-hover', webAppDeliveryInfo.disabled && 'cursor-not-allowed bg-transparent hover:bg-transparent')}
+ onClick={() => {
+ if (webAppDeliveryInfo.disabled)
+ return
+ onAdd({
+ id: uuid4(),
+ type: DeliveryMethodType.WebApp,
+ enabled: true,
+ })
+ }}
+ >
+ <div className={cn('rounded-[4px] border border-divider-regular bg-components-icon-bg-indigo-solid p-1', webAppDeliveryInfo.disabled && 'opacity-50')}>
+ <RiRobot2Fill className="h-4 w-4 text-text-primary-on-surface" />
+ </div>
+ <div className={cn('p-1', webAppDeliveryInfo.disabled && 'opacity-50')}>
+ <div className="system-sm-medium mb-0.5 truncate text-text-primary">{t(`${i18nPrefix}.deliveryMethod.types.webapp.title`, { ns: 'workflow' })}</div>
+ <div className="system-xs-regular truncate text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.types.webapp.description`, { ns: 'workflow' })}</div>
+ </div>
+ {webAppDeliveryInfo.added && (
+ <div className="system-xs-regular absolute right-[12px] top-[13px] text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.added`, { ns: 'workflow' })}</div>
+ )}
+ {webAppDeliveryInfo.isTriggerMode && !webAppDeliveryInfo.added && (
+ <div className="system-xs-regular absolute right-[12px] top-[13px] text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.notAvailableInTriggerMode`, { ns: 'workflow' })}</div>
+ )}
+ </div>
+ <div
+ className={cn(
+ 'relative flex cursor-pointer items-center gap-1 rounded-lg p-1 pl-3 hover:bg-state-base-hover',
+ emailDeliveryInfo.added && 'cursor-not-allowed bg-transparent hover:bg-transparent',
+ )}
+ onClick={() => {
+ if (emailDeliveryInfo.noPermission) {
+ onShowUpgradeTip()
+ return
+ }
+ if (emailDeliveryInfo.added)
+ return
+ onAdd({
+ id: uuid4(),
+ type: DeliveryMethodType.Email,
+ enabled: false,
+ })
+ }}
+ >
+ <div
+ className={cn(
+ 'rounded-[4px] border border-divider-regular bg-components-icon-bg-blue-solid p-1',
+ emailDeliveryInfo.added && 'opacity-50',
+ )}
+ >
+ <RiMailSendFill className="h-4 w-4 text-text-primary-on-surface" />
+ </div>
+ <div className={cn('p-1', emailDeliveryInfo.added && 'opacity-50')}>
+ <div className="system-sm-medium mb-0.5 truncate text-text-primary">{t(`${i18nPrefix}.deliveryMethod.types.email.title`, { ns: 'workflow' })}</div>
+ <div className="system-xs-regular truncate text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.types.email.description`, { ns: 'workflow' })}</div>
+ </div>
+ {emailDeliveryInfo.added && (
+ <div className="system-xs-regular absolute right-[12px] top-[13px] text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.added`, { ns: 'workflow' })}</div>
+ )}
+ </div>
+ {/* Slack */}
+ <div
+ className={cn('relative flex cursor-pointer items-center gap-1 rounded-lg p-1 pl-3 hover:bg-state-base-hover', 'cursor-not-allowed bg-transparent hover:bg-transparent')}
+ >
+ <div className={cn('rounded-[4px] border border-divider-regular bg-background-default-dodge p-1', 'opacity-50')}>
+ <Slack className="h-4 w-4 text-text-primary-on-surface" />
+ </div>
+ <div className={cn('p-1', 'opacity-50')}>
+ <div className="system-sm-medium mb-0.5 truncate text-text-primary">{t(`${i18nPrefix}.deliveryMethod.types.slack.title`, { ns: 'workflow' })}</div>
+ <div className="system-xs-regular truncate text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.types.slack.description`, { ns: 'workflow' })}</div>
+ </div>
+ <div className="absolute right-[8px] top-[8px]">
+ <Badge className="h-4">COMING SOON</Badge>
+ </div>
+ </div>
+ {/* Teams */}
+ <div
+ className={cn('relative flex cursor-pointer items-center gap-1 rounded-lg p-1 pl-3 hover:bg-state-base-hover', 'cursor-not-allowed bg-transparent hover:bg-transparent')}
+ >
+ <div className={cn('rounded-[4px] border border-divider-regular bg-background-default-dodge p-1', 'opacity-50')}>
+ <Teams className="h-4 w-4 text-text-primary-on-surface" />
+ </div>
+ <div className={cn('p-1', 'opacity-50')}>
+ <div className="system-sm-medium mb-0.5 truncate text-text-primary">{t(`${i18nPrefix}.deliveryMethod.types.teams.title`, { ns: 'workflow' })}</div>
+ <div className="system-xs-regular truncate text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.types.teams.description`, { ns: 'workflow' })}</div>
+ </div>
+ <div className="absolute right-[8px] top-[8px]">
+ <Badge className="h-4">COMING SOON</Badge>
+ </div>
+ </div>
+ {/* Discord */}
+ <div
+ className={cn('relative flex cursor-pointer items-center gap-1 rounded-lg p-1 pl-3 hover:bg-state-base-hover', 'cursor-not-allowed bg-transparent hover:bg-transparent')}
+ >
+ <div className={cn('rounded-[4px] border border-divider-regular bg-components-icon-bg-indigo-solid p-0.5', 'opacity-50')}>
+ <RiDiscordFill className="h-5 w-5 text-text-primary-on-surface" />
+ </div>
+ <div className={cn('p-1', 'opacity-50')}>
+ <div className="system-sm-medium mb-0.5 truncate text-text-primary">{t(`${i18nPrefix}.deliveryMethod.types.discord.title`, { ns: 'workflow' })}</div>
+ <div className="system-xs-regular truncate text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.types.discord.description`, { ns: 'workflow' })}</div>
+ </div>
+ <div className="absolute right-[8px] top-[8px]">
+ <Badge className="h-4">COMING SOON</Badge>
+ </div>
+ </div>
+ </div>
+ </div>
+ {!IS_CE_EDITION && (
+ <div className="mt-1 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
+ <div className="flex items-center gap-2 px-4 py-3">
+ <div className={cn('rounded-[4px] border border-divider-regular bg-components-icon-bg-midnight-solid p-1')}>
+ <RiLightbulbFlashFill className="h-4 w-4 text-text-primary-on-surface" />
+ </div>
+ <div className="system-sm-regular text-text-secondary">
+ <div>{t(`${i18nPrefix}.deliveryMethod.contactTip1`, { ns: 'workflow' })}</div>
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.contactTip2`}
+ ns="workflow"
+ components={{ email: <a href="mailto:[email protected]" className="text-text-accent-light-mode-only">[email protected]</a> }}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </PortalToFollowElemContent>
+ </PortalToFollowElem>
+ )
+}
+export default memo(MethodSelector)
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
new file mode 100644
index 00000000000..b7a94412e75
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-input.tsx
@@ -0,0 +1,183 @@
+import type { Recipient as RecipientItem } from '../../../types'
+import type { Member } from '@/models/common'
+import * as React from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ PortalToFollowElem,
+ PortalToFollowElemContent,
+ PortalToFollowElemTrigger,
+} from '@/app/components/base/portal-to-follow-elem'
+import { cn } from '@/utils/classnames'
+import EmailItem from './email-item'
+import MemberList from './member-list'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ email: string
+ value: RecipientItem[]
+ list: Member[]
+ onDelete: (recipient: RecipientItem) => void
+ onSelect: (value: string) => void
+ onAdd: (email: string) => void
+ disabled?: boolean
+}
+
+const EmailInput = ({
+ email,
+ value,
+ list,
+ onDelete,
+ onSelect,
+ onAdd,
+ disabled = false,
+}: Props) => {
+ const { t } = useTranslation()
+ const inputRef = useRef<HTMLInputElement>(null)
+ const [isFocus, setIsFocus] = useState(false)
+ const [open, setOpen] = useState(false)
+ const [searchKey, setSearchKey] = useState('')
+
+ const selectedEmails = useMemo(() => {
+ return value.map((item) => {
+ const member = list.find(account => account.id === item.user_id)
+ return member ? { ...item, email: member.email, name: member.name } : item
+ })
+ }, [list, value])
+
+ const isErrorMember = useCallback((emailItem: RecipientItem) => emailItem.type === 'member' && list.every(item => item.id !== emailItem.user_id), [list])
+
+ const placeholder = useMemo(() => {
+ return (selectedEmails.length === 0 || isFocus)
+ ? t(`${i18nPrefix}.deliveryMethod.emailConfigure.memberSelector.placeholder`, { ns: 'workflow' })
+ : ''
+ }, [selectedEmails, t, isFocus])
+
+ const setInputFocus = () => {
+ if (disabled)
+ return
+ setIsFocus(true)
+ const input = inputRef.current?.children[0] as HTMLInputElement
+ input?.focus()
+ }
+
+ const handleValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ setSearchKey(e.target.value)
+ if (e.target.value.trim() === '') {
+ setOpen(false)
+ return
+ }
+ setOpen(true)
+ }
+
+ const handleSelect = (value: string) => {
+ setSearchKey('')
+ setOpen(false)
+ onSelect(value)
+ setInputFocus()
+ }
+
+ const checkEmailValid = (email: string) => {
+ const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
+ return emailRegex.test(email)
+ }
+
+ const handleEmailAdd = () => {
+ const emailAddress = searchKey.trim()
+ if (!checkEmailValid(emailAddress))
+ return
+ if (value.some(item => item.email === emailAddress))
+ return
+ if (list.some(item => item.email === emailAddress)) {
+ const item = list.find(item => item.email === emailAddress)!
+ onSelect(item.id)
+ }
+ else {
+ onAdd(emailAddress)
+ }
+ setSearchKey('')
+ setOpen(false)
+ }
+
+ const handleInputBlur = () => {
+ setIsFocus(false)
+ handleEmailAdd()
+ }
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Enter' || e.key === 'Tab' || e.key === ' ' || e.key === ',') {
+ e.preventDefault()
+ handleEmailAdd()
+ }
+ else if (e.key === 'Backspace') {
+ if (searchKey === '' && value.length > 0) {
+ e.preventDefault()
+ onDelete(value[value.length - 1])
+ setSearchKey('')
+ setOpen(false)
+ }
+ }
+ }
+
+ return (
+ <div className="p-1 pt-0">
+ <div
+ className={cn(
+ 'flex max-h-24 min-h-16 flex-wrap overflow-y-auto rounded-lg border border-transparent bg-components-input-bg-normal p-2',
+ isFocus && 'border-components-input-border-active bg-components-input-bg-active shadow-xs',
+ !disabled && 'hover:border-components-input-border-hover hover:bg-components-input-bg-hover',
+ )}
+ onClick={setInputFocus}
+ >
+ {selectedEmails.map(item => (
+ <EmailItem
+ key={item.user_id || item.email}
+ email={email}
+ data={item as unknown as Member}
+ onDelete={onDelete}
+ disabled={disabled}
+ isError={isErrorMember(item)}
+ />
+ ))}
+ {!disabled && (
+ <PortalToFollowElem
+ open={open}
+ onOpenChange={setOpen}
+ placement="bottom-start"
+ offset={{
+ mainAxis: 4,
+ crossAxis: -40,
+ }}
+ >
+ <PortalToFollowElemTrigger className="block h-6 min-w-[166px]">
+ <input
+ ref={inputRef}
+ className="system-sm-regular h-6 min-w-[166px] appearance-none bg-transparent p-1 text-components-input-text-filled caret-primary-600 outline-none placeholder:text-components-input-text-placeholder"
+ placeholder={placeholder}
+ onFocus={() => setIsFocus(true)}
+ onBlur={handleInputBlur}
+ value={searchKey}
+ onChange={handleValueChange}
+ onKeyDown={handleKeyDown}
+ />
+ </PortalToFollowElemTrigger>
+ <PortalToFollowElemContent className="z-[1000]">
+ <MemberList
+ searchValue={searchKey}
+ list={list}
+ value={value}
+ onSearchChange={setSearchKey}
+ onSelect={handleSelect}
+ email={email}
+ hideSearch
+ />
+ </PortalToFollowElemContent>
+ </PortalToFollowElem>
+ )}
+ </div>
+ </div>
+ )
+}
+
+export default EmailInput
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsx
new file mode 100644
index 00000000000..be26c9becef
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/email-item.tsx
@@ -0,0 +1,52 @@
+import type { Recipient as RecipientItem } from '../../../types'
+import type { Member } from '@/models/common'
+import { RiCloseCircleFill, RiErrorWarningFill } from '@remixicon/react'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import Avatar from '@/app/components/base/avatar'
+import { cn } from '@/utils/classnames'
+
+type Props = {
+ email: string
+ data: Member
+ disabled?: boolean
+ onDelete: (recipient: RecipientItem) => void
+ isError: boolean
+}
+
+const EmailItem = ({
+ email,
+ data,
+ onDelete,
+ disabled = false,
+ isError,
+}: Props) => {
+ const { t } = useTranslation()
+
+ return (
+ <div
+ className={cn(
+ 'flex h-6 items-center gap-1 rounded-full border border-components-panel-border-subtle bg-components-badge-white-to-dark p-1 shadow-xs',
+ isError && 'border-state-destructive-hover-alt bg-state-destructive-hover',
+ )}
+ onClick={e => e.stopPropagation()}
+ >
+ {isError && (
+ <RiErrorWarningFill className="h-4 w-4 text-text-destructive" />
+ )}
+ {!isError && <Avatar avatar={data.avatar_url} size={16} name={data.name || data.email} />}
+ <div title={data.email} className="system-xs-regular max-w-[500px] truncate text-text-primary">
+ {email === data.email ? data.name : data.email}
+ {email === data.email && <span className="system-xs-regular text-text-tertiary">{t('members.you', { ns: 'common' })}</span>}
+ </div>
+ {!disabled && (
+ <RiCloseCircleFill
+ className="h-4 w-4 cursor-pointer text-text-quaternary hover:text-text-tertiary"
+ onClick={() => onDelete(data as unknown as RecipientItem)}
+ />
+ )}
+ </div>
+ )
+}
+
+export default EmailItem
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx
new file mode 100644
index 00000000000..9b5f4ef68c8
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/index.tsx
@@ -0,0 +1,102 @@
+import type { RecipientData, Recipient as RecipientItem } from '../../../types'
+import { RiGroupLine } from '@remixicon/react'
+import { produce } from 'immer'
+import { memo } from 'react'
+import { useTranslation } from 'react-i18next'
+import Switch from '@/app/components/base/switch'
+import { useAppContext } from '@/context/app-context'
+import { useMembers } from '@/service/use-common'
+import { cn } from '@/utils/classnames'
+import EmailInput from './email-input'
+import MemberSelector from './member-selector'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ data: RecipientData
+ onChange: (data: RecipientData) => void
+}
+
+const Recipient = ({
+ data,
+ onChange,
+}: Props) => {
+ const { t } = useTranslation()
+ const { userProfile, currentWorkspace } = useAppContext()
+ const { data: members } = useMembers()
+ const accounts = members?.accounts || []
+
+ const handleMemberSelect = (id: string) => {
+ onChange(
+ produce(data, (draft) => {
+ draft.items.push({
+ type: 'member',
+ user_id: id,
+ })
+ }),
+ )
+ }
+
+ const handleEmailAdd = (email: string) => {
+ onChange(
+ produce(data, (draft) => {
+ draft.items.push({
+ type: 'external',
+ email,
+ })
+ }),
+ )
+ }
+
+ const handleDelete = (recipient: RecipientItem) => {
+ onChange(
+ produce(data, (draft) => {
+ if (recipient.type === 'member')
+ draft.items = draft.items.filter(item => item.user_id !== recipient.user_id)
+ else if (recipient.type === 'external')
+ draft.items = draft.items.filter(item => item.email !== recipient.email)
+ }),
+ )
+ }
+
+ return (
+ <div className="space-y-1">
+ <div className="rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs">
+ <div className="flex h-10 items-center justify-between pl-3 pr-1">
+ <div className="flex grow items-center gap-2">
+ <RiGroupLine className="h-4 w-4 text-text-secondary" />
+ <div className="system-sm-medium text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.memberSelector.title`, { ns: 'workflow' })}</div>
+ </div>
+ <div className="w-[86px]">
+ <MemberSelector
+ value={data.items}
+ email={userProfile.email}
+ list={accounts}
+ onSelect={handleMemberSelect}
+ />
+ </div>
+ </div>
+ <EmailInput
+ email={userProfile.email}
+ value={data.items}
+ list={accounts}
+ onDelete={handleDelete}
+ onSelect={handleMemberSelect}
+ onAdd={handleEmailAdd}
+ />
+ </div>
+ <div className="flex h-10 items-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg pl-2.5 pr-3 shadow-xs">
+ <div className="flex h-5 w-5 items-center justify-center rounded-xl bg-components-icon-bg-blue-solid text-[14px]">
+ <span className="bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text font-semibold uppercase text-shadow-shadow-1 opacity-90">{currentWorkspace?.name[0]?.toLocaleUpperCase()}</span>
+ </div>
+ <div className={cn('system-sm-medium grow text-text-secondary')}>{t(`${i18nPrefix}.deliveryMethod.emailConfigure.allMembers`, { workspaceName: currentWorkspace.name.replace(/'/g, '’'), ns: 'workflow' })}</div>
+ <Switch
+ defaultValue={data.whole_workspace}
+ onChange={checked => onChange({ ...data, whole_workspace: checked })}
+ />
+ </div>
+ </div>
+ )
+}
+
+export default memo(Recipient)
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsx
new file mode 100644
index 00000000000..eca07fd6ce8
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-list.tsx
@@ -0,0 +1,91 @@
+'use client'
+import type { FC } from 'react'
+import type { Recipient } from '@/app/components/workflow/nodes/human-input/types'
+import type { Member } from '@/models/common'
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import Avatar from '@/app/components/base/avatar'
+import Input from '@/app/components/base/input'
+import { cn } from '@/utils/classnames'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ value: Recipient[]
+ searchValue: string
+ onSearchChange: (value: string) => void
+ list: Member[]
+ onSelect: (value: string) => void
+ email: string
+ hideSearch?: boolean
+}
+
+const MemberList: FC<Props> = ({ searchValue, list, value, onSearchChange, onSelect, email, hideSearch }) => {
+ const { t } = useTranslation()
+
+ const filteredList = useMemo(() => {
+ if (!list.length)
+ return []
+ if (!searchValue)
+ return list
+ return list.filter((account) => {
+ const name = account.name || ''
+ const email = account.email || ''
+ return name.toLowerCase().includes(searchValue.toLowerCase())
+ || email.toLowerCase().includes(searchValue.toLowerCase())
+ })
+ }, [list, searchValue])
+
+ if (hideSearch && filteredList.length === 0)
+ return null
+
+ return (
+ <div className="min-w-[320px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
+ {!hideSearch && (
+ <div className="p-2 pb-1">
+ <Input
+ showLeftIcon
+ value={searchValue}
+ onChange={e => onSearchChange(e.target.value)}
+ />
+ </div>
+ )}
+ {filteredList.length > 0 && (
+ <div className="max-h-[248px] overflow-y-auto p-1">
+ {filteredList.map(account => (
+ <div
+ key={account.id}
+ className={cn(
+ 'group flex cursor-pointer items-center gap-2 rounded-lg py-1 pl-2 pr-3 hover:bg-state-base-hover',
+ value.some(item => item.user_id === account.id) && 'bg-transparent hover:bg-transparent',
+ )}
+ onClick={() => {
+ if (value.some(item => item.user_id === account.id))
+ return
+ onSelect(account.id)
+ }}
+ >
+ <Avatar className={cn(value.some(item => item.user_id === account.id) && 'opacity-50')} avatar={account.avatar_url} size={24} name={account.name} />
+ <div className={cn('grow', value.some(item => item.user_id === account.id) && 'opacity-50')}>
+ <div className="system-sm-medium text-text-secondary">
+ {account.name}
+ {account.status === 'pending' && <span className="system-xs-medium ml-1 text-text-warning">{t('members.pending', { ns: 'common' })}</span>}
+ {email === account.email && <span className="system-xs-regular text-text-tertiary">{t('members.you', { ns: 'common' })}</span>}
+ </div>
+ <div className="system-xs-regular text-text-tertiary">{account.email}</div>
+ </div>
+ {!value.some(item => item.user_id === account.id) && (
+ <div className="system-xs-medium hidden text-text-accent group-hover:block">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.memberSelector.add`, { ns: 'workflow' })}</div>
+ )}
+ {value.some(item => item.user_id === account.id) && (
+ <div className="system-xs-regular text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.memberSelector.added`, { ns: 'workflow' })}</div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
+
+export default MemberList
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-selector.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-selector.tsx
new file mode 100644
index 00000000000..4ce8232a2ee
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/recipient/member-selector.tsx
@@ -0,0 +1,69 @@
+'use client'
+import type { FC } from 'react'
+import type { Recipient } from '@/app/components/workflow/nodes/human-input/types'
+import type { Member } from '@/models/common'
+import {
+ RiContactsBookLine,
+} from '@remixicon/react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger } from '@/app/components/base/portal-to-follow-elem'
+import { cn } from '@/utils/classnames'
+import MemberList from './member-list'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ value: Recipient[]
+ email: string
+ onSelect: (value: string) => void
+ list: Member[]
+}
+
+const MemberSelector: FC<Props> = ({
+ value,
+ email,
+ onSelect,
+ list = [],
+}) => {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const [searchValue, setSearchValue] = useState('')
+
+ return (
+ <PortalToFollowElem
+ open={open}
+ onOpenChange={setOpen}
+ placement="bottom-end"
+ offset={{
+ mainAxis: 4,
+ crossAxis: 35,
+ }}
+ >
+ <PortalToFollowElemTrigger
+ className="w-full"
+ onClick={() => setOpen(v => !v)}
+ >
+ <Button
+ className={cn('w-full justify-between', open && 'bg-state-accent-hover')}
+ variant="ghost-accent"
+ >
+ <RiContactsBookLine className="mr-1 h-4 w-4" />
+ <div className="">{t(`${i18nPrefix}.deliveryMethod.emailConfigure.memberSelector.trigger`, { ns: 'workflow' })}</div>
+ </Button>
+ </PortalToFollowElemTrigger>
+ <PortalToFollowElemContent className="z-[1000]">
+ <MemberList
+ searchValue={searchValue}
+ list={list}
+ value={value}
+ onSearchChange={setSearchValue}
+ onSelect={onSelect}
+ email={email}
+ />
+ </PortalToFollowElemContent>
+ </PortalToFollowElem>
+ )
+}
+export default MemberSelector
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx
new file mode 100644
index 00000000000..20fa9dfb448
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx
@@ -0,0 +1,372 @@
+import type { EmailConfig, FormInputItem } from '../../types'
+import type {
+ Node,
+ NodeOutPutVar,
+ ValueSelector,
+} from '@/app/components/workflow/types'
+import { RiArrowRightSFill, RiCloseLine } from '@remixicon/react'
+import { noop, unionBy } from 'es-toolkit/compat'
+import { memo, useCallback, useMemo, useState } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import { useStore as useAppStore } from '@/app/components/app/store'
+import Button from '@/app/components/base/button'
+import Divider from '@/app/components/base/divider'
+import Modal from '@/app/components/base/modal'
+import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'
+import FormItem from '@/app/components/workflow/nodes/_base/components/before-run-form/form-item'
+import {
+ getNodeInfoById,
+ isConversationVar,
+ isENV,
+ isSystemVar,
+} from '@/app/components/workflow/nodes/_base/components/variable/utils'
+import { InputVarType, VarType } from '@/app/components/workflow/types'
+import { useAppContext } from '@/context/app-context'
+import { useMembers } from '@/service/use-common'
+import { useTestEmailSender } from '@/service/use-workflow'
+import { cn } from '@/utils/classnames'
+import { isOutput } from '../../utils'
+import EmailInput from './recipient/email-input'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type EmailConfigureModalProps = {
+ nodeId: string
+ deliveryId: string
+ isShow: boolean
+ onClose: () => void
+ jumpToEmailConfigModal: () => void
+ config?: EmailConfig
+ formContent?: string
+ formInputs?: FormInputItem[]
+ nodesOutputVars?: NodeOutPutVar[]
+ availableNodes?: Node[]
+}
+
+const getOriginVar = (valueSelector: string[], list: NodeOutPutVar[]) => {
+ const targetVar = list.find(item => item.nodeId === valueSelector[0])
+ if (!targetVar)
+ return undefined
+
+ let curr: any = targetVar.vars
+ for (let i = 1; i < valueSelector.length; i++) {
+ const key = valueSelector[i]
+ const isLast = i === valueSelector.length - 1
+
+ if (Array.isArray(curr))
+ curr = curr.find((v: any) => v.variable.replace('conversation.', '') === key)
+
+ if (isLast)
+ return curr
+ else if (curr?.type === VarType.object || curr?.type === VarType.file)
+ curr = curr.children
+ }
+
+ return undefined
+}
+
+const EmailSenderModal = ({
+ nodeId,
+ deliveryId,
+ isShow,
+ onClose,
+ jumpToEmailConfigModal,
+ config,
+ formContent,
+ formInputs,
+ nodesOutputVars = [],
+ availableNodes = [],
+}: EmailConfigureModalProps) => {
+ const { t } = useTranslation()
+ const { userProfile, currentWorkspace } = useAppContext()
+ const appDetail = useAppStore(state => state.appDetail)
+ const { mutateAsync: testEmailSender } = useTestEmailSender()
+
+ const debugEnabled = !!config?.debug_mode
+ const onlyWholeTeam = config?.recipients?.whole_workspace && (!config?.recipients?.items || config?.recipients?.items.length === 0)
+ const onlySpecificUsers = !config?.recipients?.whole_workspace && config?.recipients?.items && config?.recipients?.items.length > 0
+ const combinedRecipients = config?.recipients?.whole_workspace && config?.recipients?.items && config?.recipients?.items.length > 0
+
+ const { data: members } = useMembers()
+ const accounts = members?.accounts || []
+
+ const generatedInputs = useMemo(() => {
+ const defaultValueSelectors = (formInputs || []).reduce((acc, input) => {
+ if (input.default.type === 'variable') {
+ acc.push(input.default.selector)
+ }
+ return acc
+ }, [] as ValueSelector[])
+ const valueSelectors = doGetInputVars((formContent || '') + (config?.body || ''))
+ const variables = unionBy([...valueSelectors, ...defaultValueSelectors], item => item.join('.')).map((item) => {
+ const varInfo = getNodeInfoById(availableNodes, item[0])?.data
+
+ return {
+ label: {
+ nodeType: varInfo?.type,
+ nodeName: varInfo?.title || availableNodes[0]?.data.title, // default start node title
+ variable: isSystemVar(item) ? item.join('.') : item[item.length - 1],
+ isChatVar: isConversationVar(item),
+ },
+ variable: `#${item.join('.')}#`,
+ value_selector: item,
+ required: true,
+ }
+ })
+ const varInputs = variables.filter(item => !isENV(item.value_selector) && !isOutput(item.value_selector)).map((item) => {
+ const originalVar = getOriginVar(item.value_selector, nodesOutputVars)
+ if (!originalVar) {
+ return {
+ label: item.label || item.variable,
+ variable: item.variable,
+ type: InputVarType.textInput,
+ required: true,
+ value_selector: item.value_selector,
+ }
+ }
+ return {
+ label: item.label || item.variable,
+ variable: item.variable,
+ type: originalVar.type === VarType.number ? InputVarType.number : InputVarType.textInput,
+ required: true,
+ }
+ })
+ return varInputs
+ }, [availableNodes, config?.body, formContent, formInputs, nodesOutputVars])
+
+ const [inputs, setInputs] = useState<Record<string, unknown>>({})
+ const [collapsed, setCollapsed] = useState(!(generatedInputs.length > 0))
+ const [sendingEmail, setSendingEmail] = useState(false)
+ const [done, setDone] = useState(false)
+
+ const handleValueChange = (variable: string, v: string) => {
+ setInputs({
+ ...inputs,
+ [variable]: v,
+ })
+ }
+
+ const confirmChecked = useMemo(() => {
+ for (const variable of generatedInputs) {
+ if (variable.required) {
+ const value = inputs[variable.variable]
+ if (value === undefined || value === null || value === '') {
+ return false
+ }
+ }
+ }
+ return true
+ }, [generatedInputs, inputs])
+
+ const handleConfirm = useCallback(async () => {
+ if (!confirmChecked)
+ return
+ setSendingEmail(true)
+ try {
+ await testEmailSender({
+ appID: appDetail?.id || '',
+ nodeID: nodeId,
+ deliveryID: deliveryId,
+ inputs,
+ })
+ setDone(true)
+ }
+ finally {
+ setSendingEmail(false)
+ }
+ }, [confirmChecked, testEmailSender, appDetail?.id, nodeId, deliveryId, inputs])
+
+ if (done) {
+ return (
+ <Modal
+ isShow={isShow}
+ onClose={noop}
+ className="relative !max-w-[480px] !p-0"
+ >
+ <div className="space-y-2 p-6 pb-3">
+ <div className="title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.deliveryMethod.emailSender.done`, { ns: 'workflow' })}</div>
+ {debugEnabled && (
+ <div className="system-md-regular text-text-secondary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.debugDone`}
+ ns="workflow"
+ components={{ email: <span className="system-md-semibold text-text-secondary"></span> }}
+ values={{ email: userProfile.email }}
+ />
+ </div>
+ )}
+ {!debugEnabled && onlyWholeTeam && (
+ <div className="system-md-regular text-text-secondary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.wholeTeamDone2`}
+ ns="workflow"
+ components={{ team: <span className="system-md-medium text-text-secondary"></span> }}
+ values={{ team: currentWorkspace.name.replace(/'/g, '’') }}
+ />
+ </div>
+ )}
+ {!debugEnabled && onlySpecificUsers && (
+ <div className="system-md-regular text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.emailSender.wholeTeamDone3`, { ns: 'workflow' })}</div>
+ )}
+ {!debugEnabled && combinedRecipients && (
+ <div className="system-md-regular text-text-secondary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.wholeTeamDone1`}
+ ns="workflow"
+ components={{ team: <span className="system-md-medium text-text-secondary"></span> }}
+ values={{ team: currentWorkspace.name.replace(/'/g, '’') }}
+ />
+ </div>
+ )}
+ </div>
+ {(onlySpecificUsers || combinedRecipients) && !debugEnabled && (
+ <div className="px-5">
+ <EmailInput
+ disabled
+ email={userProfile.email}
+ value={config?.recipients?.items}
+ list={accounts}
+ onDelete={noop}
+ onSelect={noop}
+ onAdd={noop}
+ />
+ </div>
+ )}
+ <div className="flex flex-row-reverse gap-2 p-6 pt-5">
+ <Button
+ variant="primary"
+ className="w-[72px]"
+ onClick={onClose}
+ >
+ {t('operation.ok', { ns: 'common' })}
+ </Button>
+ </div>
+ </Modal>
+ )
+ }
+
+ return (
+ <Modal
+ isShow={isShow}
+ onClose={noop}
+ className="relative !max-w-[480px] !p-0"
+ >
+ <div className="absolute right-5 top-5 cursor-pointer p-1.5" onClick={onClose}>
+ <RiCloseLine className="h-5 w-5 text-text-tertiary" />
+ </div>
+ <div className="space-y-1 p-6 pb-3">
+ <div className="title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.deliveryMethod.emailSender.title`, { ns: 'workflow' })}</div>
+ {debugEnabled && (
+ <>
+ <div className="system-sm-regular text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.emailSender.debugModeTip`, { ns: 'workflow' })}</div>
+ <div className="system-sm-regular text-text-secondary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.debugModeTip2`}
+ ns="workflow"
+ components={{ email: <span className="system-sm-semibold text-text-primary"></span> }}
+ values={{ email: userProfile.email }}
+ />
+ </div>
+ </>
+ )}
+ {!debugEnabled && onlyWholeTeam && (
+ <div className="system-sm-regular text-text-secondary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.wholeTeamTip2`}
+ ns="workflow"
+ components={{ team: <span className="system-sm-semibold text-text-primary"></span> }}
+ values={{ team: currentWorkspace.name.replace(/'/g, '’') }}
+ />
+ </div>
+ )}
+ {!debugEnabled && onlySpecificUsers && (
+ <div className="system-sm-regular text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.emailSender.wholeTeamTip3`, { ns: 'workflow' })}</div>
+ )}
+ {!debugEnabled && combinedRecipients && (
+ <div className="system-sm-regular text-text-secondary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.wholeTeamTip1`}
+ ns="workflow"
+ components={{ team: <span className="system-sm-semibold text-text-primary"></span> }}
+ values={{ team: currentWorkspace.name.replace(/'/g, '’') }}
+ />
+ </div>
+ )}
+ </div>
+ {(onlySpecificUsers || combinedRecipients) && !debugEnabled && (
+ <>
+ <div className="px-5">
+ <EmailInput
+ disabled
+ email={userProfile.email}
+ value={config?.recipients?.items}
+ list={accounts}
+ onDelete={noop}
+ onSelect={noop}
+ onAdd={noop}
+ />
+ </div>
+ <div className="system-xs-regular px-6 pt-1 text-text-tertiary">
+ <Trans
+ i18nKey={`${i18nPrefix}.deliveryMethod.emailSender.tip`}
+ ns="workflow"
+ components={{
+ strong: <span onClick={jumpToEmailConfigModal} className="system-xs-regular cursor-pointer text-text-accent"></span>,
+ }}
+ />
+ </div>
+ </>
+ )}
+ {/* vars */}
+ {generatedInputs.length > 0 && (
+ <>
+ <div className="px-6">
+ <Divider className="!mb-2 !mt-4 !h-px !w-12 bg-divider-regular" />
+ </div>
+ <div className="px-6 py-2">
+ <div className="group flex h-6 cursor-pointer items-center" onClick={() => setCollapsed(!collapsed)}>
+ <div className="system-sm-semibold-uppercase mr-1 text-text-secondary">{t(`${i18nPrefix}.deliveryMethod.emailSender.vars`, { ns: 'workflow' })}</div>
+ <RiArrowRightSFill className={cn('h-4 w-4 text-text-quaternary group-hover:text-text-primary', !collapsed && 'rotate-90')} />
+ </div>
+ <div className="system-xs-regular text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.emailSender.varsTip`, { ns: 'workflow' })}</div>
+ {!collapsed && (
+ <div className="mt-3 space-y-4">
+ {generatedInputs.map((variable, index) => (
+ <div
+ key={variable.variable}
+ className="mb-4 last-of-type:mb-0"
+ >
+ <FormItem
+ autoFocus={index === 0}
+ payload={variable}
+ value={inputs[variable.variable]}
+ onChange={v => handleValueChange(variable.variable, v)}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ <div className="flex flex-row-reverse gap-2 p-6 pt-5">
+ <Button
+ disabled={sendingEmail || !confirmChecked}
+ loading={sendingEmail}
+ variant="primary"
+ onClick={handleConfirm}
+ >
+ {t(`${i18nPrefix}.deliveryMethod.emailSender.send`, { ns: 'workflow' })}
+ </Button>
+ <Button
+ className="w-[72px]"
+ onClick={onClose}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ </div>
+ </Modal>
+ )
+}
+
+export default memo(EmailSenderModal)
diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsx
new file mode 100644
index 00000000000..8d41746b544
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/upgrade-modal.tsx
@@ -0,0 +1,76 @@
+import {
+ RiMailSendFill,
+} from '@remixicon/react'
+import { noop } from 'es-toolkit/compat'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import { SparklesSoft } from '@/app/components/base/icons/src/public/common'
+import Modal from '@/app/components/base/modal'
+import PremiumBadge from '@/app/components/base/premium-badge'
+import { useModalContextSelector } from '@/context/modal-context'
+import { cn } from '@/utils/classnames'
+
+type UpgradeModalProps = {
+ isShow: boolean
+ onClose: () => void
+}
+
+const UpgradeModal: React.FC<UpgradeModalProps> = ({
+ isShow,
+ onClose,
+}) => {
+ const { t } = useTranslation()
+ const setShowPricingModal = useModalContextSelector(s => s.setShowPricingModal)
+
+ return (
+ <Modal
+ isShow={isShow}
+ onClose={noop}
+ className="relative !w-[580px] !max-w-[580px] !p-8"
+ >
+ <div className="pb-6">
+ <div
+ className={cn(
+ 'mb-6 inline-flex rounded-xl border border-divider-regular bg-util-colors-blue-brand-blue-brand-500 p-2',
+ )}
+ >
+ <RiMailSendFill className="h-6 w-6 text-text-primary-on-surface" />
+ </div>
+ <p
+ className="title-3xl-semi-bold bg-[linear-gradient(271deg,_var(--components-input-border-active-prompt-1,_#155AEF)_-12.85%,_var(--components-input-border-active-prompt-2,_#0BA5EC)_95.4%)] bg-clip-text text-transparent"
+ >
+ {t('nodes.humanInput.deliveryMethod.upgradeTip', { ns: 'workflow' })}
+ </p>
+ <p className="system-md-regular mt-2 text-text-tertiary">
+ {t('nodes.humanInput.deliveryMethod.upgradeTipContent', { ns: 'workflow' })}
+ </p>
+ </div>
+ <div className="flex justify-end pt-5">
+ <Button
+ className="w-[72px]"
+ onClick={onClose}
+ >
+ {t('nodes.humanInput.deliveryMethod.upgradeTipHide', { ns: 'workflow' })}
+ </Button>
+ <PremiumBadge
+ size="custom"
+ color="blue"
+ allowHover={true}
+ className="ml-3 h-8 w-[93px]"
+ onClick={() => {
+ setShowPricingModal()
+ }}
+ >
+ <SparklesSoft className="flex h-3.5 w-3.5 items-center py-[1px] pl-[3px] text-components-premium-badge-indigo-text-stop-0" />
+ <div className="system-sm-medium">
+ <span className="p-1">
+ {t('upgradeBtn.encourageShort', { ns: 'billing' })}
+ </span>
+ </div>
+ </PremiumBadge>
+ </div>
+ </Modal>
+ )
+}
+
+export default UpgradeModal
diff --git a/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx b/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx
new file mode 100644
index 00000000000..d0001810a57
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/form-content-preview.tsx
@@ -0,0 +1,101 @@
+'use client'
+import type { FC } from 'react'
+import type { FormInputItem, UserAction } from '../types'
+import type { ButtonProps } from '@/app/components/base/button'
+import { RiCloseLine } from '@remixicon/react'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import ActionButton from '@/app/components/base/action-button'
+import Badge from '@/app/components/base/badge'
+import Button from '@/app/components/base/button'
+import { getButtonStyle } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
+import { Markdown } from '@/app/components/base/markdown'
+import { useStore } from '@/app/components/workflow/store'
+import useNodes from '@/app/components/workflow/store/workflow/use-nodes'
+import { Note, rehypeNotes, rehypeVariable, Variable } from './variable-in-markdown'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type FormContentPreviewProps = {
+ content: string
+ formInputs: FormInputItem[]
+ userActions: UserAction[]
+ onClose: () => void
+}
+
+const FormContentPreview: FC<FormContentPreviewProps> = ({
+ content,
+ formInputs,
+ userActions,
+ onClose,
+}) => {
+ const { t } = useTranslation()
+ const panelWidth = useStore(state => state.panelWidth)
+ const nodes = useNodes()
+
+ const nodeName = React.useCallback((nodeId: string) => {
+ const node = nodes.find(n => n.id === nodeId)
+ return node?.data.title || nodeId
+ }, [nodes])
+
+ return (
+ <div
+ className="fixed top-[112px] z-10 max-h-[calc(100vh-116px)] w-[600px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg py-3 shadow-xl"
+ style={{
+ right: panelWidth + 8,
+ }}
+ >
+ <div className="flex h-[26px] items-center justify-between px-4">
+ <Badge uppercase className="border-text-accent-secondary text-text-accent-secondary">{t(`${i18nPrefix}.formContent.preview`, { ns: 'workflow' })}</Badge>
+ <ActionButton onClick={onClose}><RiCloseLine className="w-5 text-text-tertiary" /></ActionButton>
+ </div>
+ <div className="max-h-[calc(100vh-167px)] overflow-y-auto px-4">
+ <Markdown
+ content={content}
+ rehypePlugins={[rehypeVariable, rehypeNotes]}
+ customComponents={{
+ variable: ({ node }: { node: { properties?: { [key: string]: string } } }) => {
+ const path = node.properties?.['data-path'] as string
+ let newPath = path
+ if (path) {
+ newPath = path.replace(/#([^#.]+)([.#])/g, (match, nodeId, sep) => {
+ return `#${nodeName(nodeId)}${sep}`
+ })
+ }
+ return <Variable path={newPath} />
+ },
+ section: ({ node }: { node: { properties?: { [key: string]: string } } }) => (() => {
+ const name = node.properties?.['data-name'] as string
+ const input = formInputs.find(i => i.output_variable_name === name)
+ if (!input) {
+ return (
+ <div>
+ Can't find note:
+ {name}
+ </div>
+ )
+ }
+ const defaultInput = input.default
+ return (
+ <Note defaultInput={defaultInput!} nodeName={nodeName} />
+ )
+ })(),
+ }}
+ />
+ <div className="mt-3 flex flex-wrap gap-1 py-1">
+ {userActions.map((action: UserAction) => (
+ <Button
+ key={action.id}
+ variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
+ >
+ {action.title}
+ </Button>
+ ))}
+ </div>
+ <div className="system-xs-regular mt-1 text-text-tertiary">{t('nodes.humanInput.editor.previewTip', { ns: 'workflow' })}</div>
+ </div>
+ </div>
+ )
+}
+
+export default React.memo(FormContentPreview)
diff --git a/web/app/components/workflow/nodes/human-input/components/form-content.tsx b/web/app/components/workflow/nodes/human-input/components/form-content.tsx
new file mode 100644
index 00000000000..fa9d1a539a1
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/form-content.tsx
@@ -0,0 +1,175 @@
+'use client'
+import type { LexicalCommand } from 'lexical'
+import type { FC } from 'react'
+import type { FormInputItem } from '../types'
+import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'
+import { useBoolean } from 'ahooks'
+import * as React from 'react'
+import { useEffect, useState } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import PromptEditor from '@/app/components/base/prompt-editor'
+import { INSERT_HITL_INPUT_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/hitl-input-block'
+import { cn } from '@/utils/classnames'
+import { useWorkflowVariableType } from '../../../hooks'
+import { BlockEnum } from '../../../types'
+import { isMac } from '../../../utils'
+import AddInputField from './add-input-field'
+
+type FormContentProps = {
+ nodeId: string
+ value: string
+ onChange: (value: string) => void
+ formInputs: FormInputItem[]
+ onFormInputsChange: (payload: FormInputItem[]) => void
+ onFormInputItemRename: (payload: FormInputItem, oldName: string) => void
+ onFormInputItemRemove: (varName: string) => void
+ editorKey: number
+ isExpand: boolean
+ availableVars: NodeOutPutVar[]
+ availableNodes: Node[]
+ readonly?: boolean
+}
+
+const Key: FC<{ children: React.ReactNode, className?: string }> = ({ children, className }) => {
+ return <span className={cn('system-kbd mx-0.5 inline-flex size-4 items-center justify-center rounded-[4px] bg-components-kbd-bg-gray text-text-placeholder ', className)}>{children}</span>
+}
+
+const CtrlKey: FC = () => {
+ return <Key className={cn('mr-0', !isMac() && 'w-7')}>{isMac() ? '⌘' : 'Ctrl'}</Key>
+}
+
+const FormContent: FC<FormContentProps> = ({
+ nodeId,
+ value,
+ onChange,
+ formInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ editorKey,
+ isExpand,
+ availableVars,
+ availableNodes,
+ readonly,
+}) => {
+ const { t } = useTranslation()
+
+ const getVarType = useWorkflowVariableType()
+
+ const [needToAddFormInput, setNeedToAddFormInput] = useState(false)
+ const [newFormInputs, setNewFormInputs] = useState<FormInputItem[]>([])
+ const handleInsertHITLNode = (onInsert: (command: LexicalCommand<unknown>, params: any) => void) => {
+ return (payload: FormInputItem) => {
+ const newFormInputs = [...(formInputs || []), payload]
+ onInsert(INSERT_HITL_INPUT_BLOCK_COMMAND, {
+ variableName: payload.output_variable_name,
+ nodeId,
+ formInputs: newFormInputs,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ })
+ setNewFormInputs(newFormInputs)
+ setNeedToAddFormInput(true)
+ }
+ }
+
+ // avoid update formInputs would overwrite the value just inserted
+ useEffect(() => {
+ if (needToAddFormInput) {
+ onFormInputsChange(newFormInputs)
+ setNeedToAddFormInput(false)
+ }
+ }, [value])
+
+ const [isFocus, {
+ setTrue: setFocus,
+ setFalse: setBlur,
+ }] = useBoolean(false)
+
+ const workflowNodesMap = availableNodes.reduce((acc: any, node) => {
+ acc[node.id] = {
+ title: node.data.title,
+ type: node.data.type,
+ width: node.width,
+ height: node.height,
+ position: node.position,
+ }
+ if (node.data.type === BlockEnum.Start) {
+ acc.sys = {
+ title: t('blocks.start', { ns: 'workflow' }),
+ type: BlockEnum.Start,
+ }
+ }
+ return acc
+ }, {})
+
+ return (
+ <div
+ className={cn(
+ 'flex grow flex-col rounded-[10px] border border-components-input-bg-normal bg-components-input-bg-normal pt-1',
+ isFocus && 'border-components-input-border-active bg-components-input-bg-active',
+ !isFocus && 'pb-[32px]',
+ readonly && 'pointer-events-none',
+ )}
+ >
+ <div className={cn('max-h-[300px] overflow-y-auto px-3', isExpand && 'h-0 max-h-full grow')}>
+ <PromptEditor
+ key={editorKey}
+ value={value}
+ onChange={onChange}
+ className={cn('min-h-[80px] ', isExpand && 'h-full')}
+ onFocus={setFocus}
+ onBlur={setBlur}
+ placeholder={t('nodes.humanInput.formContent.placeholder', { ns: 'workflow' })}
+ hitlInputBlock={{
+ show: true,
+ formInputs,
+ nodeId,
+ onFormInputsChange,
+ onFormInputItemRename,
+ onFormInputItemRemove,
+ variables: availableVars || [],
+ workflowNodesMap,
+ getVarType,
+ readonly,
+ }}
+ workflowVariableBlock={{
+ show: true,
+ variables: availableVars || [],
+ getVarType: getVarType as any,
+ workflowNodesMap,
+ }}
+ editable={!readonly}
+ shortcutPopups={readonly
+ ? []
+ : [{
+ hotkey: ['mod', '/'],
+ Popup: ({ onClose, onInsert }) => (
+ <AddInputField
+ nodeId={nodeId}
+ onSave={handleInsertHITLNode(onInsert!)}
+ onCancel={onClose}
+ />
+ ),
+ }]}
+ />
+ </div>
+ {isFocus && (
+ <div className="system-xs-regular flex h-8 shrink-0 items-center px-3 text-components-input-text-placeholder">
+ <Trans
+ i18nKey="nodes.humanInput.formContent.hotkeyTip"
+ ns="workflow"
+ components={
+ {
+ Key: <Key>/</Key>,
+ CtrlKey: <CtrlKey />,
+ }
+ }
+ />
+ </div>
+ )}
+ </div>
+ )
+}
+export default React.memo(FormContent)
diff --git a/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx b/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx
new file mode 100644
index 00000000000..7fd0c740003
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/single-run-form.tsx
@@ -0,0 +1,87 @@
+'use client'
+import type { ButtonProps } from '@/app/components/base/button'
+import type { UserAction } from '@/app/components/workflow/nodes/human-input/types'
+import type { HumanInputFormData } from '@/types/workflow'
+import { RiArrowLeftLine } from '@remixicon/react'
+import * as React from 'react'
+
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import ContentItem from '@/app/components/base/chat/chat/answer/human-input-content/content-item'
+import { getButtonStyle, initializeInputs, splitByOutputVar } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
+
+type Props = {
+ nodeName: string
+ data: HumanInputFormData
+ showBackButton?: boolean
+ handleBack?: () => void
+ onSubmit?: ({ inputs, action }: { inputs: Record<string, string>, action: string }) => Promise<void>
+}
+
+const FormContent = ({
+ nodeName,
+ data,
+ showBackButton,
+ handleBack,
+ onSubmit,
+}: Props) => {
+ const { t } = useTranslation()
+ const defaultInputs = initializeInputs(data.inputs, data.resolved_default_values || {})
+ const contentList = splitByOutputVar(data.form_content)
+ const [inputs, setInputs] = useState(defaultInputs)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+
+ const handleInputsChange = (name: string, value: string) => {
+ setInputs(prev => ({
+ ...prev,
+ [name]: value,
+ }))
+ }
+
+ const submit = async (actionID: string) => {
+ setIsSubmitting(true)
+ await onSubmit?.({ inputs, action: actionID })
+ setIsSubmitting(false)
+ }
+
+ return (
+ <>
+ {showBackButton && (
+ <div className="flex items-center p-4 pb-1">
+ <div className="system-sm-semibold-uppercase flex cursor-pointer items-center text-text-accent" onClick={handleBack}>
+ <RiArrowLeftLine className="mr-1 h-4 w-4" />
+ {t('nodes.humanInput.singleRun.back', { ns: 'workflow' })}
+ </div>
+ <div className="system-xs-regular mx-1 text-divider-deep">/</div>
+ <div className="system-sm-semibold-uppercase text-text-secondary">{nodeName}</div>
+ </div>
+ )}
+ <div className="px-4 py-3">
+ {contentList.map((content, index) => (
+ <ContentItem
+ key={index}
+ content={content}
+ formInputFields={data.inputs}
+ inputs={inputs}
+ onInputChange={handleInputsChange}
+ />
+ ))}
+ <div className="flex flex-wrap gap-1 py-1">
+ {data.actions.map((action: UserAction) => (
+ <Button
+ key={action.id}
+ disabled={isSubmitting}
+ variant={getButtonStyle(action.button_style) as ButtonProps['variant']}
+ onClick={() => submit(action.id)}
+ >
+ {action.title}
+ </Button>
+ ))}
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default React.memo(FormContent)
diff --git a/web/app/components/workflow/nodes/human-input/components/timeout.tsx b/web/app/components/workflow/nodes/human-input/components/timeout.tsx
new file mode 100644
index 00000000000..a5ccf9556f2
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/timeout.tsx
@@ -0,0 +1,69 @@
+import type { FC } from 'react'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import Input from '@/app/components/base/input'
+import { cn } from '@/utils/classnames'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Props = {
+ timeout: number
+ unit: 'day' | 'hour'
+ onChange: (state: { timeout: number, unit: 'day' | 'hour' }) => void
+ readonly?: boolean
+}
+
+const TimeoutInput: FC<Props> = ({
+ timeout,
+ unit,
+ onChange,
+ readonly,
+}) => {
+ const { t } = useTranslation()
+
+ const handleValueChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const value = e.target.value
+ if (/^\d*$/.test(value))
+ onChange({ timeout: Number(value) || 1, unit })
+ else
+ onChange({ timeout: 1, unit })
+ }
+ return (
+ <div className="flex items-center gap-1">
+ <Input
+ wrapperClassName="w-16"
+ type="number"
+ value={timeout}
+ min={1}
+ onChange={handleValueChange}
+ disabled={readonly}
+ />
+ <div className="flex items-center gap-0.5 rounded-[10px] bg-components-segmented-control-bg-normal p-0.5">
+ <div
+ className={cn(
+ 'rounded-lg px-2 py-1 text-text-tertiary',
+ !readonly && 'cursor-pointer hover:bg-state-base-hover hover:text-text-secondary',
+ unit === 'day' && 'bg-components-segmented-control-item-active-bg text-text-accent-light-mode-only shadow-sm',
+ !readonly && unit === 'day' && 'hover:bg-components-segmented-control-item-active-bg hover:text-text-accent-light-mode-only',
+ )}
+ onClick={() => !readonly && onChange({ timeout, unit: 'day' })}
+ >
+ <div className="system-sm-medium p-0.5">{t(`${i18nPrefix}.timeout.days`, { ns: 'workflow' })}</div>
+ </div>
+ <div
+ className={cn(
+ 'rounded-lg px-2 py-1 text-text-tertiary',
+ !readonly && 'cursor-pointer hover:bg-state-base-hover hover:text-text-secondary',
+ unit === 'hour' && 'bg-components-segmented-control-item-active-bg text-text-accent-light-mode-only shadow-sm',
+ !readonly && unit === 'hour' && 'hover:bg-components-segmented-control-item-active-bg hover:text-text-accent-light-mode-only',
+ )}
+ onClick={() => !readonly && onChange({ timeout, unit: 'hour' })}
+ >
+ <div className="system-sm-medium p-0.5">{t(`${i18nPrefix}.timeout.hours`, { ns: 'workflow' })}</div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default TimeoutInput
diff --git a/web/app/components/workflow/nodes/human-input/components/user-action.tsx b/web/app/components/workflow/nodes/human-input/components/user-action.tsx
new file mode 100644
index 00000000000..d124a80051f
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/user-action.tsx
@@ -0,0 +1,111 @@
+import type { FC } from 'react'
+import type { UserAction } from '../types'
+import {
+ RiDeleteBinLine,
+} from '@remixicon/react'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import Button from '@/app/components/base/button'
+import Input from '@/app/components/base/input'
+import Toast from '@/app/components/base/toast'
+import ButtonStyleDropdown from './button-style-dropdown'
+
+const i18nPrefix = 'nodes.humanInput'
+const ACTION_ID_MAX_LENGTH = 20
+const BUTTON_TEXT_MAX_LENGTH = 20
+
+type UserActionItemProps = {
+ data: UserAction
+ onChange: (state: UserAction) => void
+ onDelete: (id: string) => void
+ readonly?: boolean
+}
+
+const UserActionItem: FC<UserActionItemProps> = ({
+ data,
+ onChange,
+ onDelete,
+ readonly,
+}) => {
+ const { t } = useTranslation()
+
+ const handleIDChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const value = e.target.value
+ if (!value.trim()) {
+ onChange({ ...data, id: '' })
+ return
+ }
+ // Convert spaces to underscores, then only allow characters matching /^[A-Za-z_][A-Za-z0-9_]*$/
+ const withUnderscores = value.replace(/ /g, '_')
+ let sanitized = withUnderscores
+ .split('')
+ .filter((char, index) => {
+ if (index === 0)
+ return /^[a-z_]$/i.test(char)
+ return /^\w$/.test(char)
+ })
+ .join('')
+
+ if (sanitized !== withUnderscores) {
+ Toast.notify({ type: 'error', message: t(`${i18nPrefix}.userActions.actionIdFormatTip`, { ns: 'workflow' }) })
+ return
+ }
+
+ // Limit to 20 characters
+ if (sanitized.length > ACTION_ID_MAX_LENGTH) {
+ sanitized = sanitized.slice(0, ACTION_ID_MAX_LENGTH)
+ Toast.notify({ type: 'error', message: t(`${i18nPrefix}.userActions.actionIdTooLong`, { ns: 'workflow', maxLength: ACTION_ID_MAX_LENGTH }) })
+ }
+
+ if (sanitized)
+ onChange({ ...data, id: sanitized })
+ }
+
+ const handleTextChange = (e: React.ChangeEvent<HTMLInputElement>) => {
+ let value = e.target.value
+ if (value.length > BUTTON_TEXT_MAX_LENGTH) {
+ value = value.slice(0, BUTTON_TEXT_MAX_LENGTH)
+ Toast.notify({ type: 'error', message: t(`${i18nPrefix}.userActions.buttonTextTooLong`, { ns: 'workflow', maxLength: BUTTON_TEXT_MAX_LENGTH }) })
+ }
+ onChange({ ...data, title: value })
+ }
+
+ return (
+ <div className="flex items-center gap-1">
+ <div className="shrink-0">
+ <Input
+ wrapperClassName="w-[120px]"
+ value={data.id}
+ placeholder={t(`${i18nPrefix}.userActions.actionNamePlaceholder`, { ns: 'workflow' })}
+ onChange={handleIDChange}
+ disabled={readonly}
+ />
+ </div>
+ <div className="grow">
+ <Input
+ value={data.title}
+ placeholder={t(`${i18nPrefix}.userActions.buttonTextPlaceholder`, { ns: 'workflow' })}
+ onChange={handleTextChange}
+ disabled={readonly}
+ />
+ </div>
+ <ButtonStyleDropdown
+ text={data.title}
+ data={data.button_style}
+ onChange={type => onChange({ ...data, button_style: type })}
+ readonly={readonly}
+ />
+ {!readonly && (
+ <Button
+ className="px-2"
+ variant="tertiary"
+ onClick={() => onDelete(data.id)}
+ >
+ <RiDeleteBinLine className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ )
+}
+
+export default UserActionItem
diff --git a/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx b/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx
new file mode 100644
index 00000000000..2b9387d7bfd
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx
@@ -0,0 +1,140 @@
+import type * as React from 'react'
+import type { FormInputItemDefault } from '../types'
+
+const variableRegex = /\{\{#(.+?)#\}\}/g
+const noteRegex = /\{\{#\$(.+?)#\}\}/g
+
+export function rehypeVariable() {
+ return (tree: any) => {
+ const iterate = (node: any, index: number, parent: any) => {
+ const value = node.value
+
+ variableRegex.lastIndex = 0
+ noteRegex.lastIndex = 0
+ if (node.type === 'text' && variableRegex.test(value) && !noteRegex.test(value)) {
+ let m: RegExpExecArray | null
+ let last = 0
+ const parts: any[] = []
+ variableRegex.lastIndex = 0
+ m = variableRegex.exec(value)
+ while (m !== null) {
+ if (m.index > last)
+ parts.push({ type: 'text', value: value.slice(last, m.index) })
+
+ parts.push({
+ type: 'element',
+ tagName: 'variable',
+ properties: { 'data-path': m[0].trim() },
+ children: [],
+ })
+
+ last = m.index + m[0].length
+ m = variableRegex.exec(value)
+ }
+
+ if (parts.length) {
+ if (last < value.length)
+ parts.push({ type: 'text', value: value.slice(last) })
+
+ parent.children.splice(index, 1, ...parts)
+ }
+ }
+ if (node.children) {
+ let i = 0
+ // Caution: can not use forEach. Because the length of tree.children may be changed because of change content: parent.children.splice(index, 1, ...parts)
+ while (i < node.children.length) {
+ iterate(node.children[i], i, node)
+ i++
+ }
+ }
+ }
+ let i = 0
+ // Caution: can not use forEach. Because the length of tree.children may be changed because of change content: parent.children.splice(index, 1, ...parts)
+ while (i < tree.children.length) {
+ iterate(tree.children[i], i, tree)
+ i++
+ }
+ }
+}
+
+export function rehypeNotes() {
+ return (tree: any) => {
+ const iterate = (node: any, index: number, parent: any) => {
+ const value = node.value
+
+ noteRegex.lastIndex = 0
+ if (node.type === 'text' && noteRegex.test(value)) {
+ let m: RegExpExecArray | null
+ let last = 0
+ const parts: any[] = []
+ noteRegex.lastIndex = 0
+ m = noteRegex.exec(value)
+ while (m !== null) {
+ if (m.index > last)
+ parts.push({ type: 'text', value: value.slice(last, m.index) })
+
+ const name = m[0].split('.').slice(-1)[0].replace('#}}', '')
+ parts.push({
+ type: 'element',
+ tagName: 'section',
+ properties: { 'data-name': name },
+ children: [],
+ })
+
+ last = m.index + m[0].length
+ m = noteRegex.exec(value)
+ }
+
+ if (parts.length) {
+ if (last < value.length)
+ parts.push({ type: 'text', value: value.slice(last) })
+
+ parent.children.splice(index, 1, ...parts)
+ parent.tagName = 'div' // h2 can not in p. In note content include the h2
+ }
+ }
+ if (node.children) {
+ let i = 0
+ // Caution: can not use forEach. Because the length of tree.children may be changed because of change content: parent.children.splice(index, 1, ...parts)
+ while (i < node.children.length) {
+ iterate(node.children[i], i, node)
+ i++
+ }
+ }
+ }
+ let i = 0
+ // Caution: can not use forEach. Because the length of tree.children may be changed because of change content: parent.children.splice(index, 1, ...parts)
+ while (i < tree.children.length) {
+ iterate(tree.children[i], i, tree)
+ i++
+ }
+ }
+}
+
+export const Variable: React.FC<{ path: string }> = ({ path }) => {
+ return (
+ <span className="text-text-accent">
+ {
+ path.replaceAll('.', '/')
+ .replace('{{#', '{{')
+ .replace('#}}', '}}')
+ }
+ </span>
+ )
+}
+
+export const Note: React.FC<{ defaultInput: FormInputItemDefault, nodeName: (nodeId: string) => string }> = ({ defaultInput, nodeName }) => {
+ const isVariable = defaultInput.type === 'variable'
+ const path = `{{#${defaultInput.selector.join('.')}#}}`
+ let newPath = path
+ if (path) {
+ newPath = path.replace(/#([^#.]+)([.#])/g, (match, nodeId, sep) => {
+ return `#${nodeName(nodeId)}${sep}`
+ })
+ }
+ return (
+ <div className="my-3 rounded-[10px] bg-components-input-bg-normal px-2.5 py-2">
+ {isVariable ? <Variable path={newPath} /> : <span>{defaultInput.value}</span>}
+ </div>
+ )
+}
diff --git a/web/app/components/workflow/nodes/human-input/default.ts b/web/app/components/workflow/nodes/human-input/default.ts
new file mode 100644
index 00000000000..7e3d8d581e7
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/default.ts
@@ -0,0 +1,75 @@
+import type { NodeDefault, Var } from '../../types'
+import type { HumanInputNodeType } from './types'
+import { BlockClassificationEnum } from '@/app/components/workflow/block-selector/types'
+import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import { genNodeMetaData } from '@/app/components/workflow/utils'
+
+const i18nPrefix = 'nodes.humanInput.errorMsg'
+
+const metaData = genNodeMetaData({
+ classification: BlockClassificationEnum.Logic,
+ sort: 1,
+ type: BlockEnum.HumanInput,
+})
+
+const buildOutputVars = (variables: string[]): Var[] => {
+ return variables.map((variable) => {
+ return {
+ variable,
+ type: VarType.string,
+ }
+ })
+}
+
+const nodeDefault: NodeDefault<HumanInputNodeType> = {
+ metaData,
+ defaultValue: {
+ delivery_methods: [],
+ user_actions: [],
+ form_content: '',
+ inputs: [],
+ timeout: 3,
+ timeout_unit: 'day',
+ },
+ checkValid(payload: HumanInputNodeType, t: (str: string, options: Record<string, unknown>) => string) {
+ let errorMessages = ''
+ if (!errorMessages && !payload.delivery_methods.length)
+ errorMessages = t(`${i18nPrefix}.noDeliveryMethod`, { ns: 'workflow' })
+
+ if (!errorMessages && payload.delivery_methods.length > 0 && !payload.delivery_methods.some(method => method.enabled))
+ errorMessages = t(`${i18nPrefix}.noDeliveryMethodEnabled`, { ns: 'workflow' })
+
+ if (!errorMessages && !payload.user_actions.length)
+ errorMessages = t(`${i18nPrefix}.noUserActions`, { ns: 'workflow' })
+
+ if (!errorMessages && payload.user_actions.length > 0) {
+ const actionIds = payload.user_actions.map(action => action.id)
+ const hasDuplicateIds = actionIds.length !== new Set(actionIds).size
+ if (hasDuplicateIds)
+ errorMessages = t(`${i18nPrefix}.duplicateActionId`, { ns: 'workflow' })
+ }
+
+ if (!errorMessages && payload.user_actions.length > 0) {
+ const hasEmptyId = payload.user_actions.some(action => !action.id?.trim())
+ if (hasEmptyId)
+ errorMessages = t(`${i18nPrefix}.emptyActionId`, { ns: 'workflow' })
+ }
+
+ if (!errorMessages && payload.user_actions.length > 0) {
+ const hasEmptyTitle = payload.user_actions.some(action => !action.title?.trim())
+ if (hasEmptyTitle)
+ errorMessages = t(`${i18nPrefix}.emptyActionTitle`, { ns: 'workflow' })
+ }
+
+ return {
+ isValid: !errorMessages,
+ errorMessage: errorMessages,
+ }
+ },
+ getOutputVars(payload, _allPluginInfoList, _ragVars) {
+ const variables = payload.inputs.map(input => input.output_variable_name)
+ return buildOutputVars(variables)
+ },
+}
+
+export default nodeDefault
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-config.ts b/web/app/components/workflow/nodes/human-input/hooks/use-config.ts
new file mode 100644
index 00000000000..dc87cadf1e1
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-config.ts
@@ -0,0 +1,85 @@
+import type { DeliveryMethod, HumanInputNodeType, UserAction } from '../types'
+import { produce } from 'immer'
+import { useState } from 'react'
+import { useUpdateNodeInternals } from 'reactflow'
+import {
+ useNodesReadOnly,
+} from '@/app/components/workflow/hooks'
+import { useEdgesInteractions } from '@/app/components/workflow/hooks/use-edges-interactions'
+import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
+import useFormContent from './use-form-content'
+
+const useConfig = (id: string, payload: HumanInputNodeType) => {
+ const updateNodeInternals = useUpdateNodeInternals()
+ const { nodesReadOnly: readOnly } = useNodesReadOnly()
+ const { inputs, setInputs } = useNodeCrud<HumanInputNodeType>(id, payload)
+ const formContentHook = useFormContent(id, payload)
+ const { handleEdgeDeleteByDeleteBranch, handleEdgeSourceHandleChange } = useEdgesInteractions()
+ const [structuredOutputCollapsed, setStructuredOutputCollapsed] = useState(true)
+
+ const handleDeliveryMethodChange = (methods: DeliveryMethod[]) => {
+ setInputs({
+ ...inputs,
+ delivery_methods: methods,
+ })
+ }
+
+ const handleUserActionAdd = (newAction: UserAction) => {
+ setInputs({
+ ...inputs,
+ user_actions: [...inputs.user_actions, newAction],
+ })
+ }
+
+ const handleUserActionChange = (index: number, updatedAction: UserAction) => {
+ const newActions = produce(inputs.user_actions, (draft) => {
+ if (draft[index])
+ draft[index] = updatedAction
+ })
+ setInputs({
+ ...inputs,
+ user_actions: newActions,
+ })
+
+ // Update edges to use the new handle
+ const oldAction = inputs.user_actions[index]
+
+ if (oldAction && oldAction.id !== updatedAction.id) {
+ handleEdgeSourceHandleChange(id, oldAction.id, updatedAction.id)
+ updateNodeInternals(id) // Update handles
+ }
+ }
+
+ const handleUserActionDelete = (actionId: string) => {
+ const newActions = inputs.user_actions.filter(action => action.id !== actionId)
+ setInputs({
+ ...inputs,
+ user_actions: newActions,
+ })
+ // Delete edges connected to this action
+ handleEdgeDeleteByDeleteBranch(id, actionId)
+ }
+
+ const handleTimeoutChange = ({ timeout, unit }: { timeout: number, unit: 'hour' | 'day' }) => {
+ setInputs({
+ ...inputs,
+ timeout,
+ timeout_unit: unit,
+ })
+ }
+
+ return {
+ readOnly,
+ inputs,
+ handleDeliveryMethodChange,
+ handleUserActionAdd,
+ handleUserActionChange,
+ handleUserActionDelete,
+ handleTimeoutChange,
+ structuredOutputCollapsed,
+ setStructuredOutputCollapsed,
+ ...formContentHook,
+ }
+}
+
+export default useConfig
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts b/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts
new file mode 100644
index 00000000000..c1a75914373
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-form-content.ts
@@ -0,0 +1,65 @@
+import type { FormInputItem, HumanInputNodeType } from '../types'
+import { produce } from 'immer'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { useWorkflow } from '@/app/components/workflow/hooks'
+import useNodeCrud from '../../_base/hooks/use-node-crud'
+
+const useFormContent = (id: string, payload: HumanInputNodeType) => {
+ const [editorKey, setEditorKey] = useState(0)
+ const { inputs, setInputs } = useNodeCrud<HumanInputNodeType>(id, payload)
+ const { handleOutVarRenameChange } = useWorkflow()
+ const inputsRef = useRef(inputs)
+ useEffect(() => {
+ inputsRef.current = inputs
+ }, [inputs])
+ const handleFormContentChange = useCallback((value: string) => {
+ setInputs({
+ ...inputs,
+ form_content: value,
+ })
+ }, [inputs, setInputs])
+
+ const handleFormInputsChange = useCallback((formInputs: FormInputItem[]) => {
+ setInputs({
+ ...inputs,
+ inputs: formInputs,
+ })
+ setEditorKey(editorKey => editorKey + 1)
+ }, [inputs, setInputs])
+
+ const handleFormInputItemRename = useCallback((payload: FormInputItem, oldName: string) => {
+ const inputs = inputsRef.current
+ const newInputs = produce(inputs, (draft) => {
+ draft.form_content = draft.form_content.replaceAll(`{{#$output.${oldName}#}}`, `{{#$output.${payload.output_variable_name}#}}`)
+ draft.inputs = draft.inputs.map(item => item.output_variable_name === oldName ? payload : item)
+ if (!draft.inputs.find(item => item.output_variable_name === payload.output_variable_name))
+ draft.inputs = [...draft.inputs, payload]
+ })
+ setInputs(newInputs)
+ setEditorKey(editorKey => editorKey + 1)
+
+ // Update downstream nodes that reference this variable
+ if (oldName !== payload.output_variable_name)
+ handleOutVarRenameChange(id, [id, oldName], [id, payload.output_variable_name])
+ }, [setInputs, handleOutVarRenameChange, id])
+
+ const handleFormInputItemRemove = useCallback((varName: string) => {
+ const inputs = inputsRef.current
+ const newInputs = produce(inputs, (draft) => {
+ draft.form_content = draft.form_content.replaceAll(`{{#$output.${varName}#}}`, '')
+ draft.inputs = draft.inputs.filter(item => item.output_variable_name !== varName)
+ })
+ setInputs(newInputs)
+ setEditorKey(editorKey => editorKey + 1)
+ }, [setInputs])
+
+ return {
+ editorKey,
+ handleFormContentChange,
+ handleFormInputsChange,
+ handleFormInputItemRename,
+ handleFormInputItemRemove,
+ }
+}
+
+export default useFormContent
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
new file mode 100644
index 00000000000..de7084390b3
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
@@ -0,0 +1,128 @@
+import type { HumanInputNodeType } from '../types'
+import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
+import type { InputVar } from '@/app/components/workflow/types'
+import type { HumanInputFormData } from '@/types/workflow'
+import { useCallback, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useStore as useAppStore } from '@/app/components/app/store'
+import { fetchHumanInputNodeStepRunForm, submitHumanInputNodeStepRunForm } from '@/service/workflow'
+import { AppModeEnum } from '@/types/app'
+import useNodeCrud from '../../_base/hooks/use-node-crud'
+import { isOutput } from '../utils'
+
+const i18nPrefix = 'nodes.humanInput'
+
+type Params = {
+ id: string
+ payload: HumanInputNodeType
+ runInputData: Record<string, string>
+ getInputVars: (textList: string[]) => InputVar[]
+ setRunInputData: (data: Record<string, string>) => void
+}
+const useSingleRunFormParams = ({
+ id,
+ payload,
+ runInputData,
+ getInputVars,
+ setRunInputData,
+}: Params) => {
+ const { t } = useTranslation()
+ const { inputs } = useNodeCrud<HumanInputNodeType>(id, payload)
+ const [showGeneratedForm, setShowGeneratedForm] = useState(false)
+ const [formData, setFormData] = useState<HumanInputFormData | null>(null)
+ const [requiredInputs, setRequiredInputs] = useState<Record<string, string>>({})
+ const generatedInputs = useMemo(() => {
+ const defaultInputs = inputs.inputs.reduce((acc, input) => {
+ if (input.default.type === 'variable') {
+ acc.push(`{{#${input.default.selector.join('.')}#}}`)
+ }
+ return acc
+ }, [] as string[])
+ const allInputs = getInputVars([...defaultInputs, inputs.form_content || '']).filter(item => !isOutput(item.value_selector || []))
+ return allInputs
+ }, [getInputVars, inputs.form_content, inputs.inputs])
+
+ const forms = useMemo(() => {
+ const forms: FormProps[] = [{
+ label: t(`${i18nPrefix}.singleRun.label`, { ns: 'workflow' })!,
+ inputs: generatedInputs,
+ values: runInputData,
+ onChange: setRunInputData,
+ }]
+ return forms
+ }, [t, generatedInputs, runInputData, setRunInputData])
+
+ const getDependentVars = () => {
+ return generatedInputs.map((item) => {
+ // Guard against null/undefined variable to prevent app crash
+ if (!item.variable || typeof item.variable !== 'string')
+ return []
+
+ return item.variable.slice(1, -1).split('.')
+ }).filter(arr => arr.length > 0)
+ }
+
+ const appDetail = useAppStore(s => s.appDetail)
+ const appId = appDetail?.id
+ const isWorkflowMode = appDetail?.mode === AppModeEnum.WORKFLOW
+ const fetchURL = useMemo(() => {
+ if (!appId)
+ return ''
+ if (!isWorkflowMode) {
+ return `/apps/${appId}/advanced-chat/workflows/draft/human-input/nodes/${id}/form`
+ }
+ else {
+ return `/apps/${appId}/workflows/draft/human-input/nodes/${id}/form`
+ }
+ }, [appId, id, isWorkflowMode])
+
+ const handleFetchFormContent = useCallback(async (inputs: Record<string, string>) => {
+ if (!fetchURL)
+ return null
+ let requestParamsObj: Record<string, string> = {}
+ Object.keys(inputs).forEach((key) => {
+ if (inputs[key] === undefined) {
+ delete inputs[key]
+ }
+ })
+ requestParamsObj = { ...inputs }
+ const data = await fetchHumanInputNodeStepRunForm(fetchURL, { inputs: requestParamsObj! })
+ setFormData(data)
+ setRequiredInputs(requestParamsObj)
+ return data
+ }, [fetchURL])
+
+ const handleSubmitHumanInputForm = useCallback(async (formData: {
+ inputs: Record<string, string> | undefined
+ form_inputs: Record<string, string> | undefined
+ action: string
+ }) => {
+ await submitHumanInputNodeStepRunForm(fetchURL, {
+ inputs: requiredInputs,
+ form_inputs: formData.inputs,
+ action: formData.action,
+ })
+ }, [fetchURL, requiredInputs])
+
+ const handleShowGeneratedForm = async (formValue: Record<string, string>) => {
+ setShowGeneratedForm(true)
+ await handleFetchFormContent(formValue)
+ }
+
+ const handleHideGeneratedForm = () => {
+ setShowGeneratedForm(false)
+ }
+
+ return {
+ forms,
+ getDependentVars,
+ showGeneratedForm,
+ handleShowGeneratedForm,
+ handleHideGeneratedForm,
+ formData,
+ handleFetchFormContent,
+ handleSubmitHumanInputForm,
+ }
+}
+
+export default useSingleRunFormParams
diff --git a/web/app/components/workflow/nodes/human-input/node.tsx b/web/app/components/workflow/nodes/human-input/node.tsx
new file mode 100644
index 00000000000..289c2efdc7f
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/node.tsx
@@ -0,0 +1,74 @@
+import type { FC } from 'react'
+import type { HumanInputNodeType } from './types'
+import type { NodeProps } from '@/app/components/workflow/types'
+import {
+ RiMailSendFill,
+ RiRobot2Fill,
+} from '@remixicon/react'
+import * as React from 'react'
+import { useTranslation } from 'react-i18next'
+import { NodeSourceHandle } from '../_base/components/node-handle'
+import { DeliveryMethodType } from './types'
+
+const i18nPrefix = 'nodes.humanInput'
+
+const Node: FC<NodeProps<HumanInputNodeType>> = (props) => {
+ const { t } = useTranslation()
+
+ const { data } = props
+ const deliveryMethods = data.delivery_methods
+ const userActions = data.user_actions
+
+ return (
+ <>
+ {deliveryMethods.length > 0 && (
+ <div className="space-y-0.5 py-1">
+ <div className="system-2xs-medium-uppercase px-2.5 py-0.5 text-text-tertiary">{t(`${i18nPrefix}.deliveryMethod.title`, { ns: 'workflow' })}</div>
+ <div className="space-y-0.5 px-2.5">
+ {deliveryMethods.map(method => (
+ <div key={method.type} className="flex items-center gap-1 rounded-[6px] bg-workflow-block-parma-bg p-1">
+ {method.type === DeliveryMethodType.WebApp && (
+ <div className="rounded-[4px] border border-divider-regular bg-components-icon-bg-indigo-solid p-0.5">
+ <RiRobot2Fill className="h-3.5 w-3.5 text-text-primary-on-surface" />
+ </div>
+ )}
+ {method.type === DeliveryMethodType.Email && (
+ <div className="rounded-[4px] border border-divider-regular bg-components-icon-bg-blue-solid p-0.5">
+ <RiMailSendFill className="h-3.5 w-3.5 text-text-primary-on-surface" />
+ </div>
+ )}
+ <span className="system-xs-regular capitalize text-text-secondary">{method.type}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ <div className="space-y-0.5 py-1">
+ {userActions.length > 0 && (
+ <>
+ {userActions.map(userAction => (
+ <div key={userAction.id} className="relative flex flex-row-reverse items-center px-4 py-1">
+ <span className="system-xs-semibold-uppercase truncate text-text-secondary">{userAction.id}</span>
+ <NodeSourceHandle
+ {...props}
+ handleId={userAction.id}
+ handleClassName="!top-1/2 !-right-[9px] !-translate-y-1/2"
+ />
+ </div>
+ ))}
+ </>
+ )}
+ <div className="relative flex flex-row-reverse items-center px-4 py-1">
+ <div className="system-xs-semibold-uppercase truncate text-text-secondary">Timeout</div>
+ <NodeSourceHandle
+ {...props}
+ handleId="__timeout"
+ handleClassName="!top-1/2 !-right-[9px] !-translate-y-1/2"
+ />
+ </div>
+ </div>
+ </>
+ )
+}
+
+export default React.memo(Node)
diff --git a/web/app/components/workflow/nodes/human-input/panel.tsx b/web/app/components/workflow/nodes/human-input/panel.tsx
new file mode 100644
index 00000000000..525821d0424
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/panel.tsx
@@ -0,0 +1,251 @@
+import type { FC } from 'react'
+import type { HumanInputNodeType } from './types'
+import type { NodePanelProps, Var } from '@/app/components/workflow/types'
+import {
+ RiAddLine,
+ RiClipboardLine,
+ RiCollapseDiagonalLine,
+ RiExpandDiagonalLine,
+ RiEyeLine,
+} from '@remixicon/react'
+import { useBoolean } from 'ahooks'
+import copy from 'copy-to-clipboard'
+import * as React from 'react'
+import { useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import ActionButton from '@/app/components/base/action-button'
+import Button from '@/app/components/base/button'
+import Divider from '@/app/components/base/divider'
+import Toast from '@/app/components/base/toast'
+import Tooltip from '@/app/components/base/tooltip'
+import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'
+import Split from '@/app/components/workflow/nodes/_base/components/split'
+import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
+import { useStore } from '@/app/components/workflow/store'
+import { VarType } from '@/app/components/workflow/types'
+import { cn } from '@/utils/classnames'
+import DeliveryMethod from './components/delivery-method'
+import FormContent from './components/form-content'
+import FormContentPreview from './components/form-content-preview'
+import TimeoutInput from './components/timeout'
+import UserActionItem from './components/user-action'
+import useConfig from './hooks/use-config'
+import { UserActionButtonType } from './types'
+
+const i18nPrefix = 'nodes.humanInput'
+
+const Panel: FC<NodePanelProps<HumanInputNodeType>> = ({
+ id,
+ data,
+}) => {
+ const { t } = useTranslation()
+ const {
+ readOnly,
+ inputs,
+ handleDeliveryMethodChange,
+ handleUserActionAdd,
+ handleUserActionChange,
+ handleUserActionDelete,
+ handleTimeoutChange,
+ handleFormContentChange,
+ handleFormInputsChange,
+ handleFormInputItemRename,
+ handleFormInputItemRemove,
+ editorKey,
+ structuredOutputCollapsed,
+ setStructuredOutputCollapsed,
+ } = useConfig(id, data)
+
+ const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {
+ onlyLeafNodeVar: false,
+ filterVar: (varPayload: Var) => {
+ return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
+ },
+ })
+
+ const [isExpandFormContent, {
+ toggle: toggleExpandFormContent,
+ }] = useBoolean(false)
+ const nodePanelWidth = useStore(state => state.nodePanelWidth)
+
+ const [isPreview, {
+ toggle: togglePreview,
+ setFalse: hidePreview,
+ }] = useBoolean(false)
+
+ const onAddUseAction = useCallback(() => {
+ const index = inputs.user_actions.length + 1
+ handleUserActionAdd({
+ id: `action_${index}`,
+ title: `Button Text ${index}`,
+ button_style: UserActionButtonType.Default,
+ })
+ }, [handleUserActionAdd, inputs.user_actions.length])
+
+ return (
+ <div className="py-2">
+ {/* delivery methods */}
+ <DeliveryMethod
+ nodeId={id}
+ value={inputs.delivery_methods || []}
+ formContent={inputs.form_content}
+ formInputs={inputs.inputs}
+ nodesOutputVars={availableVars}
+ availableNodes={availableNodesWithParent}
+ onChange={handleDeliveryMethodChange}
+ readonly={readOnly}
+ />
+ <div className="px-4 py-2">
+ <Divider className="!my-0 !h-px !bg-divider-subtle" />
+ </div>
+ {/* form content */}
+ <div
+ className={cn('px-4 py-2', isExpandFormContent && 'fixed bottom-[8px] right-[4px] top-[244px] z-10 flex flex-col rounded-b-2xl bg-components-panel-bg')}
+ style={{
+ width: isExpandFormContent ? nodePanelWidth : '100%',
+ }}
+ >
+ <div className="mb-1 flex shrink-0 items-center justify-between">
+ <div className="flex h-6 items-center gap-0.5">
+ <div className="system-sm-semibold-uppercase text-text-secondary">{t(`${i18nPrefix}.formContent.title`, { ns: 'workflow' })}</div>
+ <Tooltip
+ popupContent={t(`${i18nPrefix}.formContent.tooltip`, { ns: 'workflow' })}
+ />
+ </div>
+ {!readOnly && (
+ <div className="flex items-center ">
+ <Button
+ variant="ghost"
+ size="small"
+ className={cn(
+ 'flex items-center space-x-1 px-2',
+ isPreview && 'bg-state-accent-active text-text-accent',
+ )}
+ onClick={togglePreview}
+ >
+ <RiEyeLine className="size-3.5" />
+ <div className="system-xs-medium">{t(`${i18nPrefix}.formContent.preview`, { ns: 'workflow' })}</div>
+ </Button>
+ <div className="mx-2 h-3 w-px bg-divider-regular"></div>
+ <div className="flex items-center space-x-1">
+ <div
+ className="flex size-6 cursor-pointer items-center justify-center rounded-md hover:bg-components-button-ghost-bg-hover"
+ onClick={() => {
+ copy(inputs.form_content)
+ Toast.notify({ type: 'success', message: t('actionMsg.copySuccessfully', { ns: 'common' }) })
+ }}
+ >
+ <RiClipboardLine className="h-4 w-4 text-text-secondary" />
+ </div>
+ <div className={cn('flex size-6 cursor-pointer items-center justify-center rounded-md text-text-secondary hover:bg-components-button-ghost-bg-hover', isExpandFormContent && 'bg-state-accent-active text-text-accent')} onClick={toggleExpandFormContent}>
+ {isExpandFormContent ? <RiCollapseDiagonalLine className="h-4 w-4" /> : <RiExpandDiagonalLine className="h-4 w-4" />}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ <FormContent
+ editorKey={editorKey}
+ nodeId={id}
+ value={inputs.form_content}
+ onChange={handleFormContentChange}
+ formInputs={inputs.inputs}
+ onFormInputsChange={handleFormInputsChange}
+ onFormInputItemRename={handleFormInputItemRename}
+ onFormInputItemRemove={handleFormInputItemRemove}
+ isExpand={isExpandFormContent}
+ availableVars={availableVars}
+ availableNodes={availableNodesWithParent}
+ readonly={readOnly}
+ />
+ </div>
+ {/* user actions */}
+ <div className="px-4 py-2">
+ <div className="mb-1 flex items-center justify-between">
+ <div className="flex items-center gap-0.5">
+ <div className="system-sm-semibold-uppercase text-text-secondary">{t(`${i18nPrefix}.userActions.title`, { ns: 'workflow' })}</div>
+ <Tooltip
+ popupContent={t(`${i18nPrefix}.userActions.tooltip`, { ns: 'workflow' })}
+ />
+ </div>
+ {!readOnly && (
+ <div className="flex items-center px-1">
+ <ActionButton
+ onClick={onAddUseAction}
+ >
+ <RiAddLine className="h-4 w-4" />
+ </ActionButton>
+ </div>
+ )}
+ </div>
+ {!inputs.user_actions.length && (
+ <div className="system-xs-regular flex items-center justify-center rounded-[10px] bg-background-section p-3 text-text-tertiary">{t(`${i18nPrefix}.userActions.emptyTip`, { ns: 'workflow' })}</div>
+ )}
+ {inputs.user_actions.length > 0 && (
+ <div className="space-y-2">
+ {inputs.user_actions.map((action, index) => (
+ <UserActionItem
+ key={index}
+ data={action}
+ onChange={data => handleUserActionChange(index, data)}
+ onDelete={handleUserActionDelete}
+ readonly={readOnly}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="px-4 py-2">
+ <Divider className="!my-0 !h-px !bg-divider-subtle" />
+ </div>
+ {/* timeout */}
+ <div className="flex items-center justify-between px-4 py-2">
+ <div className="system-sm-semibold-uppercase text-text-secondary">{t(`${i18nPrefix}.timeout.title`, { ns: 'workflow' })}</div>
+ <TimeoutInput
+ timeout={inputs.timeout}
+ unit={inputs.timeout_unit}
+ onChange={handleTimeoutChange}
+ readonly={readOnly}
+ />
+ </div>
+ {/* output vars */}
+ <Split />
+ <OutputVars
+ collapsed={structuredOutputCollapsed}
+ onCollapse={setStructuredOutputCollapsed}
+ >
+ {
+ inputs.inputs.map(input => (
+ <VarItem
+ key={input.output_variable_name}
+ name={input.output_variable_name}
+ type={VarType.string}
+ description="Form input value"
+ />
+ ))
+ }
+ <VarItem
+ name="__action_id"
+ type="string"
+ description="Action ID user triggered"
+ />
+ <VarItem
+ name="__rendered_content"
+ type="string"
+ description="Rendered content"
+ />
+ </OutputVars>
+
+ {isPreview && (
+ <FormContentPreview
+ content={inputs.form_content}
+ formInputs={inputs.inputs}
+ userActions={inputs.user_actions}
+ onClose={hidePreview}
+ />
+ )}
+ </div>
+ )
+}
+
+export default React.memo(Panel)
diff --git a/web/app/components/workflow/nodes/human-input/types.ts b/web/app/components/workflow/nodes/human-input/types.ts
new file mode 100644
index 00000000000..128cfd8b98d
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/types.ts
@@ -0,0 +1,72 @@
+import type {
+ CommonNodeType,
+ InputVarType,
+ ValueSelector,
+} from '@/app/components/workflow/types'
+
+export type HumanInputNodeType = CommonNodeType & {
+ delivery_methods: DeliveryMethod[]
+ form_content: string
+ inputs: FormInputItem[]
+ user_actions: UserAction[]
+ timeout: number
+ timeout_unit: 'hour' | 'day'
+}
+
+export enum DeliveryMethodType {
+ WebApp = 'webapp',
+ Email = 'email',
+ Slack = 'slack',
+ Teams = 'teams',
+ Discord = 'discord',
+}
+
+export type Recipient = {
+ type: 'member' | 'external'
+ email?: string
+ user_id?: string
+}
+
+export type RecipientData = {
+ whole_workspace: boolean
+ items: Recipient[]
+}
+
+export type EmailConfig = {
+ recipients: RecipientData
+ subject: string
+ body: string
+ debug_mode: boolean
+}
+
+export type DeliveryMethod = {
+ id: string
+ type: DeliveryMethodType
+ enabled: boolean
+ config?: EmailConfig
+}
+
+export enum UserActionButtonType {
+ Primary = 'primary',
+ Default = 'default',
+ Accent = 'accent',
+ Ghost = 'ghost',
+}
+
+export type UserAction = {
+ id: string
+ title: string
+ button_style: UserActionButtonType
+}
+
+export type FormInputItemDefault = {
+ selector: ValueSelector
+ type: 'variable' | 'constant'
+ value: string
+}
+
+export type FormInputItem = {
+ type: InputVarType
+ output_variable_name: string
+ default: FormInputItemDefault
+}
diff --git a/web/app/components/workflow/nodes/human-input/utils.ts b/web/app/components/workflow/nodes/human-input/utils.ts
new file mode 100644
index 00000000000..59358fab1eb
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/utils.ts
@@ -0,0 +1,3 @@
+export const isOutput = (valueSelector: string[]) => {
+ return valueSelector[0] === '$output'
+}
diff --git a/web/app/components/workflow/nodes/llm/panel.tsx b/web/app/components/workflow/nodes/llm/panel.tsx
index 670d3149be5..7146d9e64a1 100644
--- a/web/app/components/workflow/nodes/llm/panel.tsx
+++ b/web/app/components/workflow/nodes/llm/panel.tsx
@@ -94,7 +94,8 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({
handleModelChanged(model)
}
})()
- }, [inputs.model.completion_params])
+ }, [handleCompletionParamsChange, handleModelChanged, inputs.model.completion_params, t])
+
return (
<div className="mt-2">
<div className="space-y-4 px-4 pb-4">
diff --git a/web/app/components/workflow/nodes/tool/components/mixed-variable-text-input/placeholder.tsx b/web/app/components/workflow/nodes/tool/components/mixed-variable-text-input/placeholder.tsx
index 6e999975f17..a1f71527964 100644
--- a/web/app/components/workflow/nodes/tool/components/mixed-variable-text-input/placeholder.tsx
+++ b/web/app/components/workflow/nodes/tool/components/mixed-variable-text-input/placeholder.tsx
@@ -4,12 +4,14 @@ import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge'
import { CustomTextNode } from '@/app/components/base/prompt-editor/plugins/custom-text/node'
+import { cn } from '@/utils/classnames'
type PlaceholderProps = {
disableVariableInsertion?: boolean
+ hideBadge?: boolean
}
-const Placeholder = ({ disableVariableInsertion = false }: PlaceholderProps) => {
+const Placeholder = ({ disableVariableInsertion = false, hideBadge = false }: PlaceholderProps) => {
const { t } = useTranslation()
const [editor] = useLexicalComposerContext()
@@ -23,7 +25,10 @@ const Placeholder = ({ disableVariableInsertion = false }: PlaceholderProps) =>
return (
<div
- className="pointer-events-auto flex h-full w-full cursor-text items-center px-2"
+ className={cn(
+ 'pointer-events-auto flex h-full w-full cursor-text px-2',
+ !hideBadge ? 'items-center' : 'items-start py-1',
+ )}
onClick={(e) => {
e.stopPropagation()
handleInsert('')
@@ -47,11 +52,13 @@ const Placeholder = ({ disableVariableInsertion = false }: PlaceholderProps) =>
</>
)}
</div>
- <Badge
- className="shrink-0"
- text="String"
- uppercase={false}
- />
+ {!hideBadge && (
+ <Badge
+ className="shrink-0"
+ text="String"
+ uppercase={false}
+ />
+ )}
</div>
)
}
diff --git a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx
index 8ff356cad7f..d7023c079ca 100644
--- a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx
@@ -18,7 +18,7 @@ import {
useStore,
useWorkflowStore,
} from '../../store'
-import { BlockEnum } from '../../types'
+import { BlockEnum, WorkflowRunningStatus } from '../../types'
import ConversationVariableModal from './conversation-variable-modal'
import Empty from './empty'
import { useChat } from './hooks'
@@ -84,7 +84,9 @@ const ChatWrapper = (
suggestedQuestions,
handleSend,
handleRestart,
- setTargetMessageId,
+ handleSwitchSibling,
+ handleSubmitHumanInputForm,
+ getHumanInputNodeData,
} = useChat(
config,
{
@@ -121,6 +123,22 @@ const ChatWrapper = (
doSend(editedQuestion ? editedQuestion.message : question.content, editedQuestion ? editedQuestion.files : question.message_files, true, isValidGeneratedAnswer(parentAnswer) ? parentAnswer : null)
}, [chatList, doSend])
+ const doSwitchSibling = useCallback((siblingMessageId: string) => {
+ handleSwitchSibling(siblingMessageId, {
+ onGetSuggestedQuestions: (messageId, getAbortController) => fetchSuggestedQuestions(appDetail!.id, messageId, getAbortController),
+ })
+ }, [handleSwitchSibling, appDetail])
+
+ const doHumanInputFormSubmit = useCallback(async (formToken: string, formData: any) => {
+ // Handle human input form submission
+ await handleSubmitHumanInputForm(formToken, formData)
+ }, [handleSubmitHumanInputForm])
+
+ const inputDisabled = useMemo(() => {
+ const latestMessage = chatList[chatList.length - 1]
+ return latestMessage?.isAnswer && (latestMessage.workflowProcess?.status === WorkflowRunningStatus.Paused)
+ }, [chatList])
+
const { eventEmitter } = useEventEmitterContextContext()
eventEmitter?.useSubscription((v: any) => {
if (v.type === EVENT_WORKFLOW_STOP)
@@ -168,6 +186,8 @@ const ChatWrapper = (
inputsForm={(startVariables || []) as any}
onRegenerate={doRegenerate}
onStopResponding={handleStop}
+ onHumanInputFormSubmit={doHumanInputFormSubmit}
+ getHumanInputNodeData={getHumanInputNodeData}
chatNode={(
<>
{showInputsFieldsPanel && <UserInput />}
@@ -182,7 +202,9 @@ const ChatWrapper = (
suggestedQuestions={suggestedQuestions}
showPromptLog
chatAnswerContainerInner="!pr-2"
- switchSibling={setTargetMessageId}
+ switchSibling={doSwitchSibling}
+ inputDisabled={inputDisabled}
+ hideAvatar
/>
{showConversationVariableModal && (
<ConversationVariableModal
diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.ts
index 2c46833df8e..b31673ee260 100644
--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts
@@ -5,6 +5,7 @@ import type {
Inputs,
} from '@/app/components/base/chat/types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
+import type { IOtherOptions } from '@/service/base'
import { uniqBy } from 'es-toolkit/compat'
import { produce, setAutoFreeze } from 'immer'
import {
@@ -15,6 +16,7 @@ import {
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
+import { useStoreApi } from 'reactflow'
import {
getProcessedInputs,
processOpeningStatement,
@@ -25,7 +27,12 @@ import {
getProcessedFilesFromResponse,
} from '@/app/components/base/file-uploader/utils'
import { useToastContext } from '@/app/components/base/toast'
+import {
+ CUSTOM_NODE,
+} from '@/app/components/workflow/constants'
+import { sseGet } from '@/service/base'
import { useInvalidAllLastRun } from '@/service/use-workflow'
+import { submitHumanInputForm } from '@/service/workflow'
import { TransferMethod } from '@/types/app'
import { DEFAULT_ITER_TIMES, DEFAULT_LOOP_TIMES } from '../../constants'
import {
@@ -58,6 +65,7 @@ export const useChat = (
const taskIdRef = useRef('')
const [isResponding, setIsResponding] = useState(false)
const isRespondingRef = useRef(false)
+ const workflowEventsAbortControllerRef = useRef<AbortController | null>(null)
const configsMap = useHooksStore(s => s.configsMap)
const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)
const { fetchInspectVars } = useSetWorkflowVarsWithValue()
@@ -67,6 +75,7 @@ export const useChat = (
setIterTimes,
setLoopTimes,
} = workflowStore.getState()
+ const store = useStoreApi()
const handleResponding = useCallback((isResponding: boolean) => {
setIsResponding(isResponding)
@@ -131,6 +140,29 @@ export const useChat = (
})
}, [])
+ type UpdateChatTreeNode = {
+ (id: string, fields: Partial<ChatItemInTree>): void
+ (id: string, update: (node: ChatItemInTree) => void): void
+ }
+
+ const updateChatTreeNode: UpdateChatTreeNode = useCallback((
+ id: string,
+ fieldsOrUpdate: Partial<ChatItemInTree> | ((node: ChatItemInTree) => void),
+ ) => {
+ const nextState = produceChatTreeNode(id, (node) => {
+ if (typeof fieldsOrUpdate === 'function') {
+ fieldsOrUpdate(node)
+ }
+ else {
+ Object.keys(fieldsOrUpdate).forEach((key) => {
+ (node as any)[key] = (fieldsOrUpdate as any)[key]
+ })
+ }
+ })
+ setChatTree(nextState)
+ chatTreeRef.current = nextState
+ }, [produceChatTreeNode])
+
const handleStop = useCallback(() => {
hasStopResponded.current = true
handleResponding(false)
@@ -140,6 +172,8 @@ export const useChat = (
setLoopTimes(DEFAULT_LOOP_TIMES)
if (suggestedQuestionsAbortControllerRef.current)
suggestedQuestionsAbortControllerRef.current.abort()
+ if (workflowEventsAbortControllerRef.current)
+ workflowEventsAbortControllerRef.current.abort()
}, [handleResponding, setIterTimes, setLoopTimes, stopChat])
const handleRestart = useCallback(() => {
@@ -206,6 +240,10 @@ export const useChat = (
return false
}
+ // Abort previous handleResume SSE connection if any
+ if (workflowEventsAbortControllerRef.current)
+ workflowEventsAbortControllerRef.current.abort()
+
const parentMessage = threadMessages.find(item => item.id === params.parent_message_id)
const placeholderQuestionId = `question-${Date.now()}`
@@ -243,6 +281,8 @@ export const useChat = (
isAnswer: true,
parentMessageId: questionItem.id,
siblingIndex: parentMessage?.children?.length ?? chatTree.length,
+ humanInputFormDataList: [],
+ humanInputFilledFormDataList: [],
}
handleResponding(true)
@@ -270,6 +310,9 @@ export const useChat = (
handleRun(
bodyParams,
{
+ getAbortController: (abortController) => {
+ workflowEventsAbortControllerRef.current = abortController
+ },
onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
responseItem.content = responseItem.content + message
@@ -295,35 +338,38 @@ export const useChat = (
})
},
async onCompleted(hasError?: boolean, errorMessage?: string) {
+ const { workflowRunningData } = workflowStore.getState()
handleResponding(false)
- fetchInspectVars({})
- invalidAllLastRun()
-
- if (hasError) {
- if (errorMessage) {
- responseItem.content = errorMessage
- responseItem.isError = true
- updateCurrentQAOnTree({
- placeholderQuestionId,
- questionItem,
- responseItem,
- parentId: params.parent_message_id,
- })
+ if (workflowRunningData?.result.status !== WorkflowRunningStatus.Paused) {
+ fetchInspectVars({})
+ invalidAllLastRun()
+
+ if (hasError) {
+ if (errorMessage) {
+ responseItem.content = errorMessage
+ responseItem.isError = true
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: params.parent_message_id,
+ })
+ }
+ return
}
- return
- }
- if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
- try {
- const { data }: any = await onGetSuggestedQuestions(
- responseItem.id,
- newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
- )
- setSuggestQuestions(data)
- }
- // eslint-disable-next-line unused-imports/no-unused-vars
- catch (error) {
- setSuggestQuestions([])
+ if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
+ try {
+ const { data }: any = await onGetSuggestedQuestions(
+ responseItem.id,
+ newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ )
+ setSuggestQuestions(data)
+ }
+ // eslint-disable-next-line unused-imports/no-unused-vars
+ catch (error) {
+ setSuggestQuestions([])
+ }
}
}
},
@@ -345,12 +391,29 @@ export const useChat = (
onError() {
handleResponding(false)
},
- onWorkflowStarted: ({ workflow_run_id, task_id }) => {
- taskIdRef.current = task_id
- responseItem.workflow_run_id = workflow_run_id
- responseItem.workflowProcess = {
- status: WorkflowRunningStatus.Running,
- tracing: [],
+ onWorkflowStarted: ({ workflow_run_id, task_id, conversation_id, message_id }) => {
+ // If there are no streaming messages, we still need to set the conversation_id to avoid create a new conversation when regeneration in chat-flow.
+ if (conversation_id) {
+ conversationId.current = conversation_id
+ }
+ if (message_id && !hasSetResponseId) {
+ questionItem.id = `question-${message_id}`
+ responseItem.id = message_id
+ responseItem.parentMessageId = questionItem.id
+ hasSetResponseId = true
+ }
+
+ if (responseItem.workflowProcess && responseItem.workflowProcess.tracing.length > 0) {
+ handleResponding(true)
+ responseItem.workflowProcess.status = WorkflowRunningStatus.Running
+ }
+ else {
+ taskIdRef.current = task_id
+ responseItem.workflow_run_id = workflow_run_id
+ responseItem.workflowProcess = {
+ status: WorkflowRunningStatus.Running,
+ tracing: [],
+ }
}
updateCurrentQAOnTree({
placeholderQuestionId,
@@ -423,10 +486,19 @@ export const useChat = (
}
},
onNodeStarted: ({ data }) => {
- responseItem.workflowProcess!.tracing!.push({
- ...data,
- status: NodeRunningStatus.Running,
- } as any)
+ const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
+ if (currentIndex > -1) {
+ responseItem.workflowProcess!.tracing![currentIndex] = {
+ ...data,
+ status: NodeRunningStatus.Running,
+ }
+ }
+ else {
+ responseItem.workflowProcess!.tracing!.push({
+ ...data,
+ status: NodeRunningStatus.Running,
+ })
+ }
updateCurrentQAOnTree({
placeholderQuestionId,
questionItem,
@@ -499,17 +571,383 @@ export const useChat = (
})
}
},
+ onHumanInputRequired: ({ data }) => {
+ if (!responseItem.humanInputFormDataList) {
+ responseItem.humanInputFormDataList = [data]
+ }
+ else {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
+ if (currentFormIndex > -1) {
+ responseItem.humanInputFormDataList[currentFormIndex] = data
+ }
+ else {
+ responseItem.humanInputFormDataList.push(data)
+ }
+ }
+ const currentTracingIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)
+ if (currentTracingIndex > -1) {
+ responseItem.workflowProcess!.tracing[currentTracingIndex].status = NodeRunningStatus.Paused
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: params.parent_message_id,
+ })
+ }
+ },
+ onHumanInputFormFilled: ({ data }) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
+ responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
+ if (!responseItem.humanInputFilledFormDataList) {
+ responseItem.humanInputFilledFormDataList = [data]
+ }
+ else {
+ responseItem.humanInputFilledFormDataList.push(data)
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: params.parent_message_id,
+ })
+ },
+ onHumanInputFormTimeout: ({ data }) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === data.node_id)
+ responseItem.humanInputFormDataList[currentFormIndex].expiration_time = data.expiration_time
+ }
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: params.parent_message_id,
+ })
+ },
+ onWorkflowPaused: ({ data: _data }) => {
+ responseItem.workflowProcess!.status = WorkflowRunningStatus.Paused
+ updateCurrentQAOnTree({
+ placeholderQuestionId,
+ questionItem,
+ responseItem,
+ parentId: params.parent_message_id,
+ })
+ },
+ },
+ )
+ }, [threadMessages, chatTree.length, updateCurrentQAOnTree, handleResponding, formSettings?.inputsForm, handleRun, notify, t, workflowStore, fetchInspectVars, invalidAllLastRun, config?.suggested_questions_after_answer?.enabled])
+
+ const handleSubmitHumanInputForm = async (formToken: string, formData: any) => {
+ await submitHumanInputForm(formToken, formData)
+ }
+
+ const getHumanInputNodeData = (nodeID: string) => {
+ const {
+ getNodes,
+ } = store.getState()
+ const nodes = getNodes().filter(node => node.type === CUSTOM_NODE)
+ const node = nodes.find(n => n.id === nodeID)
+ return node
+ }
+
+ const handleResume = useCallback((
+ messageId: string,
+ workflowRunId: string,
+ {
+ onGetSuggestedQuestions,
+ }: SendCallback,
+ ) => {
+ // Re-subscribe to workflow events for the specific message
+ const url = `/workflow/${workflowRunId}/events?include_state_snapshot=true`
+
+ const otherOptions: IOtherOptions = {
+ getAbortController: (abortController) => {
+ workflowEventsAbortControllerRef.current = abortController
+ },
+ onData: (message: string, _isFirstMessage: boolean, { conversationId: newConversationId, messageId: msgId, taskId }: any) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ responseItem.content = responseItem.content + message
+ if (msgId)
+ responseItem.id = msgId
+ })
+
+ if (newConversationId)
+ conversationId.current = newConversationId
+
+ if (taskId)
+ taskIdRef.current = taskId
+ },
+ async onCompleted(hasError?: boolean) {
+ const { workflowRunningData } = workflowStore.getState()
+ handleResponding(false)
+
+ if (workflowRunningData?.result.status !== WorkflowRunningStatus.Paused) {
+ fetchInspectVars({})
+ invalidAllLastRun()
+
+ if (hasError)
+ return
+
+ if (config?.suggested_questions_after_answer?.enabled && !hasStopResponded.current && onGetSuggestedQuestions) {
+ try {
+ const { data }: any = await onGetSuggestedQuestions(
+ messageId,
+ newAbortController => suggestedQuestionsAbortControllerRef.current = newAbortController,
+ )
+ setSuggestQuestions(data)
+ }
+ catch {
+ setSuggestQuestions([])
+ }
+ }
+ }
+ },
+ onMessageEnd: (messageEnd) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ responseItem.citation = messageEnd.metadata?.retriever_resources || []
+ const processedFilesFromResponse = getProcessedFilesFromResponse(messageEnd.files || [])
+ responseItem.allFiles = uniqBy([...(responseItem.allFiles || []), ...(processedFilesFromResponse || [])], 'id')
+ })
},
+ onMessageReplace: (messageReplace) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ responseItem.content = messageReplace.answer
+ })
+ },
+ onError() {
+ handleResponding(false)
+ },
+ onWorkflowStarted: ({ workflow_run_id, task_id }) => {
+ handleResponding(true)
+ hasStopResponded.current = false
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.workflowProcess && responseItem.workflowProcess.tracing.length > 0) {
+ responseItem.workflowProcess.status = WorkflowRunningStatus.Running
+ }
+ else {
+ taskIdRef.current = task_id
+ responseItem.workflow_run_id = workflow_run_id
+ responseItem.workflowProcess = {
+ status: WorkflowRunningStatus.Running,
+ tracing: [],
+ }
+ }
+ })
+ },
+ onWorkflowFinished: ({ data: workflowFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.workflowProcess)
+ responseItem.workflowProcess.status = workflowFinishedData.status as WorkflowRunningStatus
+ })
+ },
+ onIterationStart: ({ data: iterationStartedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+ responseItem.workflowProcess.tracing.push({
+ ...iterationStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ })
+ },
+ onIterationFinish: ({ data: iterationFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess?.tracing)
+ return
+ const tracing = responseItem.workflowProcess.tracing
+ const iterationIndex = tracing.findIndex(item => item.node_id === iterationFinishedData.node_id
+ && (item.execution_metadata?.parallel_id === iterationFinishedData.execution_metadata?.parallel_id || item.parallel_id === iterationFinishedData.execution_metadata?.parallel_id))!
+ if (iterationIndex > -1) {
+ tracing[iterationIndex] = {
+ ...tracing[iterationIndex],
+ ...iterationFinishedData,
+ status: WorkflowRunningStatus.Succeeded,
+ }
+ }
+ })
+ },
+ onNodeStarted: ({ data: nodeStartedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+
+ const currentIndex = responseItem.workflowProcess.tracing.findIndex(item => item.node_id === nodeStartedData.node_id)
+ if (currentIndex > -1) {
+ responseItem.workflowProcess.tracing[currentIndex] = {
+ ...nodeStartedData,
+ status: NodeRunningStatus.Running,
+ }
+ }
+ else {
+ if (nodeStartedData.iteration_id)
+ return
+
+ responseItem.workflowProcess.tracing.push({
+ ...nodeStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ }
+ })
+ },
+ onNodeFinished: ({ data: nodeFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess?.tracing)
+ return
+
+ if (nodeFinishedData.iteration_id)
+ return
+
+ const currentIndex = responseItem.workflowProcess.tracing.findIndex((item) => {
+ if (!item.execution_metadata?.parallel_id)
+ return item.id === nodeFinishedData.id
+
+ return item.id === nodeFinishedData.id && (item.execution_metadata?.parallel_id === nodeFinishedData.execution_metadata?.parallel_id)
+ })
+ if (currentIndex > -1)
+ responseItem.workflowProcess.tracing[currentIndex] = nodeFinishedData as any
+ })
+ },
+ onLoopStart: ({ data: loopStartedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess)
+ return
+ if (!responseItem.workflowProcess.tracing)
+ responseItem.workflowProcess.tracing = []
+ responseItem.workflowProcess.tracing.push({
+ ...loopStartedData,
+ status: WorkflowRunningStatus.Running,
+ })
+ })
+ },
+ onLoopFinish: ({ data: loopFinishedData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.workflowProcess?.tracing)
+ return
+ const tracing = responseItem.workflowProcess.tracing
+ const loopIndex = tracing.findIndex(item => item.node_id === loopFinishedData.node_id
+ && (item.execution_metadata?.parallel_id === loopFinishedData.execution_metadata?.parallel_id || item.parallel_id === loopFinishedData.execution_metadata?.parallel_id))!
+ if (loopIndex > -1) {
+ tracing[loopIndex] = {
+ ...tracing[loopIndex],
+ ...loopFinishedData,
+ status: WorkflowRunningStatus.Succeeded,
+ }
+ }
+ })
+ },
+ onHumanInputRequired: ({ data: humanInputRequiredData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (!responseItem.humanInputFormDataList) {
+ responseItem.humanInputFormDataList = [humanInputRequiredData]
+ }
+ else {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentFormIndex > -1) {
+ responseItem.humanInputFormDataList[currentFormIndex] = humanInputRequiredData
+ }
+ else {
+ responseItem.humanInputFormDataList.push(humanInputRequiredData)
+ }
+ }
+ if (responseItem.workflowProcess?.tracing) {
+ const currentTracingIndex = responseItem.workflowProcess.tracing.findIndex(item => item.node_id === humanInputRequiredData.node_id)
+ if (currentTracingIndex > -1)
+ responseItem.workflowProcess.tracing[currentTracingIndex].status = NodeRunningStatus.Paused
+ }
+ })
+ },
+ onHumanInputFormFilled: ({ data: humanInputFilledFormData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputFilledFormData.node_id)
+ if (currentFormIndex > -1)
+ responseItem.humanInputFormDataList.splice(currentFormIndex, 1)
+ }
+ if (!responseItem.humanInputFilledFormDataList) {
+ responseItem.humanInputFilledFormDataList = [humanInputFilledFormData]
+ }
+ else {
+ responseItem.humanInputFilledFormDataList.push(humanInputFilledFormData)
+ }
+ })
+ },
+ onHumanInputFormTimeout: ({ data: humanInputFormTimeoutData }) => {
+ updateChatTreeNode(messageId, (responseItem) => {
+ if (responseItem.humanInputFormDataList?.length) {
+ const currentFormIndex = responseItem.humanInputFormDataList.findIndex(item => item.node_id === humanInputFormTimeoutData.node_id)
+ responseItem.humanInputFormDataList[currentFormIndex].expiration_time = humanInputFormTimeoutData.expiration_time
+ }
+ })
+ },
+ onWorkflowPaused: ({ data: workflowPausedData }) => {
+ const resumeUrl = `/workflow/${workflowPausedData.workflow_run_id}/events`
+ sseGet(
+ resumeUrl,
+ {},
+ otherOptions,
+ )
+ updateChatTreeNode(messageId, (responseItem) => {
+ responseItem.workflowProcess!.status = WorkflowRunningStatus.Paused
+ })
+ },
+ }
+
+ if (workflowEventsAbortControllerRef.current)
+ workflowEventsAbortControllerRef.current.abort()
+
+ sseGet(
+ url,
+ {},
+ otherOptions,
)
- }, [threadMessages, chatTree.length, updateCurrentQAOnTree, handleResponding, formSettings?.inputsForm, handleRun, notify, t, config?.suggested_questions_after_answer?.enabled, fetchInspectVars, invalidAllLastRun])
+ }, [updateChatTreeNode, handleResponding, workflowStore, fetchInspectVars, invalidAllLastRun, config?.suggested_questions_after_answer])
+
+ const handleSwitchSibling = useCallback((
+ siblingMessageId: string,
+ callbacks: SendCallback,
+ ) => {
+ setTargetMessageId(siblingMessageId)
+
+ // Helper to find message in tree
+ const findMessageInTree = (nodes: ChatItemInTree[], targetId: string): ChatItemInTree | undefined => {
+ for (const node of nodes) {
+ if (node.id === targetId)
+ return node
+ if (node.children) {
+ const found = findMessageInTree(node.children, targetId)
+ if (found)
+ return found
+ }
+ }
+ return undefined
+ }
+
+ const targetMessage = findMessageInTree(chatTreeRef.current, siblingMessageId)
+ if (targetMessage?.workflow_run_id && targetMessage.humanInputFormDataList && targetMessage.humanInputFormDataList.length > 0) {
+ handleResume(
+ targetMessage.id,
+ targetMessage.workflow_run_id,
+ callbacks,
+ )
+ }
+ }, [handleResume])
return {
conversationId: conversationId.current,
chatList,
setTargetMessageId,
+ handleSwitchSibling,
handleSend,
handleStop,
handleRestart,
+ handleResume,
+ handleSubmitHumanInputForm,
+ getHumanInputNodeData,
isResponding,
suggestedQuestions,
}
diff --git a/web/app/components/workflow/panel/human-input-filled-form-list.tsx b/web/app/components/workflow/panel/human-input-filled-form-list.tsx
new file mode 100644
index 00000000000..7f39e939fe9
--- /dev/null
+++ b/web/app/components/workflow/panel/human-input-filled-form-list.tsx
@@ -0,0 +1,34 @@
+import type { HumanInputFilledFormData } from '@/types/workflow'
+import ContentWrapper from '@/app/components/base/chat/chat/answer/human-input-content/content-wrapper'
+import { SubmittedHumanInputContent } from '@/app/components/base/chat/chat/answer/human-input-content/submitted'
+
+type HumanInputFilledFormListProps = {
+ humanInputFilledFormDataList: HumanInputFilledFormData[]
+}
+
+const HumanInputFilledFormList = ({
+ humanInputFilledFormDataList,
+}: HumanInputFilledFormListProps) => {
+ return (
+ <div className="mt-3 flex flex-col gap-y-3 first:mt-0">
+ {
+ humanInputFilledFormDataList.map(formData => (
+ <ContentWrapper
+ key={formData.node_id}
+ nodeTitle={formData.node_title}
+ showExpandIcon
+ className="bg-components-panel-bg"
+ expanded
+ >
+ <SubmittedHumanInputContent
+ key={formData.node_id}
+ formData={formData}
+ />
+ </ContentWrapper>
+ ))
+ }
+ </div>
+ )
+}
+
+export default HumanInputFilledFormList
diff --git a/web/app/components/workflow/panel/human-input-form-list.tsx b/web/app/components/workflow/panel/human-input-form-list.tsx
new file mode 100644
index 00000000000..e032bfbb89c
--- /dev/null
+++ b/web/app/components/workflow/panel/human-input-form-list.tsx
@@ -0,0 +1,83 @@
+import type { DeliveryMethod } from '@/app/components/workflow/nodes/human-input/types'
+import type { HumanInputFormData } from '@/types/workflow'
+import { useCallback, useMemo } from 'react'
+import { useStoreApi } from 'reactflow'
+import ContentWrapper from '@/app/components/base/chat/chat/answer/human-input-content/content-wrapper'
+import { UnsubmittedHumanInputContent } from '@/app/components/base/chat/chat/answer/human-input-content/unsubmitted'
+import { CUSTOM_NODE } from '@/app/components/workflow/constants'
+import { DeliveryMethodType } from '@/app/components/workflow/nodes/human-input/types'
+
+type HumanInputFormListProps = {
+ humanInputFormDataList: HumanInputFormData[]
+ onHumanInputFormSubmit?: (formToken: string, formData: any) => Promise<void>
+}
+
+const HumanInputFormList = ({
+ humanInputFormDataList,
+ onHumanInputFormSubmit,
+}: HumanInputFormListProps) => {
+ const store = useStoreApi()
+
+ const getHumanInputNodeData = useCallback((nodeID: string) => {
+ const {
+ getNodes,
+ } = store.getState()
+ const nodes = getNodes().filter(node => node.type === CUSTOM_NODE)
+ const node = nodes.find(n => n.id === nodeID)
+ return node
+ }, [store])
+
+ const deliveryMethodsConfig = useMemo((): Record<string, { showEmailTip: boolean, isEmailDebugMode: boolean, showDebugModeTip: boolean }> => {
+ if (!humanInputFormDataList.length)
+ return {}
+ return humanInputFormDataList.reduce((acc, formData) => {
+ const deliveryMethodsConfig = getHumanInputNodeData(formData.node_id)?.data.delivery_methods || []
+ if (!deliveryMethodsConfig.length) {
+ acc[formData.node_id] = {
+ showEmailTip: false,
+ isEmailDebugMode: false,
+ showDebugModeTip: false,
+ }
+ return acc
+ }
+ const isWebappEnabled = deliveryMethodsConfig.some((method: DeliveryMethod) => method.type === DeliveryMethodType.WebApp && method.enabled)
+ const isEmailEnabled = deliveryMethodsConfig.some((method: DeliveryMethod) => method.type === DeliveryMethodType.Email && method.enabled)
+ const isEmailDebugMode = deliveryMethodsConfig.some((method: DeliveryMethod) => method.type === DeliveryMethodType.Email && method.config?.debug_mode)
+ acc[formData.node_id] = {
+ showEmailTip: isEmailEnabled,
+ isEmailDebugMode,
+ showDebugModeTip: !isWebappEnabled,
+ }
+ return acc
+ }, {} as Record<string, { showEmailTip: boolean, isEmailDebugMode: boolean, showDebugModeTip: boolean }>)
+ }, [getHumanInputNodeData, humanInputFormDataList])
+
+ const filteredHumanInputFormDataList = useMemo(() => {
+ return humanInputFormDataList.filter(formData => formData.display_in_ui)
+ }, [humanInputFormDataList])
+
+ return (
+ <div className="flex flex-col gap-y-3">
+ {
+ filteredHumanInputFormDataList.map(formData => (
+ <ContentWrapper
+ key={formData.node_id}
+ nodeTitle={formData.node_title}
+ className="bg-components-panel-bg"
+ >
+ <UnsubmittedHumanInputContent
+ key={formData.node_id}
+ formData={formData}
+ showEmailTip={!!deliveryMethodsConfig[formData.node_id]?.showEmailTip}
+ isEmailDebugMode={!!deliveryMethodsConfig[formData.node_id]?.isEmailDebugMode}
+ showDebugModeTip={!!deliveryMethodsConfig[formData.node_id]?.showDebugModeTip}
+ onSubmit={onHumanInputFormSubmit}
+ />
+ </ContentWrapper>
+ ))
+ }
+ </div>
+ )
+}
+
+export default HumanInputFormList
diff --git a/web/app/components/workflow/panel/inputs-panel.tsx b/web/app/components/workflow/panel/inputs-panel.tsx
index faf60944a17..4162526d22b 100644
--- a/web/app/components/workflow/panel/inputs-panel.tsx
+++ b/web/app/components/workflow/panel/inputs-panel.tsx
@@ -44,15 +44,18 @@ const InputsPanel = ({ onRun }: Props) => {
const startVariables = startNode?.data.variables
const { checkInputsForm } = useCheckInputsForms()
- const initialInputs = { ...inputs }
- if (startVariables) {
- startVariables.forEach((variable) => {
- if (variable.default)
- initialInputs[variable.variable] = variable.default
- if (inputs[variable.variable] !== undefined)
- initialInputs[variable.variable] = inputs[variable.variable]
- })
- }
+ const initialInputs = useMemo(() => {
+ const result = { ...inputs }
+ if (startVariables) {
+ startVariables.forEach((variable) => {
+ if (variable.default)
+ result[variable.variable] = variable.default
+ if (inputs[variable.variable] !== undefined)
+ result[variable.variable] = inputs[variable.variable]
+ })
+ }
+ return result
+ }, [inputs, startVariables])
const variables = useMemo(() => {
const data = startVariables || []
@@ -97,10 +100,7 @@ const InputsPanel = ({ onRun }: Props) => {
}, [files, handleRun, initialInputs, onRun, variables, checkInputsForm])
const canRun = useMemo(() => {
- if (files?.some(item => (item.transfer_method as any) === TransferMethod.local_file && !item.upload_file_id))
- return false
-
- return true
+ return !(files?.some(item => (item.transfer_method as any) === TransferMethod.local_file && !item.upload_file_id))
}, [files])
return (
diff --git a/web/app/components/workflow/panel/workflow-preview.tsx b/web/app/components/workflow/panel/workflow-preview.tsx
index bb90f777489..7f23f5bc74d 100644
--- a/web/app/components/workflow/panel/workflow-preview.tsx
+++ b/web/app/components/workflow/panel/workflow-preview.tsx
@@ -12,6 +12,7 @@ import {
import { useTranslation } from 'react-i18next'
import Button from '@/app/components/base/button'
import Loading from '@/app/components/base/loading'
+import { submitHumanInputForm } from '@/service/workflow'
import { cn } from '@/utils/classnames'
import Toast from '../../base/toast'
import {
@@ -25,6 +26,8 @@ import {
WorkflowRunningStatus,
} from '../types'
import { formatWorkflowRunIdentifier } from '../utils'
+import HumanInputFilledFormList from './human-input-filled-form-list'
+import HumanInputFormList from './human-input-form-list'
import InputsPanel from './inputs-panel'
const WorkflowPreview = () => {
@@ -37,6 +40,8 @@ const WorkflowPreview = () => {
const panelWidth = useStore(s => s.previewPanelWidth)
const setPreviewPanelWidth = useStore(s => s.setPreviewPanelWidth)
const showDebugAndPreviewPanel = useStore(s => s.showDebugAndPreviewPanel)
+ const humanInputFormDataList = useStore(s => s.workflowRunningData?.humanInputFormDataList)
+ const humanInputFilledFormDataList = useStore(s => s.workflowRunningData?.humanInputFilledFormDataList)
const [currentTab, setCurrentTab] = useState<string>(showInputsPanel ? 'INPUT' : 'TRACING')
const switchTab = async (tab: string) => {
@@ -45,7 +50,7 @@ const WorkflowPreview = () => {
useEffect(() => {
if (showDebugAndPreviewPanel && showInputsPanel)
- setCurrentTab('INPUT')
+ switchTab('INPUT')
}, [showDebugAndPreviewPanel, showInputsPanel])
useEffect(() => {
@@ -60,6 +65,8 @@ const WorkflowPreview = () => {
if ((status === WorkflowRunningStatus.Succeeded || status === WorkflowRunningStatus.Failed) && !workflowRunningData.resultText && !workflowRunningData.result.files?.length)
switchTab('DETAIL')
+ if (status === WorkflowRunningStatus.Paused)
+ switchTab('RESULT')
}, [workflowRunningData])
const [isResizing, setIsResizing] = useState(false)
@@ -94,6 +101,10 @@ const WorkflowPreview = () => {
}
}, [resize, stopResizing])
+ const handleSubmitHumanInputForm = useCallback(async (formToken: string, formData: any) => {
+ await submitHumanInputForm(formToken, formData)
+ }, [])
+
return (
<div
className="relative flex h-full flex-col rounded-l-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl"
@@ -174,9 +185,21 @@ const WorkflowPreview = () => {
<InputsPanel onRun={() => switchTab('RESULT')} />
)}
{currentTab === 'RESULT' && (
- <>
+ <div className="p-2">
+ {humanInputFormDataList && humanInputFormDataList.length > 0 && (
+ <HumanInputFormList
+ humanInputFormDataList={humanInputFormDataList}
+ onHumanInputFormSubmit={handleSubmitHumanInputForm}
+ />
+ )}
+ {humanInputFilledFormDataList && humanInputFilledFormDataList.length > 0 && (
+ <HumanInputFilledFormList
+ humanInputFilledFormDataList={humanInputFilledFormDataList}
+ />
+ )}
<ResultText
isRunning={workflowRunningData?.result?.status === WorkflowRunningStatus.Running || !workflowRunningData?.result}
+ isPaused={workflowRunningData?.result?.status === WorkflowRunningStatus.Paused}
outputs={workflowRunningData?.resultText}
allFiles={workflowRunningData?.result?.files}
error={workflowRunningData?.result?.error}
@@ -198,7 +221,7 @@ const WorkflowPreview = () => {
<div>{t('operation.copy', { ns: 'common' })}</div>
</Button>
)}
- </>
+ </div>
)}
{currentTab === 'DETAIL' && (
<ResultPanel
diff --git a/web/app/components/workflow/run/index.tsx b/web/app/components/workflow/run/index.tsx
index 51f641f265c..441002c86c4 100644
--- a/web/app/components/workflow/run/index.tsx
+++ b/web/app/components/workflow/run/index.tsx
@@ -2,7 +2,6 @@
import type { FC } from 'react'
import type { WorkflowRunDetailResponse } from '@/models/log'
import type { NodeTracing } from '@/types/workflow'
-import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
@@ -182,6 +181,7 @@ const RunPanel: FC<RunProps> = ({
steps={runDetail.total_steps}
exceptionCounts={runDetail.exceptions_count}
isListening={isListening}
+ workflowRunId={runDetail.id}
/>
)}
{!loading && currentTab === 'DETAIL' && !runDetail && isListening && (
diff --git a/web/app/components/workflow/run/meta.tsx b/web/app/components/workflow/run/meta.tsx
index 39f7ac314f1..af01af454a3 100644
--- a/web/app/components/workflow/run/meta.tsx
+++ b/web/app/components/workflow/run/meta.tsx
@@ -50,6 +50,9 @@ const MetaData: FC<Props> = ({
{status === 'stopped' && (
<span>STOP</span>
)}
+ {status === 'paused' && (
+ <span>PENDING</span>
+ )}
</div>
</div>
<div className="flex">
@@ -88,10 +91,10 @@ const MetaData: FC<Props> = ({
<div className="flex">
<div className="system-xs-regular w-[104px] shrink-0 truncate px-2 py-1.5 text-text-tertiary">{t('meta.tokens', { ns: 'runLog' })}</div>
<div className="system-xs-regular grow px-2 py-1.5 text-text-secondary">
- {status === 'running' && (
- <div className="my-1 h-2 w-[48px] rounded-sm bg-text-quaternary" />
+ {['running', 'paused'].includes(status) && (
+ <div className="my-1 h-2 w-[48px] animate-pulse rounded-sm bg-text-quaternary" />
)}
- {status !== 'running' && (
+ {!['running', 'paused'].includes(status) && (
<span>{`${tokens || 0} Tokens`}</span>
)}
</div>
diff --git a/web/app/components/workflow/run/node.tsx b/web/app/components/workflow/run/node.tsx
index c99ff6ce912..06899c48819 100644
--- a/web/app/components/workflow/run/node.tsx
+++ b/web/app/components/workflow/run/node.tsx
@@ -11,8 +11,9 @@ import {
RiAlertFill,
RiArrowRightSLine,
RiCheckboxCircleFill,
- RiErrorWarningLine,
+ RiErrorWarningFill,
RiLoader2Line,
+ RiPauseCircleFill,
} from '@remixicon/react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -144,7 +145,7 @@ const NodePanel: FC<Props> = ({
{nodeInfo.title}
</div>
</Tooltip>
- {nodeInfo.status !== 'running' && !hideInfo && (
+ {!['running', 'paused'].includes(nodeInfo.status) && !hideInfo && (
<div className="system-xs-regular shrink-0 text-text-tertiary">
{nodeInfo.execution_metadata?.total_tokens ? `${getTokenCount(nodeInfo.execution_metadata?.total_tokens || 0)} tokens · ` : ''}
{`${getTime(nodeInfo.elapsed_time || 0)}`}
@@ -154,11 +155,14 @@ const NodePanel: FC<Props> = ({
<RiCheckboxCircleFill className="ml-2 h-3.5 w-3.5 shrink-0 text-text-success" />
)}
{nodeInfo.status === 'failed' && (
- <RiErrorWarningLine className="ml-2 h-3.5 w-3.5 shrink-0 text-text-warning" />
+ <RiErrorWarningFill className="ml-2 h-3.5 w-3.5 shrink-0 text-text-destructive" />
)}
{nodeInfo.status === 'stopped' && (
<RiAlertFill className={cn('ml-2 h-4 w-4 shrink-0 text-text-warning-secondary', inMessage && 'h-3.5 w-3.5')} />
)}
+ {nodeInfo.status === 'paused' && (
+ <RiPauseCircleFill className={cn('ml-2 h-4 w-4 shrink-0 text-text-warning-secondary', inMessage && 'h-3.5 w-3.5')} />
+ )}
{nodeInfo.status === 'exception' && (
<RiAlertFill className={cn('ml-2 h-4 w-4 shrink-0 text-text-warning-secondary', inMessage && 'h-3.5 w-3.5')} />
)}
@@ -229,6 +233,11 @@ const NodePanel: FC<Props> = ({
{nodeInfo.error}
</StatusContainer>
)}
+ {(nodeInfo.status === 'paused') && (
+ <StatusContainer status="paused">
+ <div className="system-xs-regular text-text-warning">{t('nodes.humanInput.log.reasonContent', { ns: 'workflow' })}</div>
+ </StatusContainer>
+ )}
</div>
{nodeInfo.inputs && (
<div className={cn('mb-1')}>
diff --git a/web/app/components/workflow/run/result-panel.tsx b/web/app/components/workflow/run/result-panel.tsx
index 873be71b5b2..58f783e6c48 100644
--- a/web/app/components/workflow/run/result-panel.tsx
+++ b/web/app/components/workflow/run/result-panel.tsx
@@ -41,6 +41,7 @@ export type ResultPanelProps = {
exceptionCounts?: number
execution_metadata?: any
isListening?: boolean
+ workflowRunId?: string
handleShowIterationResultList?: (detail: NodeTracing[][], iterDurationMap: any) => void
handleShowLoopResultList?: (detail: NodeTracing[][], loopDurationMap: any) => void
onShowRetryDetail?: (detail: NodeTracing[]) => void
@@ -67,6 +68,7 @@ const ResultPanel: FC<ResultPanelProps> = ({
exceptionCounts,
execution_metadata,
isListening = false,
+ workflowRunId,
handleShowIterationResultList,
handleShowLoopResultList,
onShowRetryDetail,
@@ -89,6 +91,7 @@ const ResultPanel: FC<ResultPanelProps> = ({
error={error}
exceptionCounts={exceptionCounts}
isListening={isListening}
+ workflowRunId={workflowRunId}
/>
</div>
<div className="px-4">
diff --git a/web/app/components/workflow/run/result-text.tsx b/web/app/components/workflow/run/result-text.tsx
index 026e5b7c053..4169f452b20 100644
--- a/web/app/components/workflow/run/result-text.tsx
+++ b/web/app/components/workflow/run/result-text.tsx
@@ -9,6 +9,7 @@ import StatusContainer from '@/app/components/workflow/run/status-container'
type ResultTextProps = {
isRunning?: boolean
+ isPaused?: boolean
outputs?: any
error?: string
onClick?: () => void
@@ -17,6 +18,7 @@ type ResultTextProps = {
const ResultText: FC<ResultTextProps> = ({
isRunning,
+ isPaused,
outputs,
error,
onClick,
@@ -37,7 +39,7 @@ const ResultText: FC<ResultTextProps> = ({
</StatusContainer>
</div>
)}
- {!isRunning && !outputs && !error && !allFiles?.length && (
+ {!isPaused && !isRunning && !outputs && !error && !allFiles?.length && (
<div className="mt-[120px] flex flex-col items-center px-4 py-2 text-[13px] leading-[18px] text-gray-500">
<ImageIndentLeft className="h-6 w-6 text-gray-400" />
<div className="mr-2">{t('resultEmpty.title', { ns: 'runLog' })}</div>
diff --git a/web/app/components/workflow/run/status-container.tsx b/web/app/components/workflow/run/status-container.tsx
index d9351352315..fc33bd46a76 100644
--- a/web/app/components/workflow/run/status-container.tsx
+++ b/web/app/components/workflow/run/status-container.tsx
@@ -28,9 +28,9 @@ const StatusContainer: FC<Props> = ({
status === 'failed' && 'border-[rgba(240,68,56,0.8)] bg-workflow-display-error-bg bg-[url(~@/app/components/workflow/run/assets/bg-line-error.svg)] text-text-warning',
status === 'failed' && theme === Theme.light && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.5),inset_0_1px_3px_0_rgba(0,0,0,0.12),inset_0_2px_24px_0_rgba(240,68,56,0.2),0_1px_2px_0_rgba(9,9,11,0.05),0_0_0_1px_rgba(0,0,0,0.05)]',
status === 'failed' && theme === Theme.dark && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.12),inset_0_1px_3px_0_rgba(0,0,0,0.4),inset_0_2px_24px_0_rgba(240,68,56,0.25),0_1px_2px_0_rgba(0,0,0,0.1),0_0_0_1px_rgba(24, 24, 27, 0.95)]',
- status === 'stopped' && 'border-[rgba(247,144,9,0.8)] bg-workflow-display-warning-bg bg-[url(~@/app/components/workflow/run/assets/bg-line-warning.svg)] text-text-destructive',
- status === 'stopped' && theme === Theme.light && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.5),inset_0_1px_3px_0_rgba(0,0,0,0.12),inset_0_2px_24px_0_rgba(247,144,9,0.2),0_1px_2px_0_rgba(9,9,11,0.05),0_0_0_1px_rgba(0,0,0,0.05)]',
- status === 'stopped' && theme === Theme.dark && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.12),inset_0_1px_3px_0_rgba(0,0,0,0.4),inset_0_2px_24px_0_rgba(247,144,9,0.25),0_1px_2px_0_rgba(0,0,0,0.1),0_0_0_1px_rgba(24, 24, 27, 0.95)]',
+ (status === 'stopped' || status === 'paused') && 'border-[rgba(247,144,9,0.8)] bg-workflow-display-warning-bg bg-[url(~@/app/components/workflow/run/assets/bg-line-warning.svg)] text-text-destructive',
+ (status === 'stopped' || status === 'paused') && theme === Theme.light && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.5),inset_0_1px_3px_0_rgba(0,0,0,0.12),inset_0_2px_24px_0_rgba(247,144,9,0.2),0_1px_2px_0_rgba(9,9,11,0.05),0_0_0_1px_rgba(0,0,0,0.05)]',
+ (status === 'stopped' || status === 'paused') && theme === Theme.dark && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.12),inset_0_1px_3px_0_rgba(0,0,0,0.4),inset_0_2px_24px_0_rgba(247,144,9,0.25),0_1px_2px_0_rgba(0,0,0,0.1),0_0_0_1px_rgba(24, 24, 27, 0.95)]',
status === 'exception' && 'border-[rgba(247,144,9,0.8)] bg-workflow-display-warning-bg bg-[url(~@/app/components/workflow/run/assets/bg-line-warning.svg)] text-text-destructive',
status === 'exception' && theme === Theme.light && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.5),inset_0_1px_3px_0_rgba(0,0,0,0.12),inset_0_2px_24px_0_rgba(247,144,9,0.2),0_1px_2px_0_rgba(9,9,11,0.05),0_0_0_1px_rgba(0,0,0,0.05)]',
status === 'exception' && theme === Theme.dark && 'shadow-[inset_2px_2px_0_0_rgba(255,255,255,0.12),inset_0_1px_3px_0_rgba(0,0,0,0.4),inset_0_2px_24px_0_rgba(247,144,9,0.25),0_1px_2px_0_rgba(0,0,0,0.1),0_0_0_1px_rgba(24, 24, 27, 0.95)]',
diff --git a/web/app/components/workflow/run/status.tsx b/web/app/components/workflow/run/status.tsx
index 33799a6269a..81ae3ede144 100644
--- a/web/app/components/workflow/run/status.tsx
+++ b/web/app/components/workflow/run/status.tsx
@@ -1,9 +1,11 @@
'use client'
import type { FC } from 'react'
+import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import Indicator from '@/app/components/header/indicator'
import StatusContainer from '@/app/components/workflow/run/status-container'
import { useDocLink } from '@/context/i18n'
+import { useWorkflowPausedDetails } from '@/service/use-log'
import { cn } from '@/utils/classnames'
type ResultProps = {
@@ -13,6 +15,7 @@ type ResultProps = {
error?: string
exceptionCounts?: number
isListening?: boolean
+ workflowRunId?: string
}
const StatusPanel: FC<ResultProps> = ({
@@ -22,9 +25,45 @@ const StatusPanel: FC<ResultProps> = ({
error,
exceptionCounts,
isListening = false,
+ workflowRunId,
}) => {
const { t } = useTranslation()
const docLink = useDocLink()
+ const { data: pausedDetails } = useWorkflowPausedDetails({
+ workflowRunId: workflowRunId || '',
+ enabled: status === 'paused',
+ })
+
+ const pausedReasons = useMemo(() => {
+ const reasons: string[] = []
+ if (!pausedDetails)
+ return reasons
+ const hasHumanInputNode = pausedDetails.paused_nodes.some(
+ node => node.pause_type.type === 'human_input',
+ )
+ if (hasHumanInputNode) {
+ reasons.push(t('nodes.humanInput.log.reasonContent', { ns: 'workflow' }))
+ }
+ return reasons
+ }, [pausedDetails, t])
+
+ const pausedInputURLs = useMemo(() => {
+ const inputURLs: string[] = []
+ if (!pausedDetails)
+ return inputURLs
+ const { paused_nodes } = pausedDetails
+ const hasHumanInputNode = paused_nodes.some(
+ node => node.pause_type.type === 'human_input',
+ )
+ if (hasHumanInputNode) {
+ paused_nodes.forEach((node) => {
+ if (node.pause_type.type === 'human_input') {
+ inputURLs.push(node.pause_type.backstage_input_url)
+ }
+ })
+ }
+ return inputURLs
+ }, [pausedDetails])
return (
<StatusContainer status={status}>
@@ -41,7 +80,7 @@ const StatusPanel: FC<ResultProps> = ({
status === 'succeeded' && 'text-util-colors-green-green-600',
status === 'partial-succeeded' && 'text-util-colors-green-green-600',
status === 'failed' && 'text-util-colors-red-red-600',
- status === 'stopped' && 'text-util-colors-warning-warning-600',
+ (status === 'stopped' || status === 'paused') && 'text-util-colors-warning-warning-600',
status === 'running' && 'text-util-colors-blue-light-blue-light-600',
)}
>
@@ -81,15 +120,21 @@ const StatusPanel: FC<ResultProps> = ({
<span>STOP</span>
</>
)}
+ {status === 'paused' && (
+ <>
+ <Indicator color="yellow" />
+ <span>PENDING</span>
+ </>
+ )}
</div>
</div>
<div className="max-w-[152px] flex-[33%]">
<div className="system-2xs-medium-uppercase mb-1 text-text-tertiary">{t('resultPanel.time', { ns: 'runLog' })}</div>
<div className="system-sm-medium flex items-center gap-1 text-text-secondary">
- {status === 'running' && (
- <div className="h-2 w-16 rounded-sm bg-text-quaternary" />
+ {(status === 'running' || status === 'paused') && (
+ <div className="h-2 w-16 animate-pulse rounded-sm bg-text-quaternary" />
)}
- {status !== 'running' && (
+ {status !== 'running' && status !== 'paused' && (
<span>{time ? `${time?.toFixed(3)}s` : '-'}</span>
)}
</div>
@@ -97,10 +142,10 @@ const StatusPanel: FC<ResultProps> = ({
<div className="flex-[33%]">
<div className="system-2xs-medium-uppercase mb-1 text-text-tertiary">{t('resultPanel.tokens', { ns: 'runLog' })}</div>
<div className="system-sm-medium flex items-center gap-1 text-text-secondary">
- {status === 'running' && (
- <div className="h-2 w-20 rounded-sm bg-text-quaternary" />
+ {(status === 'running' || status === 'paused') && (
+ <div className="h-2 w-20 animate-pulse rounded-sm bg-text-quaternary" />
)}
- {status !== 'running' && (
+ {status !== 'running' && status !== 'paused' && (
<span>{`${tokens || 0} Tokens`}</span>
)}
</div>
@@ -149,6 +194,40 @@ const StatusPanel: FC<ResultProps> = ({
</>
)
}
+ {status === 'paused' && (
+ <>
+ <div className="my-2 h-[0.5px] bg-divider-deep" />
+ <div className="system-xs-medium flex flex-col gap-y-2">
+ <div className="flex flex-col gap-y-0.5">
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('nodes.humanInput.log.reason', { ns: 'workflow' })}</div>
+ {
+ pausedReasons.length > 0
+ ? pausedReasons.map(reason => (
+ <div className="system-xs-medium truncate text-text-secondary" key={reason}>{reason}</div>
+ ))
+ : (
+ <div className="h-2 w-20 animate-pulse rounded-sm bg-text-quaternary" />
+ )
+ }
+ </div>
+ {pausedInputURLs.length > 0 && (
+ <div className="flex flex-col gap-y-0.5">
+ <div className="system-2xs-medium-uppercase text-text-tertiary">{t('nodes.humanInput.log.backstageInputURL', { ns: 'workflow' })}</div>
+ {pausedInputURLs.map(url => (
+ <a
+ key={url}
+ href={url}
+ target="_blank"
+ className="system-xs-medium text-text-accent"
+ >
+ {url}
+ </a>
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ )}
</StatusContainer>
)
}
diff --git a/web/app/components/workflow/run/utils/format-log/human-input/index.ts b/web/app/components/workflow/run/utils/format-log/human-input/index.ts
new file mode 100644
index 00000000000..f8fbe7974c9
--- /dev/null
+++ b/web/app/components/workflow/run/utils/format-log/human-input/index.ts
@@ -0,0 +1,59 @@
+import type { NodeTracing } from '@/types/workflow'
+import { BlockEnum } from '@/app/components/workflow/types'
+
+/**
+ * Format human-input nodes to ensure only the latest status is kept for each node.
+ * Human-input nodes can have multiple log entries as their status changes
+ * (e.g., running -> paused -> succeeded/failed).
+ * This function keeps only the entry with the latest index for each unique node_id.
+ */
+const formatHumanInputNode = (list: NodeTracing[]): NodeTracing[] => {
+ // Group human-input nodes by node_id
+ const humanInputNodeMap = new Map<string, NodeTracing>()
+
+ // Track which node_ids are human-input type
+ const humanInputNodeIds = new Set<string>()
+
+ // First pass: identify human-input nodes and keep the one with the highest index
+ list.forEach((item) => {
+ if (item.node_type === BlockEnum.HumanInput) {
+ humanInputNodeIds.add(item.node_id)
+
+ const existingNode = humanInputNodeMap.get(item.node_id)
+ if (!existingNode || item.index > existingNode.index) {
+ humanInputNodeMap.set(item.node_id, item)
+ }
+ }
+ })
+
+ // If no human-input nodes, return the list as is
+ if (humanInputNodeIds.size === 0)
+ return list
+
+ // Second pass: filter the list to remove duplicate human-input nodes
+ // and keep only the latest one for each node_id
+ const result: NodeTracing[] = []
+ const addedHumanInputNodeIds = new Set<string>()
+
+ list.forEach((item) => {
+ if (item.node_type === BlockEnum.HumanInput) {
+ // Only add the human-input node with the highest index
+ if (!addedHumanInputNodeIds.has(item.node_id)) {
+ const latestNode = humanInputNodeMap.get(item.node_id)
+ if (latestNode) {
+ result.push(latestNode)
+ addedHumanInputNodeIds.add(item.node_id)
+ }
+ }
+ // Skip duplicate human-input nodes
+ }
+ else {
+ // Keep all non-human-input nodes
+ result.push(item)
+ }
+ })
+
+ return result
+}
+
+export default formatHumanInputNode
diff --git a/web/app/components/workflow/run/utils/format-log/index.ts b/web/app/components/workflow/run/utils/format-log/index.ts
index c152a5156ab..2393f9837fb 100644
--- a/web/app/components/workflow/run/utils/format-log/index.ts
+++ b/web/app/components/workflow/run/utils/format-log/index.ts
@@ -2,6 +2,7 @@ import type { NodeTracing } from '@/types/workflow'
import { cloneDeep } from 'es-toolkit/object'
import { BlockEnum } from '../../../types'
import formatAgentNode from './agent'
+import formatHumanInputNode from './human-input'
import { addChildrenToIterationNode } from './iteration'
import { addChildrenToLoopNode } from './loop'
import formatParallelNode from './parallel'
@@ -83,7 +84,8 @@ const formatToTracingNodeList = (list: NodeTracing[], t: any) => {
* Because Handle struct node will put the node in different
*/
const formattedAgentList = formatAgentNode(allItems)
- const formattedRetryList = formatRetryNode(formattedAgentList) // retry one node
+ const formattedHumanInputList = formatHumanInputNode(formattedAgentList) // Keep only latest status for human-input nodes
+ const formattedRetryList = formatRetryNode(formattedHumanInputList) // retry one node
// would change the structure of the list. Iteration and parallel can include each other.
const formattedLoopAndIterationList = formatIterationAndLoopNode(formattedRetryList, t)
const formattedParallelList = formatParallelNode(formattedLoopAndIterationList, t)
diff --git a/web/app/components/workflow/store/workflow/workflow-slice.ts b/web/app/components/workflow/store/workflow/workflow-slice.ts
index df240589758..5a479d3e44b 100644
--- a/web/app/components/workflow/store/workflow/workflow-slice.ts
+++ b/web/app/components/workflow/store/workflow/workflow-slice.ts
@@ -9,6 +9,8 @@ import type { FileUploadConfigResponse } from '@/models/common'
type PreviewRunningData = WorkflowRunningData & {
resultTabActive?: boolean
resultText?: string
+ // human input form schema or data cached when node is in 'Paused' status
+ extraContentAndFormData?: Record<string, any>
}
export type WorkflowSliceShape = {
diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.ts
index be1254d33ce..871ca301277 100644
--- a/web/app/components/workflow/types.ts
+++ b/web/app/components/workflow/types.ts
@@ -17,7 +17,13 @@ import type { VarType as VarKindType } from '@/app/components/workflow/nodes/too
import type { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
import type { SchemaTypeDefinition } from '@/service/use-common'
import type { Resolution, TransferMethod } from '@/types/app'
-import type { FileResponse, NodeTracing, PanelProps } from '@/types/workflow'
+import type {
+ FileResponse,
+ HumanInputFilledFormData,
+ HumanInputFormData,
+ NodeTracing,
+ PanelProps,
+} from '@/types/workflow'
export enum BlockEnum {
Start = 'start',
@@ -43,6 +49,7 @@ export enum BlockEnum {
Loop = 'loop',
LoopStart = 'loop-start',
LoopEnd = 'loop-end',
+ HumanInput = 'human-input',
DataSource = 'datasource',
DataSourceEmpty = 'datasource-empty',
KnowledgeBase = 'knowledge-index',
@@ -191,7 +198,6 @@ export enum InputVarType {
paragraph = 'paragraph',
select = 'select',
number = 'number',
- checkbox = 'checkbox',
url = 'url',
files = 'files',
json = 'json', // obj, array
@@ -201,6 +207,7 @@ export enum InputVarType {
singleFile = 'file',
multiFiles = 'file-list',
loop = 'loop', // loop input
+ checkbox = 'checkbox',
}
export type InputVar = {
@@ -350,6 +357,7 @@ export enum WorkflowRunningStatus {
Succeeded = 'succeeded',
Failed = 'failed',
Stopped = 'stopped',
+ Paused = 'paused',
}
export enum WorkflowVersion {
@@ -367,6 +375,7 @@ export enum NodeRunningStatus {
Exception = 'exception',
Retry = 'retry',
Stopped = 'stopped',
+ Paused = 'paused',
}
export type OnNodeAdd = (
@@ -426,6 +435,8 @@ export type WorkflowRunningData = {
exceptions_count?: number
}
tracing?: NodeTracing[]
+ humanInputFormDataList?: HumanInputFormData[]
+ humanInputFilledFormDataList?: HumanInputFilledFormData[]
}
export type HistoryWorkflowData = {
diff --git a/web/app/components/workflow/utils/elk-layout.ts b/web/app/components/workflow/utils/elk-layout.ts
index c3b37c8f16d..280d0f7b1dc 100644
--- a/web/app/components/workflow/utils/elk-layout.ts
+++ b/web/app/components/workflow/utils/elk-layout.ts
@@ -1,4 +1,5 @@
import type { ElkNode, LayoutOptions } from 'elkjs/lib/elk-api'
+import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
import type { CaseItem, IfElseNodeType } from '@/app/components/workflow/nodes/if-else/types'
import type {
Edge,
@@ -345,6 +346,76 @@ const buildIfElseWithPorts = (
}
}
+/**
+ * Build Human Input node with ELK native Ports for multiple branches
+ * Handles user actions as branches with __timeout as the last fixed branch
+ */
+const buildHumanInputWithPorts = (
+ humanInputNode: Node,
+ edges: Edge[],
+): { node: ElkNodeShape, portMap: Map<string, string> } | null => {
+ const childEdges = edges.filter(edge => edge.source === humanInputNode.id)
+
+ if (childEdges.length <= 1)
+ return null
+
+ // Sort child edges: user actions first (by order), then __timeout last
+ const sortedChildEdges = [...childEdges].sort((edgeA, edgeB) => {
+ const handleA = edgeA.sourceHandle
+ const handleB = edgeB.sourceHandle
+
+ if (handleA && handleB) {
+ const userActions = (humanInputNode.data as HumanInputNodeType).user_actions || []
+ const isATimeout = handleA === '__timeout'
+ const isBTimeout = handleB === '__timeout'
+
+ // __timeout should always be last
+ if (isATimeout)
+ return 1
+ if (isBTimeout)
+ return -1
+
+ // Sort by user_actions order
+ const indexA = userActions.findIndex(action => action.id === handleA)
+ const indexB = userActions.findIndex(action => action.id === handleB)
+
+ if (indexA !== -1 && indexB !== -1)
+ return indexA - indexB
+ }
+
+ return 0
+ })
+
+ // Create ELK ports for each branch
+ const ports: ElkPortShape[] = sortedChildEdges.map((edge, index) => ({
+ id: `${humanInputNode.id}-port-${edge.sourceHandle || index}`,
+ layoutOptions: {
+ 'port.side': 'EAST',
+ 'port.index': String(index),
+ },
+ }))
+
+ // Build port mapping: edge.id -> portId
+ const portMap = new Map<string, string>()
+ sortedChildEdges.forEach((edge, index) => {
+ const portId = `${humanInputNode.id}-port-${edge.sourceHandle || index}`
+ portMap.set(edge.id, portId)
+ })
+
+ return {
+ node: {
+ id: humanInputNode.id,
+ width: humanInputNode.width ?? DEFAULT_NODE_WIDTH,
+ height: humanInputNode.height ?? DEFAULT_NODE_HEIGHT,
+ ports,
+ layoutOptions: {
+ 'elk.portConstraints': 'FIXED_ORDER',
+ },
+ },
+ portMap,
+ }
+}
+
const normaliseBounds = (layout: LayoutResult): LayoutResult => {
const {
nodes,
@@ -388,7 +459,7 @@ export const getLayoutByDagre = async (originNodes: Node[], originEdges: Edge[])
// Track which edges have been processed for If/Else nodes with ports
const edgeToPortMap = new Map<string, string>()
- // Build nodes with ports for If/Else nodes
+ // Build nodes with ports for If/Else and Human Input nodes
nodes.forEach((node) => {
if (node.data.type === BlockEnum.IfElse) {
const portsResult = buildIfElseWithPorts(node, edges)
@@ -405,6 +476,21 @@ export const getLayoutByDagre = async (originNodes: Node[], originEdges: Edge[])
elkNodes.push(toElkNode(node))
}
}
+ else if (node.data.type === BlockEnum.HumanInput) {
+ const portsResult = buildHumanInputWithPorts(node, edges)
+ if (portsResult) {
+ // Use node with ports
+ elkNodes.push(portsResult.node)
+ // Store port mappings for edges
+ portsResult.portMap.forEach((portId, edgeId) => {
+ edgeToPortMap.set(edgeId, portId)
+ })
+ }
+ else {
+ // No multiple branches, use normal node
+ elkNodes.push(toElkNode(node))
+ }
+ }
else {
elkNodes.push(toElkNode(node))
}
diff --git a/web/app/components/workflow/utils/workflow.ts b/web/app/components/workflow/utils/workflow.ts
index 7fabc51a455..a69ab54ec1c 100644
--- a/web/app/components/workflow/utils/workflow.ts
+++ b/web/app/components/workflow/utils/workflow.ts
@@ -33,6 +33,7 @@ export const canRunBySingle = (nodeType: BlockEnum, isChildNode: boolean) => {
|| nodeType === BlockEnum.IfElse
|| nodeType === BlockEnum.VariableAggregator
|| nodeType === BlockEnum.Assigner
+ || nodeType === BlockEnum.HumanInput
|| nodeType === BlockEnum.DataSource
|| nodeType === BlockEnum.TriggerSchedule
|| nodeType === BlockEnum.TriggerWebhook
diff --git a/web/app/components/workflow/workflow-preview/components/nodes/base.tsx b/web/app/components/workflow/workflow-preview/components/nodes/base.tsx
index d75964b5255..53a3fb55918 100644
--- a/web/app/components/workflow/workflow-preview/components/nodes/base.tsx
+++ b/web/app/components/workflow/workflow-preview/components/nodes/base.tsx
@@ -68,7 +68,7 @@ const BaseCard = ({
handleId="target"
/>
{
- data.type !== BlockEnum.IfElse && data.type !== BlockEnum.QuestionClassifier && (
+ data.type !== BlockEnum.IfElse && data.type !== BlockEnum.QuestionClassifier && data.type !== BlockEnum.HumanInput && (
<NodeSourceHandle
id={id}
data={data}
diff --git a/web/app/components/workflow/workflow-preview/components/nodes/constants.ts b/web/app/components/workflow/workflow-preview/components/nodes/constants.ts
index dedca308fc7..072b5bd2496 100644
--- a/web/app/components/workflow/workflow-preview/components/nodes/constants.ts
+++ b/web/app/components/workflow/workflow-preview/components/nodes/constants.ts
@@ -4,6 +4,7 @@ import IterationNode from './iteration/node'
import LoopNode from './loop/node'
import QuestionClassifierNode from './question-classifier/node'
+// todo: add human-input node support
export const NodeComponentMap: Record<string, any> = {
[BlockEnum.QuestionClassifier]: QuestionClassifierNode,
[BlockEnum.IfElse]: IfElseNode,
diff --git a/web/config/index.ts b/web/config/index.ts
index 08ce14b2649..c3a4c5c3b17 100644
--- a/web/config/index.ts
+++ b/web/config/index.ts
@@ -341,8 +341,10 @@ export const VAR_REGEX
export const resetReg = () => (VAR_REGEX.lastIndex = 0)
-export const DISABLE_UPLOAD_IMAGE_AS_ICON
- = process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON === 'true'
+export const HITL_INPUT_REG = /\{\{(#\$output\.(?:[a-z_]\w{0,29}){1,10}#)\}\}/gi
+export const resetHITLInputReg = () => HITL_INPUT_REG.lastIndex = 0
+
+export const DISABLE_UPLOAD_IMAGE_AS_ICON = process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON === 'true'
export const GITHUB_ACCESS_TOKEN
= process.env.NEXT_PUBLIC_GITHUB_ACCESS_TOKEN || ''
diff --git a/web/context/provider-context.tsx b/web/context/provider-context.tsx
index d350d08b4ac..2a71d9cf939 100644
--- a/web/context/provider-context.tsx
+++ b/web/context/provider-context.tsx
@@ -64,6 +64,7 @@ export type ProviderContextState = {
refreshLicenseLimit: () => void
isAllowTransferWorkspace: boolean
isAllowPublishAsCustomKnowledgePipelineTemplate: boolean
+ humanInputEmailDeliveryEnabled: boolean
}
export const baseProviderContextValue: ProviderContextState = {
@@ -96,6 +97,7 @@ export const baseProviderContextValue: ProviderContextState = {
refreshLicenseLimit: noop,
isAllowTransferWorkspace: false,
isAllowPublishAsCustomKnowledgePipelineTemplate: false,
+ humanInputEmailDeliveryEnabled: false,
}
const ProviderContext = createContext<ProviderContextState>(baseProviderContextValue)
@@ -137,6 +139,7 @@ export const ProviderContextProvider = ({
const { data: educationAccountInfo, isLoading: isLoadingEducationAccountInfo, isFetching: isFetchingEducationAccountInfo, isFetchedAfterMount: isEducationDataFetchedAfterMount } = useEducationStatus(!enableEducationPlan)
const [isAllowTransferWorkspace, setIsAllowTransferWorkspace] = useState(false)
const [isAllowPublishAsCustomKnowledgePipelineTemplate, setIsAllowPublishAsCustomKnowledgePipelineTemplate] = useState(false)
+ const [humanInputEmailDeliveryEnabled, setHumanInputEmailDeliveryEnabled] = useState(false)
const refreshModelProviders = () => {
queryClient.invalidateQueries({ queryKey: ['common', 'model-providers'] })
@@ -173,6 +176,8 @@ export const ProviderContextProvider = ({
setIsAllowTransferWorkspace(data.is_allow_transfer_workspace)
if (data.knowledge_pipeline?.publish_enabled)
setIsAllowPublishAsCustomKnowledgePipelineTemplate(data.knowledge_pipeline?.publish_enabled)
+ if (data.human_input_email_delivery_enabled)
+ setHumanInputEmailDeliveryEnabled(data.human_input_email_delivery_enabled)
}
catch (error) {
console.error('Failed to fetch plan info:', error)
@@ -250,6 +255,7 @@ export const ProviderContextProvider = ({
refreshLicenseLimit: fetchPlan,
isAllowTransferWorkspace,
isAllowPublishAsCustomKnowledgePipelineTemplate,
+ humanInputEmailDeliveryEnabled,
}}
>
{children}
diff --git a/web/eslint-suppressions.json b/web/eslint-suppressions.json
index 63f10d238c4..2662e979c14 100644
--- a/web/eslint-suppressions.json
+++ b/web/eslint-suppressions.json
@@ -99,6 +99,11 @@
"count": 1
}
},
+ "app/(humanInputLayout)/form/[token]/form.tsx": {
+ "react-hooks-extra/no-direct-set-state-in-use-effect": {
+ "count": 1
+ }
+ },
"app/(shareLayout)/components/splash.tsx": {
"react-hooks-extra/no-direct-set-state-in-use-effect": {
"count": 1
@@ -245,9 +250,6 @@
}
},
"app/components/app/app-publisher/index.tsx": {
- "react-hooks-extra/no-direct-set-state-in-use-effect": {
- "count": 3
- },
"ts/no-explicit-any": {
"count": 6
}
@@ -740,7 +742,7 @@
},
"app/components/base/chat/chat-with-history/chat-wrapper.tsx": {
"ts/no-explicit-any": {
- "count": 6
+ "count": 7
}
},
"app/components/base/chat/chat-with-history/context.tsx": {
@@ -789,9 +791,17 @@
"count": 1
}
},
+ "app/components/base/chat/chat/answer/human-input-content/utils.ts": {
+ "ts/no-explicit-any": {
+ "count": 1
+ }
+ },
"app/components/base/chat/chat/answer/index.tsx": {
"react-hooks-extra/no-direct-set-state-in-use-effect": {
- "count": 2
+ "count": 3
+ },
+ "ts/no-explicit-any": {
+ "count": 1
}
},
"app/components/base/chat/chat/answer/workflow-process.tsx": {
@@ -822,7 +832,7 @@
"count": 2
},
"ts/no-explicit-any": {
- "count": 14
+ "count": 17
}
},
"app/components/base/chat/chat/index.tsx": {
@@ -830,7 +840,7 @@
"count": 1
},
"ts/no-explicit-any": {
- "count": 1
+ "count": 3
}
},
"app/components/base/chat/chat/type.ts": {
@@ -845,7 +855,7 @@
},
"app/components/base/chat/embedded-chatbot/chat-wrapper.tsx": {
"ts/no-explicit-any": {
- "count": 6
+ "count": 7
}
},
"app/components/base/chat/embedded-chatbot/context.tsx": {
@@ -1225,7 +1235,7 @@
},
"app/components/base/markdown/react-markdown-wrapper.tsx": {
"ts/no-explicit-any": {
- "count": 8
+ "count": 9
}
},
"app/components/base/mermaid/index.tsx": {
@@ -1331,7 +1341,7 @@
},
"app/components/base/prompt-editor/index.tsx": {
"ts/no-explicit-any": {
- "count": 2
+ "count": 4
}
},
"app/components/base/prompt-editor/plugins/component-picker-block/index.tsx": {
@@ -1344,16 +1354,31 @@
"count": 1
}
},
+ "app/components/base/prompt-editor/plugins/draggable-plugin/index.tsx": {
+ "ts/no-explicit-any": {
+ "count": 2
+ }
+ },
"app/components/base/prompt-editor/plugins/history-block/component.tsx": {
"ts/no-explicit-any": {
"count": 1
}
},
+ "app/components/base/prompt-editor/plugins/hitl-input-block/hitl-input-block-replacement-block.tsx": {
+ "ts/no-explicit-any": {
+ "count": 1
+ }
+ },
"app/components/base/prompt-editor/plugins/on-blur-or-focus-block.tsx": {
"ts/no-explicit-any": {
"count": 1
}
},
+ "app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx": {
+ "ts/no-explicit-any": {
+ "count": 2
+ }
+ },
"app/components/base/prompt-editor/plugins/update-block.tsx": {
"ts/no-explicit-any": {
"count": 2
@@ -2918,7 +2943,7 @@
},
"app/components/workflow/nodes/_base/components/before-run-form/index.tsx": {
"ts/no-explicit-any": {
- "count": 8
+ "count": 11
}
},
"app/components/workflow/nodes/_base/components/editor/code-editor/editor-support-vars.tsx": {
@@ -3253,6 +3278,27 @@
"count": 5
}
},
+ "app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx": {
+ "ts/no-explicit-any": {
+ "count": 2
+ }
+ },
+ "app/components/workflow/nodes/human-input/components/form-content.tsx": {
+ "react-hooks-extra/no-direct-set-state-in-use-effect": {
+ "count": 1
+ },
+ "react/no-nested-component-definitions": {
+ "count": 1
+ },
+ "ts/no-explicit-any": {
+ "count": 3
+ }
+ },
+ "app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx": {
+ "ts/no-explicit-any": {
+ "count": 8
+ }
+ },
"app/components/workflow/nodes/if-else/components/condition-list/condition-input.tsx": {
"ts/no-explicit-any": {
"count": 1
@@ -3738,7 +3784,7 @@
},
"app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx": {
"ts/no-explicit-any": {
- "count": 5
+ "count": 6
}
},
"app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx": {
@@ -3748,7 +3794,7 @@
},
"app/components/workflow/panel/debug-and-preview/hooks.ts": {
"ts/no-explicit-any": {
- "count": 7
+ "count": 12
}
},
"app/components/workflow/panel/env-panel/variable-modal.tsx": {
@@ -3759,6 +3805,11 @@
"count": 1
}
},
+ "app/components/workflow/panel/human-input-form-list.tsx": {
+ "ts/no-explicit-any": {
+ "count": 1
+ }
+ },
"app/components/workflow/panel/inputs-panel.tsx": {
"ts/no-explicit-any": {
"count": 4
@@ -3770,11 +3821,8 @@
}
},
"app/components/workflow/panel/workflow-preview.tsx": {
- "react-hooks-extra/no-direct-set-state-in-use-effect": {
- "count": 1
- },
"ts/no-explicit-any": {
- "count": 1
+ "count": 2
}
},
"app/components/workflow/run/hooks.ts": {
@@ -3888,6 +3936,11 @@
"count": 1
}
},
+ "app/components/workflow/store/workflow/workflow-slice.ts": {
+ "ts/no-explicit-any": {
+ "count": 1
+ }
+ },
"app/components/workflow/types.ts": {
"ts/no-empty-object-type": {
"count": 3
@@ -4305,7 +4358,7 @@
},
"service/use-workflow.ts": {
"ts/no-explicit-any": {
- "count": 2
+ "count": 3
}
},
"service/utils.spec.ts": {
@@ -4345,7 +4398,7 @@
},
"types/workflow.ts": {
"ts/no-explicit-any": {
- "count": 15
+ "count": 17
}
},
"utils/clipboard.ts": {
diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.json
index d6e329c3df8..91704726429 100644
--- a/web/i18n/en-US/common.json
+++ b/web/i18n/en-US/common.json
@@ -511,6 +511,8 @@
"promptEditor.placeholder": "Write your prompt word here, enter '{' to insert a variable, enter '/' to insert a prompt content block",
"promptEditor.query.item.desc": "Insert user query template",
"promptEditor.query.item.title": "Query",
+ "promptEditor.requestURL.item.desc": "Insert request URL",
+ "promptEditor.requestURL.item.title": "Request URL",
"promptEditor.variable.item.desc": "Insert Variables & External Tools",
"promptEditor.variable.item.title": "Variables & External Tools",
"promptEditor.variable.modal.add": "New variable",
diff --git a/web/i18n/en-US/share.json b/web/i18n/en-US/share.json
index 3b417f316e0..adb75ce1818 100644
--- a/web/i18n/en-US/share.json
+++ b/web/i18n/en-US/share.json
@@ -58,5 +58,15 @@
"generation.tabs.create": "Run Once",
"generation.tabs.saved": "Saved",
"generation.title": "AI Completion",
+ "humanInput.completed": "Seems like this request was dealt with elsewhere.",
+ "humanInput.expirationTimeNowOrFuture": "This action will expire {{relativeTime}}.",
+ "humanInput.expired": "Seems like this request has expired.",
+ "humanInput.expiredTip": "This action has expired.",
+ "humanInput.formNotFound": "Form not found.",
+ "humanInput.rateLimitExceeded": "Too many requests, please try again later.",
+ "humanInput.recorded": "Your input has been recorded.",
+ "humanInput.sorry": "Sorry!",
+ "humanInput.submissionID": "submission_id: {{id}}",
+ "humanInput.thanks": "Thanks!",
"login.backToHome": "Back to Home"
}
diff --git a/web/i18n/en-US/workflow.json b/web/i18n/en-US/workflow.json
index 107dad5b288..4d9f5adbacb 100644
--- a/web/i18n/en-US/workflow.json
+++ b/web/i18n/en-US/workflow.json
@@ -8,6 +8,7 @@
"blocks.document-extractor": "Doc Extractor",
"blocks.end": "Output",
"blocks.http-request": "HTTP Request",
+ "blocks.human-input": "Human Input",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "Iteration",
"blocks.iteration-start": "Iteration Start",
@@ -38,6 +39,7 @@
"blocksAbout.document-extractor": "Used to parse uploaded documents into text content that is easily understandable by LLM.",
"blocksAbout.end": "Define the output and result type of a workflow",
"blocksAbout.http-request": "Allow server requests to be sent over the HTTP protocol",
+ "blocksAbout.human-input": "Ask for human to confirm before generating the next step",
"blocksAbout.if-else": "Allows you to split the workflow into two branches based on if/else conditions",
"blocksAbout.iteration": "Perform multiple steps on a list object until all results are outputted.",
"blocksAbout.iteration-start": "Iteration Start node",
@@ -145,6 +147,9 @@
"common.fileUploadTip": "Image upload features have been upgraded to file upload. ",
"common.goBackToEdit": "Go back to editor",
"common.handMode": "Hand Mode",
+ "common.humanInputEmailTip": "Email (Delivery Method) sent to your configured recipients",
+ "common.humanInputEmailTipInDebugMode": "Email (Delivery Method) sent to <email>{{email}}</email>",
+ "common.humanInputWebappTip": "Debug preview only, user will not see this in web app.",
"common.importDSL": "Import DSL",
"common.importDSLTip": "Current draft will be overwritten.\nExport workflow as backup before importing.",
"common.importFailure": "Import Failed",
@@ -500,6 +505,104 @@
"nodes.http.value": "Value",
"nodes.http.verifySSL.title": "Verify SSL Certificate",
"nodes.http.verifySSL.warningTooltip": "Disabling SSL verification is not recommended for production environments. This should only be used in development or testing, as it makes the connection vulnerable to security threats like man-in-the-middle attacks.",
+ "nodes.humanInput.deliveryMethod.added": "Added",
+ "nodes.humanInput.deliveryMethod.contactTip1": "Missing a delivery method you need?",
+ "nodes.humanInput.deliveryMethod.contactTip2": "Tell us at <email>[email protected]</email>.",
+ "nodes.humanInput.deliveryMethod.emailConfigure.allMembers": "All members ({{workspaceName}})",
+ "nodes.humanInput.deliveryMethod.emailConfigure.body": "Body",
+ "nodes.humanInput.deliveryMethod.emailConfigure.bodyPlaceholder": "Enter email body",
+ "nodes.humanInput.deliveryMethod.emailConfigure.debugMode": "Debug Mode",
+ "nodes.humanInput.deliveryMethod.emailConfigure.debugModeTip1": "In debug mode, the email will only be sent to your account email <email>{{email}}</email>.",
+ "nodes.humanInput.deliveryMethod.emailConfigure.debugModeTip2": "The production environment is not affected.",
+ "nodes.humanInput.deliveryMethod.emailConfigure.description": "Send request for input via email",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.add": "+ Add",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.added": "Added",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.placeholder": "Email, comma separated",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.title": "Add workspace members or external recipients",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.trigger": "Select",
+ "nodes.humanInput.deliveryMethod.emailConfigure.recipient": "Recipient",
+ "nodes.humanInput.deliveryMethod.emailConfigure.requestURLTip": "The request URL variable is the trigger entry for human input.",
+ "nodes.humanInput.deliveryMethod.emailConfigure.subject": "Subject",
+ "nodes.humanInput.deliveryMethod.emailConfigure.subjectPlaceholder": "Enter email subject",
+ "nodes.humanInput.deliveryMethod.emailConfigure.title": "Email Configuration",
+ "nodes.humanInput.deliveryMethod.emailSender.debugDone": "A test email has been sent to <email>{{email}}</email>. Please check your inbox.",
+ "nodes.humanInput.deliveryMethod.emailSender.debugModeTip": "Debug mode is enabled.",
+ "nodes.humanInput.deliveryMethod.emailSender.debugModeTip2": "Email will be sent to <email>{{email}}</email>.",
+ "nodes.humanInput.deliveryMethod.emailSender.done": "Email Sent",
+ "nodes.humanInput.deliveryMethod.emailSender.optional": "(optional)",
+ "nodes.humanInput.deliveryMethod.emailSender.send": "Send Email",
+ "nodes.humanInput.deliveryMethod.emailSender.testSendTip": "Send test emails to your configured recipients",
+ "nodes.humanInput.deliveryMethod.emailSender.testSendTipInDebugMode": "Send a test email to {{email}}",
+ "nodes.humanInput.deliveryMethod.emailSender.tip": "It is recommended to <strong>enable Debug Mode</strong> for testing email delivery.",
+ "nodes.humanInput.deliveryMethod.emailSender.title": "Test Email Sender",
+ "nodes.humanInput.deliveryMethod.emailSender.vars": "Variables in Form Content",
+ "nodes.humanInput.deliveryMethod.emailSender.varsTip": "Fill in form variables to emulate what recipients actually see.",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone1": "Email has been sent to <team>{{team}}</team> members and the following email addresses:",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone2": "Email has been sent to <team>{{team}}</team> members.",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone3": "Email has been sent to the following email addresses:",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamTip1": "Email will be sent to <team>{{team}}</team> members and the following email addresses:",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamTip2": "Email will be sent to <team>{{team}}</team> members.",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamTip3": "Email will be sent to the following email addresses:",
+ "nodes.humanInput.deliveryMethod.emptyTip": "No delivery method added, the operation cannot be triggered.",
+ "nodes.humanInput.deliveryMethod.notAvailableInTriggerMode": "Not available",
+ "nodes.humanInput.deliveryMethod.notConfigured": "Not configured",
+ "nodes.humanInput.deliveryMethod.title": "Delivery Method",
+ "nodes.humanInput.deliveryMethod.tooltip": "How the human input form is delivered to the user.",
+ "nodes.humanInput.deliveryMethod.types.discord.description": "Send request for input via Discord",
+ "nodes.humanInput.deliveryMethod.types.discord.title": "Discord",
+ "nodes.humanInput.deliveryMethod.types.email.description": "Send request for input via email",
+ "nodes.humanInput.deliveryMethod.types.email.title": "Email",
+ "nodes.humanInput.deliveryMethod.types.slack.description": "Send request for input via Slack",
+ "nodes.humanInput.deliveryMethod.types.slack.title": "Slack",
+ "nodes.humanInput.deliveryMethod.types.teams.description": "Send request for input via Teams",
+ "nodes.humanInput.deliveryMethod.types.teams.title": "Teams",
+ "nodes.humanInput.deliveryMethod.types.webapp.description": "Display to end-user in webapp",
+ "nodes.humanInput.deliveryMethod.types.webapp.title": "Webapp",
+ "nodes.humanInput.deliveryMethod.upgradeTip": "Unlock Email delivery for Human Input",
+ "nodes.humanInput.deliveryMethod.upgradeTipContent": "Send confirmation requests via email before agents take action — useful for publishing and approval workflows.",
+ "nodes.humanInput.deliveryMethod.upgradeTipHide": "Dismiss",
+ "nodes.humanInput.editor.previewTip": "In preview mode, action buttons are not functional.",
+ "nodes.humanInput.errorMsg.duplicateActionId": "Duplicate action ID found in user actions",
+ "nodes.humanInput.errorMsg.emptyActionId": "Action ID cannot be empty",
+ "nodes.humanInput.errorMsg.emptyActionTitle": "Action title cannot be empty",
+ "nodes.humanInput.errorMsg.noDeliveryMethod": "Please select at least one delivery method",
+ "nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Please enable at least one delivery method",
+ "nodes.humanInput.errorMsg.noUserActions": "Please add at least one user action",
+ "nodes.humanInput.formContent.hotkeyTip": "Press <Key/> to insert variable, <CtrlKey/><Key/> to insert input field",
+ "nodes.humanInput.formContent.placeholder": "Type content here",
+ "nodes.humanInput.formContent.preview": "Preview",
+ "nodes.humanInput.formContent.title": "Form Content",
+ "nodes.humanInput.formContent.tooltip": "What users will see after opening the form. Supports Markdown formatting.",
+ "nodes.humanInput.insertInputField.insert": "Insert",
+ "nodes.humanInput.insertInputField.prePopulateField": "Pre-populate Field",
+ "nodes.humanInput.insertInputField.prePopulateFieldPlaceholder": "Add <staticContent/> or <variable/> users will see this content initially, or leave empty.",
+ "nodes.humanInput.insertInputField.saveResponseAs": "Save Response As",
+ "nodes.humanInput.insertInputField.saveResponseAsPlaceholder": "Name this variable for later reference",
+ "nodes.humanInput.insertInputField.staticContent": "Static Content",
+ "nodes.humanInput.insertInputField.title": "Insert Input Field",
+ "nodes.humanInput.insertInputField.useConstantInstead": "Use Constant Instead",
+ "nodes.humanInput.insertInputField.useVarInstead": "Use Variable Instead",
+ "nodes.humanInput.insertInputField.variable": "variable",
+ "nodes.humanInput.insertInputField.variableNameInvalid": "Variable name can only contain letters, numbers, and underscores, and cannot start with a number",
+ "nodes.humanInput.log.backstageInputURL": "Backstage input URL:",
+ "nodes.humanInput.log.reason": "Reason:",
+ "nodes.humanInput.log.reasonContent": "Human input required to proceed",
+ "nodes.humanInput.singleRun.back": "Back",
+ "nodes.humanInput.singleRun.button": "Generate Form",
+ "nodes.humanInput.singleRun.label": "Form variables",
+ "nodes.humanInput.timeout.days": "Days",
+ "nodes.humanInput.timeout.hours": "Hours",
+ "nodes.humanInput.timeout.title": "Timeout",
+ "nodes.humanInput.userActions.actionIdFormatTip": "Action ID must start with a letter or underscores, followed by letters, numbers, or underscores",
+ "nodes.humanInput.userActions.actionIdTooLong": "Action ID must be {{maxLength}} characters or less",
+ "nodes.humanInput.userActions.actionNamePlaceholder": "Action Name",
+ "nodes.humanInput.userActions.buttonTextPlaceholder": "Button display Text",
+ "nodes.humanInput.userActions.buttonTextTooLong": "Button text must be {{maxLength}} characters or less",
+ "nodes.humanInput.userActions.chooseStyle": "Choose a button style",
+ "nodes.humanInput.userActions.emptyTip": "Click the '+' button to add user actions",
+ "nodes.humanInput.userActions.title": "User Actions",
+ "nodes.humanInput.userActions.tooltip": "Define buttons that users can click to respond to this form. Each button can trigger different workflow paths. Action ID must start with a letter or underscores, followed by letters, numbers, or underscores.",
+ "nodes.humanInput.userActions.triggered": "<strong>{{actionName}}</strong> has been triggered",
"nodes.ifElse.addCondition": "Add Condition",
"nodes.ifElse.addSubVariable": "Sub Variable",
"nodes.ifElse.and": "and",
diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.json
index ebc7c00037d..8e521c2f208 100644
--- a/web/i18n/zh-Hans/common.json
+++ b/web/i18n/zh-Hans/common.json
@@ -511,6 +511,8 @@
"promptEditor.placeholder": "在这里写你的提示词,输入'{' 插入变量、输入'/' 插入提示内容块",
"promptEditor.query.item.desc": "插入用户查询模板",
"promptEditor.query.item.title": "查询内容",
+ "promptEditor.requestURL.item.desc": "插入请求 URL",
+ "promptEditor.requestURL.item.title": "请求 URL",
"promptEditor.variable.item.desc": "插入变量和外部工具",
"promptEditor.variable.item.title": "变量 & 外部工具",
"promptEditor.variable.modal.add": "添加新变量",
diff --git a/web/i18n/zh-Hans/share.json b/web/i18n/zh-Hans/share.json
index eb884396c35..0a16583d225 100644
--- a/web/i18n/zh-Hans/share.json
+++ b/web/i18n/zh-Hans/share.json
@@ -58,5 +58,14 @@
"generation.tabs.create": "运行一次",
"generation.tabs.saved": "已保存",
"generation.title": "AI 智能书写",
+ "humanInput.completed": "此请求似乎在其他地方得到了处理。",
+ "humanInput.expirationTimeNowOrFuture": "此操作将在 {{relativeTime}}过期。",
+ "humanInput.expired": "此请求似乎已过期。",
+ "humanInput.expiredTip": "此操作已过期。",
+ "humanInput.formNotFound": "表单不存在。",
+ "humanInput.rateLimitExceeded": "请求过于频繁,请稍后再试。",
+ "humanInput.recorded": "您的输入已被记录。",
+ "humanInput.sorry": "抱歉!",
+ "humanInput.thanks": "谢谢!",
"login.backToHome": "返回首页"
}
diff --git a/web/i18n/zh-Hans/workflow.json b/web/i18n/zh-Hans/workflow.json
index 7787c9db4b6..acda7db2fce 100644
--- a/web/i18n/zh-Hans/workflow.json
+++ b/web/i18n/zh-Hans/workflow.json
@@ -8,6 +8,7 @@
"blocks.document-extractor": "文档提取器",
"blocks.end": "输出",
"blocks.http-request": "HTTP 请求",
+ "blocks.human-input": "人工介入",
"blocks.if-else": "条件分支",
"blocks.iteration": "迭代",
"blocks.iteration-start": "迭代开始",
@@ -38,6 +39,7 @@
"blocksAbout.document-extractor": "用于将用户上传的文档解析为 LLM 便于理解的文本内容。",
"blocksAbout.end": "定义一个 workflow 流程的输出和结果类型",
"blocksAbout.http-request": "允许通过 HTTP 协议发送服务器请求",
+ "blocksAbout.human-input": "人工输入,确认后生成下一步",
"blocksAbout.if-else": "允许你根据 if/else 条件将 workflow 拆分成两个分支",
"blocksAbout.iteration": "对列表对象执行多次步骤直至输出所有结果。",
"blocksAbout.iteration-start": "迭代开始节点",
@@ -145,6 +147,9 @@
"common.fileUploadTip": "图片上传功能已扩展为文件上传。",
"common.goBackToEdit": "返回编辑模式",
"common.handMode": "手模式",
+ "common.humanInputEmailTip": "电子邮件(传递方式)发送到您配置的收件人。",
+ "common.humanInputEmailTipInDebugMode": "电子邮件(传递方式)发送到 <email>{{email}}</email>",
+ "common.humanInputWebappTip": "仅调试预览,用户在 Web 应用中看不到此内容。",
"common.importDSL": "导入 DSL",
"common.importDSLTip": "当前草稿将被覆盖。在导入之前请导出工作流作为备份。",
"common.importFailure": "导入失败",
@@ -500,6 +505,104 @@
"nodes.http.value": "值",
"nodes.http.verifySSL.title": "验证 SSL 证书",
"nodes.http.verifySSL.warningTooltip": "不建议在生产环境中禁用 SSL 验证。这仅应在开发或测试中使用,因为它会使连接容易受到诸如中间人攻击等安全威胁。",
+ "nodes.humanInput.deliveryMethod.added": "已添加",
+ "nodes.humanInput.deliveryMethod.contactTip1": "缺少所需的提交方式?",
+ "nodes.humanInput.deliveryMethod.contactTip2": "请告诉我们 <email>[email protected]</email>",
+ "nodes.humanInput.deliveryMethod.emailConfigure.allMembers": "所有成员({{workspaceName}})",
+ "nodes.humanInput.deliveryMethod.emailConfigure.body": "邮件正文",
+ "nodes.humanInput.deliveryMethod.emailConfigure.bodyPlaceholder": "输入邮件正文",
+ "nodes.humanInput.deliveryMethod.emailConfigure.debugMode": "调试模式",
+ "nodes.humanInput.deliveryMethod.emailConfigure.debugModeTip1": "在调试模式下,电子邮件将仅发送到您的帐户电子邮件 <email>{{email}}</email>。",
+ "nodes.humanInput.deliveryMethod.emailConfigure.debugModeTip2": "生产环境不受影响。",
+ "nodes.humanInput.deliveryMethod.emailConfigure.description": "通过电子邮件发送输入请求",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.add": "+ 添加",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.added": "已添加",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.placeholder": "电子邮件,以逗号分隔",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.title": "添加工作区成员或外部收件人",
+ "nodes.humanInput.deliveryMethod.emailConfigure.memberSelector.trigger": "选择",
+ "nodes.humanInput.deliveryMethod.emailConfigure.recipient": "收件人",
+ "nodes.humanInput.deliveryMethod.emailConfigure.requestURLTip": "请求 URL 变量是人工介入的触发入口。",
+ "nodes.humanInput.deliveryMethod.emailConfigure.subject": "邮件主题",
+ "nodes.humanInput.deliveryMethod.emailConfigure.subjectPlaceholder": "输入邮件主题",
+ "nodes.humanInput.deliveryMethod.emailConfigure.title": "电子邮件配置",
+ "nodes.humanInput.deliveryMethod.emailSender.debugDone": "测试邮件已发送到 <email>{{email}}</email>。请检查您的收件箱。",
+ "nodes.humanInput.deliveryMethod.emailSender.debugModeTip": "调试模式已启用。",
+ "nodes.humanInput.deliveryMethod.emailSender.debugModeTip2": "邮件将发送到 <email>{{email}}</email>。",
+ "nodes.humanInput.deliveryMethod.emailSender.done": "邮件已发送",
+ "nodes.humanInput.deliveryMethod.emailSender.optional": "(可选)",
+ "nodes.humanInput.deliveryMethod.emailSender.send": "发送邮件",
+ "nodes.humanInput.deliveryMethod.emailSender.testSendTip": "发送测试邮件到您的配置收件人",
+ "nodes.humanInput.deliveryMethod.emailSender.testSendTipInDebugMode": "发送测试邮件到 {{email}}",
+ "nodes.humanInput.deliveryMethod.emailSender.tip": "建议为测试邮件发送启用 <strong>调试模式</strong>。",
+ "nodes.humanInput.deliveryMethod.emailSender.title": "测试邮件发送器",
+ "nodes.humanInput.deliveryMethod.emailSender.vars": "表单内容中的变量",
+ "nodes.humanInput.deliveryMethod.emailSender.varsTip": "填写表单变量以模拟收件人实际看到的内容。",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone1": "邮件已发送给 <team>{{team}}</team> 成员和以下邮件地址:",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone2": "邮件已发送给 <team>{{team}}</team> 成员。",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamDone3": "邮件已发送到以下邮件地址:",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamTip1": "邮件将发送给 <team>{{team}}</team> 成员和以下邮件地址:",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamTip2": "邮件将发送给 <team>{{team}}</team> 成员。",
+ "nodes.humanInput.deliveryMethod.emailSender.wholeTeamTip3": "邮件将发送到以下邮件地址:",
+ "nodes.humanInput.deliveryMethod.emptyTip": "未添加提交方式,无法触发操作。",
+ "nodes.humanInput.deliveryMethod.notAvailableInTriggerMode": "不可用",
+ "nodes.humanInput.deliveryMethod.notConfigured": "未配置",
+ "nodes.humanInput.deliveryMethod.title": "提交方式",
+ "nodes.humanInput.deliveryMethod.tooltip": "人工介入表单如何传递给用户。",
+ "nodes.humanInput.deliveryMethod.types.discord.description": "通过 Discord 发送输入请求",
+ "nodes.humanInput.deliveryMethod.types.discord.title": "Discord",
+ "nodes.humanInput.deliveryMethod.types.email.description": "通过电子邮件发送输入请求",
+ "nodes.humanInput.deliveryMethod.types.email.title": "Email",
+ "nodes.humanInput.deliveryMethod.types.slack.description": "通过 Slack 发送输入请求",
+ "nodes.humanInput.deliveryMethod.types.slack.title": "Slack",
+ "nodes.humanInput.deliveryMethod.types.teams.description": "通过 Teams 发送输入请求",
+ "nodes.humanInput.deliveryMethod.types.teams.title": "Teams",
+ "nodes.humanInput.deliveryMethod.types.webapp.description": "在 Web 应用中显示给最终用户",
+ "nodes.humanInput.deliveryMethod.types.webapp.title": "Webapp",
+ "nodes.humanInput.deliveryMethod.upgradeTip": "解锁人工介入的电子邮件发送功能",
+ "nodes.humanInput.deliveryMethod.upgradeTipContent": "在 Agent 采取行动之前,通过电子邮件发送确认请求——适用于发布和审批工作流。",
+ "nodes.humanInput.deliveryMethod.upgradeTipHide": "关闭",
+ "nodes.humanInput.editor.previewTip": "在预览模式下,操作按钮无法使用。",
+ "nodes.humanInput.errorMsg.duplicateActionId": "用户操作中存在重复的操作 ID",
+ "nodes.humanInput.errorMsg.emptyActionId": "操作 ID 不能为空",
+ "nodes.humanInput.errorMsg.emptyActionTitle": "操作标题不能为空",
+ "nodes.humanInput.errorMsg.noDeliveryMethod": "请至少选择一种提交方式",
+ "nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "请至少启用一种提交方式",
+ "nodes.humanInput.errorMsg.noUserActions": "请添加至少一个用户操作",
+ "nodes.humanInput.formContent.hotkeyTip": "按 <Key/> 插入变量,按 <CtrlKey/><Key/> 插入输入字段",
+ "nodes.humanInput.formContent.placeholder": "在此输入内容",
+ "nodes.humanInput.formContent.preview": "预览",
+ "nodes.humanInput.formContent.title": "表单内容",
+ "nodes.humanInput.formContent.tooltip": "用户打开表单后看到的内容。支持 Markdown 格式。",
+ "nodes.humanInput.insertInputField.insert": "插入",
+ "nodes.humanInput.insertInputField.prePopulateField": "预填充字段",
+ "nodes.humanInput.insertInputField.prePopulateFieldPlaceholder": "添加 <staticContent/> 或 <variable/> 用户将最初看到此内容,或留空。",
+ "nodes.humanInput.insertInputField.saveResponseAs": "保存响应为",
+ "nodes.humanInput.insertInputField.saveResponseAsPlaceholder": "为此变量命名以便将来引用",
+ "nodes.humanInput.insertInputField.staticContent": "静态内容",
+ "nodes.humanInput.insertInputField.title": "插入输入字段",
+ "nodes.humanInput.insertInputField.useConstantInstead": "使用常量代替",
+ "nodes.humanInput.insertInputField.useVarInstead": "使用变量代替",
+ "nodes.humanInput.insertInputField.variable": "变量",
+ "nodes.humanInput.insertInputField.variableNameInvalid": "只能包含字母、数字和下划线,且不能以数字开头",
+ "nodes.humanInput.log.backstageInputURL": "表单输入 URL:",
+ "nodes.humanInput.log.reason": "原因:",
+ "nodes.humanInput.log.reasonContent": "需要人工介入才能继续",
+ "nodes.humanInput.singleRun.back": "返回",
+ "nodes.humanInput.singleRun.button": "生成表单",
+ "nodes.humanInput.singleRun.label": "表单变量",
+ "nodes.humanInput.timeout.days": "日",
+ "nodes.humanInput.timeout.hours": "小时",
+ "nodes.humanInput.timeout.title": "超时设置",
+ "nodes.humanInput.userActions.actionIdFormatTip": "操作 ID 必须以字母或下划线开头,后跟字母、数字或下划线",
+ "nodes.humanInput.userActions.actionIdTooLong": "操作 ID 不能超过 {{maxLength}} 个字符",
+ "nodes.humanInput.userActions.actionNamePlaceholder": "操作名称",
+ "nodes.humanInput.userActions.buttonTextPlaceholder": "按钮显示文本",
+ "nodes.humanInput.userActions.buttonTextTooLong": "按钮文本不能超过 {{maxLength}} 个字符",
+ "nodes.humanInput.userActions.chooseStyle": "选择按钮样式",
+ "nodes.humanInput.userActions.emptyTip": "点击 '+' 按钮添加用户操作",
+ "nodes.humanInput.userActions.title": "用户操作",
+ "nodes.humanInput.userActions.tooltip": "定义用户可以点击以响应此表单的按钮。每个按钮都可以触发不同的工作流路径。操作 ID 必须以字母或下划线开头,后跟字母、数字或下划线。",
+ "nodes.humanInput.userActions.triggered": "已触发<strong>{{actionName}}</strong>",
"nodes.ifElse.addCondition": "添加条件",
"nodes.ifElse.addSubVariable": "添加子变量",
"nodes.ifElse.and": "and",
diff --git a/web/models/log.ts b/web/models/log.ts
index d15d6d66883..ab1282b8af3 100644
--- a/web/models/log.ts
+++ b/web/models/log.ts
@@ -93,7 +93,7 @@ export type MessageContent = {
export type CompletionConversationGeneralDetail = {
id: string
- status: 'normal' | 'finished'
+ status: 'normal' | 'finished' | 'paused'
from_source: 'api' | 'console'
from_end_user_id: string
from_end_user_session_id: string
@@ -367,3 +367,22 @@ export type AgentLogDetailResponse = {
iterations: AgentIteration[]
files: AgentLogFile[]
}
+
+export type PauseType = {
+ type: 'human_input'
+ form_id: string
+ backstage_input_url: string
+} | {
+ type: 'breakpoint'
+}
+
+export type PauseDetail = {
+ node_id: string
+ node_title: string
+ pause_type: PauseType
+}
+
+export type WorkflowPausedDetailsResponse = {
+ paused_at: string
+ paused_nodes: PauseDetail[]
+}
diff --git a/web/service/base.ts b/web/service/base.ts
index fb32ce6bcf4..fb8999d7a58 100644
--- a/web/service/base.ts
+++ b/web/service/base.ts
@@ -8,6 +8,9 @@ import type {
} from '@/types/pipeline'
import type {
AgentLogResponse,
+ HumanInputFormFilledResponse,
+ HumanInputFormTimeoutResponse,
+ HumanInputRequiredResponse,
IterationFinishedResponse,
IterationNextResponse,
IterationStartedResponse,
@@ -21,6 +24,7 @@ import type {
TextChunkResponse,
TextReplaceResponse,
WorkflowFinishedResponse,
+ WorkflowPausedResponse,
WorkflowStartedResponse,
} from '@/types/workflow'
import Cookies from 'js-cookie'
@@ -29,7 +33,7 @@ import { API_PREFIX, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, IS_CE_EDITION, PASSPORT
import { asyncRunSafe } from '@/utils'
import { basePath } from '@/utils/var'
import { base, ContentType, getBaseOptions } from './fetch'
-import { refreshAccessTokenOrRelogin } from './refresh-token'
+import { refreshAccessTokenOrReLogin } from './refresh-token'
import { getWebAppPassport } from './webapp-auth'
const TIME_OUT = 100000
@@ -70,6 +74,10 @@ export type IOnLoopNext = (workflowStarted: LoopNextResponse) => void
export type IOnLoopFinished = (workflowFinished: LoopFinishedResponse) => void
export type IOnAgentLog = (agentLog: AgentLogResponse) => void
+export type IOHumanInputRequired = (humanInputRequired: HumanInputRequiredResponse) => void
+export type IOnHumanInputFormFilled = (humanInputFormFilled: HumanInputFormFilledResponse) => void
+export type IOnHumanInputFormTimeout = (humanInputFormTimeout: HumanInputFormTimeoutResponse) => void
+export type IOWorkflowPaused = (workflowPaused: WorkflowPausedResponse) => void
export type IOnDataSourceNodeProcessing = (dataSourceNodeProcessing: DataSourceNodeProcessingResponse) => void
export type IOnDataSourceNodeCompleted = (dataSourceNodeCompleted: DataSourceNodeCompletedResponse) => void
export type IOnDataSourceNodeError = (dataSourceNodeError: DataSourceNodeErrorResponse) => void
@@ -113,6 +121,10 @@ export type IOtherOptions = {
onLoopNext?: IOnLoopNext
onLoopFinish?: IOnLoopFinished
onAgentLog?: IOnAgentLog
+ onHumanInputRequired?: IOHumanInputRequired
+ onHumanInputFormFilled?: IOnHumanInputFormFilled
+ onHumanInputFormTimeout?: IOnHumanInputFormTimeout
+ onWorkflowPaused?: IOWorkflowPaused
// Pipeline data source node run
onDataSourceNodeProcessing?: IOnDataSourceNodeProcessing
@@ -153,6 +165,14 @@ function requiredWebSSOLogin(message?: string, code?: number) {
globalThis.location.href = `${globalThis.location.origin}${basePath}${WBB_APP_LOGIN_PATH}?${params.toString()}`
}
+function formatURL(url: string, isPublicAPI: boolean) {
+ const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
+ if (url.startsWith('http://') || url.startsWith('https://'))
+ return url
+ const urlWithoutProtocol = url.startsWith('/') ? url : `/${url}`
+ return `${urlPrefix}${urlWithoutProtocol}`
+}
+
export function format(text: string) {
let res = text.trim()
if (res.startsWith('\n'))
@@ -187,6 +207,10 @@ export const handleStream = (
onTTSEnd?: IOnTTSEnd,
onTextReplace?: IOnTextReplace,
onAgentLog?: IOnAgentLog,
+ onHumanInputRequired?: IOHumanInputRequired,
+ onHumanInputFormFilled?: IOnHumanInputFormFilled,
+ onHumanInputFormTimeout?: IOnHumanInputFormTimeout,
+ onWorkflowPaused?: IOWorkflowPaused,
onDataSourceNodeProcessing?: IOnDataSourceNodeProcessing,
onDataSourceNodeCompleted?: IOnDataSourceNodeCompleted,
onDataSourceNodeError?: IOnDataSourceNodeError,
@@ -319,6 +343,18 @@ export const handleStream = (
else if (bufferObj.event === 'tts_message_end') {
onTTSEnd?.(bufferObj.message_id, bufferObj.audio)
}
+ else if (bufferObj.event === 'human_input_required') {
+ onHumanInputRequired?.(bufferObj as HumanInputRequiredResponse)
+ }
+ else if (bufferObj.event === 'human_input_form_filled') {
+ onHumanInputFormFilled?.(bufferObj as HumanInputFormFilledResponse)
+ }
+ else if (bufferObj.event === 'human_input_form_timeout') {
+ onHumanInputFormTimeout?.(bufferObj as HumanInputFormTimeoutResponse)
+ }
+ else if (bufferObj.event === 'workflow_paused') {
+ onWorkflowPaused?.(bufferObj as WorkflowPausedResponse)
+ }
else if (bufferObj.event === 'datasource_processing') {
onDataSourceNodeProcessing?.(bufferObj as DataSourceNodeProcessingResponse)
}
@@ -441,6 +477,10 @@ export const ssePost = async (
onLoopStart,
onLoopNext,
onLoopFinish,
+ onHumanInputRequired,
+ onHumanInputFormFilled,
+ onHumanInputFormTimeout,
+ onWorkflowPaused,
onDataSourceNodeProcessing,
onDataSourceNodeCompleted,
onDataSourceNodeError,
@@ -467,10 +507,7 @@ export const ssePost = async (
getAbortController?.(abortController)
- const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
- const urlWithPrefix = (url.startsWith('http://') || url.startsWith('https://'))
- ? url
- : `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
+ const urlWithPrefix = formatURL(url, isPublicAPI)
const { body } = options
if (body)
@@ -495,7 +532,7 @@ export const ssePost = async (
})
}
else {
- refreshAccessTokenOrRelogin(TIME_OUT).then(() => {
+ refreshAccessTokenOrReLogin(TIME_OUT).then(() => {
ssePost(url, fetchOptions, otherOptions)
}).catch((err) => {
console.error(err)
@@ -545,6 +582,157 @@ export const ssePost = async (
onTTSEnd,
onTextReplace,
onAgentLog,
+ onHumanInputRequired,
+ onHumanInputFormFilled,
+ onHumanInputFormTimeout,
+ onWorkflowPaused,
+ onDataSourceNodeProcessing,
+ onDataSourceNodeCompleted,
+ onDataSourceNodeError,
+ )
+ })
+ .catch((e) => {
+ if (e.toString() !== 'AbortError: The user aborted a request.' && !e.toString().errorMessage.includes('TypeError: Cannot assign to read only property'))
+ Toast.notify({ type: 'error', message: e })
+ onError?.(e)
+ })
+}
+
+export const sseGet = async (
+ url: string,
+ fetchOptions: FetchOptionType,
+ otherOptions: IOtherOptions,
+) => {
+ const {
+ isPublicAPI = false,
+ onData,
+ onCompleted,
+ onThought,
+ onFile,
+ onMessageEnd,
+ onMessageReplace,
+ onWorkflowStarted,
+ onWorkflowFinished,
+ onNodeStarted,
+ onNodeFinished,
+ onIterationStart,
+ onIterationNext,
+ onIterationFinish,
+ onNodeRetry,
+ onParallelBranchStarted,
+ onParallelBranchFinished,
+ onTextChunk,
+ onTTSChunk,
+ onTTSEnd,
+ onTextReplace,
+ onAgentLog,
+ onError,
+ getAbortController,
+ onLoopStart,
+ onLoopNext,
+ onLoopFinish,
+ onHumanInputRequired,
+ onHumanInputFormFilled,
+ onHumanInputFormTimeout,
+ onWorkflowPaused,
+ onDataSourceNodeProcessing,
+ onDataSourceNodeCompleted,
+ onDataSourceNodeError,
+ } = otherOptions
+ const abortController = new AbortController()
+
+ const baseOptions = getBaseOptions()
+ const shareCode = globalThis.location.pathname.split('/').slice(-1)[0]
+ const options = Object.assign({}, baseOptions, {
+ signal: abortController.signal,
+ headers: new Headers({
+ [CSRF_HEADER_NAME]: Cookies.get(CSRF_COOKIE_NAME()) || '',
+ [WEB_APP_SHARE_CODE_HEADER_NAME]: shareCode,
+ [PASSPORT_HEADER_NAME]: getWebAppPassport(shareCode),
+ }),
+ } as RequestInit, fetchOptions)
+
+ const contentType = (options.headers as Headers).get('Content-Type')
+ if (!contentType)
+ (options.headers as Headers).set('Content-Type', ContentType.json)
+
+ getAbortController?.(abortController)
+
+ const urlWithPrefix = formatURL(url, isPublicAPI)
+
+ globalThis.fetch(urlWithPrefix, options as RequestInit)
+ .then((res) => {
+ if (!/^[23]\d{2}$/.test(String(res.status))) {
+ if (res.status === 401) {
+ if (isPublicAPI) {
+ res.json().then((data: { code?: string, message?: string }) => {
+ if (isPublicAPI) {
+ if (data.code === 'web_app_access_denied')
+ requiredWebSSOLogin(data.message, 403)
+
+ if (data.code === 'web_sso_auth_required')
+ requiredWebSSOLogin()
+
+ if (data.code === 'unauthorized')
+ requiredWebSSOLogin()
+ }
+ })
+ }
+ else {
+ refreshAccessTokenOrReLogin(TIME_OUT).then(() => {
+ sseGet(url, fetchOptions, otherOptions)
+ }).catch((err) => {
+ console.error(err)
+ })
+ }
+ }
+ else {
+ res.json().then((data) => {
+ Toast.notify({ type: 'error', message: data.message || 'Server Error' })
+ })
+ onError?.('Server Error')
+ }
+ return
+ }
+ return handleStream(
+ res,
+ (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
+ if (moreInfo.errorMessage) {
+ onError?.(moreInfo.errorMessage, moreInfo.errorCode)
+ // TypeError: Cannot assign to read only property ... will happen in page leave, so it should be ignored.
+ if (moreInfo.errorMessage !== 'AbortError: The user aborted a request.' && !moreInfo.errorMessage.includes('TypeError: Cannot assign to read only property'))
+ Toast.notify({ type: 'error', message: moreInfo.errorMessage })
+ return
+ }
+ onData?.(str, isFirstMessage, moreInfo)
+ },
+ onCompleted,
+ onThought,
+ onMessageEnd,
+ onMessageReplace,
+ onFile,
+ onWorkflowStarted,
+ onWorkflowFinished,
+ onNodeStarted,
+ onNodeFinished,
+ onIterationStart,
+ onIterationNext,
+ onIterationFinish,
+ onLoopStart,
+ onLoopNext,
+ onLoopFinish,
+ onNodeRetry,
+ onParallelBranchStarted,
+ onParallelBranchFinished,
+ onTextChunk,
+ onTTSChunk,
+ onTTSEnd,
+ onTextReplace,
+ onAgentLog,
+ onHumanInputRequired,
+ onHumanInputFormFilled,
+ onHumanInputFormTimeout,
+ onWorkflowPaused,
onDataSourceNodeProcessing,
onDataSourceNodeCompleted,
onDataSourceNodeError,
@@ -612,7 +800,7 @@ export const request = async<T>(url: string, options = {}, otherOptions?: IOther
}
// refresh token
- const [refreshErr] = await asyncRunSafe(refreshAccessTokenOrRelogin(TIME_OUT))
+ const [refreshErr] = await asyncRunSafe(refreshAccessTokenOrReLogin(TIME_OUT))
if (refreshErr === null)
return baseFetch<T>(url, options, otherOptionsForBaseFetch)
if (location.pathname !== `${basePath}/signin` || !IS_CE_EDITION) {
diff --git a/web/service/refresh-token.ts b/web/service/refresh-token.ts
index 998b7f2461c..b00a46eb6eb 100644
--- a/web/service/refresh-token.ts
+++ b/web/service/refresh-token.ts
@@ -80,7 +80,7 @@ function releaseRefreshLock() {
globalThis.removeEventListener('beforeunload', releaseRefreshLock)
}
-export async function refreshAccessTokenOrRelogin(timeout: number) {
+export async function refreshAccessTokenOrReLogin(timeout: number) {
return Promise.race([new Promise<void>((resolve, reject) => setTimeout(() => {
releaseRefreshLock()
reject(new Error('request timeout'))
diff --git a/web/service/share.ts b/web/service/share.ts
index add1256f304..4726ded7d16 100644
--- a/web/service/share.ts
+++ b/web/service/share.ts
@@ -2,20 +2,10 @@ import type {
IOnCompleted,
IOnData,
IOnError,
- IOnIterationFinished,
- IOnIterationNext,
- IOnIterationStarted,
- IOnLoopFinished,
- IOnLoopNext,
- IOnLoopStarted,
IOnMessageReplace,
- IOnNodeFinished,
- IOnNodeStarted,
- IOnTextChunk,
- IOnTextReplace,
- IOnWorkflowFinished,
- IOnWorkflowStarted,
+ IOtherOptions,
} from './base'
+import type { FormData as HumanInputFormData } from '@/app/(humanInputLayout)/form/[token]/form'
import type { FeedbackType } from '@/app/components/base/chat/chat/type'
import type { ChatConfig } from '@/app/components/base/chat/types'
import type { AccessMode } from '@/models/access-control'
@@ -95,33 +85,7 @@ export const sendCompletionMessage = async (body: Record<string, any>, { onData,
export const sendWorkflowMessage = async (
body: Record<string, any>,
- {
- onWorkflowStarted,
- onNodeStarted,
- onNodeFinished,
- onWorkflowFinished,
- onIterationStart,
- onIterationNext,
- onIterationFinish,
- onLoopStart,
- onLoopNext,
- onLoopFinish,
- onTextChunk,
- onTextReplace,
- }: {
- onWorkflowStarted: IOnWorkflowStarted
- onNodeStarted: IOnNodeStarted
- onNodeFinished: IOnNodeFinished
- onWorkflowFinished: IOnWorkflowFinished
- onIterationStart: IOnIterationStarted
- onIterationNext: IOnIterationNext
- onIterationFinish: IOnIterationFinished
- onLoopStart: IOnLoopStarted
- onLoopNext: IOnLoopNext
- onLoopFinish: IOnLoopFinished
- onTextChunk: IOnTextChunk
- onTextReplace: IOnTextReplace
- },
+ otherOptions: IOtherOptions,
appSourceType: AppSourceType,
appId = '',
) => {
@@ -131,19 +95,8 @@ export const sendWorkflowMessage = async (
response_mode: 'streaming',
},
}, {
- onNodeStarted,
- onWorkflowStarted,
- onWorkflowFinished,
+ ...otherOptions,
isPublicAPI: getIsPublicAPI(appSourceType),
- onNodeFinished,
- onIterationStart,
- onIterationNext,
- onIterationFinish,
- onLoopStart,
- onLoopNext,
- onLoopFinish,
- onTextChunk,
- onTextReplace,
})
}
@@ -320,3 +273,14 @@ export const getUserCanAccess = (appId: string, isInstalledApp: boolean) => {
export const getAppAccessModeByAppCode = (appCode: string) => {
return get<{ accessMode: AccessMode }>(`/webapp/access-mode?appCode=${appCode}`)
}
+
+export const getHumanInputForm = (token: string) => {
+ return get<HumanInputFormData>(`/form/human_input/${token}`)
+}
+
+export const submitHumanInputForm = (token: string, data: {
+ inputs: Record<string, string>
+ action: string
+}) => {
+ return post(`/form/human_input/${token}`, { body: data })
+}
diff --git a/web/service/use-common.ts b/web/service/use-common.ts
index ca0845d95ae..002d154d1de 100644
--- a/web/service/use-common.ts
+++ b/web/service/use-common.ts
@@ -108,7 +108,7 @@ export const useLangGeniusVersion = (currentVersion?: string | null, enabled?: b
export const useCurrentWorkspace = () => {
return useQuery<ICurrentWorkspace>({
queryKey: commonQueryKeys.currentWorkspace,
- queryFn: () => post<ICurrentWorkspace>('/workspaces/current', { body: {} }),
+ queryFn: () => post<ICurrentWorkspace>('/workspaces/current'),
})
}
diff --git a/web/service/use-log.ts b/web/service/use-log.ts
index b120adda2fd..310c5000d6a 100644
--- a/web/service/use-log.ts
+++ b/web/service/use-log.ts
@@ -7,6 +7,7 @@ import type {
CompletionConversationsRequest,
CompletionConversationsResponse,
WorkflowLogsResponse,
+ WorkflowPausedDetailsResponse,
} from '@/models/log'
import { useQuery } from '@tanstack/react-query'
import { get } from './base'
@@ -87,3 +88,18 @@ export const useWorkflowLogs = ({ appId, params }: WorkflowLogsParams) => {
enabled: !!appId,
})
}
+
+// ============ Workflow Pause Details ============
+
+type WorkflowPausedDetailsParams = {
+ workflowRunId: string
+ enabled?: boolean
+}
+
+export const useWorkflowPausedDetails = ({ workflowRunId, enabled = true }: WorkflowPausedDetailsParams) => {
+ return useQuery<WorkflowPausedDetailsResponse>({
+ queryKey: [NAME_SPACE, 'workflow-paused-details', workflowRunId],
+ queryFn: () => get<WorkflowPausedDetailsResponse>(`/workflow/${workflowRunId}/pause-details`),
+ enabled: enabled && !!workflowRunId,
+ })
+}
diff --git a/web/service/use-share.ts b/web/service/use-share.ts
index cb99525a78c..68e9229c1b9 100644
--- a/web/service/use-share.ts
+++ b/web/service/use-share.ts
@@ -1,5 +1,6 @@
+import type { FormData as HumanInputFormData } from '@/app/(humanInputLayout)/form/[token]/form'
import type { AppConversationData, ConversationItem } from '@/models/share'
-import { useQuery } from '@tanstack/react-query'
+import { useMutation, useQuery } from '@tanstack/react-query'
import {
AppSourceType,
fetchAppInfo,
@@ -9,6 +10,8 @@ import {
fetchConversations,
generationConversationName,
getAppAccessModeByAppCode,
+ getHumanInputForm,
+ submitHumanInputForm,
} from './share'
import { useInvalid } from './use-base'
@@ -49,6 +52,7 @@ export const shareQueryKeys = {
conversationList: (params: ShareConversationsParams) => [NAME_SPACE, 'conversations', params] as const,
chatList: (params: ShareChatListParams) => [NAME_SPACE, 'chatList', params] as const,
conversationName: (params: ShareConversationNameParams) => [NAME_SPACE, 'conversationName', params] as const,
+ humanInputForm: (token: string) => [NAME_SPACE, 'humanInputForm', token] as const,
}
export const useGetWebAppAccessModeByCode = (code: string | null) => {
@@ -149,3 +153,60 @@ export const useShareConversationName = (params: ShareConversationNameParams, op
export const useInvalidateShareConversations = () => {
return useInvalid(shareQueryKeys.conversations)
}
+
+export class HumanInputFormError extends Error {
+ code: string
+ status: number
+
+ constructor(code: string, message: string, status: number) {
+ super(message)
+ this.name = 'HumanInputFormError'
+ this.code = code
+ this.status = status
+ }
+}
+
+export const useGetHumanInputForm = (token: string, options: ShareQueryOptions = {}) => {
+ const {
+ enabled = true,
+ refetchOnReconnect,
+ refetchOnWindowFocus,
+ } = options
+ return useQuery<HumanInputFormData, HumanInputFormError>({
+ queryKey: shareQueryKeys.humanInputForm(token),
+ queryFn: async () => {
+ try {
+ return await getHumanInputForm(token)
+ }
+ catch (error) {
+ const response = error as Response
+ if (response.status && response.json) {
+ const errorData = await response.json() as { code: string, message: string }
+ throw new HumanInputFormError(errorData.code, errorData.message, response.status)
+ }
+ throw error
+ }
+ },
+ enabled: enabled && !!token,
+ refetchOnReconnect,
+ refetchOnWindowFocus,
+ retry: false,
+ })
+}
+
+export type SubmitHumanInputFormParams = {
+ token: string
+ data: {
+ inputs: Record<string, string>
+ action: string
+ }
+}
+
+export const useSubmitHumanInputForm = () => {
+ return useMutation({
+ mutationKey: [NAME_SPACE, 'submit-human-input-form'],
+ mutationFn: ({ token, data }: SubmitHumanInputFormParams) => {
+ return submitHumanInputForm(token, data)
+ },
+ })
+}
diff --git a/web/service/use-workflow.ts b/web/service/use-workflow.ts
index 754fb6b0032..2f9f5d2fb77 100644
--- a/web/service/use-workflow.ts
+++ b/web/service/use-workflow.ts
@@ -227,3 +227,18 @@ export const useEditInspectorVar = (flowType: FlowType, flowId: string) => {
},
})
}
+
+export const useTestEmailSender = () => {
+ return useMutation({
+ mutationKey: [NAME_SPACE, 'test email sender'],
+ mutationFn: async (data: { appID: string, nodeID: string, deliveryID: string, inputs: Record<string, any> }) => {
+ const { appID, nodeID, deliveryID, inputs } = data
+ return post<CommonResponse>(`/apps/${appID}/workflows/draft/human-input/nodes/${nodeID}/delivery-test`, {
+ body: {
+ delivery_method_id: deliveryID,
+ inputs,
+ },
+ })
+ },
+ })
+}
diff --git a/web/service/workflow.ts b/web/service/workflow.ts
index 3a37db791b9..bf0075a761e 100644
--- a/web/service/workflow.ts
+++ b/web/service/workflow.ts
@@ -4,6 +4,7 @@ import type { FlowType } from '@/types/common'
import type {
ConversationVariableResponse,
FetchWorkflowDraftResponse,
+ HumanInputFormData,
NodesDefaultConfigsResponse,
VarInInspect,
} from '@/types/workflow'
@@ -96,3 +97,30 @@ export const fetchNodeInspectVars = async (flowType: FlowType, flowId: string, n
const { items } = (await get(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/nodes/${nodeId}/variables`)) as { items: VarInInspect[] }
return items
}
+
+export const submitHumanInputForm = (token: string, data: {
+ inputs: Record<string, string>
+ action: string
+}) => {
+ return post(`/form/human_input/${token}`, { body: data })
+}
+
+export const fetchHumanInputNodeStepRunForm = (
+ url: string,
+ data: {
+ inputs: Record<string, string>
+ },
+) => {
+ return post<HumanInputFormData>(`${url}/preview`, { body: data })
+}
+
+export const submitHumanInputNodeStepRunForm = (
+ url: string,
+ data: {
+ inputs: Record<string, string> | undefined
+ form_inputs: Record<string, string> | undefined
+ action: string
+ },
+) => {
+ return post<CommonResponse>(`${url}/run`, { body: data })
+}
diff --git a/web/tailwind-common-config.ts b/web/tailwind-common-config.ts
index 2c3128d5075..59ae5e730f8 100644
--- a/web/tailwind-common-config.ts
+++ b/web/tailwind-common-config.ts
@@ -227,6 +227,7 @@ const config = {
'chat-bubble-bg': 'var(--color-chat-bubble-bg)',
'chat-input-mask': 'var(--color-chat-input-mask)',
'workflow-process-bg': 'var(--color-workflow-process-bg)',
+ 'workflow-process-paused-bg': 'var(--color-workflow-process-paused-bg)',
'workflow-run-failed-bg': 'var(--color-workflow-run-failed-bg)',
'workflow-batch-failed-bg': 'var(--color-workflow-batch-failed-bg)',
'mask-top2bottom-gray-50-to-transparent': 'var(--mask-top2bottom-gray-50-to-transparent)',
@@ -263,6 +264,7 @@ const config = {
'billing-plan-card-enterprise-bg': 'var(--color-billing-plan-card-enterprise-bg)',
'knowledge-pipeline-creation-footer-bg': 'var(--color-knowledge-pipeline-creation-footer-bg)',
'progress-bar-indeterminate-stripe': 'var(--color-progress-bar-indeterminate-stripe)',
+ 'chat-answer-human-input-form-divider-bg': 'var(--color-chat-answer-human-input-form-divider-bg)',
},
animation: {
'spin-slow': 'spin 2s linear infinite',
diff --git a/web/themes/manual-dark.css b/web/themes/manual-dark.css
index eb33f93030e..8a114204d82 100644
--- a/web/themes/manual-dark.css
+++ b/web/themes/manual-dark.css
@@ -11,6 +11,12 @@ html[data-theme="dark"] {
--color-workflow-process-bg: linear-gradient(90deg,
rgba(24, 24, 27, 0.25) 0%,
rgba(24, 24, 27, 0.04) 100%);
+ --color-workflow-process-paused-bg: linear-gradient(90deg,
+ rgba(247, 144, 9, 0.14) 0%,
+ rgba(247, 144, 9, 0.00) 100%);
+ --color-workflow-process-failed-bg: linear-gradient(90deg,
+ rgba(240, 68, 56, 0.14) 0%,
+ rgba(240, 68, 56, 0.00) 100%);
--color-workflow-run-failed-bg: linear-gradient(98deg,
rgba(240, 68, 56, 0.12) 0%,
rgba(0, 0, 0, 0) 26.01%);
@@ -75,4 +81,5 @@ html[data-theme="dark"] {
--color-billing-plan-card-enterprise-bg: linear-gradient(180deg, #03F 0%, rgba(0, 51, 255, 0.00) 100%);
--color-knowledge-pipeline-creation-footer-bg: linear-gradient(90deg, rgba(34, 34, 37, 1) 4.89%, rgba(0, 0, 0, 0) 100%);
--color-progress-bar-indeterminate-stripe: repeating-linear-gradient(-55deg, #3A3A40, #3A3A40 2px, transparent 2px, transparent 5px);
+ --color-chat-answer-human-input-form-divider-bg: linear-gradient(0deg, rgba(200, 206, 218, 0.14) 0%, rgba(0, 0, 0, 0) 212.5%);
}
diff --git a/web/themes/manual-light.css b/web/themes/manual-light.css
index 62ff4b21780..4cc633d3bc6 100644
--- a/web/themes/manual-light.css
+++ b/web/themes/manual-light.css
@@ -11,6 +11,12 @@ html[data-theme="light"] {
--color-workflow-process-bg: linear-gradient(90deg,
rgba(200, 206, 218, 0.2) 0%,
rgba(200, 206, 218, 0.04) 100%);
+ --color-workflow-process-paused-bg: linear-gradient(90deg,
+ #FFFAEB 0%,
+ rgba(255, 250, 235, 0.00) 100%);
+ --color-workflow-process-failed-bg: linear-gradient(90deg,
+ #FEF3F2 0%,
+ rgba(254, 243, 242, 0.00) 100%);
--color-workflow-run-failed-bg: linear-gradient(98deg,
rgba(240, 68, 56, 0.10) 0%,
rgba(255, 255, 255, 0) 26.01%);
@@ -75,4 +81,5 @@ html[data-theme="light"] {
--color-billing-plan-card-enterprise-bg: linear-gradient(180deg, #03F 0%, rgba(0, 51, 255, 0.00) 100%);
--color-knowledge-pipeline-creation-footer-bg: linear-gradient(90deg, #FCFCFD 4.89%, rgba(255, 255, 255, 0.00) 100%);
--color-progress-bar-indeterminate-stripe: repeating-linear-gradient(-55deg, #D0D5DD, #D0D5DD 2px, transparent 2px, transparent 5px);
+ --color-chat-answer-human-input-form-divider-bg: linear-gradient(0deg, rgba(16, 24, 40, 0.08) 0%, rgba(255, 255, 255, 0.00) 212.5%);
}
diff --git a/web/types/workflow.ts b/web/types/workflow.ts
index 5f74ef2c129..156a704b48f 100644
--- a/web/types/workflow.ts
+++ b/web/types/workflow.ts
@@ -2,6 +2,7 @@ import type { RefObject } from 'react'
import type { Viewport } from 'reactflow'
import type { BeforeRunFormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form'
import type { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
+import type { FormInputItem, UserAction } from '@/app/components/workflow/nodes/human-input/types'
import type { SpecialResultPanelProps } from '@/app/components/workflow/run/special-result-panel'
import type { BlockEnum, CommonNodeType, ConversationVariable, Edge, EnvironmentVariable, InputVar, Node, ValueSelector, Variable, VarType } from '@/app/components/workflow/types'
import type { RAGPipelineVariables } from '@/models/pipeline'
@@ -165,6 +166,20 @@ export type WorkflowStartedResponse = {
workflow_id: string
created_at: number
}
+ conversation_id?: string // only in chatflow
+ message_id?: string // only in chatflow
+}
+
+export type WorkflowPausedResponse = {
+ task_id: string
+ workflow_run_id: string
+ event: string
+ data: {
+ outputs: any // todo: remove any
+ paused_nodes: string[]
+ reasons: any[] // todo: remove any
+ workflow_run_id: string
+ }
}
export type WorkflowFinishedResponse = {
@@ -298,6 +313,54 @@ export type AgentLogResponse = {
data: AgentLogItemWithChildren
}
+export type HumanInputFormData = {
+ form_id: string
+ node_id: string
+ node_title: string
+ form_content: string
+ inputs: FormInputItem[]
+ actions: UserAction[]
+ form_token: string
+ resolved_default_values: Record<string, string>
+ display_in_ui: boolean
+ expiration_time: number
+}
+
+export type HumanInputRequiredResponse = {
+ task_id: string
+ workflow_run_id: string
+ event: string
+ data: HumanInputFormData
+}
+
+export type HumanInputFilledFormData = {
+ node_id: string
+ node_title: string
+ rendered_content: string
+ action_id: string
+ action_text: string
+}
+
+export type HumanInputFormFilledResponse = {
+ task_id: string
+ workflow_run_id: string
+ event: string
+ data: HumanInputFilledFormData
+}
+
+export type HumanInputFormTimeoutData = {
+ node_id: string
+ node_title: string
+ expiration_time: number
+}
+
+export type HumanInputFormTimeoutResponse = {
+ task_id: string
+ workflow_run_id: string
+ event: string
+ data: HumanInputFormTimeoutData
+}
+
export type WorkflowRunHistory = {
id: string
version: string