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.

fix(web): resolve HITL IM and contact management regressions (#45293)

zxhlyhe59087762fc1
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 3781f32bdf9..9136a54a93d 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -4920,11 +4920,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/human-input/components/single-run-form.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/human-input/components/variable-in-markdown.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 1
diff --git a/web/__tests__/env.spec.ts b/web/__tests__/env.spec.ts
index cf60a72c4e8..4c007c4931a 100644
--- a/web/__tests__/env.spec.ts
+++ b/web/__tests__/env.spec.ts
@@ -19,8 +19,8 @@ describe('env runtime transport', () => {
beforeEach(() => {
vi.resetModules()
vi.doUnmock('../utils/client')
- previousAttributes = attributes.map((name) => document.body.getAttribute(name))
- attributes.forEach((name) => document.body.removeAttribute(name))
+ previousAttributes = attributes.map((name) => document.documentElement.getAttribute(name))
+ attributes.forEach((name) => document.documentElement.removeAttribute(name))
envKeys.forEach((name) => vi.stubEnv(name, undefined))
})
@@ -29,8 +29,8 @@ describe('env runtime transport', () => {
vi.doUnmock('../utils/client')
attributes.forEach((name, index) => {
const value = previousAttributes[index]
- if (value == null) document.body.removeAttribute(name)
- else document.body.setAttribute(name, value)
+ if (value == null) document.documentElement.removeAttribute(name)
+ else document.documentElement.setAttribute(name, value)
})
})
@@ -50,7 +50,10 @@ describe('env runtime transport', () => {
const dataset = getDatasetMap()
expect(dataset['data-enable-hitl-im']).toBe(enabled)
- document.body.setAttribute('data-enable-hitl-im', String(dataset['data-enable-hitl-im']))
+ document.documentElement.setAttribute(
+ 'data-enable-hitl-im',
+ String(dataset['data-enable-hitl-im']),
+ )
vi.stubEnv('NEXT_PUBLIC_ENABLE_HITL_IM', String(!enabled))
vi.resetModules()
vi.doMock('../utils/client', () => ({ isClient: true, isServer: false }))
@@ -65,8 +68,38 @@ describe('env runtime transport', () => {
expect(env.NEXT_PUBLIC_ENABLE_HITL_IM).toBe(false)
})
+ it('preserves runtime configuration when modules load before the streamed body', async () => {
+ const body = document.body
+ const root = document.documentElement
+ const runtimeAttributes = {
+ 'data-api-prefix': 'https://runtime.example.com/console/api',
+ 'data-base-path': '/runtime',
+ 'data-enable-hitl-im': 'true',
+ 'data-enable-agent-v2': 'true',
+ }
+ const previous = Object.keys(runtimeAttributes).map((key) => root.getAttribute(key))
+ Object.entries(runtimeAttributes).forEach(([key, value]) => root.setAttribute(key, value))
+ body.remove()
+
+ try {
+ expect(document.body).toBeNull()
+ const { env } = await import('../env')
+ expect(env.NEXT_PUBLIC_API_PREFIX).toBe(runtimeAttributes['data-api-prefix'])
+ expect(env.NEXT_PUBLIC_BASE_PATH).toBe('/runtime')
+ expect(env.NEXT_PUBLIC_ENABLE_HITL_IM).toBe(true)
+ expect(env.NEXT_PUBLIC_ENABLE_AGENT_V2).toBe(true)
+ } finally {
+ root.append(body)
+ Object.keys(runtimeAttributes).forEach((key, index) => {
+ const value = previous[index]
+ if (value == null) root.removeAttribute(key)
+ else root.setAttribute(key, value)
+ })
+ }
+ })
+
it('should read NEXT_PUBLIC_ENABLE_AGENT_V2 from the browser runtime dataset key', async () => {
- document.body.setAttribute('data-enable-agent-v2', 'true')
+ document.documentElement.setAttribute('data-enable-agent-v2', 'true')
const { env } = await import('../env')
@@ -89,7 +122,10 @@ describe('env runtime transport', () => {
})
it('should read Markdown form field name extra characters from the browser runtime dataset', async () => {
- document.body.setAttribute('data-markdown-form-field-name-extra-chars', '()!*&()!*&-')
+ document.documentElement.setAttribute(
+ 'data-markdown-form-field-name-extra-chars',
+ '()!*&()!*&-',
+ )
const { env } = await import('../env')
@@ -117,7 +153,7 @@ describe('env runtime transport', () => {
})
it('should read the Markdown form field name maximum length from the browser runtime dataset', async () => {
- document.body.setAttribute('data-markdown-form-field-name-max-length', '64')
+ document.documentElement.setAttribute('data-markdown-form-field-name-max-length', '64')
const { env } = await import('../env')
@@ -139,7 +175,7 @@ describe('env runtime transport', () => {
})
it('should read the Turnstile site key from the browser runtime dataset', async () => {
- document.body.setAttribute('data-turnstile-site-key', 'site-key-for-tests')
+ document.documentElement.setAttribute('data-turnstile-site-key', 'site-key-for-tests')
const { env } = await import('../env')
diff --git a/web/app/(humanInputLayout)/form-v2/[token]/form.tsx b/web/app/(humanInputLayout)/form-v2/[token]/form.tsx
index e683a8ea4c3..544645dc232 100644
--- a/web/app/(humanInputLayout)/form-v2/[token]/form.tsx
+++ b/web/app/(humanInputLayout)/form-v2/[token]/form.tsx
@@ -1,12 +1,10 @@
'use client'
import * as React from 'react'
import HumanInputV2Form from '@/features/human-input/public/form'
-import useDocumentTitle from '@/hooks/use-document-title'
import { useParams } from '@/next/navigation'
const FormContent = () => {
const { token } = useParams<{ token: string }>()
- useDocumentTitle('')
return <HumanInputV2Form key={token} token={token} />
}
diff --git a/web/app/(humanInputLayout)/form-v2/[token]/page.tsx b/web/app/(humanInputLayout)/form-v2/[token]/page.tsx
index 8cf60616fbe..ca64a5059e7 100644
--- a/web/app/(humanInputLayout)/form-v2/[token]/page.tsx
+++ b/web/app/(humanInputLayout)/form-v2/[token]/page.tsx
@@ -5,9 +5,9 @@ import FormContent from './form'
const FormPage = () => {
if (!ENABLE_HITL_IM) notFound()
return (
- <div className="h-full min-w-75 bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
+ <main className="h-dvh min-w-75 bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
<FormContent />
- </div>
+ </main>
)
}
diff --git a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
index a5709bb2410..d9ad971d6f6 100644
--- a/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/__tests__/form.spec.tsx
@@ -273,18 +273,39 @@ describe.each([false, true])('Human input share form with IM gate %s', (enabled)
const user = userEvent.setup()
render(<FormContent />)
const approve = await screen.findByRole('button', { name: 'Approve' })
- expect(approve).toBeDisabled()
+ await user.click(approve)
+ expect(mockSubmitForm).not.toHaveBeenCalled()
+ if (enabled)
+ expect(
+ screen.getByText('common.errorMsg.fieldRequired:{"field":"attachments"}'),
+ ).toBeInTheDocument()
const upload = await uploadLocalAttachment(user)
act(() => upload.onProgressCallback(50))
- expect(approve).toBeDisabled()
+ await user.click(approve)
+ expect(mockSubmitForm).not.toHaveBeenCalled()
await completeUpload()
expect(approve).toBeEnabled()
- await user.clear(screen.getByRole('textbox', { name: 'summary' }))
- expect(approve).toBeDisabled()
- await user.type(screen.getByRole('textbox', { name: 'summary' }), 'ready')
- expect(approve).toBeEnabled()
+ const summary = screen.getByRole('textbox', { name: 'summary' })
+ await user.clear(summary)
+ await user.click(approve)
expect(mockSubmitForm).not.toHaveBeenCalled()
+ if (enabled)
+ expect(summary).toHaveAccessibleDescription(
+ 'common.errorMsg.fieldRequired:{"field":"summary"}',
+ )
+
+ await user.type(summary, 'ready')
+ await user.click(approve)
+ await waitFor(() =>
+ expect(mockSubmitForm).toHaveBeenCalledExactlyOnceWith(
+ 'token-123',
+ expect.objectContaining({
+ action: 'approve',
+ inputs: expect.objectContaining({ summary: 'ready' }),
+ }),
+ ),
+ )
})
it('hides branding when removal is enabled', async () => {
diff --git a/web/app/(humanInputLayout)/form/[token]/form.tsx b/web/app/(humanInputLayout)/form/[token]/form.tsx
index 8f58d1dd668..07ec4e3609a 100644
--- a/web/app/(humanInputLayout)/form/[token]/form.tsx
+++ b/web/app/(humanInputLayout)/form/[token]/form.tsx
@@ -65,6 +65,7 @@ const FormContent = () => {
if (success) {
return (
<FormStatusCard
+ legacy={!ENABLE_HITL_IM}
iconClassName="i-ri-checkbox-circle-fill text-text-success"
title={t(($) => $['humanInput.thanks'], { ns: 'share' })}
subtitle={t(($) => $['humanInput.recorded'], { ns: 'share' })}
@@ -78,6 +79,7 @@ const FormContent = () => {
if (expired) {
return (
<FormStatusCard
+ legacy={!ENABLE_HITL_IM}
iconClassName="i-ri-information-2-fill text-text-accent"
title={t(($) => $['humanInput.sorry'], { ns: 'share' })}
subtitle={t(($) => $['humanInput.expired'], { ns: 'share' })}
@@ -89,6 +91,7 @@ const FormContent = () => {
if (submitted) {
return (
<FormStatusCard
+ legacy={!ENABLE_HITL_IM}
iconClassName="i-ri-information-2-fill text-text-accent"
title={t(($) => $['humanInput.sorry'], { ns: 'share' })}
subtitle={t(($) => $['humanInput.completed'], { ns: 'share' })}
@@ -100,6 +103,7 @@ const FormContent = () => {
if (rateLimitExceeded) {
return (
<FormStatusCard
+ legacy={!ENABLE_HITL_IM}
iconClassName="i-ri-error-warning-fill text-text-destructive"
title={t(($) => $['humanInput.rateLimitExceeded'], { ns: 'share' })}
/>
@@ -109,6 +113,7 @@ const FormContent = () => {
if (!formData) {
return (
<FormStatusCard
+ legacy={!ENABLE_HITL_IM}
iconClassName="i-ri-error-warning-fill text-text-destructive"
title={t(($) => $['humanInput.formNotFound'], { ns: 'share' })}
/>
diff --git a/web/app/(humanInputLayout)/human-input/[formToken]/page.tsx b/web/app/(humanInputLayout)/human-input/[formToken]/page.tsx
index 5be24f2fb0d..13787575ce4 100644
--- a/web/app/(humanInputLayout)/human-input/[formToken]/page.tsx
+++ b/web/app/(humanInputLayout)/human-input/[formToken]/page.tsx
@@ -9,7 +9,7 @@ export default async function Page({ params }: { params: Promise<{ formToken: st
return (
<CommonLayoutHydrationBoundary>
- <main className="h-full min-w-75 bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
+ <main className="h-dvh min-w-75 bg-chatbot-bg pb-[env(safe-area-inset-bottom)]">
<ConsoleHumanInputForm key={formToken} formToken={formToken} />
</main>
</CommonLayoutHydrationBoundary>
diff --git a/web/app/__tests__/layout.spec.tsx b/web/app/__tests__/layout.spec.tsx
index c15db9a20b6..4e42b0f5782 100644
--- a/web/app/__tests__/layout.spec.tsx
+++ b/web/app/__tests__/layout.spec.tsx
@@ -3,6 +3,7 @@ import { renderToStaticMarkup } from 'react-dom/server'
const mocks = vi.hoisted(() => ({
dehydrateSystemFeatures: vi.fn(() => ({ mutations: [], queries: [] })),
getOptionalSystemFeatures: vi.fn(),
+ getDatasetMap: vi.fn<() => Record<string, string>>(() => ({})),
headers: vi.fn(async () => new Headers()),
}))
@@ -18,7 +19,7 @@ vi.mock('@/env', async (importOriginal) => {
return {
...actual,
- getDatasetMap: () => ({}),
+ getDatasetMap: mocks.getDatasetMap,
}
})
@@ -33,6 +34,7 @@ vi.mock('@/next/headers', () => ({
describe('Root layout System Features bootstrap', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.getDatasetMap.mockReturnValue({})
mocks.headers.mockResolvedValue(new Headers())
})
@@ -66,6 +68,22 @@ describe('Root layout System Features bootstrap', () => {
},
)
+ it('makes runtime configuration available on html before head scripts', async () => {
+ const dataset = {
+ 'data-api-prefix': 'https://runtime.example.com/console/api',
+ 'data-enable-hitl-im': 'true',
+ }
+ mocks.getDatasetMap.mockReturnValue(dataset)
+ mocks.headers.mockResolvedValue(new Headers({ 'x-dify-pathname': '/webapp-unavailable' }))
+ const { default: RootLayout } = await import('../layout')
+ const html = renderToStaticMarkup(await RootLayout({ children: <main>App unavailable</main> }))
+ const document = new DOMParser().parseFromString(html, 'text/html')
+ for (const [key, value] of Object.entries(dataset)) {
+ expect(document.documentElement).toHaveAttribute(key, value)
+ expect(document.body).not.toHaveAttribute(key)
+ }
+ })
+
it('uses optional System Features for branded metadata', async () => {
mocks.getOptionalSystemFeatures.mockResolvedValue({
branding: {
diff --git a/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx b/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx
index df080117adf..e9d6cdd29d3 100644
--- a/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/index.hitl-v2.spec.tsx
@@ -13,7 +13,6 @@ import GenerationItem from '../index'
const mocks = vi.hoisted(() => ({
submitShare: vi.fn(),
- submitWebApp: vi.fn(),
submitWorkflow: vi.fn(),
}))
@@ -32,9 +31,6 @@ vi.mock('@/service/workflow', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/workflow')>()),
submitHumanInputForm: mocks.submitWorkflow,
}))
-vi.mock('@/service/webapp-human-input', () => ({
- submitWebAppHumanInputForm: mocks.submitWebApp,
-}))
const renderItem = (ui: ReactElement) =>
render(<ChatContextProvider chatList={[]}>{ui}</ChatContextProvider>)
@@ -84,12 +80,10 @@ describe('GenerationItem HITL routing', () => {
await user.click(screen.getByRole('button', { name: 'Submit' }))
await user.click(screen.getByText('runLog.detail'))
- const expectedSubmit =
- appSourceType === AppSourceType.webApp ? mocks.submitWebApp : mocks.submitShare
- expect(expectedSubmit).toHaveBeenCalledWith(
+ expect(mocks.submitShare).toHaveBeenCalledWith(
'token-1',
{ action: 'submit', inputs: { name: 'Dify' } },
- ...(appSourceType === AppSourceType.webApp ? [formVersion] : []),
+ formVersion,
)
expect(mocks.submitWorkflow).not.toHaveBeenCalled()
expect(screen.getByText('JSON OUTPUT')).toBeInTheDocument()
@@ -126,18 +120,18 @@ describe('GenerationItem HITL routing', () => {
await user.type(screen.getByRole('textbox', { name: 'name' }), 'Dify')
await user.click(screen.getByRole('button', { name: 'Submit' }))
expect(prepareHumanInputSubmission).toHaveBeenCalledOnce()
- expect(mocks.submitWebApp).not.toHaveBeenCalled()
+ expect(mocks.submitShare).not.toHaveBeenCalled()
await act(async () => resolvePreparation?.(ready))
if (ready) {
- expect(mocks.submitWebApp).toHaveBeenCalledExactlyOnceWith(
+ expect(mocks.submitShare).toHaveBeenCalledExactlyOnceWith(
'token-1',
{ inputs: { name: 'Dify' }, action: 'submit' },
undefined,
)
} else {
- expect(mocks.submitWebApp).not.toHaveBeenCalled()
+ expect(mocks.submitShare).not.toHaveBeenCalled()
}
},
)
diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsx
index ff20e6d56fa..2985ffbb0e5 100644
--- a/web/app/components/app/text-generate/item/index.tsx
+++ b/web/app/components/app/text-generate/item/index.tsx
@@ -16,13 +16,13 @@ import { Markdown } from '@/app/components/base/markdown'
import { toast } from '@/app/notifications'
import { useParams } from '@/next/navigation'
import { fetchTextGenerationMessage } from '@/service/debug'
+import { prepareHumanInputFormSubmission } from '@/service/human-input-submission'
import {
AppSourceType,
fetchMoreLikeThis,
submitHumanInputForm,
updateFeedback,
} from '@/service/share'
-import { submitWebAppHumanInputForm } from '@/service/webapp-human-input'
import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import GenerationActionGroups from './action-groups'
import {
@@ -195,17 +195,16 @@ const GenerationItem: FC<IGenerationItemProps> = ({
}, [workflowProcessData])
const handleSubmitHumanInputForm = useCallback(
async (formToken: string, formData: HumanInputFormSubmitData) => {
- const form = workflowProcessData?.humanInputFormDataList?.find(
- (item) => item.form_token === formToken,
- )
+ const { form_version: formVersion, ...submission } = formData
if (appSourceType === AppSourceType.installedApp) {
- await submitHumanInputFormService(formToken, formData, form?.form_version)
- } else if (appSourceType === AppSourceType.webApp) {
- if (prepareHumanInputSubmission && !(await prepareHumanInputSubmission())) return
- await submitWebAppHumanInputForm(formToken, formData, form?.form_version)
- } else await submitHumanInputForm(formToken, formData)
+ await submitHumanInputFormService(formToken, submission, formVersion)
+ } else {
+ if (appSourceType === AppSourceType.webApp && prepareHumanInputSubmission)
+ await prepareHumanInputFormSubmission(prepareHumanInputSubmission)
+ await submitHumanInputForm(formToken, submission, formVersion)
+ }
},
- [appSourceType, prepareHumanInputSubmission, workflowProcessData?.humanInputFormDataList],
+ [appSourceType, prepareHumanInputSubmission],
)
return (
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.hitl-v2.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.hitl-v2.spec.tsx
index 29a3a326297..aa8b31fe387 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.hitl-v2.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.hitl-v2.spec.tsx
@@ -9,7 +9,7 @@ import { UserActionButtonType } from '@/app/components/workflow/nodes/human-inpu
import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
// oxlint-disable-next-line no-restricted-imports -- Exercise the existing chat SSE transport at its network boundary.
import { sseGet } from '@/service/base'
-import { submitWebAppHumanInputForm } from '@/service/webapp-human-input'
+import { submitHumanInputForm as submitWebAppHumanInputForm } from '@/service/share'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createChatConfigFixture } from '@/test/fixtures/chat'
import {
@@ -38,8 +38,9 @@ vi.mock('@/service/base', async (importOriginal) => ({
sseGet: vi.fn(),
ssePost: vi.fn(),
}))
-vi.mock('@/service/webapp-human-input', () => ({
- submitWebAppHumanInputForm: vi.fn().mockResolvedValue(undefined),
+vi.mock('@/service/share', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/share')>()),
+ submitHumanInputForm: vi.fn().mockResolvedValue(undefined),
}))
const createForm = (formVersion: HumanInputFormData['form_version']): HumanInputFormData =>
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx
index f133a247d8c..77ba38aba2a 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/chat-wrapper.spec.tsx
@@ -7,8 +7,12 @@ import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { registerWebAppEventTracker } from '@/app/components/base/amplitude/web-app-event'
import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
-import { fetchChatList, fetchSuggestedQuestions, stopChatMessageResponding } from '@/service/share'
-import { submitWebAppHumanInputForm as submitHumanInputForm } from '@/service/webapp-human-input'
+import {
+ fetchChatList,
+ fetchSuggestedQuestions,
+ stopChatMessageResponding,
+ submitHumanInputForm,
+} from '@/service/share'
import { submitHumanInputForm as submitInstalledForm } from '@/service/workflow'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createChatConfigFixture, createChatFileFixture } from '@/test/fixtures/chat'
@@ -746,5 +750,3 @@ it.each([
})
expect(screen.getByRole('img', { name: label })).toHaveTextContent(initial)
})
-
-vi.mock('@/service/webapp-human-input', () => ({ submitWebAppHumanInputForm: vi.fn() }))
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 35355457e27..b10147d155a 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
@@ -14,14 +14,15 @@ import InputsForm from '@/app/components/base/chat/chat-with-history/inputs-form
import SuggestedQuestions from '@/app/components/base/chat/chat/answer/suggested-questions'
import { Markdown } from '@/app/components/base/markdown'
import { InputVarType } from '@/app/components/workflow/types'
+import { prepareHumanInputFormSubmission } from '@/service/human-input-submission'
import {
AppSourceType,
fetchChatList,
fetchSuggestedQuestions,
getUrl,
stopChatMessageResponding,
+ submitHumanInputForm,
} from '@/service/share'
-import { submitWebAppHumanInputForm } from '@/service/webapp-human-input'
import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import { TransferMethod } from '@/types/app'
import { getAvatarInitial } from '@/utils/avatar'
@@ -289,15 +290,12 @@ const ChatWrapper = () => {
const handleSubmitHumanInputForm = useCallback(
async (formToken: string, formData: HumanInputFormSubmitData) => {
- if (!(await prepareHumanInputSubmission())) return
-
- const form = chatList
- .flatMap((item) => item.humanInputFormDataList ?? [])
- .find((item) => item.form_token === formToken)
- if (isInstalledApp) await submitHumanInputFormService(formToken, formData, form?.form_version)
- else await submitWebAppHumanInputForm(formToken, formData, form?.form_version)
+ const { form_version: formVersion, ...submission } = formData
+ await prepareHumanInputFormSubmission(prepareHumanInputSubmission)
+ if (isInstalledApp) await submitHumanInputFormService(formToken, submission, formVersion)
+ else await submitHumanInputForm(formToken, submission, formVersion)
},
- [chatList, isInstalledApp, prepareHumanInputSubmission],
+ [isInstalledApp, prepareHumanInputSubmission],
)
const [collapsed, setCollapsed] = useState(!!currentConversationId)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx
index e8161ebce09..95afb32f61e 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/content-item.spec.tsx
@@ -5,6 +5,11 @@ import { useState } from 'react'
import { InputVarType } from '@/app/components/workflow/types'
import ContentItem from '../content-item'
+// Load the real code-split renderer before assertions start their interaction deadlines.
+beforeAll(async () => {
+ await import('@/app/components/base/markdown/streamdown-wrapper')
+})
+
const fields: ComponentProps<typeof ContentItem>['formInputFields'] = [
{
type: InputVarType.paragraph,
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx
index 4f80e923a90..6d4e36e3665 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/human-input-form.spec.tsx
@@ -106,6 +106,7 @@ describe('HumanInputForm', () => {
expect(onSubmit).toHaveBeenCalledWith('token_123', {
action: 'action_1',
inputs: { field1: 'initial' },
+ form_version,
})
},
)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/unsubmitted.spec.tsx b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/unsubmitted.spec.tsx
index 397c9c1c51a..29564999960 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/__tests__/unsubmitted.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/__tests__/unsubmitted.spec.tsx
@@ -112,8 +112,8 @@ describe('UnsubmittedHumanInputContent Integration', () => {
{ error: new Error('Approval expired'), message: 'Approval expired' },
{ error: new Response(null, { status: 410 }), message: 'common.api.actionFailed' },
])(
- 'should show $message and allow retry after a rejected submission',
- async ({ error, message }) => {
+ 'keeps legacy transport errors out of the form and allows retry ($message)',
+ async ({ error }) => {
const user = userEvent.setup()
const handleSubmit = vi.fn().mockRejectedValueOnce(error).mockResolvedValueOnce(undefined)
@@ -127,7 +127,7 @@ describe('UnsubmittedHumanInputContent Integration', () => {
const submitButton = screen.getByRole('button', { name: 'Submit' })
await user.click(submitButton)
- expect(await screen.findByRole('alert')).toHaveTextContent(message)
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
await waitFor(() => expect(submitButton).toBeEnabled())
expect(input).toHaveValue('Preserved value')
await user.click(submitButton)
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx b/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx
index e199958b4da..b211630b5a4 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx
+++ b/web/app/components/base/chat/chat/answer/human-input-content/field-renderer.tsx
@@ -26,15 +26,16 @@ export type HumanInputFieldValue = string | FileEntity | FileEntity[] | null
type Props = Readonly<{
field: FormInputItem
+ label?: string
value?: HumanInputFieldValue
onChange: (value: HumanInputFieldValue) => void
}>
-const HumanInputFieldRenderer = ({ field, value, onChange }: Props) => {
+const HumanInputFieldRenderer = ({ field, label, value, onChange }: Props) => {
if (isParagraphFormInput(field)) {
return (
<Textarea
- aria-label={field.output_variable_name}
+ aria-label={label ?? field.output_variable_name}
className="h-26 sm:text-xs"
value={typeof value === 'string' ? value : ''}
onValueChange={(nextValue) => onChange(nextValue)}
@@ -57,7 +58,11 @@ const HumanInputFieldRenderer = ({ field, value, onChange }: Props) => {
onChange(nextValue)
}}
>
- <SelectTrigger size="large" className="w-full" aria-label={field.output_variable_name}>
+ <SelectTrigger
+ size="large"
+ className="w-full"
+ aria-label={label ?? field.output_variable_name}
+ >
<SelectValue />
</SelectTrigger>
<SelectPortal>
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
index 767bdec4c7c..ff4fb0f1a5c 100644
--- 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
@@ -7,6 +7,7 @@ import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ENABLE_HITL_IM } from '@/config'
+import { HumanInputSubmissionPreparationError } from '@/service/human-input-submission'
import ContentItem from './content-item'
import {
getButtonStyle,
@@ -45,13 +46,11 @@ const HumanInputFormContent = ({ formData, onSubmit }: HumanInputFormProps) => {
await onSubmit?.(formToken, {
inputs: getProcessedHumanInputFormInputs(renderedFormInputs, inputs) || {},
action: actionID,
+ form_version: formData.form_version,
})
} catch (error) {
- setSubmissionError(
- error instanceof Error && error.message
- ? error.message
- : t(($) => $['api.actionFailed'], { ns: 'common' }),
- )
+ if (error instanceof HumanInputSubmissionPreparationError)
+ setSubmissionError(t(($) => $['api.actionFailed'], { ns: 'common' }))
} finally {
setIsSubmitting(false)
}
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
index 7d01a281a85..3b690077628 100644
--- 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
@@ -27,6 +27,7 @@ export type HumanInputFormProps = {
export type HumanInputFormSubmitData = {
inputs: Record<string, unknown>
action: string
+ form_version?: HumanInputFormData['form_version']
}
export type ContentItemProps = {
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.hitl-v2.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.hitl-v2.spec.tsx
index 43463eb5687..5b2c4c86292 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.hitl-v2.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.hitl-v2.spec.tsx
@@ -9,7 +9,6 @@ import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/t
// oxlint-disable-next-line no-restricted-imports -- Exercise the existing chat SSE transport at its network boundary.
import { sseGet } from '@/service/base'
import { AppSourceType, submitHumanInputForm } from '@/service/share'
-import { submitWebAppHumanInputForm } from '@/service/webapp-human-input'
import { submitHumanInputForm as submitInstalledHumanInput } from '@/service/workflow'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createChatConfigFixture } from '@/test/fixtures/chat'
@@ -46,9 +45,6 @@ vi.mock('@/service/workflow', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/workflow')>()),
submitHumanInputForm: vi.fn().mockResolvedValue(undefined),
}))
-vi.mock('@/service/webapp-human-input', () => ({
- submitWebAppHumanInputForm: vi.fn().mockResolvedValue(undefined),
-}))
const createForm = (formVersion: HumanInputFormData['form_version']): HumanInputFormData =>
createHumanInputFormFixture({
@@ -151,7 +147,6 @@ describe('EmbeddedChatbot human-input submission', () => {
),
)
expect(submitHumanInputForm).not.toHaveBeenCalled()
- expect(submitWebAppHumanInputForm).not.toHaveBeenCalled()
},
)
@@ -171,7 +166,6 @@ describe('EmbeddedChatbot human-input submission', () => {
),
)
expect(submitInstalledHumanInput).not.toHaveBeenCalled()
- expect(submitWebAppHumanInputForm).not.toHaveBeenCalled()
},
)
@@ -181,17 +175,15 @@ describe('EmbeddedChatbot human-input submission', () => {
const user = renderSubject(formVersion, { appSourceType: AppSourceType.webApp })
await submitVisibleForm(user)
- expect(submitWebAppHumanInputForm).not.toHaveBeenCalled()
await confirmWorkflowReady()
await waitFor(() =>
- expect(submitWebAppHumanInputForm).toHaveBeenCalledExactlyOnceWith(
+ expect(submitHumanInputForm).toHaveBeenCalledExactlyOnceWith(
'form-token',
{ inputs: { review: 'Approved' }, action: 'approve' },
formVersion,
),
)
expect(submitInstalledHumanInput).not.toHaveBeenCalled()
- expect(submitHumanInputForm).not.toHaveBeenCalled()
},
)
})
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx
index fcaaae691f9..c55316005f4 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/chat-wrapper.spec.tsx
@@ -7,8 +7,12 @@ import { UserActionButtonType } from '@/app/components/workflow/nodes/human-inpu
import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
// oxlint-disable-next-line no-restricted-imports -- Exercise the existing chat SSE transport at its network boundary.
import { sseGet, ssePost } from '@/service/base'
-import { AppSourceType, fetchSuggestedQuestions, stopChatMessageResponding } from '@/service/share'
-import { submitWebAppHumanInputForm as submitHumanInputForm } from '@/service/webapp-human-input'
+import {
+ AppSourceType,
+ fetchSuggestedQuestions,
+ stopChatMessageResponding,
+ submitHumanInputForm,
+} from '@/service/share'
import { submitHumanInputForm as submitInstalledHumanInput } from '@/service/workflow'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createChatConfigFixture, createChatFileFixture } from '@/test/fixtures/chat'
@@ -418,5 +422,3 @@ describe('Embedded chatbot orchestration', () => {
expect(screen.getByText('Welcome to the app')).toBeVisible()
})
})
-
-vi.mock('@/service/webapp-human-input', () => ({ submitWebAppHumanInputForm: vi.fn() }))
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 2e51df3e95c..0cbdbb77085 100644
--- a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
@@ -14,6 +14,7 @@ import InputsForm from '@/app/components/base/chat/embedded-chatbot/inputs-form'
import LogoAvatar from '@/app/components/base/logo/logo-embedded-chat-avatar'
import { Markdown } from '@/app/components/base/markdown'
import { InputVarType } from '@/app/components/workflow/types'
+import { prepareHumanInputFormSubmission } from '@/service/human-input-submission'
import {
AppSourceType,
fetchSuggestedQuestions,
@@ -21,7 +22,6 @@ import {
stopChatMessageResponding,
submitHumanInputForm,
} from '@/service/share'
-import { submitWebAppHumanInputForm } from '@/service/webapp-human-input'
import { submitHumanInputForm as submitHumanInputFormService } from '@/service/workflow'
import { TransferMethod } from '@/types/app'
import { getAvatarInitial } from '@/utils/avatar'
@@ -368,17 +368,12 @@ const ChatWrapper = () => {
const handleSubmitHumanInputForm = useCallback(
async (formToken: string, formData: HumanInputFormSubmitData) => {
- if (!(await prepareHumanInputSubmission())) return
-
- const form = chatList
- .flatMap((item) => item.humanInputFormDataList ?? [])
- .find((item) => item.form_token === formToken)
- if (isInstalledApp) await submitHumanInputFormService(formToken, formData, form?.form_version)
- else if (appSourceType === AppSourceType.webApp)
- await submitWebAppHumanInputForm(formToken, formData, form?.form_version)
- else await submitHumanInputForm(formToken, formData, form?.form_version)
+ const { form_version: formVersion, ...submission } = formData
+ await prepareHumanInputFormSubmission(prepareHumanInputSubmission)
+ if (isInstalledApp) await submitHumanInputFormService(formToken, submission, formVersion)
+ else await submitHumanInputForm(formToken, submission, formVersion)
},
- [chatList, isInstalledApp, appSourceType, prepareHumanInputSubmission],
+ [isInstalledApp, prepareHumanInputSubmission],
)
const welcome = useMemo(() => {
diff --git a/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx b/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx
index a5d19d861c6..bd7a2fab352 100644
--- a/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx
+++ b/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx
@@ -13,14 +13,14 @@ describe('StreamdownWrapper Markdown form field names', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.resetModules()
- document.body.setAttribute(
+ document.documentElement.setAttribute(
'data-markdown-form-field-name-extra-chars',
'。.;;+=—()!*&()!*&-',
)
})
afterEach(() => {
- document.body.removeAttribute('data-markdown-form-field-name-extra-chars')
+ document.documentElement.removeAttribute('data-markdown-form-field-name-extra-chars')
})
it('should preserve and submit field names containing configured punctuation', async () => {
diff --git a/web/app/components/base/prompt-editor/index.tsx b/web/app/components/base/prompt-editor/index.tsx
index 728dcc124fb..7d3919e664d 100644
--- a/web/app/components/base/prompt-editor/index.tsx
+++ b/web/app/components/base/prompt-editor/index.tsx
@@ -91,7 +91,12 @@ const EditableSyncPlugin: FC<{ editable: boolean }> = ({ editable }) => {
type PromptEditorAriaProps = Pick<
React.AriaAttributes,
- 'aria-controls' | 'aria-haspopup' | 'aria-label' | 'aria-labelledby'
+ | 'aria-controls'
+ | 'aria-haspopup'
+ | 'aria-label'
+ | 'aria-labelledby'
+ | 'aria-describedby'
+ | 'aria-invalid'
>
type PromptEditorProps = PromptEditorAriaProps & {
@@ -136,6 +141,8 @@ const PromptEditor: FC<PromptEditorProps> = ({
'aria-haspopup': ariaHasPopup,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-invalid': ariaInvalid,
instanceId,
children,
compact,
@@ -241,6 +248,8 @@ const PromptEditor: FC<PromptEditorProps> = ({
aria-haspopup={ariaHasPopup}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy}
+ aria-describedby={ariaDescribedBy}
+ aria-invalid={ariaInvalid}
compact={compact}
className={className}
placeholder={placeholder}
diff --git a/web/app/components/base/prompt-editor/prompt-editor-content.tsx b/web/app/components/base/prompt-editor/prompt-editor-content.tsx
index 4b788dd0e74..55671824a1c 100644
--- a/web/app/components/base/prompt-editor/prompt-editor-content.tsx
+++ b/web/app/components/base/prompt-editor/prompt-editor-content.tsx
@@ -59,7 +59,12 @@ type ShortcutPopup = {
type PromptEditorContentAriaProps = Pick<
React.AriaAttributes,
- 'aria-controls' | 'aria-haspopup' | 'aria-label' | 'aria-labelledby'
+ | 'aria-controls'
+ | 'aria-haspopup'
+ | 'aria-label'
+ | 'aria-labelledby'
+ | 'aria-describedby'
+ | 'aria-invalid'
>
type PromptEditorContentProps = PromptEditorContentAriaProps & {
@@ -107,6 +112,8 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({
'aria-haspopup': ariaHasPopup,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-invalid': ariaInvalid,
compact,
className,
placeholder,
@@ -144,6 +151,8 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({
aria-haspopup={ariaHasPopup}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy}
+ aria-describedby={ariaDescribedBy}
+ aria-invalid={ariaInvalid}
className={cn(
'group/editable text-text-secondary outline-hidden group-[.clamp]:max-h-24 group-[.clamp]:overflow-y-auto',
compact ? 'text-[13px] leading-5' : 'text-sm/6',
diff --git a/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx b/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx
index d08948e2912..42ca00e53c8 100644
--- a/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx
+++ b/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx
@@ -279,6 +279,24 @@ describe('AccountSetting', () => {
})
describe('Rendering', () => {
+ it.each(['editor', 'normal', 'dataset_operator'])(
+ 'hides Channels and rejects its deep link for the %s role',
+ (role) => {
+ mockConsoleState.current = {
+ ...baseConsoleState,
+ currentWorkspace: { ...baseConsoleState.currentWorkspace, role },
+ isCurrentWorkspaceManager: false,
+ isCurrentWorkspaceOwner: false,
+ isCurrentWorkspaceDatasetOperator: role === 'dataset_operator',
+ }
+ renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.IM_PLATFORM })
+ expect(
+ screen.queryByRole('button', { name: 'contacts.imPlatform.title' }),
+ ).not.toBeInTheDocument()
+ expect(screen.queryByTestId('contacts-im-platform-page')).not.toBeInTheDocument()
+ },
+ )
+
it('hides workspace channels when centrally managed even in Community edition', () => {
renderAccountSetting({ deploymentEdition: 'COMMUNITY', imCentrallyManaged: true })
@@ -287,7 +305,7 @@ describe('AccountSetting', () => {
).not.toBeInTheDocument()
})
- it('allows workspace channels in Enterprise edition when not centrally managed', () => {
+ it('allows workspace channels in Enterprise edition when not centrally managed', async () => {
renderAccountSetting({
initialTab: ACCOUNT_SETTING_TAB.IM_PLATFORM,
deploymentEdition: 'ENTERPRISE',
@@ -295,7 +313,7 @@ describe('AccountSetting', () => {
})
expect(screen.getByRole('button', { name: 'contacts.imPlatform.title' })).toBeInTheDocument()
- expect(screen.getByTestId('contacts-im-platform-page')).toBeInTheDocument()
+ expect(await screen.findByTestId('contacts-im-platform-page')).toBeInTheDocument()
})
it('keeps workspace channels available for older successful features responses', () => {
@@ -318,7 +336,7 @@ describe('AccountSetting', () => {
it('closes workspace channels if the features request becomes unavailable', async () => {
const { queryClient } = renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.IM_PLATFORM })
- expect(screen.getByTestId('contacts-im-platform-page')).toBeInTheDocument()
+ expect(await screen.findByTestId('contacts-im-platform-page')).toBeInTheDocument()
await act(async () => {
mockConfig.getFeatures.mockRejectedValue(new Error('features unavailable'))
@@ -345,13 +363,13 @@ describe('AccountSetting', () => {
expect(screen.getAllByText('navigation.settings.members').length).toBeGreaterThan(0)
})
- it('keeps released IM channels available when unrelated feature previews are disabled', () => {
+ it('keeps released IM channels available when unrelated feature previews are disabled', async () => {
mockConfig.ENABLE_FEATURE_PREVIEW = false
renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.IM_PLATFORM })
expect(screen.getByRole('button', { name: 'contacts.imPlatform.title' })).toBeInTheDocument()
- expect(screen.getByTestId('contacts-im-platform-page')).toBeInTheDocument()
+ expect(await screen.findByTestId('contacts-im-platform-page')).toBeInTheDocument()
})
it('rejects centrally managed workspace channels deep links', () => {
@@ -367,12 +385,12 @@ describe('AccountSetting', () => {
})
describe('Tab Navigation', () => {
- it('should mount the Contacts-owned IM platform page from its entry', () => {
+ it('should mount the Contacts-owned IM platform page from its entry', async () => {
renderAccountSetting()
fireEvent.click(screen.getByRole('button', { name: 'contacts.imPlatform.title' }))
- expect(screen.getByTestId('contacts-im-platform-page')).toBeInTheDocument()
+ expect(await screen.findByTestId('contacts-im-platform-page')).toBeInTheDocument()
})
})
})
diff --git a/web/app/components/header/account-setting/index.tsx b/web/app/components/header/account-setting/index.tsx
index bcda1e0029b..152ce53f7c2 100644
--- a/web/app/components/header/account-setting/index.tsx
+++ b/web/app/components/header/account-setting/index.tsx
@@ -11,7 +11,7 @@ import {
} from '@langgenius/dify-ui/scroll-area'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { Suspense, useRef } from 'react'
+import { lazy, Suspense, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import BillingPage from '@/app/components/billing/billing-page'
@@ -28,7 +28,6 @@ import {
} from '@/context/workspace-state'
import { env } from '@/env'
import { selectIMCentrallyManaged } from '@/features/contacts/im-capability'
-import { ContactsImPlatformAccountSettingPage } from '@/features/contacts/im-platform/account-setting-page'
import { isContactsImPlatformEnabled } from '@/features/contacts/im-platform/feature-flag'
import { canReadNetworkAccessAtom } from '@/features/network-access/permissions'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
@@ -42,6 +41,12 @@ import PreferencePage from './preference-page'
import ResourceAccessTokenPage from './resource-access-token-page'
import WorkflowLogArchivesPage from './workflow-log-archives-page'
+const ContactsImPlatformAccountSettingPage = lazy(() =>
+ import('@/features/contacts/im-platform/account-setting-page').then((module) => ({
+ default: module.ContactsImPlatformAccountSettingPage,
+ })),
+)
+
const iconClassName = `
size-4 shrink-0 sm:me-2
`
@@ -57,6 +62,7 @@ type GroupItem = {
name: string
title?: string
description?: string
+ docLink?: { href: string; label: string }
icon: React.JSX.Element
activeIcon: React.JSX.Element
}
@@ -93,6 +99,7 @@ export default function AccountSetting({
const canViewWorkflowLogArchives =
systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceManager
const canViewContactsImPlatform =
+ isCurrentWorkspaceManager &&
featuresQuery.isSuccess &&
isContactsImPlatformEnabled(selectIMCentrallyManaged(featuresQuery.data))
const canViewIpPolicies = useAtomValue(canReadNetworkAccessAtom)
@@ -128,6 +135,10 @@ export default function AccountSetting({
key: ACCOUNT_SETTING_TAB.IM_PLATFORM,
name: t(($) => $['imPlatform.title'], { ns: 'contacts' }),
description: t(($) => $['imPlatform.description'], { ns: 'contacts' }),
+ docLink: {
+ href: docLink('/use-dify/nodes/human-input'),
+ label: t(($) => $['imPlatform.learnMore'], { ns: 'contacts' }),
+ },
icon: <span className={cn('i-ri-chat-ai-line', iconClassName)} />,
activeIcon: <span className={cn('i-ri-chat-ai-fill', iconClassName)} />,
},
@@ -186,7 +197,6 @@ export default function AccountSetting({
},
]
const activeItem = settingItems.find((item) => item.key === activeMenu)
- const isChannelsPage = activeMenu === ACCOUNT_SETTING_TAB.IM_PLATFORM
const visibleSettingItems: GroupItem[] = (() => {
const visibleTabs: AccountSettingTab[] = []
@@ -296,14 +306,14 @@ export default function AccountSetting({
{activeItem?.description && (
<p className="mt-1 system-sm-regular wrap-break-word whitespace-normal text-text-tertiary">
{activeItem.description}
- {isChannelsPage && (
+ {activeItem?.docLink && (
<a
- href={docLink('/use-dify/nodes/human-input')}
+ href={activeItem.docLink.href}
target="_blank"
rel="noopener noreferrer"
className="ms-0.5 inline-flex items-center text-text-accent focus-visible:rounded-sm focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
- {t(($) => $['imPlatform.learnMore'], { ns: 'contacts' })}
+ {activeItem.docLink.label}
<span aria-hidden className="i-ri-external-link-line size-3" />
</a>
)}
@@ -321,12 +331,7 @@ export default function AccountSetting({
style={{ minWidth: 0 }}
className="min-h-full w-full max-w-full pb-4"
>
- <div
- className={cn(
- 'max-w-full min-w-0 px-4 sm:px-8',
- isChannelsPage ? 'pt-4' : 'pt-6',
- )}
- >
+ <div className="max-w-full min-w-0 px-4 pt-6 sm:px-8">
{/* First-use translations and queries must not suspend the dialog shell. */}
<Suspense fallback={<LoadingPlaceholder className="py-10" />}>
{activeMenu === ACCOUNT_SETTING_TAB.MEMBERS && <MembersPage />}
diff --git a/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
index 38ee9ae6e22..759728ca0de 100644
--- a/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/__tests__/delete-member.browser.spec.tsx
@@ -2,12 +2,6 @@ import type { AccountWithRoleResponse } from '@dify/contracts/api/console/worksp
import type { consoleClient } from '@/service/console'
import { page, userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
-import { createContactsMockRepository } from '@/features/contacts/management/__tests__/fixtures/repository'
-import {
- ContactsMockScenario,
- createContactsMockScenario,
-} from '@/features/contacts/management/__tests__/fixtures/scenarios'
-import { ContactsManagementProvider } from '@/features/contacts/management/composition'
import { consoleQuery } from '@/service/console'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { QueryClientTestProvider } from '@/test/console/query-provider'
@@ -67,7 +61,7 @@ afterEach(() => {
vi.unstubAllGlobals()
})
-async function setup(ids: string[], contactRemoval = false) {
+async function setup(ids: string[]) {
let accounts = ids.map(member)
api.members.mockReset().mockImplementation(async () => ({ accounts }))
api.remove.mockReset().mockImplementation(async ({ params }) => {
@@ -79,31 +73,9 @@ async function setup(ids: string[], contactRemoval = false) {
workspacePermissionKeys: ['workspace.member.manage'],
})
api.features.mockResolvedValue(queryClient.getQueryData(consoleQuery.features.get.queryKey())!)
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const contactsRepository = createContactsMockRepository({ scenario })
- const removeContactMember = vi
- .spyOn(contactsRepository, 'removeMember')
- .mockImplementation(async ({ memberId }) => {
- accounts = accounts.filter((account) => account.id !== memberId)
- return { kind: 'removed', contactId: null, contactOutcome: 'not_found' }
- })
const screen = await render(
<QueryClientTestProvider queryClient={queryClient}>
- {contactRemoval ? (
- <ContactsManagementProvider
- repository={contactsRepository}
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: true,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }}
- >
- <MembersPage />
- </ContactsManagementProvider>
- ) : (
- <MembersPage />
- )}
+ <MembersPage />
</QueryClientTestProvider>,
)
const open = async (id: string) => {
@@ -114,27 +86,18 @@ async function setup(ids: string[], contactRemoval = false) {
await expect.element(screen.getByRole('alertdialog')).toBeVisible()
await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
}
- return { screen, open, removeContactMember }
+ return { screen, open }
}
-it('returns focus to the next member after contact-aware removal deletes the opening row', async () => {
+it('returns focus after deleting a member with Contacts enabled, using the supported member API', async () => {
api.contactsEnabled.mockReturnValue(true)
- const { screen, open, removeContactMember } = await setup(['Alpha', 'Beta'], true)
+ const { screen, open } = await setup(['Alpha', 'Beta'])
await open('Alpha')
- const retention = screen.getByRole('checkbox', { name: /memberRemoval\.keepPlatform/ })
- await expect.element(retention).toBeChecked()
- await retention.click()
+ await expect.element(screen.getByRole('checkbox')).not.toBeInTheDocument()
await screen.getByRole('button', { name: 'contacts.memberRemoval.remove', exact: true }).click()
await expect.element(screen.getByRole('alertdialog')).not.toBeInTheDocument()
- await expect
- .element(screen.getByRole('button', { name: 'Alpha', exact: true }))
- .not.toBeInTheDocument()
await expect.element(screen.getByRole('button', { name: 'Beta', exact: true })).toHaveFocus()
- expect(removeContactMember).toHaveBeenCalledExactlyOnceWith({
- memberId: 'Alpha',
- keepAsPlatformContact: false,
- })
- expect(api.remove).not.toHaveBeenCalled()
+ expect(api.remove).toHaveBeenCalledExactlyOnceWith({ params: { member_id: 'Alpha' } })
})
it('removes the member before a slow list refresh completes', async () => {
diff --git a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx
index d18f6a00700..42dbe2a16ff 100644
--- a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx
@@ -1,25 +1,11 @@
import type { AccountWithRoleResponse } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ContactsManagementRepository } from '@/features/contacts/management/repository'
-import type {
- ContactsFeatureContextValue,
- RemoveMemberResult,
-} from '@/features/contacts/management/types'
import type { Role } from '@/models/access-control'
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
-import { QueryObserver } from '@tanstack/react-query'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
-import { onTestFinished } from 'vite-plus/test'
-import { createContactsMockRepository } from '@/features/contacts/management/__tests__/fixtures/repository'
-import {
- ContactsMockScenario,
- createContactsMockScenario,
-} from '@/features/contacts/management/__tests__/fixtures/scenarios'
-import { ContactsManagementProvider } from '@/features/contacts/management/composition'
import { consoleQuery } from '@/service/console'
import { renderWithConsoleQuery } from '@/test/console/query-data'
-import { createDeferred } from '@/test/deferred'
import MembersPage from '../index'
const {
@@ -113,26 +99,20 @@ const choices = [
createRole({ id: 'role-next', name: 'Next role' }),
createRole({ id: 'role-extra', name: 'Extra role' }),
]
-async function renderMembersPage(
- options: ConsoleQueryTestOptions = {},
- contacts?: { context: ContactsFeatureContextValue; repository: ContactsManagementRepository },
-) {
+async function renderMembersPage(options: ConsoleQueryTestOptions = {}) {
const page = (
<NuqsTestingAdapter>
<MembersPage />
</NuqsTestingAdapter>
)
- const view = renderWithConsoleQuery(
- contacts ? <ContactsManagementProvider {...contacts}>{page}</ContactsManagementProvider> : page,
- {
- accountProfile: { id: '1', email: '[email protected]' },
- currentWorkspace: { name: 'Test Workspace', role: 'owner' },
- workspacePermissionKeys: ['workspace.member.manage'],
- features: { is_allow_transfer_workspace: true },
- systemFeatures: { is_email_setup: true },
- ...options,
- },
- )
+ const view = renderWithConsoleQuery(page, {
+ accountProfile: { id: '1', email: '[email protected]' },
+ currentWorkspace: { name: 'Test Workspace', role: 'owner' },
+ workspacePermissionKeys: ['workspace.member.manage'],
+ features: { is_allow_transfer_workspace: true },
+ systemFeatures: { is_email_setup: true },
+ ...options,
+ })
await screen.findByRole('button', { name: 'Admin User' })
return view
}
@@ -184,22 +164,6 @@ beforeEach(() => {
})
})
-function contactRemoval() {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const context: ContactsFeatureContextValue = {
- deployment: scenario.deployment,
- imCentrallyManaged: true,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }
- const repository = createContactsMockRepository({ scenario })
- const remove = vi.spyOn(repository, 'removeMember').mockImplementation(async ({ memberId }) => {
- accounts = accounts.filter((account) => account.id !== memberId)
- return { kind: 'removed', contactId: null, contactOutcome: 'not_found' }
- })
- return { context, repository, remove }
-}
-
async function openAdminRemoval(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole('button', { name: /members\.memberActions: Admin User/ }))
await user.click(screen.getByRole('menuitem', { name: /members\.removeFromTeam$/ }))
@@ -210,113 +174,18 @@ const contactOptionsKey = consoleQuery.workspaces.current.humanInput.v2.contactO
type: 'query',
})
-describe('MembersPage contact removal', () => {
- it('submits the contact retention choice and removes the member from the list', async () => {
- contactsEnabled.mockReturnValue(true)
- const contacts = contactRemoval()
- const user = userEvent.setup()
- const { queryClient } = await renderMembersPage({}, contacts)
- queryClient.setQueryData(contactOptionsKey, { cached: true })
- const refresh = createDeferred<{ cached: boolean }>()
- const contactOptions = new QueryObserver(queryClient, {
- queryKey: contactOptionsKey,
- queryFn: () => refresh.promise,
- staleTime: Infinity,
- })
- const unsubscribe = contactOptions.subscribe(() => {})
- onTestFinished(() => {
- refresh.resolve({ cached: false })
- unsubscribe()
- })
- const dialog = await openAdminRemoval(user)
- const retention = within(dialog).getByRole('checkbox', { name: /memberRemoval\.keepPlatform/ })
- expect(retention).toBeChecked()
- await user.click(retention)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.memberRemoval.remove' }))
-
- await waitFor(() =>
- expect(contacts.remove).toHaveBeenCalledExactlyOnceWith({
- memberId: '2',
- keepAsPlatformContact: false,
- }),
- )
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(screen.queryByRole('row', { name: /[email protected]/ })).not.toBeInTheDocument()
- expect(removeMember).not.toHaveBeenCalled()
- expect(queryClient.getQueryState(contactOptionsKey)?.isInvalidated).toBe(true)
- })
-
- it('blocks dismissal during contact removal and starts a fresh choice after closing a failure', async () => {
- contactsEnabled.mockReturnValue(true)
- const contacts = contactRemoval()
- const request = createDeferred<RemoveMemberResult>()
- contacts.remove.mockReturnValueOnce(request.promise)
- const user = userEvent.setup()
- await renderMembersPage({}, contacts)
- const dialog = await openAdminRemoval(user)
- const retention = within(dialog).getByRole('checkbox', { name: /memberRemoval\.keepPlatform/ })
- await user.click(retention)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.memberRemoval.remove' }))
- await user.keyboard('{Escape}')
- expect(dialog).toBeInTheDocument()
- expect(within(dialog).getByRole('button', { name: 'contacts.action.cancel' })).toBeDisabled()
- expect(contacts.remove).toHaveBeenCalledOnce()
- await act(async () => request.resolve({ kind: 'failed' }))
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.memberRemoval.failed',
- )
- expect(retention).not.toBeChecked()
- await user.click(within(dialog).getByRole('button', { name: 'contacts.action.cancel' }))
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
-
- const reopened = await openAdminRemoval(user)
- expect(
- within(reopened).getByRole('checkbox', { name: /memberRemoval\.keepPlatform/ }),
- ).toBeChecked()
- expect(within(reopened).queryByRole('alert')).not.toBeInTheDocument()
- await user.click(
- within(reopened).getByRole('button', { name: 'contacts.memberRemoval.remove' }),
- )
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(contacts.remove).toHaveBeenLastCalledWith({ memberId: '2', keepAsPlatformContact: true })
- })
-
- it('retains the contact choice after failure and submits it on a successful retry', async () => {
- contactsEnabled.mockReturnValue(true)
- const contacts = contactRemoval()
- contacts.remove.mockResolvedValueOnce({ kind: 'failed' })
- const user = userEvent.setup()
- await renderMembersPage({}, contacts)
- const dialog = await openAdminRemoval(user)
- const retention = within(dialog).getByRole('checkbox', { name: /memberRemoval\.keepPlatform/ })
- await user.click(retention)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.memberRemoval.remove' }))
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.memberRemoval.failed',
- )
- expect(retention).not.toBeChecked()
- await user.click(within(dialog).getByRole('button', { name: 'contacts.memberRemoval.remove' }))
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(contacts.remove).toHaveBeenCalledTimes(2)
- expect(contacts.remove).toHaveBeenLastCalledWith({
- memberId: '2',
- keepAsPlatformContact: false,
- })
- })
-
+describe('MembersPage removal', () => {
it.each([
- { status: 'active', supportsMemberManagement: false, enabled: true, contactCopy: true },
- { status: 'pending', supportsMemberManagement: true, enabled: true, contactCopy: false },
- { status: 'active', supportsMemberManagement: true, enabled: false, contactCopy: false },
+ { status: 'active', enabled: true, contactCopy: true },
+ { status: 'pending', enabled: true, contactCopy: false },
+ { status: 'active', enabled: false, contactCopy: false },
])(
- 'uses standard removal for status=$status with contact support=$supportsMemberManagement',
- async ({ status, supportsMemberManagement, enabled, contactCopy }) => {
+ 'uses the supported member endpoint for status=$status and gate=$enabled',
+ async ({ status, enabled, contactCopy }) => {
contactsEnabled.mockReturnValue(enabled)
accounts[1] = { ...accounts[1]!, status }
- const contacts = contactRemoval()
- contacts.repository.supportsMemberManagement = supportsMemberManagement
const user = userEvent.setup()
- const { queryClient } = await renderMembersPage({}, contacts)
+ const { queryClient } = await renderMembersPage()
queryClient.setQueryData(contactOptionsKey, { cached: true })
const dialog = await openAdminRemoval(user)
expect(within(dialog).queryByRole('checkbox')).not.toBeInTheDocument()
@@ -329,7 +198,6 @@ describe('MembersPage contact removal', () => {
await waitFor(() =>
expect(removeMember).toHaveBeenCalledExactlyOnceWith({ params: { member_id: '2' } }),
)
- expect(contacts.remove).not.toHaveBeenCalled()
expect(queryClient.getQueryState(contactOptionsKey)?.isInvalidated).toBe(true)
},
)
diff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsx
index 14512c2d8dd..d36840d0256 100644
--- a/web/app/components/header/account-setting/members-page/index.tsx
+++ b/web/app/components/header/account-setting/members-page/index.tsx
@@ -1,12 +1,12 @@
'use client'
import type {
- AccountWithRoleListResponse,
AccountWithRoleResponse,
MemberInviteResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type { Role } from '@/models/access-control'
import {
AlertDialog,
+ AlertDialogBody,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
@@ -25,7 +25,7 @@ import {
} from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -35,11 +35,7 @@ import UpgradeBtn from '@/app/components/billing/upgrade-btn'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { currentWorkspaceAtom, isCurrentWorkspaceOwnerAtom } from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
-import { ContactsManagementRuntimeProvider } from '@/features/contacts/management/composition'
-import { useOptionalContactsManagement } from '@/features/contacts/management/composition-context'
import { isContactsManagementEnabled } from '@/features/contacts/management/feature-flag'
-import { useRemoveContactMember } from '@/features/contacts/management/hooks'
-import { MemberRemovalContactImpactContent } from '@/features/contacts/management/member-removal-content'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { getAccessControlTemplateLanguage, LanguagesSupported } from '@/i18n/language'
import { consoleQuery } from '@/service/console'
@@ -61,9 +57,6 @@ const MembersPageContent = () => {
'navigation',
'contacts',
])
- const queryClient = useQueryClient()
- const contactsManagement = useOptionalContactsManagement()
- const contactRemoval = useRemoveContactMember()
const locale = useLocale()
const language = getAccessControlTemplateLanguage(locale)
@@ -292,17 +285,12 @@ const MembersPageContent = () => {
<AlertDialog
handle={removeDialog}
onOpenChange={(open, details) => {
- if (
- !open &&
- (removal.isPending || contactRemoval.isPending) &&
- details.reason !== 'imperative-action'
- )
+ if (!open && removal.isPending && details.reason !== 'imperative-action')
details.cancel()
}}
onOpenChangeComplete={(open) => {
if (!open) {
removal.reset()
- contactRemoval.reset()
}
}}
>
@@ -310,12 +298,6 @@ const MembersPageContent = () => {
const showContactsRemovalDesign = Boolean(
payload && isContactsManagementEnabled() && payload.member.status !== 'pending',
)
- const useContactsAwareRemoval = Boolean(
- showContactsRemovalDesign &&
- contactsManagement.context &&
- contactsManagement.repository &&
- contactsManagement.repository.supportsMemberManagement !== false,
- )
const memberName = payload?.member.name || payload?.member.email || ''
return (
<AlertDialogContent
@@ -331,124 +313,108 @@ const MembersPageContent = () => {
return false
}}
>
- {useContactsAwareRemoval && payload ? (
- <MemberRemovalContactImpactContent
- key={payload.member.id}
- member={payload.member}
- removal={contactRemoval}
- onRemoved={() => {
- queryClient.setQueriesData<AccountWithRoleListResponse>(
- { queryKey: consoleQuery.workspaces.current.members.get.key() },
- (cached) =>
- cached && {
- ...cached,
- accounts: cached.accounts.filter(
- (account) => account.id !== payload.member.id,
- ),
- },
- )
- payload.fallbackFocus.current = listRef.current
- removeDialog.close()
- }}
- />
- ) : (
- <>
- <AlertDialogHeader>
- {showContactsRemovalDesign && payload ? (
- <>
- <AlertDialogTitle>
- {t(
- ($) =>
- $[
- currentWorkspace.name
- ? 'memberRemoval.workspaceTitle'
- : 'memberRemoval.title'
- ],
- {
- ns: 'contacts',
- memberName,
- workspaceName: currentWorkspace.name,
- },
- )}
- </AlertDialogTitle>
- <div className="flex items-center gap-2.5 rounded-xl bg-background-section-burn py-2 ps-3 pe-2">
- <Avatar size="md">
- <AvatarImage
- src={payload.member.avatar_url || undefined}
- alt={memberName}
- />
- <AvatarFallback>
- {memberName[0]?.toLocaleUpperCase()}
- </AvatarFallback>
- </Avatar>
- <div className="min-w-0 py-0.5">
- <div className="system-md-medium wrap-break-word text-text-secondary">
- {memberName}
- </div>
- <div className="system-xs-regular wrap-anywhere text-text-tertiary">
- {payload.member.email}
- </div>
+ <>
+ {showContactsRemovalDesign && payload ? (
+ <>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(
+ ($) =>
+ $[
+ currentWorkspace.name
+ ? 'memberRemoval.workspaceTitle'
+ : 'memberRemoval.title'
+ ],
+ {
+ ns: 'contacts',
+ memberName,
+ workspaceName: currentWorkspace.name,
+ },
+ )}
+ </AlertDialogTitle>
+ </AlertDialogHeader>
+ <AlertDialogBody className="flex flex-col gap-2">
+ <div className="flex items-center gap-2.5 rounded-xl bg-background-section-burn py-2 ps-3 pe-2">
+ <Avatar size="md">
+ <AvatarImage src={payload.member.avatar_url || undefined} alt="" />
+ <AvatarFallback aria-hidden>
+ {memberName[0]?.toLocaleUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ <div className="min-w-0 py-0.5">
+ <div className="system-md-medium wrap-break-word text-text-secondary">
+ {memberName}
+ </div>
+ <div className="system-xs-regular wrap-anywhere text-text-tertiary">
+ {payload.member.email}
</div>
</div>
- <AlertDialogDescription render={<div />}>
- <p>
- {t(($) => $['memberRemoval.accessImpact'], {
- ns: 'contacts',
- memberName,
- })}
- </p>
- <p>
- {t(($) => $['memberRemoval.contentImpact'], { ns: 'contacts' })}
- </p>
- </AlertDialogDescription>
- </>
- ) : (
- <>
- <AlertDialogTitle>
- {t(($) => $['members.removeFromTeamConfirmTitle'], {
- ns: 'workspaceMembers',
- memberName: payload?.member.name || payload?.member.email || '',
- })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $['members.removeFromTeamConfirmDescription'], {
- ns: 'workspaceMembers',
+ </div>
+ <AlertDialogDescription render={<div />}>
+ <p>
+ {t(($) => $['memberRemoval.accessImpact'], {
+ ns: 'contacts',
+ memberName,
})}
- </AlertDialogDescription>
- </>
- )}
+ </p>
+ <p>{t(($) => $['memberRemoval.contentImpact'], { ns: 'contacts' })}</p>
+ </AlertDialogDescription>
+ {removal.isError && (
+ <p role="alert" className="text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ )}
+ </AlertDialogBody>
+ </>
+ ) : (
+ <>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $['members.removeFromTeamConfirmTitle'], {
+ ns: 'workspaceMembers',
+ memberName: payload?.member.name || payload?.member.email || '',
+ })}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $['members.removeFromTeamConfirmDescription'], {
+ ns: 'workspaceMembers',
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
{removal.isError && (
- <p role="alert" className="text-text-destructive">
- {t(($) => $['api.actionFailed'], { ns: 'common' })}
- </p>
+ <AlertDialogBody>
+ <p role="alert" className="text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ </AlertDialogBody>
)}
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton disabled={removal.isPending}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- loading={removal.isPending}
- onClick={() => {
- if (!payload || removal.isPending) return
- removal.mutate(
- { params: { member_id: payload.member.id } },
- {
- onSuccess: () => {
- payload.fallbackFocus.current = listRef.current
- removeDialog.close()
- },
+ </>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={removal.isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ loading={removal.isPending}
+ onClick={() => {
+ if (!payload || removal.isPending) return
+ removal.mutate(
+ { params: { member_id: payload.member.id } },
+ {
+ onSuccess: () => {
+ payload.fallbackFocus.current = listRef.current
+ removeDialog.close()
},
- )
- }}
- >
- {showContactsRemovalDesign
- ? t(($) => $['memberRemoval.remove'], { ns: 'contacts' })
- : t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </>
- )}
+ },
+ )
+ }}
+ >
+ {showContactsRemovalDesign
+ ? t(($) => $['memberRemoval.remove'], { ns: 'contacts' })
+ : t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </>
</AlertDialogContent>
)
}}
@@ -481,11 +447,5 @@ const MembersPageContent = () => {
}
export default function MembersPage() {
- const { context, repository } = useOptionalContactsManagement()
- if (!isContactsManagementEnabled() || (context && repository)) return <MembersPageContent />
- return (
- <ContactsManagementRuntimeProvider>
- <MembersPageContent />
- </ContactsManagementRuntimeProvider>
- )
+ return <MembersPageContent />
}
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.hitl-v2.spec.tsx b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.hitl-v2.spec.tsx
index 49edf6db20e..517c5c75976 100644
--- a/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.hitl-v2.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/invite-modal/__tests__/index.hitl-v2.spec.tsx
@@ -1,17 +1,14 @@
import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen'
import type { MemberInviteResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import { QueryClient } from '@tanstack/react-query'
-import { render, screen, waitFor, within } from '@testing-library/react'
+import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { vi } from 'vite-plus/test'
-import { ContactsManagementMockProvider } from '@/features/contacts/management/__tests__/fixtures/composition'
-import {
- ContactsMockScenario,
- createContactsMockScenario,
-} from '@/features/contacts/management/__tests__/fixtures/scenarios'
+import { consoleQuery } from '@/service/console'
import { seedCurrentWorkspaceQuery } from '@/test/console/current-workspace'
import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'
import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
import { InviteModal } from '../index'
vi.mock('@/config', async (importOriginal) => ({
@@ -85,13 +82,11 @@ describe('InviteModal', () => {
open = true,
isEmailSetup = true,
queryClient = createQueryClient(),
- contactsScenario,
workspaceMembers = { enabled: true, size: 5, limit: 10 },
}: {
open?: boolean
isEmailSetup?: boolean
queryClient?: QueryClient
- contactsScenario?: ContactsMockScenario
workspaceMembers?: GetFeaturesResponse['workspace_members']
} = {}) => {
seedCurrentWorkspaceQuery(queryClient)
@@ -101,13 +96,7 @@ describe('InviteModal', () => {
const result = render(
<QueryClientTestProvider queryClient={queryClient}>
- {contactsScenario ? (
- <ContactsManagementMockProvider scenario={createContactsMockScenario(contactsScenario)}>
- <InviteModal isEmailSetup={isEmailSetup} onSend={onSend} />
- </ContactsManagementMockProvider>
- ) : (
- <InviteModal isEmailSetup={isEmailSetup} onSend={onSend} />
- )}
+ <InviteModal isEmailSetup={isEmailSetup} onSend={onSend} />
</QueryClientTestProvider>,
)
if (open) {
@@ -128,90 +117,44 @@ describe('InviteModal', () => {
await user.paste(value)
}
- it('asks for confirmation before inviting an email used by an External Contact', async () => {
+ it('uses the supported invitation endpoint directly when HITL is enabled', async () => {
const user = userEvent.setup()
inviteMember.mockResolvedValue({
result: 'success',
invitation_results: [],
tenant_id: 'tenant-id',
} satisfies MemberInviteResponse)
- await renderModal({ contactsScenario: ContactsMockScenario.EeMixed })
+ await renderModal()
- await addRecipients(user, '[email protected]')
+ await addRecipients(user, '[email protected]')
await selectAdminRole(user)
await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))
- const confirmation = await screen.findByRole('alertdialog', {
- name: /contacts\.memberInviteUpgrade\.title/i,
- })
- expect(inviteMember).not.toHaveBeenCalled()
-
- await user.click(
- within(confirmation).getByRole('button', { name: /contacts\.action\.cancel/i }),
- )
-
- await waitFor(() => {
- expect(
- screen.queryByRole('alertdialog', {
- name: /contacts\.memberInviteUpgrade\.title/i,
- }),
- ).not.toBeInTheDocument()
- })
- expect(screen.getByText('[email protected]')).toBeInTheDocument()
- expect(screen.getByRole('combobox', { name: /members\.role/i })).toHaveTextContent('Admin')
- expect(inviteMember).not.toHaveBeenCalled()
+ await waitFor(() => expect(inviteMember).toHaveBeenCalledOnce())
+ expect(
+ screen.queryByRole('alertdialog', { name: /contacts\.memberInviteUpgrade\.title/i }),
+ ).not.toBeInTheDocument()
})
- it('submits the pending invitation only after Add and upgrade is confirmed', async () => {
+ it('keeps cache invalidation when the invitation owner unmounts before success', async () => {
const user = userEvent.setup()
- inviteMember.mockResolvedValue({
- result: 'success',
- invitation_results: [],
- tenant_id: 'tenant-id',
- } satisfies MemberInviteResponse)
- await renderModal({ contactsScenario: ContactsMockScenario.EeMixed })
-
- await addRecipients(user, '[email protected]')
+ const request = createDeferred<MemberInviteResponse>()
+ inviteMember.mockReturnValueOnce(request.promise)
+ const queryClient = createQueryClient()
+ const membersKey = consoleQuery.workspaces.current.members.get.queryKey()
+ queryClient.setQueryData(membersKey, { accounts: [] })
+ const view = await renderModal({ queryClient })
+ await addRecipients(user, '[email protected]')
await selectAdminRole(user)
await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))
-
- const confirmation = await screen.findByRole('alertdialog', {
- name: /contacts\.memberInviteUpgrade\.title/i,
- })
- await user.click(
- within(confirmation).getByRole('button', {
- name: /contacts\.memberInviteUpgrade\.confirm/i,
- }),
- )
-
+ expect(inviteMember).toHaveBeenCalledOnce()
+ view.unmount()
+ request.resolve({ result: 'success', invitation_results: [], tenant_id: 'tenant-id' })
await waitFor(() => {
- expect(inviteMember).toHaveBeenCalledOnce()
- expect(inviteMember.mock.calls[0]?.[0]).toEqual({
- body: {
- emails: ['[email protected]'],
- role: 'admin',
- language: 'en-US',
- },
- })
+ expect(queryClient.getQueryState(membersKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(consoleQuery.features.get.queryKey())?.isInvalidated).toBe(
+ true,
+ )
})
})
-
- it('submits directly when no invited email belongs to an External Contact', async () => {
- const user = userEvent.setup()
- inviteMember.mockResolvedValue({
- result: 'success',
- invitation_results: [],
- tenant_id: 'tenant-id',
- } satisfies MemberInviteResponse)
- await renderModal({ contactsScenario: ContactsMockScenario.EeMixed })
-
- await addRecipients(user, '[email protected]')
- await selectAdminRole(user)
- await user.click(screen.getByRole('button', { name: /members\.sendInvite/i }))
-
- await waitFor(() => expect(inviteMember).toHaveBeenCalledOnce())
- expect(
- screen.queryByRole('alertdialog', { name: /contacts\.memberInviteUpgrade\.title/i }),
- ).not.toBeInTheDocument()
- })
})
diff --git a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx
index 18704b5dde6..fcd7eb92d4e 100644
--- a/web/app/components/header/account-setting/members-page/invite-modal/index.tsx
+++ b/web/app/components/header/account-setting/members-page/invite-modal/index.tsx
@@ -23,9 +23,6 @@ import { useAtomValue } from 'jotai'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
-import { isContactsManagementEnabled } from '@/features/contacts/management/feature-flag'
-import { useOptionalMemberInviteContactUpgrade } from '@/features/contacts/management/hooks'
-import { MemberInviteContactUpgradeDialog } from '@/features/contacts/management/member-invite-contact-upgrade-dialog'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
import { InviteButton } from '../invite-button'
@@ -38,9 +35,6 @@ type InviteModalProps = {
onSend: (invitationResults: MemberInviteResponse['invitation_results']) => void
}
-type InviteSubmission = { emails: string[]; role: string }
-type PendingUpgradeConfirmation = { contactIds: string[]; submission: InviteSubmission }
-
type InviteFieldName = 'emails' | 'role'
type InviteFormValues = {
emails: string
@@ -182,56 +176,25 @@ export function InviteModal({ isEmailSetup, onSend }: InviteModalProps) {
const queryClient = useQueryClient()
const actionsRef = useRef<DialogActions>(null)
const formRef = useRef<HTMLFormElement>(null)
- const contactUpgrade = useOptionalMemberInviteContactUpgrade()
- const [pendingUpgradeConfirmation, setPendingUpgradeConfirmation] =
- useState<PendingUpgradeConfirmation | null>(null)
- const [preparationFailed, setPreparationFailed] = useState(false)
const { mutate, reset, isPending, error } = useMutation(
consoleQuery.workspaces.current.members.inviteEmail.post.mutationOptions({
context: { silent: true },
+ onSuccess: (response) => {
+ void queryClient.invalidateQueries({ queryKey: consoleQuery.features.get.queryKey() })
+ void queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.members.get.key(),
+ })
+ onSend(response.invitation_results)
+ actionsRef.current?.close()
+ },
}),
)
- const isBusy = isPending || contactUpgrade.isChecking || contactUpgrade.isUpgrading
- const submitInvitation = (submission: InviteSubmission, contactIds: string[] = []) => {
- mutate(
- { body: { ...submission, language: locale } },
- {
- onSuccess: async (response) => {
- void queryClient.invalidateQueries({ queryKey: consoleQuery.features.get.queryKey() })
- if (contactIds.length > 0) await contactUpgrade.upgradeContacts({ contactIds })
- setPendingUpgradeConfirmation(null)
- void queryClient.invalidateQueries({
- queryKey: consoleQuery.workspaces.current.members.get.key(),
- })
- onSend(response.invitation_results)
- actionsRef.current?.close()
- },
- onError: () => setPendingUpgradeConfirmation(null),
- },
- )
- }
- const handleSubmit = async (emails: string[], role: string) => {
- if (isBusy) return
+ const isBusy = isPending
+ const handleSubmit = (emails: string[], role: string) => {
+ if (isPending) return
reset()
- setPreparationFailed(false)
- const submission = { emails, role }
- if (isContactsManagementEnabled() && contactUpgrade.available) {
- try {
- const conflicts = await contactUpgrade.findConflicts({ emails })
- if (conflicts.length > 0) {
- setPendingUpgradeConfirmation({
- contactIds: conflicts.map((contact) => contact.id),
- submission,
- })
- return
- }
- } catch {
- setPreparationFailed(true)
- return
- }
- }
- submitInvitation(submission)
+ mutate({ body: { emails, role, language: locale } })
}
return (
@@ -245,8 +208,6 @@ export function InviteModal({ isEmailSetup, onSend }: InviteModalProps) {
// A failure stays visible through the exit transition and ends with the session.
if (!open) {
reset()
- setPreparationFailed(false)
- setPendingUpgradeConfirmation(null)
}
}}
>
@@ -276,32 +237,16 @@ export function InviteModal({ isEmailSetup, onSend }: InviteModalProps) {
isPending={isBusy}
// The link marks a documented code as defined, so `error.code` narrows to the invite contract.
errorCode={isDefinedError(error) ? error.code : null}
- hasError={!!error || preparationFailed}
+ hasError={!!error}
onSubmit={(emails, role) => {
void handleSubmit(emails, role)
}}
onDismissError={() => {
reset()
- setPreparationFailed(false)
}}
/>
</DialogContent>
</Dialog>
- <MemberInviteContactUpgradeDialog
- conflictCount={pendingUpgradeConfirmation?.contactIds.length ?? 0}
- open={Boolean(pendingUpgradeConfirmation)}
- pending={isPending || contactUpgrade.isUpgrading}
- onOpenChange={(open) => {
- if (!open && !isBusy) setPendingUpgradeConfirmation(null)
- }}
- onConfirm={() => {
- if (pendingUpgradeConfirmation && !isBusy)
- submitInvitation(
- pendingUpgradeConfirmation.submission,
- pendingUpgradeConfirmation.contactIds,
- )
- }}
- />
</>
)
}
diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsx
index 8adf8f676e3..f41d01385d7 100644
--- a/web/app/components/main-nav/index.tsx
+++ b/web/app/components/main-nav/index.tsx
@@ -33,8 +33,7 @@ import { isMainNavRouteVisible, MAIN_NAV_ROUTES } from './routes'
const WebAppsSection = lazy(() => import('./components/web-apps-section'))
export function MainNav({ className, initialPlatform }: MainNavProps) {
- const { t } = useTranslation(['common', 'navigation'])
- const { t: tContacts } = useTranslation(['contacts'])
+ const { t } = useTranslation(['common', 'navigation', 'contacts'])
const pathname = usePathname()
const isCurrentWorkspaceDatasetOperator = useAtomValue(isCurrentWorkspaceDatasetOperatorAtom)
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
@@ -71,8 +70,8 @@ export function MainNav({ className, initialPlatform }: MainNavProps) {
const label =
'label' in route
? route.label
- : route.key === 'contacts'
- ? tContacts(($) => $['directory.title'])
+ : 'ns' in route
+ ? t(($) => $[route.labelKey], { ns: route.ns })
: t(($) => $[route.labelKey], { ns: 'navigation' })
return {
@@ -92,7 +91,6 @@ export function MainNav({ className, initialPlatform }: MainNavProps) {
isCurrentWorkspaceManager,
marketplaceEnabled,
t,
- tContacts,
],
)
diff --git a/web/app/components/main-nav/routes.ts b/web/app/components/main-nav/routes.ts
index 024bf5c44ac..23bb7b79167 100644
--- a/web/app/components/main-nav/routes.ts
+++ b/web/app/components/main-nav/routes.ts
@@ -6,6 +6,7 @@ const DATASET_COLLECTION_ROUTES = new Set(['create', 'create-from-pipeline', 'co
export type MainNavRouteConfig = {
key: string
+ ns?: 'navigation' | 'contacts'
href: string
active: (pathname: string) => boolean
icon: string
@@ -83,6 +84,7 @@ export const MAIN_NAV_ROUTES = [
key: 'contacts',
href: '/contacts',
labelKey: 'directory.title',
+ ns: 'contacts',
active: (path: string) => isPathUnderRoute(path, '/contacts'),
icon: 'i-ri-contacts-book-2-line',
activeIcon: 'i-ri-contacts-book-2-fill',
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
index 9fd90c03dbf..ac11bf30f17 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
@@ -177,7 +177,7 @@ const originalNavigation = navigationSettings.disableMainFrameNavigation
beforeEach(() => {
navigationSettings.disableMainFrameNavigation = true
- document.body.setAttribute('data-is-marketplace', '')
+ document.documentElement.setAttribute('data-is-marketplace', '')
window.__marketplaceTracking__ = {
track: mockTrackMarketplaceSiteEvent,
rememberReferrer: vi.fn(),
@@ -190,7 +190,7 @@ beforeEach(() => {
afterEach(() => {
delete window.__marketplaceTracking__
- document.body.removeAttribute('data-is-marketplace')
+ document.documentElement.removeAttribute('data-is-marketplace')
navigationSettings.disableMainFrameNavigation = originalNavigation
vi.unstubAllGlobals()
vi.restoreAllMocks()
diff --git a/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx b/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx
index 9d90981c07e..668397f351e 100644
--- a/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx
+++ b/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx
@@ -53,7 +53,7 @@ const plugin = createMarketplacePluginFixture()
describe('CardWrapper', () => {
afterEach(() => {
delete window.__marketplaceTracking__
- document.body.removeAttribute('data-is-marketplace')
+ document.documentElement.removeAttribute('data-is-marketplace')
})
const renderCardWrapper = (
@@ -116,7 +116,7 @@ describe('CardWrapper', () => {
const user = userEvent.setup()
const track = vi.fn()
const rememberReferrer = vi.fn()
- document.body.setAttribute('data-is-marketplace', '')
+ document.documentElement.setAttribute('data-is-marketplace', '')
window.__marketplaceTracking__ = {
track,
rememberReferrer,
diff --git a/web/app/components/workflow-app/components/workflow-main.tsx b/web/app/components/workflow-app/components/workflow-main.tsx
index 1022f52909e..37e9567dfdc 100644
--- a/web/app/components/workflow-app/components/workflow-main.tsx
+++ b/web/app/components/workflow-app/components/workflow-main.tsx
@@ -11,10 +11,11 @@ import { useTranslation } from 'react-i18next'
import { useReactFlow } from 'reactflow'
import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
-import { WorkflowWithInnerContext } from '@/app/components/workflow'
+import { Workflow } from '@/app/components/workflow'
import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'
import { useCollaboration } from '@/app/components/workflow/collaboration/hooks/use-collaboration'
import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'
+import { HooksStoreContextProvider } from '@/app/components/workflow/hooks-store'
import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'
import { useInspectVarsCrudCommon as useInspectVarsCrud } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'
import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'
@@ -530,21 +531,22 @@ const WorkflowMain = ({ nodes, edges, viewport }: WorkflowMainProps) => {
return (
<div ref={containerRef} className="relative size-full">
- <WorkflowWithInnerContext
- nodes={nodes}
- edges={edges}
- viewport={viewport}
- onWorkflowDataUpdate={handleWorkflowDataUpdate}
- hooksStore={hooksStore as unknown as Partial<HooksStoreShape>}
- isCollaborationEnabled={isCollaborationEnabled}
- cursors={filteredCursors}
- myUserId={myUserId}
- onlineUsers={onlineUsers}
- >
+ <HooksStoreContextProvider {...(hooksStore as unknown as Partial<HooksStoreShape>)}>
<HumanInputMigrationProvider canEdit={appACLCapabilities.canEdit}>
- <WorkflowChildren />
+ <Workflow
+ nodes={nodes}
+ edges={edges}
+ viewport={viewport}
+ onWorkflowDataUpdate={handleWorkflowDataUpdate}
+ isCollaborationEnabled={isCollaborationEnabled}
+ cursors={filteredCursors}
+ myUserId={myUserId}
+ onlineUsers={onlineUsers}
+ >
+ <WorkflowChildren />
+ </Workflow>
</HumanInputMigrationProvider>
- </WorkflowWithInnerContext>
+ </HooksStoreContextProvider>
{isCollaborationEnabled &&
(collaborationGraphState.appId !== appId || !collaborationGraphState.isReady) && (
<div
diff --git a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
index db76ced26fb..954c6594cba 100644
--- a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx
@@ -220,7 +220,7 @@ describe('Blocks', () => {
</HumanInputMigrationContext>,
)
- const humanInputButton = screen.getByRole('button', { name: 'Human Input' })
+ const humanInputButton = screen.getByRole('button', { name: /^Human Input/ })
expect(humanInputButton).toHaveAttribute('aria-disabled', 'true')
expect(humanInputButton).toHaveAccessibleDescription(
expect.stringContaining('workflow.nodes.humanInputMigration.disabledReason'),
@@ -234,7 +234,7 @@ describe('Blocks', () => {
name: /workflow.nodes.humanInputMigration.action.migrateNow/,
})
expect(
- screen.getByText('workflow.nodes.humanInputMigration.preview.author'),
+ await screen.findByText('workflow.nodes.humanInputMigration.preview.author'),
).toBeInTheDocument()
expect(
screen.getByText('workflow.nodes.humanInputMigration.preview.description'),
@@ -253,7 +253,7 @@ describe('Blocks', () => {
/>
</HumanInputMigrationContext>,
)
- const enabledButton = screen.getByRole('button', { name: 'Human Input' })
+ const enabledButton = screen.getByRole('button', { name: /^Human Input/ })
expect(enabledButton).toHaveAttribute('aria-disabled', 'false')
await user.click(enabledButton)
expect(onSelect).toHaveBeenCalledWith(BlockEnum.HumanInputV2)
@@ -292,7 +292,7 @@ describe('Blocks', () => {
</HumanInputMigrationContext>,
)
- await user.hover(screen.getByRole('button', { name: 'Human Input' }))
+ await user.hover(screen.getByRole('button', { name: /^Human Input/ }))
expect(
await screen.findByText('workflow.nodes.humanInputMigration.preview.description'),
).toBeInTheDocument()
diff --git a/web/app/components/workflow/block-selector/blocks.tsx b/web/app/components/workflow/block-selector/blocks.tsx
index 552429360ce..236ed89425a 100644
--- a/web/app/components/workflow/block-selector/blocks.tsx
+++ b/web/app/components/workflow/block-selector/blocks.tsx
@@ -1,7 +1,6 @@
import type { NodeDefault, OnSelectBlock } from '../types'
import type { BlockClassification } from './types'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
import {
createPreviewCardHandle,
PreviewCard,
@@ -40,6 +39,7 @@ const Blocks = ({
}: BlocksProps) => {
const { t } = useTranslation(['workflow', 'workflowLogic', 'navigation'])
const store = useStoreApi()
+ const migration = useHumanInputMigration()
const blocksFromHooks = useBlocks()
const [previewCardHandle] = useState(() => createPreviewCardHandle<BlockPreviewPayload>())
const previewDescriptionBaseId = useId()
@@ -166,25 +166,19 @@ const Blocks = ({
render={
<button
type="button"
- aria-label={block.metaData.title}
aria-describedby={describedBy || undefined}
aria-disabled={isHumanInputDisabled}
data-disabled={isHumanInputDisabled || undefined}
- className="flex h-8 w-full cursor-pointer items-center rounded-lg px-3 text-start hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid focus-visible:outline-hidden data-[disabled]:cursor-not-allowed data-[disabled]:text-text-disabled data-[disabled]:hover:bg-transparent"
+ className="group/block-row flex h-8 w-full cursor-pointer items-center rounded-lg px-3 text-start hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid focus-visible:outline-hidden data-disabled:cursor-not-allowed data-disabled:text-text-disabled data-disabled:hover:bg-transparent"
onClick={() => {
if (!isHumanInputDisabled) onSelect(block.metaData.type)
}}
>
<BlockIcon
- className={cn('me-2 shrink-0', isHumanInputDisabled && 'opacity-30')}
+ className="me-2 shrink-0 group-data-disabled/block-row:opacity-30"
type={block.metaData.type}
/>
- <span
- className={cn(
- 'min-w-0 grow truncate text-sm text-text-secondary',
- isHumanInputDisabled && 'opacity-30',
- )}
- >
+ <span className="min-w-0 grow truncate text-sm text-text-secondary group-data-disabled/block-row:opacity-30">
{block.metaData.title}
</span>
{isHumanInputDisabled && (
@@ -193,7 +187,7 @@ const Blocks = ({
ns: 'workflow',
})}
size="xs"
- className="ms-2 shrink-0 px-[5px] py-[3px]"
+ className="ms-2 shrink-0 px-1.25 py-0.75"
/>
)}
{block.metaData.type === BlockEnum.KnowledgeRetrievalV2 && (
@@ -213,6 +207,16 @@ const Blocks = ({
</button>
}
/>
+ {isHumanInputDisabled && migration?.canEdit && (
+ <Button
+ className="my-1 ms-3"
+ size="small"
+ loading={migration.pending}
+ onClick={migration.openMigrationDialog}
+ >
+ {t(($) => $['nodes.humanInputMigration.action.migrateNow'], { ns: 'workflow' })}
+ </Button>
+ )}
{previewDescriptionId && (
<span id={previewDescriptionId} className="sr-only">
{block.metaData.description}
@@ -229,7 +233,7 @@ const Blocks = ({
</div>
)
},
- [groups, onSelect, previewCardHandle, previewDescriptionBaseId, t, store],
+ [groups, onSelect, previewCardHandle, previewDescriptionBaseId, t, store, migration],
)
return (
@@ -253,7 +257,6 @@ type BlockPreviewCardProps = {
function BlockPreviewCard({ payload }: BlockPreviewCardProps) {
const { t } = useTranslation(['workflow'])
- const migration = useHumanInputMigration()
if (!payload) return null
const { block, disabled } = payload
@@ -284,18 +287,6 @@ function BlockPreviewCard({ payload }: BlockPreviewCardProps) {
{t(($) => $['nodes.humanInputMigration.preview.description'], { ns: 'workflow' })}
</div>
</div>
- {migration?.canEdit && (
- <Button
- size="small"
- variant="primary"
- className="mt-2 gap-0.5"
- disabled={migration.pending}
- onClick={migration.openMigrationDialog}
- >
- {t(($) => $['nodes.humanInputMigration.action.migrateNow'], { ns: 'workflow' })}
- <span aria-hidden className="i-ri-arrow-right-line size-3.5" />
- </Button>
- )}
</div>
</div>
</BlockSelectorPreviewCardContent>
diff --git a/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts b/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts
index af9bbe89927..116e97a15d8 100644
--- a/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts
+++ b/web/app/components/workflow/block-selector/snippets/use-insert-snippet.ts
@@ -7,7 +7,6 @@ import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useStoreApi } from 'reactflow'
import { toast } from '@/app/notifications'
-import { ENABLE_HITL_IM } from '@/config'
import { consoleQuery } from '@/service/console'
import { useIncrementSnippetUseCountMutation } from '@/service/use-snippets'
import { CUSTOM_EDGE, NESTED_ELEMENT_Z_INDEX, NODE_WIDTH_X_OFFSET, X_OFFSET } from '../../constants'
@@ -16,7 +15,8 @@ import { useWorkflowHistory, WorkflowHistoryEvent } from '../../hooks/use-workfl
import { getNodeUsedVars, updateNodeVars } from '../../nodes/_base/components/variable/utils'
import { hasAgentV2OutputRoutes } from '../../nodes/agent-v2/types'
import { AssignerNodeInputType } from '../../nodes/assigner/types'
-import { canInsertHumanInputNodes } from '../../nodes/human-input-v2/migration/policy'
+import { notifyHumanInputInsertionBlocked } from '../../nodes/human-input-v2/migration/insertion-feedback'
+import { getHumanInputNodesInsertionBlocker } from '../../nodes/human-input-v2/migration/policy'
import { BlockEnum } from '../../types'
import { getNodesConnectedSourceOrTargetHandleIdsMap } from '../../utils'
@@ -407,6 +407,7 @@ const createBoundaryEdges = ({
export const useInsertSnippet = () => {
const { t } = useTranslation(['snippet', 'workflow'])
+ const { t: workflowT } = useTranslation(['workflow'])
const queryClient = useQueryClient()
const store = useStoreApi()
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
@@ -430,18 +431,9 @@ export const useInsertSnippet = () => {
const { getNodes, setNodes, edges, setEdges } = store.getState()
const currentNodes = getNodes()
- if (!canInsertHumanInputNodes(currentNodes, snippetNodes)) {
- toast.warning(
- t(
- ($) =>
- $[
- ENABLE_HITL_IM
- ? 'nodes.humanInputMigration.disabledReason'
- : 'nodes.humanInputV2.disabled'
- ],
- { ns: 'workflow' },
- ),
- )
+ const insertionBlocker = getHumanInputNodesInsertionBlocker(currentNodes, snippetNodes)
+ if (insertionBlocker) {
+ notifyHumanInputInsertionBlocked(insertionBlocker, workflowT)
return false
}
const remappedGraph = remapSnippetGraph(
@@ -597,7 +589,15 @@ export const useInsertSnippet = () => {
return false
}
},
- [handleSyncWorkflowDraft, incrementSnippetUseCount, queryClient, saveStateToHistory, store, t],
+ [
+ handleSyncWorkflowDraft,
+ incrementSnippetUseCount,
+ queryClient,
+ saveStateToHistory,
+ store,
+ t,
+ workflowT,
+ ],
)
return {
diff --git a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.tsx b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.tsx
index e94a9ae507c..b706779199a 100644
--- a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.tsx
+++ b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.tsx
@@ -1,9 +1,13 @@
import type { AgentSoulDifyToolConfig } from '@dify/contracts/api/console/apps/types.gen'
-import type { ToolProviderListResponse } from '@dify/contracts/api/console/workspaces/types.gen'
+import type {
+ BatchGetContactOptionsResponse,
+ ToolProviderListResponse,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import type { PluginsFromMarketplaceByInfoResponse } from '@dify/contracts/marketplace'
import type { ReactNode } from 'react'
import type { AvailableNodesMetaData } from '../../hooks-store/store'
import type { CodeNodeType } from '../../nodes/code/types'
+import type { HumanInputV2Recipient } from '../../nodes/human-input-v2/types'
import type { CommonEdgeType, CommonNodeType, Edge, Node } from '../../types'
import type { ChecklistItem } from '../use-checklist'
import { zWorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/zod.gen'
@@ -39,6 +43,18 @@ import { BlockEnum, PromptRole, VarType } from '../../types'
import { useChecklist, useChecklistBeforePublish, useWorkflowRunValidation } from '../use-checklist'
const mockHitlIm = vi.hoisted(() => ({ enabled: true }))
+const resolveContacts = vi.hoisted(() => vi.fn<() => Promise<BatchGetContactOptionsResponse>>())
+
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.humanInput.v2.contactOptions.batch.get': resolveContacts,
+ }),
+ }
+})
vi.mock('@/config', async (importOriginal) => ({
...(await importOriginal<typeof import('@/config')>()),
@@ -126,6 +142,7 @@ function renderChecklist(nodes: Node[], edges: Edge[], options: ChecklistOptions
beforeEach(() => {
mockHitlIm.enabled = true
+ resolveContacts.mockReset().mockResolvedValue({ data: [] })
resetFixtureCounters()
marketplace.mockReset().mockImplementation((url: string) => {
throw new Error(`Unexpected marketplace request: ${url}`)
@@ -752,3 +769,221 @@ describe('HITL release gate in workflow validation', () => {
},
)
})
+
+describe('HITL contact recipient availability', () => {
+ const existingContact = {
+ id: 'existing',
+ name: 'Existing contact',
+ email: '[email protected]',
+ type: 'external' as const,
+ im_providers: [],
+ }
+
+ function graphWithRecipients(recipients: HumanInputV2Recipient[], version: '1' | '2' = '2') {
+ return {
+ nodes: [
+ createInputNode(),
+ createNode({
+ id: 'review',
+ data: {
+ type: BlockEnum.HumanInput,
+ title: 'Review',
+ version,
+ form_content: 'Please approve',
+ inputs: [],
+ user_actions: [{ id: 'approve', title: 'Approve', button_style: 'primary' }],
+ timeout: 36,
+ timeout_unit: 'hour',
+ ...(version === '1'
+ ? { delivery_methods: [{ id: 'webapp', type: 'webapp', enabled: true }] }
+ : {
+ recipients_spec: recipients,
+ message_template: { subject: 'Review request', body: 'Please review {{#url#}}' },
+ debug_mode: { enabled: false, channels: [] },
+ }),
+ },
+ }),
+ ],
+ edges: [createEdge({ source: 'start', target: 'review' })],
+ }
+ }
+
+ function renderRecipientValidation(
+ recipients: HumanInputV2Recipient[],
+ version: '1' | '2' = '2',
+ ) {
+ const queryClient = createChecklistQueryClient()
+ const { wrapper } = createChecklistWrapper(graphWithRecipients(recipients, version), {
+ queryClient,
+ })
+ return {
+ ...renderHook(
+ () => ({ run: useWorkflowRunValidation(), publish: useChecklistBeforePublish() }),
+ { wrapper },
+ ),
+ queryClient,
+ }
+ }
+
+ it.each([
+ {
+ label: 'the only recipient',
+ recipients: [{ type: 'contact' as const, contact_id: 'deleted' }],
+ },
+ {
+ label: 'one of several recipients',
+ recipients: [
+ { type: 'contact' as const, contact_id: 'deleted' },
+ { type: 'contact' as const, contact_id: 'existing' },
+ ],
+ },
+ ])(
+ 'shows a checklist warning and blocks publication when $label was deleted',
+ async ({ recipients }) => {
+ resolveContacts.mockResolvedValue({ data: [existingContact] })
+ const { result } = renderRecipientValidation(recipients)
+
+ await waitFor(() =>
+ expect(result.current.run.warningNodes).toEqual([
+ expect.objectContaining({ id: 'review', errorMessages: [expect.any(String)] }),
+ ]),
+ )
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(false)
+ })
+ },
+ )
+
+ it('revalidates cached contacts before publishing and exposes deletion in the checklist', async () => {
+ resolveContacts.mockResolvedValue({ data: [existingContact] })
+ const { result } = renderRecipientValidation([{ type: 'contact', contact_id: 'existing' }])
+ await waitFor(() => expect(resolveContacts).toHaveBeenCalled())
+ await waitFor(() => expect(result.current.run.warningNodes).toEqual([]))
+
+ resolveContacts.mockResolvedValue({ data: [] })
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(false)
+ })
+ await waitFor(() =>
+ expect(result.current.run.warningNodes).toEqual([
+ expect.objectContaining({ id: 'review', errorMessages: [expect.any(String)] }),
+ ]),
+ )
+ })
+
+ it('updates the checklist after contact deletion invalidates the active contact query', async () => {
+ resolveContacts.mockResolvedValue({ data: [existingContact] })
+ const { result, queryClient } = renderRecipientValidation([
+ { type: 'contact', contact_id: 'existing' },
+ ])
+ await waitFor(() => expect(resolveContacts).toHaveBeenCalled())
+ await waitFor(() => expect(result.current.run.hasValidationErrors).toBe(false))
+
+ resolveContacts.mockResolvedValue({ data: [] })
+ await act(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.humanInput.v2.contactOptions.batch.get.key(),
+ })
+ })
+ await waitFor(() =>
+ expect(result.current.run.warningNodes).toEqual([
+ expect.objectContaining({ id: 'review', errorMessages: [expect.any(String)] }),
+ ]),
+ )
+ expect(result.current.run.validateBeforeRun()).toBe(false)
+ })
+
+ it('keeps V2 disabled without contact requests when the release gate is off', async () => {
+ mockHitlIm.enabled = false
+ const { result } = renderRecipientValidation([{ type: 'contact', contact_id: 'existing' }])
+
+ expect(result.current.run.warningNodes).toEqual([
+ expect.objectContaining({
+ id: 'review',
+ errorMessages: ['workflow.nodes.humanInputV2.disabled'],
+ }),
+ ])
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(false)
+ })
+ expect(resolveContacts).not.toHaveBeenCalled()
+ })
+
+ it('does not report contact recipients as invalid while the lookup is pending', async () => {
+ let resolveLookup: (value: { data: (typeof existingContact)[] }) => void = () => {}
+ resolveContacts.mockReturnValue(
+ new Promise((resolve) => {
+ resolveLookup = resolve
+ }),
+ )
+ const { result } = renderRecipientValidation([{ type: 'contact', contact_id: 'existing' }])
+
+ await waitFor(() => expect(resolveContacts).toHaveBeenCalled())
+ expect(result.current.run.warningNodes).toEqual([])
+
+ await act(async () => {
+ resolveLookup({ data: [existingContact] })
+ })
+ await waitFor(() => expect(result.current.run.hasValidationErrors).toBe(false))
+ })
+
+ it('reports a failed recipient lookup as unverified, blocks publication, and allows a successful retry', async () => {
+ resolveContacts.mockRejectedValue(new Error('Contact lookup unavailable'))
+ const { result } = renderRecipientValidation([{ type: 'contact', contact_id: 'existing' }])
+
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(false)
+ })
+ await waitFor(() =>
+ expect(result.current.run.warningNodes).toEqual([
+ expect.objectContaining({
+ id: 'review',
+ errorMessages: ['workflow.nodes.humanInputV2.error.recipientVerificationFailed'],
+ }),
+ ]),
+ )
+
+ resolveContacts.mockResolvedValue({ data: [existingContact] })
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(true)
+ })
+ await waitFor(() => expect(result.current.run.warningNodes).toEqual([]))
+ })
+
+ it('does not let cached success bypass a failed fresh lookup', async () => {
+ resolveContacts.mockResolvedValue({ data: [existingContact] })
+ const { result } = renderRecipientValidation([{ type: 'contact', contact_id: 'existing' }])
+ await waitFor(() => expect(resolveContacts).toHaveBeenCalled())
+ await waitFor(() => expect(result.current.run.hasValidationErrors).toBe(false))
+
+ resolveContacts.mockRejectedValue(new Error('Contact lookup unavailable'))
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(false)
+ })
+ })
+
+ it.each([
+ {
+ label: 'V1 delivery settings',
+ version: '1' as const,
+ recipients: [],
+ },
+ {
+ label: 'V2 non-contact recipients',
+ version: '2' as const,
+ recipients: [
+ { type: 'initiator' as const },
+ { type: 'all_workspace_contacts' as const },
+ { type: 'onetime_email' as const, email: '[email protected]' },
+ ],
+ },
+ ])('keeps $label valid without contact requests', async ({ version, recipients }) => {
+ const { result } = renderRecipientValidation(recipients, version)
+
+ expect(result.current.run.warningNodes).toEqual([])
+ await act(async () => {
+ expect(await result.current.publish.handleCheckBeforePublish()).toBe(true)
+ })
+ expect(resolveContacts).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts
index dcf9125b6de..af6c058f0f0 100644
--- a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts
@@ -17,6 +17,7 @@ import { useWorkflowNodeCatalog } from '../../node-catalog'
import AgentV2Default from '../../nodes/agent-v2/default'
import endDefault from '../../nodes/end/default'
import { createDefaultFormInputByType } from '../../nodes/human-input/types'
+import { CUSTOM_ITERATION_START_NODE } from '../../nodes/iteration-start/constants'
import { BlockEnum, InputVarType } from '../../types'
import { writeWorkflowClipboard } from '../../utils/clipboard'
import { useNodesInteractions } from '../use-nodes-interactions'
@@ -590,3 +591,83 @@ it('creates an inline Agent through the service boundary and resolves the pendin
expect(result.current.nodes.find((node) => node.id === nodeId)?.data._isTempNode).toBeUndefined()
expect(sync).toHaveBeenCalledTimes(2)
})
+
+it('remaps a copied ordinary node dependency and edge while the HITL gate is off', async () => {
+ releaseGate.enabled = false
+ const source = codeNode('source-copy')
+ const target = codeNode('target-copy', {
+ data: {
+ variables: [{ variable: 'topic', value_selector: ['source-copy', 'result'] }],
+ },
+ })
+ const connection = createEdge({ id: 'copied-connection', source: source.id, target: target.id })
+ const original = structuredClone({ source, target, connection })
+ const { result } = await paste([source, target], [connection], { nodes: [] })
+ const copiedSource = result.current.nodes.find((node) => node.data.title === source.data.title)!
+ const copiedTarget = result.current.nodes.find((node) => node.data.title === target.data.title)!
+ expect(copiedSource.id).not.toBe(source.id)
+ expect(copiedTarget.id).not.toBe(target.id)
+ expect(copiedTarget.data).toMatchObject({
+ variables: [{ variable: 'topic', value_selector: [copiedSource.id, 'result'] }],
+ })
+ expect(result.current.edges).toEqual([
+ expect.objectContaining({ source: copiedSource.id, target: copiedTarget.id }),
+ ])
+ expect({ source, target, connection }).toEqual(original)
+})
+
+it('remaps iteration children and their internal references while the HITL gate is off', async () => {
+ releaseGate.enabled = false
+ const parent = workflowNode(BlockEnum.Iteration, 'iteration-copy', {
+ data: {
+ start_node_id: 'child-start',
+ _children: [
+ { nodeId: 'child-source', nodeType: BlockEnum.Code },
+ { nodeId: 'child-target', nodeType: BlockEnum.Code },
+ ],
+ },
+ })
+ const start = createNode({
+ id: 'child-start',
+ type: CUSTOM_ITERATION_START_NODE,
+ parentId: parent.id,
+ data: { type: BlockEnum.IterationStart, isInIteration: true, iteration_id: parent.id },
+ })
+ const source = codeNode('child-source', {
+ parentId: parent.id,
+ data: { isInIteration: true, iteration_id: parent.id },
+ })
+ const target = codeNode('child-target', {
+ parentId: parent.id,
+ data: {
+ isInIteration: true,
+ iteration_id: parent.id,
+ variables: [{ variable: 'topic', value_selector: [source.id, 'result'] }],
+ },
+ })
+ const { result } = await paste(
+ [parent, start, source, target],
+ [createEdge({ source: source.id, target: target.id })],
+ { nodes: [] },
+ )
+ const copiedParent = result.current.nodes.find((node) => node.data.type === BlockEnum.Iteration)!
+ const copiedSource = result.current.nodes.find((node) => node.data.title === source.data.title)!
+ const copiedTarget = result.current.nodes.find((node) => node.data.title === target.data.title)!
+ expect(copiedParent.id).not.toBe(parent.id)
+ expect(copiedSource.parentId).toBe(copiedParent.id)
+ expect(copiedTarget.parentId).toBe(copiedParent.id)
+ const startNodeId = Reflect.get(copiedParent.data, 'start_node_id')
+ expect(startNodeId).not.toBe('child-source')
+ expect(result.current.nodes.find((node) => node.id === startNodeId)).toMatchObject({
+ parentId: copiedParent.id,
+ data: { type: BlockEnum.IterationStart },
+ })
+ expect(copiedTarget.data).toMatchObject({
+ iteration_id: copiedParent.id,
+ variables: [{ variable: 'topic', value_selector: [copiedSource.id, 'result'] }],
+ })
+ expect(result.current.edges[0]).toMatchObject({
+ source: copiedSource.id,
+ target: copiedTarget.id,
+ })
+})
diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.ts
index 84e3c7233d3..2204cac5992 100644
--- a/web/app/components/workflow/hooks/use-checklist.ts
+++ b/web/app/components/workflow/hooks/use-checklist.ts
@@ -34,8 +34,9 @@ import {
} from '@/app/components/workflow/editor-resource/state'
import useNodes from '@/app/components/workflow/store/workflow/use-nodes'
import { toast } from '@/app/notifications'
-import { MAX_TREE_DEPTH } from '@/config'
+import { ENABLE_HITL_IM, MAX_TREE_DEPTH } from '@/config'
import { useGetLanguage } from '@/context/i18n'
+import { currentWorkspaceIdAtom } from '@/context/workspace-state'
import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
import {
createAgentToolProviderCatalog,
@@ -50,6 +51,8 @@ import { useDatasetsDetailStore } from '../datasets-detail-store/store'
import { getNodeUsedVars, isSpecialVar } from '../nodes/_base/components/variable/utils'
import { hasValidInlineAgentBinding, isAgentV2NodeData } from '../nodes/agent-v2/types'
import AgentDefault from '../nodes/agent/default'
+import { getContactRecipientQueryOptions } from '../nodes/human-input-v2/contact-queries'
+import { isHumanInputV2NodeData } from '../nodes/human-input-v2/types'
import { IndexMethodEnum } from '../nodes/knowledge-base/types'
import {
getLLMModelIssue,
@@ -98,6 +101,24 @@ type NodeValidator = NonNullable<
const EMPTY_ENVIRONMENT_VARIABLES: EnvironmentVariable[] = []
+const getHumanInputContactIds = (nodes: Node[]) => {
+ if (!ENABLE_HITL_IM) return []
+
+ return [
+ ...new Set(
+ nodes.flatMap((node) =>
+ node.type === CUSTOM_NODE && isHumanInputV2NodeData(node.data)
+ ? node.data.recipients_spec.flatMap((recipient) =>
+ recipient.type === 'contact' && recipient.contact_id.trim()
+ ? [recipient.contact_id]
+ : [],
+ )
+ : [],
+ ),
+ ),
+ ].sort()
+}
+
const withResourceKind = (
moreDataForCheckValid: CheckValidExtraData,
resourceKind: EditorResource['kind'],
@@ -162,6 +183,18 @@ const getDuplicateEndOutputMessages = (
export const useChecklist = (nodes: Node[], edges: Edge[]) => {
const { t } = useTranslation(['agentV2', 'common', 'workflow', 'modelProvider'])
const language = useGetLanguage()
+ const workspaceId = useAtomValue(currentWorkspaceIdAtom)
+ const contactIds = useMemo(() => getHumanInputContactIds(nodes), [nodes])
+ const contactQuery = useQuery(getContactRecipientQueryOptions(workspaceId, contactIds))
+ const contactLookup = useMemo(
+ () => ({
+ resolvedContactIds: contactQuery.isSuccess
+ ? new Set(contactQuery.data.data.map((contact) => contact.id))
+ : undefined,
+ contactLookupFailed: contactQuery.isError,
+ }),
+ [contactQuery.data, contactQuery.isError, contactQuery.isSuccess],
+ )
const { nodesMap: nodesExtraData } = useNodesMetaData()
const { data: buildInTools } = useQuery(
consoleQuery.workspaces.current.tools.builtin.get.queryOptions({
@@ -430,6 +463,8 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {
}
}
+ if (isHumanInputV2NodeData(node!.data)) moreDataForCheckValid = contactLookup
+
if (node!.type === CUSTOM_NODE) {
const checkData = getCheckData(node!.data)
const validator = resolveNodeValidator(node!.data, nodesExtraData)
@@ -613,6 +648,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {
inlineAgentConfigurationIssues,
inlineAgentToolPresentation.toolDisplayNameById,
resourceKind,
+ contactLookup,
])
useEffect(() => {
@@ -629,6 +665,7 @@ export const useChecklistBeforePublish = () => {
const { t } = useTranslation(['common', 'workflow', 'modelProvider'])
const language = useGetLanguage()
const queryClient = useQueryClient()
+ const workspaceId = useAtomValue(currentWorkspaceIdAtom)
const store = useStoreApi()
const { nodesMap: nodesExtraData } = useNodesMetaData()
const { data: strategyProviders } = useQuery(
@@ -779,9 +816,25 @@ export const useChecklistBeforePublish = () => {
return datasetsDetail || []
}
- const [embeddingProviderModelMap, datasets] = await Promise.all([
+ const fetchLatestContactLookup = async () => {
+ const contactIds = getHumanInputContactIds(filteredNodes)
+ if (!contactIds.length) return { resolvedContactIds: new Set<string>() }
+ if (!workspaceId) return { contactLookupFailed: true }
+
+ try {
+ const response = await queryClient.query(
+ getContactRecipientQueryOptions(workspaceId, contactIds),
+ )
+ return { resolvedContactIds: new Set(response.data.map((contact) => contact.id)) }
+ } catch {
+ return { contactLookupFailed: true }
+ }
+ }
+
+ const [embeddingProviderModelMap, datasets, contactLookup] = await Promise.all([
fetchKnowledgeBaseProviderModelMap(),
fetchLatestDatasets(),
+ fetchLatestContactLookup(),
])
if (datasets === null) return false
@@ -853,6 +906,8 @@ export const useChecklistBeforePublish = () => {
}
}
+ if (isHumanInputV2NodeData(node!.data)) moreDataForCheckValid = contactLookup
+
const checkData = getCheckData(node!.data, datasets, embeddingProviderModelMap)
const validator = resolveNodeValidator(node!.data, nodesExtraData)
if (validator) {
@@ -956,6 +1011,7 @@ export const useChecklistBeforePublish = () => {
strategyProviders,
modelProviders,
resourceKind,
+ workspaceId,
])
return {
diff --git a/web/app/components/workflow/hooks/use-edge-accessible-label.ts b/web/app/components/workflow/hooks/use-edge-accessible-label.ts
index 80ec70b3b27..6c7e76f2ac9 100644
--- a/web/app/components/workflow/hooks/use-edge-accessible-label.ts
+++ b/web/app/components/workflow/hooks/use-edge-accessible-label.ts
@@ -4,6 +4,7 @@ import { useLayoutEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore } from 'reactflow'
import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'
+import { HUMAN_INPUT_TIMEOUT_HANDLE } from '@/app/components/workflow/nodes/human-input/shared/constants'
import { ErrorHandleTypeEnum } from '../nodes/_base/components/error-handle/types'
import { BlockEnum } from '../types'
@@ -41,7 +42,7 @@ export const useEdgeAccessibleLabel = (
}
if (sourceData.type === BlockEnum.HumanInput) {
branchName =
- sourceHandleId === '__timeout'
+ sourceHandleId === HUMAN_INPUT_TIMEOUT_HANDLE
? t(($) => $['nodes.humanInput.timeout.title'], { ns: 'workflow' })
: (sourceData as HumanInputNodeType).user_actions?.find(
(action) => action.id === sourceHandleId,
diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.ts
index bcab6b88d83..c11f3ba30d7 100644
--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts
+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts
@@ -21,7 +21,6 @@ import { useTranslation } from 'react-i18next'
import { getConnectedEdges, getOutgoers, useReactFlow } from 'reactflow'
import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'
import { toast } from '@/app/notifications'
-import { ENABLE_HITL_IM } from '@/config'
import { consoleQuery } from '@/service/console'
import { collaborationManager } from '../collaboration/core/collaboration-manager'
import {
@@ -40,9 +39,10 @@ import {
isAgentV2NodeData,
needsInlineAgentBindingCreation,
} from '../nodes/agent-v2/types'
+import { notifyHumanInputInsertionBlocked } from '../nodes/human-input-v2/migration/insertion-feedback'
import {
- canInsertHumanInput,
- canInsertHumanInputNodes,
+ getHumanInputInsertionBlocker,
+ getHumanInputNodesInsertionBlocker,
} from '../nodes/human-input-v2/migration/policy'
import { CUSTOM_ITERATION_START_NODE } from '../nodes/iteration-start/constants'
import { useNodeIterationInteractions } from '../nodes/iteration/use-interactions'
@@ -850,23 +850,12 @@ export const useNodesInteractions = () => {
const nodeMetaData = nodesMetaDataMap?.[nodeType]
if (!nodeMetaData) return
const { defaultValue } = nodeMetaData
- if (
- !canInsertHumanInput(nodes, nodeType, {
- ...(defaultValue as Node['data']),
- ...pluginDefaultValue,
- })
- ) {
- toast.warning(
- t(
- ($) =>
- $[
- ENABLE_HITL_IM
- ? 'nodes.humanInputMigration.disabledReason'
- : 'nodes.humanInputV2.disabled'
- ],
- { ns: 'workflow' },
- ),
- )
+ const insertionBlocker = getHumanInputInsertionBlocker(nodes, nodeType, {
+ ...(defaultValue as Node['data']),
+ ...pluginDefaultValue,
+ })
+ if (insertionBlocker) {
+ notifyHumanInputInsertionBlocked(insertionBlocker, t)
return
}
const nodesWithSameType = getNodesWithSameDefaultDataType(nodes, nodeType, defaultValue)
@@ -1386,23 +1375,12 @@ export const useNodesInteractions = () => {
const nodeMetaData = nodesMetaDataMap?.[nodeType]
if (!nodeMetaData) return
const { defaultValue } = nodeMetaData
- if (
- !canInsertHumanInput(nodes, nodeType, {
- ...(defaultValue as Node['data']),
- ...pluginDefaultValue,
- })
- ) {
- toast.warning(
- t(
- ($) =>
- $[
- ENABLE_HITL_IM
- ? 'nodes.humanInputMigration.disabledReason'
- : 'nodes.humanInputV2.disabled'
- ],
- { ns: 'workflow' },
- ),
- )
+ const insertionBlocker = getHumanInputInsertionBlocker(nodes, nodeType, {
+ ...(defaultValue as Node['data']),
+ ...pluginDefaultValue,
+ })
+ if (insertionBlocker) {
+ notifyHumanInputInsertionBlocked(insertionBlocker, t)
return
}
const currentNode = nodes.find((node) => node.id === currentNodeId)!
@@ -1763,18 +1741,9 @@ export const useNodesInteractions = () => {
if (!validatedClipboardElements.length) return
const { nodes, setNodes, edges, setEdges } = collaborativeWorkflow.getState()
- if (!canInsertHumanInputNodes(nodes, validatedClipboardElements)) {
- toast.warning(
- t(
- ($) =>
- $[
- ENABLE_HITL_IM
- ? 'nodes.humanInputMigration.disabledReason'
- : 'nodes.humanInputV2.disabled'
- ],
- { ns: 'workflow' },
- ),
- )
+ const insertionBlocker = getHumanInputNodesInsertionBlocker(nodes, validatedClipboardElements)
+ if (insertionBlocker) {
+ notifyHumanInputInsertionBlocked(insertionBlocker, t)
return
}
const reservedNodeTitles = new Set(
diff --git a/web/app/components/workflow/node-catalog.ts b/web/app/components/workflow/node-catalog.ts
index 67a3e9b1314..b1d488a6fa7 100644
--- a/web/app/components/workflow/node-catalog.ts
+++ b/web/app/components/workflow/node-catalog.ts
@@ -5,12 +5,12 @@ import { useAtomValue } from 'jotai'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore } from 'reactflow'
+import { useShallow } from 'zustand/react/shallow'
import { WORKFLOW_COMMON_NODES } from '@/app/components/workflow/constants/node'
import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'
import AnswerDefault from '@/app/components/workflow/nodes/answer/default'
import EndDefault from '@/app/components/workflow/nodes/end/default'
import { getHumanInputCreationPolicy } from '@/app/components/workflow/nodes/human-input-v2/migration/policy'
-import HumanInputDefault from '@/app/components/workflow/nodes/human-input/default'
import StartPlaceholderDefault from '@/app/components/workflow/nodes/start-placeholder/default'
import StartDefault from '@/app/components/workflow/nodes/start/default'
import TriggerPluginDefault from '@/app/components/workflow/nodes/trigger-plugin/default'
@@ -44,8 +44,24 @@ export const useWorkflowNodeCatalog = () => {
select: (features) => features.enable_knowledge_fs,
}),
)
- const canContinueLegacyHumanInput = useStore(
- (state) => getHumanInputCreationPolicy(state.getNodes(), true).canAddLegacyHumanInput,
+ const humanInputData = useStore(
+ useShallow((state) =>
+ ENABLE_HITL_IM
+ ? state
+ .getNodes()
+ .filter((node) => node.data.type === BlockEnum.HumanInput)
+ .map((node) => node.data)
+ : [],
+ ),
+ )
+ const canContinueLegacyHumanInput = useMemo(
+ () =>
+ ENABLE_HITL_IM &&
+ getHumanInputCreationPolicy(
+ humanInputData.map((data) => ({ data })),
+ true,
+ ).canAddLegacyHumanInput,
+ [humanInputData],
)
const useLegacyHumanInput = !ENABLE_HITL_IM || canContinueLegacyHumanInput
@@ -107,22 +123,6 @@ export const useWorkflowNodeCatalog = () => {
[mergedNodesMetaData, t, docLink],
)
- const legacyHumanInputMetaData = useMemo(() => {
- const { metaData } = HumanInputDefault
- const title = t(($) => $[`blocks.${BlockEnum.HumanInput}`], { ns: 'workflow' })
- const description = t(($) => $[`blocksAbout.${BlockEnum.HumanInput}`], { ns: 'workflow' })
-
- return {
- ...HumanInputDefault,
- metaData: { ...metaData, title, description },
- defaultValue: {
- ...HumanInputDefault.defaultValue,
- type: BlockEnum.HumanInput,
- title,
- },
- }
- }, [t])
-
const availableNodesMetaData = useMemo(
() =>
nodesMetaData.filter(
@@ -143,11 +143,9 @@ export const useWorkflowNodeCatalog = () => {
acc![node.metaData.type] = node
return acc
},
- {
- [BlockEnum.HumanInput]: legacyHumanInputMetaData,
- } as unknown as AvailableNodesMetaData['nodesMap'],
+ {} as unknown as AvailableNodesMetaData['nodesMap'],
),
- [nodesMetaData, legacyHumanInputMetaData],
+ [nodesMetaData],
)
return useMemo(
diff --git a/web/app/components/workflow/nodes/human-input-v2/README.md b/web/app/components/workflow/nodes/human-input-v2/README.md
index fd559524353..f52edea9880 100644
--- a/web/app/components/workflow/nodes/human-input-v2/README.md
+++ b/web/app/components/workflow/nodes/human-input-v2/README.md
@@ -17,11 +17,13 @@ stop server-side runs and notifications that are already in progress.
- `types.ts` owns the exact frontend wire contract and version guard.
- `default.ts` owns catalog metadata, creation defaults, validation and outputs.
- `recipient-utils.ts` owns pure recipient validation and immutable list operations.
-- UI components edit local drafts and write the complete affected DSL field atomically.
+- Recipients and DebugMode write the affected DSL field immediately. MessageTemplate keeps a mounted dialog draft until Save or Save and test. All updates preserve unrelated node configuration.
## External modules
- Reuses only the narrow shared form/action/timeout types and components from `human-input/shared`.
- Uses existing workflow variable and edge utilities for selectors and action handles.
-- Contact options come through the local typed provider boundary; this feature does not call a Contact API.
+- Contact selection and node summaries use generated `contactOptions` queries. The publish checklist shares the authoritative batch lookup; loading or failed lookups are not proof that a contact was deleted.
+- The picker paginates explicitly. Source filtering applies to loaded records because the current editor-safe endpoint does not expose a source filter. It never loops through all pages to find a match.
+- Message-template tests save the current draft before sending through a configured channel; the dialog owns draft and mutation state for its mounted session.
- No graphon, backend, runtime or simulated execution dependency is introduced.
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/contact-provider.spec.ts b/web/app/components/workflow/nodes/human-input-v2/__tests__/contact-provider.spec.ts
deleted file mode 100644
index a1232f2f4be..00000000000
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/contact-provider.spec.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import type {
- BatchGetContactOptionsResponse,
- ListContactOptionsResponse,
-} from '@dify/contracts/api/console/workspaces/types.gen'
-import { QueryClient } from '@tanstack/react-query'
-import { createContactRecipientOptionProvider } from '../contact-provider'
-import { mockContactRecipientOptionProvider } from './fixtures/contact-provider'
-
-const api = vi.hoisted(() => ({
- search:
- vi.fn<
- (input: {
- query: { keyword: string; page: number; limit: number }
- }) => Promise<ListContactOptionsResponse>
- >(),
- resolve:
- vi.fn<
- (input: { query: { contact_ids: string[] } }) => Promise<BatchGetContactOptionsResponse>
- >(),
-}))
-
-vi.mock('@/service/console', async () => {
- const { createTanstackQueryUtils } = await import('@orpc/tanstack-query')
- return {
- consoleQuery: createTanstackQueryUtils({
- workspaces: {
- current: {
- humanInput: { v2: { contactOptions: { get: api.search, batch: { get: api.resolve } } } },
- },
- },
- }),
- }
-})
-
-const firstPage: ListContactOptionsResponse = {
- data: [
- {
- id: 'contact-1',
- name: 'First contact',
- email: null,
- avatar_url: null,
- type: 'platform',
- im_providers: [],
- },
- ],
- page: 1,
- limit: 20,
- total: 21,
-}
-
-describe('Contact recipient API provider', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('searches the editor-safe endpoint and preserves server pagination', async () => {
- api.search.mockResolvedValueOnce(firstPage).mockResolvedValueOnce({
- ...firstPage,
- data: [
- {
- id: 'contact-21',
- name: 'Last contact',
- email: '[email protected]',
- type: 'external',
- im_providers: [],
- },
- ],
- page: 2,
- })
- const provider = createContactRecipientOptionProvider('workspace-1', new QueryClient())
-
- await expect(provider.searchPage?.(' contact ', 1)).resolves.toEqual({
- data: [
- {
- id: 'contact-1',
- name: 'First contact',
- email: '',
- avatar: undefined,
- source: 'organization',
- },
- ],
- page: 1,
- hasMore: true,
- })
- await expect(provider.searchPage?.(' contact ', 2)).resolves.toMatchObject({
- data: [{ id: 'contact-21' }],
- page: 2,
- hasMore: false,
- })
- expect(api.search.mock.calls.map(([input]) => input)).toEqual([
- { query: { keyword: 'contact', limit: 20, page: 1 } },
- { query: { keyword: 'contact', limit: 20, page: 2 } },
- ])
- })
-
- it('resolves saved IDs through the editor-safe batch endpoint and omits missing contacts', async () => {
- api.resolve.mockResolvedValue({ data: firstPage.data })
- const provider = createContactRecipientOptionProvider('workspace-1', new QueryClient())
-
- await expect(
- provider.resolve({ contact_ids: ['missing', 'contact-1', 'contact-1'] }),
- ).resolves.toMatchObject([{ id: 'contact-1', name: 'First contact' }])
- expect(api.resolve.mock.calls[0]?.[0]).toEqual({
- query: { contact_ids: ['contact-1', 'missing'] },
- })
- await expect(provider.resolve({ contact_ids: [] })).resolves.toEqual([])
- expect(api.resolve).toHaveBeenCalledOnce()
- })
-
- it('does not share in-flight searches across workspaces', async () => {
- let finishFirst: (response: ListContactOptionsResponse) => void = () => undefined
- api.search
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finishFirst = resolve
- }),
- )
- .mockResolvedValueOnce({
- ...firstPage,
- data: [{ ...firstPage.data[0]!, id: 'workspace-2-contact' }],
- })
- const queryClient = new QueryClient()
- const first = createContactRecipientOptionProvider('workspace-1', queryClient).search('')
- const second = createContactRecipientOptionProvider('workspace-2', queryClient).search('')
-
- await expect(second).resolves.toMatchObject([{ id: 'workspace-2-contact' }])
- finishFirst(firstPage)
- await expect(first).resolves.toMatchObject([{ id: 'contact-1' }])
- expect(api.search).toHaveBeenCalledTimes(2)
- })
-
- it('refreshes search results after another screen creates a contact', async () => {
- api.search
- .mockResolvedValueOnce({ ...firstPage, data: [], total: 0 })
- .mockResolvedValueOnce(firstPage)
- const provider = createContactRecipientOptionProvider('workspace-1', new QueryClient())
-
- await expect(provider.search('First')).resolves.toEqual([])
- await expect(provider.search('First')).resolves.toMatchObject([{ id: 'contact-1' }])
- })
-})
-
-describe('mock Contact recipient option provider', () => {
- it('provides deterministic case-insensitive search and id resolution', async () => {
- await expect(mockContactRecipientOptionProvider.search('EVAN')).resolves.toEqual([
- expect.objectContaining({ id: 'contact-evan', name: 'Evan Zhang' }),
- ])
- await expect(
- mockContactRecipientOptionProvider.resolve({
- contact_ids: ['missing', 'contact-amanda'],
- }),
- ).resolves.toEqual([expect.objectContaining({ id: 'contact-amanda' })])
- })
-
- it('returns defensive copies', async () => {
- const first = await mockContactRecipientOptionProvider.search('')
- first[0]!.name = 'Changed'
- const second = await mockContactRecipientOptionProvider.search('')
-
- expect(second[0]!.name).toBe('Evan Zhang')
- })
-})
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/debug-mode.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/debug-mode.spec.tsx
index be5861296e3..1b9c64eb777 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/debug-mode.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/debug-mode.spec.tsx
@@ -41,7 +41,7 @@ describe('Human Input v2 Debug Mode', () => {
expect(screen.getAllByRole('checkbox')).toHaveLength(2)
})
- it('shows the real email and prevents clearing the final selected channel with an explanatory tooltip', async () => {
+ it('shows the real email and prevents clearing the final selected channel with a keyboard-reachable explanation', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
@@ -59,13 +59,13 @@ describe('Human Input v2 Debug Mode', () => {
expect(checkbox).toBeChecked()
expect(checkbox).toHaveAttribute('aria-disabled', 'true')
expect(screen.getByText('[email protected]')).toBeInTheDocument()
- await user.click(screen.getByText(channelLabel('email')))
+ await user.click(screen.getByRole('checkbox', { name: channelLabel('email') }))
+ expect(onChange).not.toHaveBeenCalled()
+ expect(checkbox).toHaveAccessibleDescription('workflow.nodes.humanInputV2.debug.keepOneChannel')
+ expect(checkbox).not.toBeDisabled()
+ await user.click(checkbox)
+ await user.keyboard(' ')
expect(onChange).not.toHaveBeenCalled()
- await user.unhover(screen.getByText(channelLabel('email')))
- await user.hover(checkbox)
- expect(await screen.findByRole('tooltip')).toHaveTextContent(
- 'workflow.nodes.humanInputV2.debug.keepOneChannel',
- )
await user.click(screen.getByRole('checkbox', { name: channelLabel('slack') }))
expect(onChange).toHaveBeenLastCalledWith({ enabled: true, channels: ['email', 'slack'] })
})
@@ -88,8 +88,10 @@ describe('Human Input v2 Debug Mode', () => {
'true',
)
expect(screen.queryByRole('checkbox', { name: channelLabel('feishu') })).not.toBeInTheDocument()
- expect(screen.getByRole('img', { name: channelLabel('email') })).toBeInTheDocument()
- await user.click(screen.getByText(channelLabel('email')))
+ expect(
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.debug.configure' }),
+ ).toHaveAccessibleDescription(channelLabel('email'))
+ await user.click(screen.getByRole('checkbox', { name: channelLabel('email') }))
expect(onChange).not.toHaveBeenCalled()
})
@@ -195,8 +197,8 @@ describe('Human Input v2 Debug Mode', () => {
)
expect(
- screen.getByRole('img', { name: `${channelLabel('email')}, ${channelLabel('slack')}` }),
- ).toBeInTheDocument()
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.debug.configure' }),
+ ).toHaveAccessibleDescription(`${channelLabel('email')}, ${channelLabel('slack')}`)
expect(
screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.debug.configure' }),
).toBeDisabled()
@@ -219,8 +221,8 @@ describe('Human Input v2 Debug Mode', () => {
)
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(
- screen.getByRole('img', { name: `${channelLabel('lark')}, ${channelLabel('email')}` }),
- ).toBeInTheDocument()
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.debug.configure' }),
+ ).toHaveAccessibleDescription(`${channelLabel('lark')}, ${channelLabel('email')}`)
await user.click(
screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.debug.configure' }),
)
@@ -234,7 +236,9 @@ describe('Human Input v2 Debug Mode', () => {
readonly={false}
/>,
)
- expect(screen.getByRole('img', { name: channelLabel('email') })).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.debug.configure' }),
+ ).toHaveAccessibleDescription(channelLabel('email'))
await user.click(screen.getByRole('checkbox', { name: channelLabel('lark') }))
expect(onChange).toHaveBeenLastCalledWith({ enabled: true, channels: ['email', 'lark'] })
})
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/fixtures/contact-api.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/fixtures/contact-api.tsx
new file mode 100644
index 00000000000..f98c9e75a5a
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/fixtures/contact-api.tsx
@@ -0,0 +1,95 @@
+import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen'
+import type {
+ BatchGetContactOptionsResponse,
+ CurrentWorkspaceSummaryResponse,
+ ListContactOptionsResponse,
+ ListContactsResponse,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ReactElement } from 'react'
+import { zGetFeaturesResponse } from '@dify/contracts/api/console/features/zod.gen'
+import { createTanstackQueryUtils } from '@orpc/tanstack-query'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { render } from '@testing-library/react'
+import { createStore, Provider } from 'jotai'
+import { queryClientAtom } from 'jotai-tanstack-query'
+import { createTestQueryClient } from '@/test/query-client'
+
+export const contactApi = {
+ features: vi.fn<() => Promise<GetFeaturesResponse>>(),
+ summary: vi.fn<() => Promise<CurrentWorkspaceSummaryResponse>>(),
+ contacts: vi.fn<() => Promise<ListContactsResponse>>(),
+ options:
+ vi.fn<
+ (input: {
+ query: { keyword?: string; page?: number; limit?: number }
+ }) => Promise<ListContactOptionsResponse>
+ >(),
+ batch:
+ vi.fn<
+ (input: { query: { contact_ids: string[] } }) => Promise<BatchGetContactOptionsResponse>
+ >(),
+}
+export const testConsoleQuery = createTanstackQueryUtils({
+ features: { get: contactApi.features },
+ workspaces: {
+ current: {
+ summary: { get: contactApi.summary },
+ humanInput: {
+ v2: {
+ contacts: { get: contactApi.contacts },
+ contactOptions: { get: contactApi.options, batch: { get: contactApi.batch } },
+ },
+ },
+ },
+ },
+})
+export const contact = {
+ id: 'contact-evan',
+ name: 'Evan Zhang',
+ email: '[email protected]',
+ type: 'workspace' as const,
+ im_providers: [],
+}
+export const organizationContact = {
+ id: 'contact-amanda',
+ name: 'Amanda Lin',
+ email: '[email protected]',
+ type: 'platform' as const,
+ im_providers: [],
+}
+export function resetContactApi() {
+ contactApi.features
+ .mockReset()
+ .mockResolvedValue({ ...zGetFeaturesResponse.parse({}), im_centrally_managed: true })
+ contactApi.contacts.mockReset().mockResolvedValue({ data: [], total: 7, page: 1, limit: 1 })
+ contactApi.options
+ .mockReset()
+ .mockResolvedValue({ data: [contact, organizationContact], total: 2, page: 1, limit: 20 })
+ contactApi.batch.mockReset().mockImplementation(async ({ query }) => ({
+ data: [contact, organizationContact].filter((contact) =>
+ query.contact_ids.includes(contact.id),
+ ),
+ }))
+}
+export function renderContactOwner(ui: ReactElement, role: 'owner' | 'editor' = 'owner') {
+ const client = createTestQueryClient()
+ client.setQueryData(testConsoleQuery.workspaces.current.summary.get.queryKey(), {
+ id: 'workspace-1',
+ name: 'QA workspace',
+ role,
+ plan: null,
+ credits: null,
+ } satisfies CurrentWorkspaceSummaryResponse)
+ const store = createStore()
+ store.set(queryClientAtom, client)
+ return {
+ ...render(ui, {
+ wrapper: ({ children }) => (
+ <Provider store={store}>
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ </Provider>
+ ),
+ }),
+ client,
+ }
+}
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/fixtures/contact-provider.ts b/web/app/components/workflow/nodes/human-input-v2/__tests__/fixtures/contact-provider.ts
deleted file mode 100644
index 59119b25a40..00000000000
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/fixtures/contact-provider.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { ContactRecipientOption, ContactRecipientOptionProvider } from '../../contact-provider'
-
-const MOCK_CONTACT_OPTIONS: ContactRecipientOption[] = [
- {
- id: 'contact-evan',
- name: 'Evan Zhang',
- email: '[email protected]',
- source: 'workspace',
- },
- {
- id: 'contact-amanda',
- name: 'Amanda Lin',
- email: '[email protected]',
- source: 'organization',
- },
- {
- id: 'contact-morgan',
- name: 'Morgan Lee',
- email: '[email protected]',
- source: 'external',
- },
-]
-
-const waitForMockTick = () => Promise.resolve()
-
-export const mockContactRecipientOptionProvider: ContactRecipientOptionProvider = {
- async search(query) {
- await waitForMockTick()
- const normalizedQuery = query.trim().toLowerCase()
- if (!normalizedQuery) return MOCK_CONTACT_OPTIONS.map((option) => ({ ...option }))
- return MOCK_CONTACT_OPTIONS.filter(
- (option) =>
- option.name.toLowerCase().includes(normalizedQuery) ||
- option.email.toLowerCase().includes(normalizedQuery),
- ).map((option) => ({ ...option }))
- },
- async resolve({ contact_ids }) {
- await waitForMockTick()
- const idSet = new Set(contact_ids)
- return MOCK_CONTACT_OPTIONS.filter((option) => idSet.has(option.id)).map((option) => ({
- ...option,
- }))
- },
-}
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template-body.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template-body.spec.tsx
index 8fccb19cc69..026ef35ab37 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template-body.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template-body.spec.tsx
@@ -71,3 +71,20 @@ describe('Human Input V2 message body editor', () => {
).toHaveAttribute('contenteditable', 'false')
})
})
+
+it('connects validation and guidance to the actual Lexical textbox', () => {
+ render(
+ <MessageTemplateBody
+ nodeId="approval"
+ value="Review"
+ onChange={vi.fn()}
+ error="A request URL is required"
+ />,
+ )
+ const editor = screen.getByRole('textbox', { name: 'workflow.nodes.humanInputV2.template.body' })
+ expect(editor).toHaveAttribute('aria-invalid', 'true')
+ expect(editor).toHaveAccessibleDescription(expect.stringContaining('A request URL is required'))
+ expect(editor).toHaveAccessibleDescription(
+ expect.stringContaining('workflow.nodes.humanInputV2.template.requestURLHint'),
+ )
+})
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx
index 322f057c452..2ff0744bc80 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/message-template.spec.tsx
@@ -46,9 +46,16 @@ const originalBody = 'Original body {{#url#}}'
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
- const { withConsoleResponses } = await import('@/test/console/service-responses')
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
return {
...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.messageTemplate.test.post': (input) =>
+ mocks.workflowTest(input),
+ 'apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.messageTemplate.test.post':
+ (input) => mocks.chatflowTest(input),
+ }),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.messageTemplate.test.post':
mocks.workflowTest,
@@ -237,6 +244,10 @@ describe('Human Input v2 Message Template', () => {
await setBody('')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(screen.getByLabelText('workflow.nodes.humanInputV2.template.subject')).toHaveAttribute(
+ 'aria-invalid',
+ 'true',
+ )
expect(
screen.getByLabelText('workflow.nodes.humanInputV2.template.subject'),
).toHaveAccessibleDescription('workflow.nodes.humanInputV2.error.subjectRequired')
@@ -278,9 +289,7 @@ describe('Human Input v2 Message Template', () => {
await openTemplate(user)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(screen.getByRole('alert')).toHaveTextContent(
- `workflow.nodes.humanInputV2.error.${error}`,
- )
+ expect(screen.getByText(`workflow.nodes.humanInputV2.error.${error}`)).toBeInTheDocument()
await waitFor(() => expect(getBodyEditor()).toHaveFocus())
expect(props.onChange).not.toHaveBeenCalled()
},
@@ -292,7 +301,7 @@ describe('Human Input v2 Message Template', () => {
{ action: 'test', body: 'Review this request', error: 'requestURLRequired' },
{ action: 'test', body: 'Review {{#url#}} or {{#url#}}', error: 'requestURLDuplicate' },
])(
- 'validates $error while editing before $action and clears it when corrected',
+ 'waits for $action before validating $error, then clears it when corrected',
async ({ action, body, error }) => {
const user = userEvent.setup()
const { props } = renderTemplate()
@@ -300,18 +309,21 @@ describe('Human Input v2 Message Template', () => {
else await openTemplate(user)
await setBody(body)
- expect(screen.getByRole('alert')).toHaveTextContent(
- `workflow.nodes.humanInputV2.error.${error}`,
- )
+ expect(
+ screen.queryByText(`workflow.nodes.humanInputV2.error.${error}`),
+ ).not.toBeInTheDocument()
if (action === 'test') await sendTest(user)
else await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
+ expect(screen.getByText(`workflow.nodes.humanInputV2.error.${error}`)).toBeInTheDocument()
await waitFor(() => expect(getBodyEditor()).toHaveFocus())
expect(props.onChange).not.toHaveBeenCalled()
expect(mocks.syncDraft).not.toHaveBeenCalled()
expectNoTemplateTest()
await setBody('Review {{#url#}}')
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ expect(
+ screen.queryByText(`workflow.nodes.humanInputV2.error.${error}`),
+ ).not.toBeInTheDocument()
if (action === 'test') {
await sendTest(user)
expect(
@@ -724,6 +736,31 @@ describe('Human Input v2 Message Template', () => {
},
)
+ it('associates test validation with its field and opts secrets out of password saving', async () => {
+ const user = userEvent.setup()
+ renderTemplate({
+ value: { subject: 'Subject', body: '{{#start.secret#}} {{#url#}}' },
+ availableVars: [
+ { nodeId: 'start', title: 'Start', vars: [{ variable: 'secret', type: VarType.secret }] },
+ ],
+ })
+ await openTest(user)
+ const secret = screen.getByLabelText('start.secret')
+ expect(secret).toHaveAttribute('type', 'password')
+ expect(secret).toHaveAttribute('autocomplete', 'new-password')
+ await sendTest(user)
+ expect(secret).toHaveAttribute('aria-invalid', 'true')
+ expect(secret).toHaveAccessibleDescription(
+ 'workflow.nodes.humanInputV2.template.testInputsRequired',
+ )
+ await waitFor(() => expect(secret).toHaveFocus())
+ await user.type(secret, 'test-value')
+ expect(secret).toHaveAttribute('aria-invalid', 'false')
+ expect(
+ screen.queryByText('workflow.nodes.humanInputV2.template.testInputsRequired'),
+ ).not.toBeInTheDocument()
+ })
+
it('keeps one request in flight when the send button is double-clicked', async () => {
const user = userEvent.setup()
const request = createDeferred<MessageTemplateTestResponse>()
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/node.spec.tsx
index dc0a2c2b341..2f97f7d7b1c 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/node.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/node.spec.tsx
@@ -1,9 +1,9 @@
import type { HumanInputV2NodeType } from '../types'
-import { render, screen } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import { BlockEnum } from '@/app/components/workflow/types'
import { UserActionButtonType } from '../../human-input/shared/types'
import { HumanInputV2Node } from '../node'
-import { mockContactRecipientOptionProvider } from './fixtures/contact-provider'
+import { contactApi, renderContactOwner as render, resetContactApi } from './fixtures/contact-api'
const mockHitlIm = vi.hoisted(() => ({ enabled: true }))
@@ -14,17 +14,9 @@ vi.mock('@/config', async (importOriginal) => ({
},
}))
-vi.mock('../contact-provider', async (importOriginal) => {
- const { mockContactRecipientOptionProvider } = await import('./fixtures/contact-provider')
- const actual = await importOriginal<typeof import('../contact-provider')>()
- return {
- ...actual,
- useContactRecipientOptionProvider: () => ({
- provider: mockContactRecipientOptionProvider,
- workspaceId: 'workspace-1',
- }),
- }
-})
+vi.mock('@/service/console', async () => ({
+ consoleQuery: (await import('./fixtures/contact-api')).testConsoleQuery,
+}))
vi.mock('../../_base/components/node-handle', () => ({
NodeSourceHandle: (props: { handleId: string }) => <div>{`handle:${props.handleId}`}</div>,
@@ -49,6 +41,7 @@ const createData = (overrides: Partial<HumanInputV2NodeType> = {}): HumanInputV2
describe('Human Input v2 node card', () => {
beforeEach(() => {
mockHitlIm.enabled = true
+ resetContactApi()
})
it('renders the empty recipient warning and shared branch handles', () => {
@@ -98,7 +91,7 @@ describe('Human Input v2 node card', () => {
).toBeInTheDocument()
})
- it('renders deterministic overflow and unresolved states', () => {
+ it('renders deterministic overflow and unresolved states', async () => {
const { rerender } = render(
<HumanInputV2Node
id="human-input-v2"
@@ -122,7 +115,7 @@ describe('Human Input v2 node card', () => {
data={createData({ recipients_spec: [{ type: 'contact', contact_id: 'unresolved' }] })}
/>,
)
- expect(screen.getByText('workflow.nodes.humanInputV2.card.invalid')).toBeInTheDocument()
+ expect(await screen.findByText('workflow.nodes.humanInputV2.card.invalid')).toBeInTheDocument()
})
it('summarizes all workspace contacts distinctly from the initiator and preserves mixed recipients', () => {
@@ -158,7 +151,7 @@ describe('Human Input v2 node card', () => {
it('preserves stored v2 branches without resolving contacts or exposing recipient summaries while disabled', () => {
mockHitlIm.enabled = false
- const resolve = vi.spyOn(mockContactRecipientOptionProvider, 'resolve')
+ contactApi.batch.mockClear()
const data = createData({ recipients_spec: [{ type: 'contact', contact_id: 'stored-contact' }] })
const original = structuredClone(data)
render(<HumanInputV2Node id="human-input-v2" data={data} />)
@@ -167,7 +160,28 @@ it('preserves stored v2 branches without resolving contacts or exposing recipien
expect(screen.getByText('handle:approve')).toBeInTheDocument()
expect(screen.getByText('handle:__timeout')).toBeInTheDocument()
expect(screen.queryByText('workflow.nodes.humanInputV2.recipients.title')).not.toBeInTheDocument()
- expect(resolve).not.toHaveBeenCalled()
+ expect(contactApi.batch).not.toHaveBeenCalled()
expect(data).toEqual(original)
- resolve.mockRestore()
+})
+
+it('does not show a deleted-contact warning while the lookup is pending or rejected', async () => {
+ mockHitlIm.enabled = true
+ resetContactApi()
+ let reject!: (error: Error) => void
+ contactApi.batch.mockImplementation(
+ () =>
+ new Promise((_, fail) => {
+ reject = fail
+ }),
+ )
+ render(
+ <HumanInputV2Node
+ id="human-input-v2"
+ data={createData({ recipients_spec: [{ type: 'contact', contact_id: 'pending' }] })}
+ />,
+ )
+ await waitFor(() => expect(contactApi.batch).toHaveBeenCalled())
+ expect(screen.queryByText('workflow.nodes.humanInputV2.card.invalid')).not.toBeInTheDocument()
+ await act(async () => reject(new Error('offline')))
+ expect(screen.queryByText('workflow.nodes.humanInputV2.card.invalid')).not.toBeInTheDocument()
})
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-contact-preview.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-contact-preview.spec.tsx
new file mode 100644
index 00000000000..9ac9f8981f5
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-contact-preview.spec.tsx
@@ -0,0 +1,135 @@
+import type { ContactOption } from '@dify/contracts/api/console/workspaces/types.gen'
+import { render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useRef } from 'react'
+import { RecipientContactPreview } from '../components/recipient-contact-preview'
+import { contact, organizationContact } from './fixtures/contact-api'
+
+function Harness({ target }: { target?: ContactOption }) {
+ const inputRef = useRef<HTMLInputElement>(null)
+ return (
+ <>
+ <input ref={inputRef} aria-label="Recipients" />
+ <RecipientContactPreview contact={target} returnFocus={inputRef}>
+ <button type="button" disabled={!target}>
+ Contact details
+ </button>
+ </RecipientContactPreview>
+ </>
+ )
+}
+
+describe('recipient contact preview', () => {
+ it('shows each bound IM provider once alongside Email with an accessible channel name', async () => {
+ const user = userEvent.setup()
+ render(
+ <Harness
+ target={{
+ ...contact,
+ im_providers: ['feishu', 'lark', 'slack', 'ding_talk', 'ms_teams', 'we_com', 'feishu'],
+ }}
+ />,
+ )
+ await user.click(screen.getByRole('button', { name: 'Contact details' }))
+ const dialog = await screen.findByRole('dialog', { name: contact.name })
+ const channels = within(dialog).getByRole('group', { name: 'contacts.details.channels' })
+ for (const name of [
+ 'contacts.directory.channel.email',
+ 'Feishu',
+ 'Lark',
+ 'Slack',
+ 'DingTalk',
+ 'Microsoft Teams',
+ 'WeCom',
+ ]) {
+ expect(within(channels).getByRole('img', { name })).toBeVisible()
+ }
+ expect(within(channels).getAllByRole('img')).toHaveLength(7)
+ })
+
+ it('shows a bound IM channel even when the contact has no email', async () => {
+ const user = userEvent.setup()
+ render(<Harness target={{ ...contact, email: null, im_providers: ['feishu'] }} />)
+ await user.click(screen.getByRole('button', { name: 'Contact details' }))
+ const dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(within(dialog).getByRole('img', { name: 'Feishu' })).toBeVisible()
+ expect(
+ within(dialog).queryByRole('img', { name: 'contacts.directory.channel.email' }),
+ ).not.toBeInTheDocument()
+ })
+
+ it('does not imply an IM binding for an email-only contact', async () => {
+ const user = userEvent.setup()
+ render(<Harness target={contact} />)
+ await user.click(screen.getByRole('button', { name: 'Contact details' }))
+ const dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(
+ within(dialog).getByRole('img', { name: 'contacts.directory.channel.email' }),
+ ).toBeVisible()
+ expect(within(dialog).getAllByRole('img')).toHaveLength(1)
+ expect(within(dialog).queryByRole('img', { name: 'Feishu' })).not.toBeInTheDocument()
+ })
+
+ it('does not display a channel when no email or IM provider is available', async () => {
+ const user = userEvent.setup()
+ render(<Harness target={{ ...contact, email: null }} />)
+ await user.click(screen.getByRole('button', { name: 'Contact details' }))
+ const dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(
+ within(dialog).queryByRole('group', { name: 'contacts.details.channels' }),
+ ).not.toBeInTheDocument()
+ expect(within(dialog).queryByRole('img')).not.toBeInTheDocument()
+ })
+
+ it('preserves the details trigger while its current contact becomes available or clears', async () => {
+ const user = userEvent.setup()
+ const { rerender } = render(<Harness />)
+ const trigger = screen.getByRole('button', { name: 'Contact details' })
+ expect(trigger).toBeDisabled()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+
+ rerender(<Harness target={contact} />)
+ expect(screen.getByRole('button', { name: 'Contact details' })).toBe(trigger)
+ await user.click(trigger)
+ expect(await screen.findByRole('dialog', { name: contact.name })).toBeVisible()
+
+ rerender(<Harness />)
+ expect(screen.getByRole('button', { name: 'Contact details' })).toBe(trigger)
+ expect(trigger).toBeDisabled()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('returns keyboard focus to the recipient input after closing details', async () => {
+ const user = userEvent.setup()
+ render(<Harness target={contact} />)
+ await user.tab()
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'Contact details' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(await screen.findByRole('dialog', { name: contact.name })).toBeVisible()
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(screen.getByRole('textbox', { name: 'Recipients' })).toHaveFocus()
+ })
+
+ it('keeps existing chip previews able to replace a conflicting contact', async () => {
+ const user = userEvent.setup()
+ const onReplace = vi.fn()
+ render(
+ <RecipientContactPreview
+ contact={organizationContact}
+ conflictingContact={contact}
+ onReplace={onReplace}
+ >
+ <button type="button">Contact details</button>
+ </RecipientContactPreview>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Contact details' }))
+ expect(await screen.findByRole('dialog', { name: organizationContact.name })).toBeVisible()
+ await user.click(
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.useThisInstead' }),
+ )
+ expect(onReplace).toHaveBeenCalledOnce()
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ })
+})
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-utils.spec.ts b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-utils.spec.ts
index 05e48417222..f37cc3c30d1 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-utils.spec.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipient-utils.spec.ts
@@ -6,7 +6,6 @@ import {
getRecipientCanonicalKey,
getRecipientValidationError,
hasDuplicateRecipients,
- removeRecipient,
replaceContactRecipient,
updateRecipient,
} from '../recipient-utils'
@@ -54,12 +53,6 @@ describe('Human Input v2 recipient utilities', () => {
expect(updateRecipient(added, 1, { type: 'contact', contact_id: 'contact-amanda' })[0]).toBe(
recipients[0],
)
- expect(removeRecipient(added, 2)).toEqual([
- recipients[0],
- recipients[1],
- recipients[3],
- added[4],
- ])
})
it.each([
@@ -142,7 +135,6 @@ describe('Human Input v2 recipient utilities', () => {
hasAllWorkspaceContacts: true,
hasInitiator: true,
})
- expect(removeRecipient(selected, 0)).toEqual([{ type: 'initiator' }])
})
it('locks only other contacts with the same normalized email', () => {
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients-keyboard.browser.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients-keyboard.browser.spec.tsx
new file mode 100644
index 00000000000..4b93850c411
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients-keyboard.browser.spec.tsx
@@ -0,0 +1,134 @@
+import type { HumanInputV2Recipient } from '../types'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { createStore, Provider } from 'jotai'
+import { queryClientAtom } from 'jotai-tanstack-query'
+import { useState } from 'react'
+import { useKeyPress } from 'reactflow'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { createTestQueryClient } from '@/test/query-client'
+import Recipients from '../components/recipients'
+import {
+ contact,
+ contactApi,
+ organizationContact,
+ resetContactApi,
+ testConsoleQuery,
+} from './fixtures/contact-api'
+
+vi.mock('@/service/console', async () => ({
+ consoleQuery: (await import('./fixtures/contact-api')).testConsoleQuery,
+}))
+vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
+ default: ({ trigger }: { trigger: React.ReactElement }) => trigger,
+}))
+
+function Harness({ observe }: { observe: (value: HumanInputV2Recipient[]) => void }) {
+ // React Flow installs this document-level listener for canvas panning, including when the
+ // recipient panel is outside the canvas. Happy DOM's simulated Space click misses its cancellation.
+ useKeyPress('Space')
+ const [value, setValue] = useState<HumanInputV2Recipient[]>([
+ { type: 'contact', contact_id: contact.id },
+ ])
+ return (
+ <Recipients
+ nodeId="hitl"
+ value={value}
+ readonly={false}
+ onChange={(next) => {
+ setValue(next)
+ observe(next)
+ }}
+ />
+ )
+}
+
+async function renderRecipients() {
+ const client = createTestQueryClient()
+ client.setQueryData(testConsoleQuery.workspaces.current.summary.get.queryKey(), {
+ id: 'workspace-1',
+ name: 'QA workspace',
+ role: 'owner',
+ plan: null,
+ credits: null,
+ })
+ const store = createStore()
+ store.set(queryClientAtom, client)
+ const observe = vi.fn()
+ await render(
+ <Provider store={store}>
+ <QueryClientProvider client={client}>
+ <Harness observe={observe} />
+ </QueryClientProvider>
+ </Provider>,
+ )
+ return { client, observe }
+}
+
+beforeEach(resetContactApi)
+
+it('preserves native contact-information activation against the canvas Space listener', async () => {
+ const { client, observe } = await renderRecipients()
+ const info = page.getByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ })
+ const dialog = page.getByRole('dialog', { name: contact.name })
+ await expect.element(info).toBeVisible()
+ info.element().focus()
+ await expect.element(info).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ await expect.element(dialog).toBeVisible()
+ await userEvent.keyboard('{Delete}{Backspace}')
+ expect(observe).not.toHaveBeenCalled()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(info).toHaveFocus()
+ await userEvent.keyboard('{Delete}{Backspace}')
+ expect(observe).not.toHaveBeenCalled()
+ await userEvent.keyboard(' ')
+ await expect.element(dialog).toBeVisible()
+ expect(observe).not.toHaveBeenCalled()
+ client.clear()
+})
+
+it('keeps footer details and the portalled replacement action operable with native Space', async () => {
+ contactApi.options.mockResolvedValue({
+ data: [contact, { ...organizationContact, email: contact.email }],
+ total: 2,
+ page: 1,
+ limit: 20,
+ })
+ const { client, observe } = await renderRecipients()
+ await page
+ .getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' })
+ .click()
+ const conflictingOption = page.getByRole('option', { name: /Amanda Lin/ })
+ await expect.element(conflictingOption).toBeVisible()
+ await userEvent.keyboard('{ArrowDown}')
+ await expect
+ .element(page.getByRole('combobox'))
+ .toHaveAttribute(
+ 'aria-activedescendant',
+ page.getByRole('option', { name: /Evan Zhang/ }).element().id,
+ )
+ await userEvent.keyboard('{ArrowDown}')
+ await expect
+ .element(page.getByRole('combobox'))
+ .toHaveAttribute('aria-activedescendant', conflictingOption.element().id)
+ await userEvent.tab()
+ await userEvent.tab()
+ const info = page.getByRole('button', { name: 'contacts.details.title' })
+ await expect.element(info).toHaveFocus()
+ await userEvent.keyboard(' ')
+ const dialog = page.getByRole('dialog', { name: organizationContact.name })
+ await expect.element(dialog).toBeVisible()
+ const replace = dialog.getByRole('button', {
+ name: 'workflow.nodes.humanInputV2.recipients.useThisInstead',
+ })
+ await expect.element(replace).toHaveFocus()
+ await userEvent.keyboard(' ')
+ expect(observe).toHaveBeenLastCalledWith([
+ { type: 'contact', contact_id: organizationContact.id },
+ ])
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(page.getByRole('combobox')).toHaveFocus()
+ client.clear()
+})
diff --git a/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients.spec.tsx
index c69bab4b988..fb5f81ddd67 100644
--- a/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/__tests__/recipients.spec.tsx
@@ -1,1659 +1,613 @@
-import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen'
-import type {
- CurrentWorkspaceSummaryResponse,
- ListContactOptionsResponse,
- ListContactsResponse,
-} from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ReactElement } from 'react'
-import type { ContactRecipientOption, ContactRecipientOptionProvider } from '../contact-provider'
import type { HumanInputV2Recipient } from '../types'
-import type { Node } from '@/app/components/workflow/types'
import { zGetFeaturesResponse } from '@dify/contracts/api/console/features/zod.gen'
-import { QueryClient } from '@tanstack/react-query'
+import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
-import {
- createEdge,
- createNode,
- createStartNode,
-} from '@/app/components/workflow/__tests__/fixtures'
-import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
-import { consoleQuery } from '@/service/console'
-import { seedModelProviderQueries } from '@/test/console/model-provider'
-import { createConsoleQueryWrapper } from '@/test/console/query-data'
-import { seedToolProviders } from '@/test/console/tool-providers'
-import { createTestQueryClient } from '@/test/query-client'
-import { renderWorkflowEditor } from '@/test/workflow-editor'
import Recipients from '../components/recipients'
-
-const runtimeApi = vi.hoisted(() => ({
- features: vi.fn<() => Promise<GetFeaturesResponse>>(),
- summary: vi.fn<() => Promise<CurrentWorkspaceSummaryResponse>>(),
- contacts:
- vi.fn<
- (input: {
- query: { group: 'workspace'; page: number; limit: number }
- }) => Promise<ListContactsResponse>
- >(),
- options: vi.fn<() => Promise<ListContactOptionsResponse>>(),
+import {
+ contact,
+ contactApi,
+ organizationContact,
+ renderContactOwner,
+ resetContactApi,
+} from './fixtures/contact-api'
+
+vi.mock('@/service/console', async () => ({
+ consoleQuery: (await import('./fixtures/contact-api')).testConsoleQuery,
}))
-
-vi.mock('@/service/console', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/service/console')>()
- const { withConsoleResponses } = await import('@/test/console/service-responses')
- return {
- ...actual,
- consoleQuery: withConsoleResponses(actual.consoleQuery, {
- 'features.get': runtimeApi.features,
- 'workspaces.current.humanInput.v2.contacts.get': runtimeApi.contacts,
- 'workspaces.current.humanInput.v2.contactOptions.get': runtimeApi.options,
- 'workspaces.current.summary.get': runtimeApi.summary,
- }),
- }
-})
-
-const createFeaturesFixture = (centrallyManaged?: boolean): GetFeaturesResponse => ({
- ...zGetFeaturesResponse.parse({}),
- ...(centrallyManaged === undefined ? {} : { im_centrally_managed: centrallyManaged }),
-})
-
-const contact: ContactRecipientOption = {
- id: 'contact-evan',
- name: 'Evan Zhang',
- email: '[email protected]',
- source: 'workspace',
-}
-
-const organizationContact: ContactRecipientOption = {
- id: 'contact-amanda',
- name: 'Amanda Lin',
- email: '[email protected]',
- source: 'organization',
-}
-
-const provider = (overrides: Partial<ContactRecipientOptionProvider> = {}) => ({
- search: vi.fn(async () => [contact]),
- resolve: vi.fn(async ({ contact_ids }: { contact_ids: string[] }) =>
- contact_ids.includes(contact.id) ? [contact] : [],
+vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({
+ default: ({
+ trigger,
+ onChange,
+ }: {
+ trigger: React.ReactElement
+ onChange: (value: string[]) => void
+ }) => (
+ <Popover>
+ <PopoverTrigger render={trigger} />
+ <PopoverContent>
+ <button type="button" onClick={() => onChange(['start', 'owner_email'])}>
+ Requester email
+ </button>
+ </PopoverContent>
+ </Popover>
),
- ...overrides,
-})
+}))
const Harness = ({
initial = [],
- optionProvider = provider(),
readonly = false,
- observe,
- availableNodes,
+ observe = () => {},
}: {
initial?: HumanInputV2Recipient[]
- optionProvider?: ContactRecipientOptionProvider
readonly?: boolean
observe?: (value: HumanInputV2Recipient[]) => void
- availableNodes?: Node[]
}) => {
const [value, setValue] = useState(initial)
return (
<Recipients
- nodeId="human-input-v2"
- value={value}
- provider={optionProvider}
- availableNodes={availableNodes}
+ nodeId="hitl"
readonly={readonly}
- onChange={(nextValue) => {
- setValue(nextValue)
- observe?.(nextValue)
+ value={value}
+ onChange={(next) => {
+ setValue(next)
+ observe(next)
}}
/>
)
}
-
-const startNode = createStartNode({
- id: 'start',
- data: {
- title: 'Start',
- variables: [
- {
- variable: 'owner_email',
- label: 'Owner email',
- type: InputVarType.textInput,
- required: false,
- },
- ],
- },
-})
-const recipientNode = createNode({
- id: 'human-input-v2',
- data: { title: 'Approval recipients', type: BlockEnum.HumanInput },
-})
-const prepareEditorQueryClient = (queryClient: QueryClient = createTestQueryClient()) => {
- createConsoleQueryWrapper({ queryClient })
- seedModelProviderQueries(queryClient)
- seedToolProviders(queryClient, {
- builtInTools: [],
- customTools: [],
- workflowTools: [],
- mcpTools: [],
- })
- queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
- // Start the real feature request before workflow-provider defaults are seeded to preserve pending and error scenarios.
- void queryClient.query(consoleQuery.features.get.queryOptions()).catch(() => undefined)
- return queryClient
-}
-const render = (ui: ReactElement, queryClient?: QueryClient) =>
- renderWorkflowEditor(ui, {
- queryClient: prepareEditorQueryClient(queryClient),
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
- nodes: [startNode, recipientNode],
- edges: [createEdge({ source: startNode.id, target: recipientNode.id })],
- })
-
-describe('Human Input v2 Recipients', () => {
- beforeEach(() => {
- runtimeApi.features.mockReset().mockResolvedValue(createFeaturesFixture(true))
- runtimeApi.contacts.mockResolvedValue({ data: [], total: 7, page: 1, limit: 1 })
- runtimeApi.options.mockResolvedValue({ data: [], total: 0, page: 1, limit: 20 })
- })
-
- it('shows the enterprise platform tab when workspace features explicitly enable centrally managed IM bindings', async () => {
- const user = userEvent.setup()
- render(<Harness />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
-
- await waitFor(() => expect(runtimeApi.features).toHaveBeenCalledOnce())
- expect(await screen.findByRole('tab', { name: 'contacts.type.platform' })).toBeInTheDocument()
- })
-
- it.each([false, undefined])(
- 'hides the enterprise platform tab when centrally managed IM bindings are %s and keeps the other sources usable',
- async (centrallyManaged) => {
- const user = userEvent.setup()
- runtimeApi.features.mockResolvedValue(createFeaturesFixture(centrallyManaged))
- const externalContact: ContactRecipientOption = {
- id: 'external-contact',
- name: 'External Reviewer',
- email: '[email protected]',
- source: 'external',
- }
- render(
- <Harness
- optionProvider={provider({
- search: vi.fn(async () => [contact, organizationContact, externalContact]),
- })}
- />,
- )
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- expect(screen.queryByRole('tab', { name: 'contacts.type.platform' })).not.toBeInTheDocument()
- expect(screen.getAllByRole('tab')).toHaveLength(3)
- expect(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.all',
- }),
- ).toHaveAttribute('aria-selected', 'true')
-
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
- }),
- )
- expect(
- screen.getByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'External Reviewer · [email protected]' }),
- ).not.toBeInTheDocument()
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.external',
- }),
- )
- expect(
- screen.getByRole('button', { name: 'External Reviewer · [email protected]' }),
- ).toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).not.toBeInTheDocument()
- },
+const openPicker = async (user: ReturnType<typeof userEvent.setup>) => {
+ await user.click(
+ await screen.findByRole('button', {
+ name: 'workflow.nodes.humanInputV2.recipients.addContact',
+ }),
)
+ return screen.findByRole('listbox')
+}
+const field = () => screen.getByRole('combobox')
+beforeEach(resetContactApi)
- it('keeps the enterprise platform tab hidden until the workspace feature request succeeds', async () => {
- const user = userEvent.setup()
- let finishFeatures: (features: GetFeaturesResponse) => void = () => undefined
- runtimeApi.features.mockImplementation(
- () =>
- new Promise((resolve) => {
- finishFeatures = resolve
- }),
- )
- render(<Harness />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- expect(screen.queryByRole('tab', { name: 'contacts.type.platform' })).not.toBeInTheDocument()
- expect(screen.getAllByRole('tab')).toHaveLength(3)
-
- await act(async () => {
- finishFeatures(createFeaturesFixture(true))
- })
- expect(await screen.findByRole('tab', { name: 'contacts.type.platform' })).toBeInTheDocument()
- })
-
- it('keeps the enterprise platform tab hidden when the workspace feature request fails', async () => {
+describe('recipient selection through generated queries', () => {
+ it('uses batch channel metadata after selecting a contact from search', async () => {
+ contactApi.batch.mockResolvedValue({ data: [{ ...contact, im_providers: ['feishu'] }] })
const user = userEvent.setup()
- const queryClient = createTestQueryClient()
- runtimeApi.features.mockRejectedValue(new Error('Features unavailable'))
- render(<Harness />, queryClient)
-
+ const observe = vi.fn()
+ renderContactOwner(<Harness observe={observe} />, 'editor')
+ await openPicker(user)
+ await user.click(await screen.findByRole('option', { name: /Evan Zhang/ }))
await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
+ await screen.findByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ }),
)
- await waitFor(() =>
- expect(queryClient.getQueryState(consoleQuery.features.get.queryKey())?.status).toBe('error'),
- )
-
- expect(screen.queryByRole('tab', { name: 'contacts.type.platform' })).not.toBeInTheDocument()
- expect(screen.getAllByRole('tab')).toHaveLength(3)
- expect(
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
+ const dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(await within(dialog).findByRole('img', { name: 'Feishu' })).toBeVisible()
+ expect(observe).toHaveBeenLastCalledWith([{ type: 'contact', contact_id: contact.id }])
+ expect(contactApi.contacts).not.toHaveBeenCalled()
})
- it('returns to all sources when centrally managed IM bindings are disabled without changing recipients', async () => {
+ it('restores selected contact channels through the editor-safe batch when details and the node reopen', async () => {
+ contactApi.batch.mockResolvedValue({ data: [{ ...contact, im_providers: ['feishu'] }] })
const user = userEvent.setup()
- const queryClient = createTestQueryClient()
const observe = vi.fn()
- render(
- <Harness
- initial={[{ type: 'contact', contact_id: organizationContact.id }]}
- observe={observe}
- optionProvider={provider({
- search: vi.fn(async () => [contact, organizationContact]),
- resolve: vi.fn(async () => [organizationContact]),
- })}
- />,
- queryClient,
- )
- const recipientLabel = await screen.findByRole('button', {
- name: 'Amanda Lin · [email protected]',
- })
+ const selected: HumanInputV2Recipient[] = [{ type: 'contact', contact_id: contact.id }]
+ const first = renderContactOwner(<Harness initial={selected} observe={observe} />, 'editor')
+ const info = await screen.findByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ })
+ await user.click(info)
+ let dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(within(dialog).getByRole('img', { name: 'Feishu' })).toBeVisible()
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(info)
+ dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(within(dialog).getByRole('img', { name: 'Feishu' })).toBeVisible()
+ first.unmount()
+ first.client.clear()
+
+ renderContactOwner(<Harness initial={selected} observe={observe} />, 'editor')
await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await user.click(await screen.findByRole('tab', { name: 'contacts.type.platform' }))
- expect(screen.getByRole('tab', { name: 'contacts.type.platform' })).toHaveAttribute(
- 'aria-selected',
- 'true',
- )
- expect(
- screen.queryByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).not.toBeInTheDocument()
-
- runtimeApi.features.mockResolvedValue(createFeaturesFixture(false))
- await act(async () => {
- await queryClient.invalidateQueries({ queryKey: consoleQuery.features.get.queryKey() })
- })
-
- await waitFor(() =>
- expect(screen.queryByRole('tab', { name: 'contacts.type.platform' })).not.toBeInTheDocument(),
+ await screen.findByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ }),
)
- expect(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.all',
- }),
- ).toHaveAttribute('aria-selected', 'true')
- expect(
- screen.getByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
- expect(recipientLabel).toBeInTheDocument()
+ dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(within(dialog).getByRole('img', { name: 'Feishu' })).toBeVisible()
+ expect(contactApi.batch).toHaveBeenCalledTimes(2)
+ expect(contactApi.options).not.toHaveBeenCalled()
+ expect(contactApi.contacts).not.toHaveBeenCalled()
expect(observe).not.toHaveBeenCalled()
})
- it('searches and selects real contacts directly from the main recipient input', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const optionProvider = provider()
- render(<Harness optionProvider={optionProvider} observe={observe} />)
-
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.type(input, 'Evan')
- expect(optionProvider.search).toHaveBeenLastCalledWith('Evan')
- expect(input).toHaveFocus()
- await user.click(await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' }))
-
+ it('adds a contact from a keyboard navigable listbox and removes the selected chip', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness observe={observe} />)
+ await openPicker(user)
+ await screen.findByRole('option', { name: /Evan Zhang/ })
+ await user.click(screen.getByRole('option', { name: /Evan Zhang/ }))
expect(observe).toHaveBeenLastCalledWith([{ type: 'contact', contact_id: contact.id }])
- expect(input).toHaveValue('')
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ await user.click(await screen.findByRole('button', { name: /recipients.remove.*Evan Zhang/ }))
+ expect(observe).toHaveBeenLastCalledWith([])
+ expect(field()).toHaveFocus()
})
- it.each(['Evan', '[email protected]'])(
- 'uses Enter to choose a matching contact before a one-time email: %s',
- async (query) => {
+ it.each([true, false])(
+ 'gates the platform source on authoritative features (%s)',
+ async (enabled) => {
+ contactApi.features.mockResolvedValue({
+ ...zGetFeaturesResponse.parse({}),
+ im_centrally_managed: enabled,
+ })
const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness observe={observe} />)
-
- await user.type(
- screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- query,
- )
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- await user.keyboard('{Enter}')
-
- expect(observe).toHaveBeenLastCalledWith([{ type: 'contact', contact_id: contact.id }])
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ renderContactOwner(<Harness />)
+ await openPicker(user)
+ await screen.findByRole('radio', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
+ })
+ await waitFor(() => expect(contactApi.features).toHaveBeenCalled())
+ expect(screen.queryByRole('radio', { name: 'contacts.type.platform' }) !== null).toBe(enabled)
},
)
- it('adds comma-separated emails atomically while preserving existing recipients', async () => {
+ it('does not fetch unbounded pages when a source has no matches in the current page', async () => {
+ contactApi.options.mockImplementation(async ({ query }) => ({
+ data: query.page === 1 ? [{ ...contact, type: 'external' as const }] : [contact],
+ total: 40,
+ page: query.page ?? 1,
+ limit: 20,
+ }))
const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'contact', contact_id: contact.id }]} observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- await user.type(input, '[email protected], [email protected]{Enter}')
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([
- { type: 'contact', contact_id: contact.id },
- { type: 'onetime_email', email: '[email protected]' },
- { type: 'onetime_email', email: '[email protected]' },
- ])
- expect(input).toHaveValue('')
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ renderContactOwner(<Harness />)
+ await openPicker(user)
+ await screen.findByRole('option', { name: /Evan Zhang/ })
+ await user.click(
+ screen.getByRole('radio', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
+ }),
+ )
+ expect(contactApi.options).toHaveBeenCalledTimes(1)
+ const more = screen.getByRole('button', { name: 'workflow.common.loadMore' })
+ await user.click(more)
+ expect(await screen.findByRole('option', { name: /Evan Zhang/ })).toBeVisible()
+ await waitFor(() => expect(more).toHaveAttribute('aria-disabled', 'true'))
+ expect(more).toHaveFocus()
+ expect(contactApi.options).toHaveBeenCalledTimes(2)
})
- it.each([
- '[email protected], invalid',
- ])(
- 'keeps the entire comma-separated draft when an email is invalid or duplicated: %s',
- async (draft) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- initial={[{ type: 'onetime_email', email: '[email protected]' }]}
- observe={observe}
- />,
- )
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
+ it('searches remotely without reusing stale results for a new query', async () => {
+ const user = userEvent.setup()
+ contactApi.options.mockImplementation(async ({ query }) => ({
+ data: query.keyword?.includes('amanda') ? [organizationContact] : [contact],
+ total: 1,
+ page: 1,
+ limit: 20,
+ }))
+ renderContactOwner(<Harness />)
+ await user.type(await screen.findByRole('combobox'), 'amanda')
+ expect(await screen.findByRole('option', { name: /Amanda Lin/ })).toBeVisible()
+ expect(screen.queryByRole('option', { name: /Evan Zhang/ })).not.toBeInTheDocument()
+ expect(
+ contactApi.options.mock.calls.every(
+ ([input]) => !input.query.keyword || input.query.keyword === 'amanda',
+ ),
+ ).toBe(true)
+ })
- await user.type(input, draft)
+ it('keeps the picker recoverable after a failed search', async () => {
+ const user = userEvent.setup()
+ contactApi.options.mockRejectedValueOnce(new Error('unavailable'))
+ renderContactOwner(<Harness />)
+ await openPicker(user)
+ await user.click(await screen.findByRole('button', { name: 'common.operation.retry' }))
+ expect(await screen.findByRole('option', { name: /Evan Zhang/ })).toBeVisible()
+ })
+
+ 'adds valid one-time email input %s',
+ async (input) => {
+ contactApi.options.mockResolvedValue({ data: [], total: 0, page: 1, limit: 20 })
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness observe={observe} />)
+ await user.type(await screen.findByRole('combobox'), input)
await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addEmail' }),
+ await screen.findByRole('button', {
+ name: 'workflow.nodes.humanInputV2.recipients.addEmail',
+ }),
)
-
- expect(screen.getByRole('alert')).toHaveTextContent(
- 'workflow.nodes.humanInputV2.recipients.emailInvalidOrDuplicate',
+ expect(observe).toHaveBeenLastCalledWith(
+ input.split(',').map((email) => ({ type: 'onetime_email', email: email.trim() })),
)
- expect(input).toHaveValue(draft)
- expect(observe).not.toHaveBeenCalled()
+ await waitFor(() => expect(field()).toHaveFocus())
},
)
- it.each(['Enter', 'add button'])(
- 'rejects a malformed one-time email through %s without changing recipients',
- async (entry) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- const email = '[email protected]'
-
- await user.type(input, email)
- if (entry === 'Enter') await user.keyboard('{Enter}')
- else
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addEmail' }),
- )
-
- expect(input).toHaveValue(email)
- expect(input).toHaveAttribute('aria-invalid', 'true')
- expect(screen.getByRole('alert')).toHaveTextContent(
+ 'rejects invalid or duplicated email input %s',
+ async (input) => {
+ contactApi.options.mockResolvedValue({ data: [], total: 0, page: 1, limit: 20 })
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness observe={observe} />)
+ await user.type(await screen.findByRole('combobox'), input)
+ await user.click(
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addEmail' }),
+ )
+ expect(await screen.findByRole('alert')).toHaveTextContent(
'workflow.nodes.humanInputV2.recipients.emailInvalidOrDuplicate',
)
+ expect(field()).toHaveAttribute('aria-invalid', 'true')
expect(observe).not.toHaveBeenCalled()
},
)
- it('opens variable insertion with slash only from an empty non-composing recipient input', async () => {
- const user = userEvent.setup()
+ it('ignores Enter while Safari reports an unfinished composition', async () => {
const observe = vi.fn()
- render(<Harness observe={observe} availableNodes={[startNode]} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- await user.type(input, 'draft/')
- expect(screen.queryByText('owner_email')).not.toBeInTheDocument()
- await user.clear(input)
- fireEvent.keyDown(input, { key: '/', isComposing: true })
- expect(screen.queryByText('owner_email')).not.toBeInTheDocument()
+ renderContactOwner(<Harness observe={observe} />)
+ const input = await screen.findByRole('combobox')
+ fireEvent.change(input, { target: { value: '[email protected]' } })
+ fireEvent.keyDown(input, { key: 'Enter', keyCode: 229 })
+ expect(observe).not.toHaveBeenCalled()
+ })
+ it('opens variable selection with slash and preserves other recipient types', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
+ await user.click(await screen.findByRole('combobox'))
await user.keyboard('/')
- expect(input).toHaveValue('')
- await user.click(await screen.findByText('owner_email'))
- expect(observe).toHaveBeenCalledExactlyOnceWith([
+ await user.click(await screen.findByRole('button', { name: 'Requester email' }))
+ expect(observe).toHaveBeenLastCalledWith([
+ { type: 'initiator' },
{ type: 'dynamic_email', selector: ['start', 'owner_email'] },
])
- expect(screen.getByText('Start')).toBeInTheDocument()
- expect(screen.getByText('owner_email')).toBeInTheDocument()
})
- it('does not add a previous search result when Enter is pressed after clearing the input', async () => {
+ it('opens highlighted contact details by keyboard and returns focus to the input', async () => {
const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- await user.type(input, 'Evan')
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- await user.clear(input)
+ renderContactOwner(<Harness />)
+ await openPicker(user)
+ await screen.findByRole('option', { name: /Evan Zhang/ })
+ await user.keyboard('{ArrowDown}')
+ await user.tab()
+ expect(
+ screen.getByRole('button', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSourceLabel',
+ }),
+ ).toHaveFocus()
+ await user.tab()
+ const info = screen.getByRole('button', { name: 'contacts.details.title' })
+ expect(info).toHaveFocus()
+ expect(info).toHaveAccessibleDescription(/Evan Zhang/)
await user.keyboard('{Enter}')
+ const dialog = await screen.findByRole('dialog')
+ expect(within(dialog).getByText(contact.email)).toBeVisible()
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(field()).toHaveFocus())
+ })
- expect(observe).not.toHaveBeenCalled()
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ it('does not retain another contact as the preview target when highlighting a special recipient', async () => {
+ const user = userEvent.setup()
+ renderContactOwner(<Harness />)
+ await openPicker(user)
+ await screen.findByRole('option', { name: /Evan Zhang/ })
+ await user.keyboard('{ArrowDown}{ArrowDown}{ArrowDown}')
+ const initiator = screen.getByRole('option', {
+ name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
+ })
+ expect(field()).toHaveAttribute('aria-activedescendant', initiator.id)
+ await user.tab()
+ const info = screen.getByRole('button', { name: 'contacts.details.title' })
+ expect(info).toHaveAttribute('aria-disabled', 'true')
+ expect(info).not.toHaveAccessibleDescription(/Evan Zhang|Amanda Lin/)
})
- it('only selects a result from the active source filter when Enter is pressed in the main input', async () => {
+ it('clears contact details when keyboard navigation returns to an initiator chip', async () => {
const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- observe={observe}
- optionProvider={provider({ search: vi.fn(async () => [contact, organizationContact]) })}
- />,
+ renderContactOwner(
+ <Harness initial={[{ type: 'contact', contact_id: contact.id }, { type: 'initiator' }]} />,
)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.type(input, 'a')
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- await user.click(
- screen.getByRole('tab', {
- name: 'contacts.type.platform',
+ await openPicker(user)
+ await screen.findByRole('option', { name: /Amanda Lin/ })
+ await user.keyboard('{ArrowDown}{Escape}{ArrowLeft}')
+ const info = screen.getByRole('button', { name: 'contacts.details.title' })
+ expect(info).toHaveAttribute('aria-disabled', 'true')
+ expect(info).not.toHaveAccessibleDescription(/Evan Zhang|Amanda Lin/)
+ })
+
+ it('allows keyboard access to source filters without entering the result list', async () => {
+ const user = userEvent.setup()
+ renderContactOwner(<Harness />)
+ const source = await screen.findByRole('button', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSourceLabel',
+ })
+ source.focus()
+ await user.keyboard('{Enter}')
+ const all = await screen.findByRole('radio', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSource.all',
+ })
+ all.focus()
+ await user.keyboard('{ArrowRight}')
+ expect(
+ screen.getByRole('radio', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
}),
- )
+ ).toHaveAttribute('aria-checked', 'true')
+ await user.keyboard('{Escape}')
+ await openPicker(user)
expect(
- screen.queryByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).not.toBeInTheDocument()
- act(() => input.focus())
- await user.keyboard('{Enter}')
-
- expect(observe).toHaveBeenLastCalledWith([
- { type: 'contact', contact_id: organizationContact.id },
- ])
+ screen.getByRole('radio', {
+ name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
+ }),
+ ).toHaveAttribute('aria-checked', 'true')
})
- it('keeps the selected contact label while pending but removes it when the server cannot resolve it', async () => {
- const user = userEvent.setup()
- let finishResolve: (options: ContactRecipientOption[]) => void = () => undefined
- const resolve = vi.fn(
+ it('keeps configured contact chips neutral while lookup is pending or fails', async () => {
+ let fail!: (error: Error) => void
+ const observe = vi.fn()
+ const contactId = '01a18af0-7d52-795b-b6a0-b96bdd8a119f'
+ contactApi.batch.mockImplementation(
() =>
- new Promise<ContactRecipientOption[]>((finish) => {
- finishResolve = finish
+ new Promise((_, reject) => {
+ fail = reject
}),
)
- render(<Harness optionProvider={provider({ resolve })} />)
- await user.type(
- screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- 'Evan',
+ renderContactOwner(
+ <Harness initial={[{ type: 'contact', contact_id: contactId }]} observe={observe} />,
)
- await user.click(await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' }))
-
+ await waitFor(() => expect(contactApi.batch).toHaveBeenCalled())
+ const pendingChip = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.loading')
+ expect(pendingChip).not.toHaveAttribute('aria-invalid', 'true')
+ expect(pendingChip).toHaveAccessibleDescription(contactId)
+ expect(within(pendingChip).getByText(contactId)).toHaveClass('sr-only')
expect(
- screen.getByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
- expect(screen.queryByText(contact.id)).not.toBeInTheDocument()
- await act(async () => finishResolve([]))
+ screen.queryByText('workflow.nodes.humanInputV2.error.recipientInvalid'),
+ ).not.toBeInTheDocument()
+ await act(async () => fail(new Error('offline')))
+ const failedChip = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.loadError')
+ expect(failedChip).not.toHaveAttribute('aria-invalid', 'true')
+ expect(failedChip).toHaveAccessibleDescription(contactId)
+ expect(within(failedChip).getByText(contactId)).toHaveClass('sr-only')
expect(
- screen.queryByRole('button', { name: 'Evan Zhang · [email protected]' }),
+ screen.queryByText('workflow.nodes.humanInputV2.error.recipientInvalid'),
).not.toBeInTheDocument()
- expect(screen.getByText(contact.id)).toBeInTheDocument()
+ expect(observe).not.toHaveBeenCalled()
})
- it('discards a previously resolved contact after a later successful response omits it', async () => {
- const resolve = vi.fn().mockResolvedValueOnce([contact]).mockResolvedValueOnce([])
- const optionProvider = provider({ resolve })
- const recipients: HumanInputV2Recipient[] = [{ type: 'contact', contact_id: contact.id }]
- const { rerender } = render(
- <Recipients
- nodeId="human-input-v2"
- value={recipients}
- provider={optionProvider}
- readonly={false}
- onChange={vi.fn()}
- />,
- )
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
-
- rerender(
- <Recipients
- nodeId="human-input-v2"
- value={[...recipients, { type: 'initiator' }]}
- provider={optionProvider}
- readonly={false}
- onChange={vi.fn()}
- />,
- )
-
- await waitFor(() =>
- expect(
- screen.queryByRole('button', {
- name: 'Evan Zhang · [email protected]',
- }),
- ).not.toBeInTheDocument(),
+ it('marks an authoritatively deleted contact invalid without dropping the configured recipient', async () => {
+ const observe = vi.fn()
+ contactApi.batch.mockResolvedValue({ data: [] })
+ renderContactOwner(
+ <Harness initial={[{ type: 'contact', contact_id: 'deleted' }]} observe={observe} />,
)
- expect(screen.getByText(contact.id)).toBeInTheDocument()
+ expect(
+ await screen.findByText('workflow.nodes.humanInputV2.error.recipientInvalid'),
+ ).toBeInTheDocument()
+ const deletedChip = screen.getByLabelText('contacts.details.notFound')
+ expect(deletedChip).toHaveAttribute('aria-invalid', 'true')
+ expect(deletedChip).toHaveAccessibleDescription(/deleted/)
+ expect(observe).not.toHaveBeenCalled()
})
- it('does not select a recipient while confirming an IME composition', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.type(input, 'Evan')
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
+ it.each(['owner', 'editor'] as const)(
+ 'only queries the manager contact count for %s',
+ async (role) => {
+ const user = userEvent.setup()
+ renderContactOwner(<Harness />, role)
+ await openPicker(user)
+ await screen.findByRole('option', { name: 'QA workspace' })
+ if (role === 'owner') await waitFor(() => expect(contactApi.contacts).toHaveBeenCalled())
+ else expect(contactApi.contacts).not.toHaveBeenCalled()
+ },
+ )
- fireEvent.keyDown(input, { key: 'Enter', isComposing: true })
- expect(observe).not.toHaveBeenCalled()
- expect(input).toHaveValue('Evan')
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ it('preserves readonly recipients without editable actions', async () => {
+ renderContactOwner(<Harness initial={[{ type: 'contact', contact_id: contact.id }]} readonly />)
+ expect(await screen.findByText(contact.name)).toBeInTheDocument()
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /recipients.remove/ })).not.toBeInTheDocument()
+ expect(contactApi.options).not.toHaveBeenCalled()
})
+})
+
+describe('recipient keyboard editing preserves existing behavior', () => {
+ it.each(['{Enter}', ' '])(
+ 'opens a selected contact information button with %s without editing recipients',
+ async (key) => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
+ <Harness initial={[{ type: 'contact', contact_id: contact.id }]} observe={observe} />,
+ )
+ const info = await screen.findByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ })
+ info.focus()
+ await user.keyboard(key)
+ const dialog = await screen.findByRole('dialog', { name: contact.name })
+ expect(within(dialog).getByText(contact.email)).toBeVisible()
+ expect(dialog).toHaveFocus()
+ await user.keyboard('{Delete}{Backspace}')
+ expect(observe).not.toHaveBeenCalled()
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(info).toHaveFocus()
+ expect(observe).not.toHaveBeenCalled()
+ },
+ )
- it('displays and updates the node title for a dynamic recipient instead of its internal id', () => {
- const source: Node = {
- id: 'node-17290001',
- position: { x: 0, y: 0 },
- data: { type: BlockEnum.Start, title: 'Request details', desc: '' },
- }
- const initial: HumanInputV2Recipient[] = [
- { type: 'dynamic_email', selector: [source.id, 'owner_email'] },
- ]
- const { rerender } = render(<Harness initial={initial} availableNodes={[source]} readonly />)
+ it.each(['{Delete}', '{Backspace}'])(
+ '%s on a contact information button cannot remove its recipient',
+ async (key) => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
+ <Harness initial={[{ type: 'contact', contact_id: contact.id }]} observe={observe} />,
+ )
+ const info = await screen.findByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ })
+ info.focus()
+ await user.keyboard(key)
+ expect(observe).not.toHaveBeenCalled()
+ expect(info).toHaveFocus()
+ },
+ )
- expect(screen.getByText('Request details')).toBeInTheDocument()
- expect(screen.getByText('owner_email')).toBeInTheDocument()
- expect(screen.queryByText(/node-17290001/)).not.toBeInTheDocument()
- rerender(
+ it('keeps selected contact information keyboard accessible in readonly mode', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
<Harness
- initial={initial}
- availableNodes={[{ ...source, data: { ...source.data, title: 'Requester' } }]}
+ initial={[{ type: 'contact', contact_id: contact.id }]}
+ observe={observe}
readonly
/>,
)
- expect(screen.getByText('Requester')).toBeInTheDocument()
- expect(screen.queryByText('Request details')).not.toBeInTheDocument()
+ const info = await screen.findByRole('button', { name: /recipients.contactInfo.*Evan Zhang/ })
+ info.focus()
+ await user.keyboard('{Enter}')
+ expect(await screen.findByRole('dialog', { name: contact.name })).toBeVisible()
+ await user.keyboard('{Delete}{Backspace}{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(info).toHaveFocus()
+ expect(observe).not.toHaveBeenCalled()
})
- it.each(['owner', 'editor'] as const)(
- 'shows the actual workspace and respects the %s permission boundary for its contact count',
- async (role) => {
- const user = userEvent.setup()
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(consoleQuery.workspaces.current.summary.get.queryKey(), {
- id: 'workspace-current',
- name: 'Actual workspace',
- role,
- plan: null,
- credits: null,
- } satisfies CurrentWorkspaceSummaryResponse)
- render(
- <Recipients nodeId="runtime-node" value={[]} onChange={vi.fn()} readonly={false} />,
- queryClient,
- )
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
+ it.each(['{Delete}', '{Backspace}'])(
+ 'retains chip arrow navigation and %s removal outside information controls',
+ async (key) => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
+ <Harness
+ initial={[
+ { type: 'contact', contact_id: contact.id },
+ { type: 'initiator' },
+ { type: 'onetime_email', email: '[email protected]' },
+ ]}
+ observe={observe}
+ />,
)
- const workspaceOption = await screen.findByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.allWorkspaceContacts',
- })
- expect(workspaceOption).toHaveTextContent('Actual workspace')
- if (role === 'owner') {
- expect(await within(workspaceOption).findByText('7')).toBeInTheDocument()
- expect(runtimeApi.contacts.mock.calls[0]?.[0]).toEqual({
- query: { group: 'workspace', page: 1, limit: 1 },
- })
- } else {
- expect(runtimeApi.contacts).not.toHaveBeenCalled()
- expect(within(workspaceOption).queryByText('7')).not.toBeInTheDocument()
- }
+ await screen.findByText(contact.name)
+ await user.click(field())
+ await user.keyboard('{Escape}{ArrowLeft}')
+ expect(screen.getByLabelText('[email protected]', { selector: 'div' })).toHaveFocus()
+ await user.keyboard('{ArrowLeft}')
+ expect(
+ screen.getByLabelText('workflow.nodes.humanInputV2.recipients.type.initiator', {
+ selector: 'div',
+ }),
+ ).toHaveFocus()
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByLabelText('[email protected]', { selector: 'div' })).toHaveFocus()
+ await user.keyboard(key)
+ expect(observe).toHaveBeenLastCalledWith([
+ { type: 'contact', contact_id: contact.id },
+ { type: 'initiator' },
+ ])
},
)
- it('discloses the full selected contact on hover and keyboard activation without changing readonly recipients', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
+ it('does not clear configured recipients with Escape, whether the popup is open or closed', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
<Harness
- initial={[{ type: 'contact', contact_id: contact.id }]}
- readonly
+ initial={[{ type: 'initiator' }, { type: 'onetime_email', email: '[email protected]' }]}
observe={observe}
/>,
)
-
- const trigger = await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- await user.hover(trigger)
- const preview = await screen.findByRole('dialog', { name: contact.name })
- expect(within(preview).getByText(contact.email)).toBeInTheDocument()
- expect(
- within(preview).getByText('workflow.nodes.humanInputV2.recipients.contactSource.workspace'),
- ).toBeInTheDocument()
+ await user.click(await screen.findByRole('combobox'))
+ await user.keyboard('{Escape}')
await user.keyboard('{Escape}')
- await waitFor(() =>
- expect(screen.queryByRole('dialog', { name: contact.name })).not.toBeInTheDocument(),
- )
-
- act(() => trigger.focus())
- await user.keyboard('{Enter}')
- expect(await screen.findByRole('dialog', { name: contact.name })).toBeInTheDocument()
expect(observe).not.toHaveBeenCalled()
+ expect(
+ screen.getByRole('button', { name: /recipients.remove.*[email protected]/ }),
+ ).toBeInTheDocument()
})
- it('previews a contact without selecting it and preserves the picker selection action', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness observe={observe} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- const row = await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- await user.hover(row)
- expect(await screen.findByRole('dialog', { name: contact.name })).toHaveTextContent(
- contact.email,
+ it('Backspace in an empty input immediately removes only the preceding recipient', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
+ <Harness
+ initial={[{ type: 'initiator' }, { type: 'onetime_email', email: '[email protected]' }]}
+ observe={observe}
+ />,
)
+ await user.click(await screen.findByRole('combobox'))
+ await user.keyboard('{Backspace}')
+ expect(observe).toHaveBeenLastCalledWith([{ type: 'initiator' }])
+ expect(field()).toHaveFocus()
+ })
+
+ it('retains text while deleting a character instead of deleting a recipient', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
+ await user.type(await screen.findByRole('combobox'), 'ab')
+ await user.keyboard('{Backspace}')
+ expect(field()).toHaveValue('a')
expect(observe).not.toHaveBeenCalled()
+ })
- await user.click(row)
+ it('selects the first matching contact on Enter without requiring a pointer click', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness observe={observe} />)
+ await user.type(await screen.findByRole('combobox'), 'Evan')
+ await screen.findByRole('option', { name: /Evan Zhang/ })
+ await user.keyboard('{Enter}')
expect(observe).toHaveBeenLastCalledWith([{ type: 'contact', contact_id: contact.id }])
- await waitFor(() =>
- expect(screen.queryByRole('dialog', { name: contact.name })).not.toBeInTheDocument(),
- )
})
- it('loads later contact pages without losing already loaded recipients', async () => {
- const user = userEvent.setup()
- const searchPage = vi
- .fn()
- .mockResolvedValueOnce({ data: [contact], page: 1, hasMore: true })
- .mockResolvedValueOnce({ data: [organizationContact], page: 2, hasMore: false })
- render(<Harness optionProvider={provider({ searchPage })} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- expect(await screen.findByText('Evan Zhang')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'workflow.common.loadMore' }))
-
- expect(await screen.findByText('Amanda Lin')).toBeInTheDocument()
- expect(screen.getByText('Evan Zhang')).toBeInTheDocument()
- expect(searchPage).toHaveBeenLastCalledWith('', 2)
- expect(
- screen.queryByRole('button', { name: 'workflow.common.loadMore' }),
- ).not.toBeInTheDocument()
- })
-
- it('finds workspace contacts beyond a full external page when switching source tabs', async () => {
- const user = userEvent.setup()
- const externalContacts: ContactRecipientOption[] = Array.from({ length: 20 }, (_, index) => ({
- id: `external-${index}`,
- name: `External ${index}`,
- email: `external-${index}@example.com`,
- source: 'external',
- }))
- const searchPage = vi
- .fn()
- .mockResolvedValueOnce({ data: externalContacts, page: 1, hasMore: true })
- .mockResolvedValueOnce({ data: [contact], page: 2, hasMore: false })
- render(<Harness optionProvider={provider({ searchPage })} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await screen.findByRole('button', { name: 'External 0 · [email protected]' })
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
- }),
- )
-
- expect(
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
- expect(searchPage).toHaveBeenLastCalledWith('', 2)
- expect(
- screen.queryByRole('button', { name: 'workflow.common.loadMore' }),
- ).not.toBeInTheDocument()
- })
-
- it('keeps loaded sources and manual pagination after finding a filtered contact', async () => {
- const user = userEvent.setup()
- const laterContact = {
- ...contact,
- id: 'contact-jane',
- name: 'Jane Workspace',
- email: '[email protected]',
- }
- const searchPage = vi
- .fn()
- .mockResolvedValueOnce({ data: [organizationContact], page: 1, hasMore: true })
- .mockResolvedValueOnce({ data: [contact], page: 2, hasMore: true })
- .mockResolvedValueOnce({ data: [laterContact], page: 3, hasMore: false })
- render(<Harness optionProvider={provider({ searchPage })} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await screen.findByRole('button', { name: 'Amanda Lin · [email protected]' })
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
- }),
- )
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- expect(searchPage).toHaveBeenCalledTimes(2)
-
- await user.click(screen.getByRole('button', { name: 'workflow.common.loadMore' }))
- expect(
- await screen.findByRole('button', { name: 'Jane Workspace · [email protected]' }),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.all',
- }),
- )
- expect(
- screen.getByRole('button', { name: 'Amanda Lin · [email protected]' }),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'Jane Workspace · [email protected]' }),
- ).toBeInTheDocument()
- expect(searchPage).toHaveBeenLastCalledWith('', 3)
- })
-
- it('checks remaining pages before showing an empty source and lets failed pages retry', async () => {
- const user = userEvent.setup()
- const searchPage = vi
- .fn()
- .mockResolvedValueOnce({ data: [organizationContact], page: 1, hasMore: true })
- .mockRejectedValueOnce(new Error('Page unavailable'))
- .mockResolvedValueOnce({ data: [], page: 2, hasMore: true })
- .mockResolvedValueOnce({ data: [organizationContact], page: 3, hasMore: false })
- render(<Harness optionProvider={provider({ searchPage })} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await screen.findByRole('button', { name: 'Amanda Lin · [email protected]' })
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
- }),
- )
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'workflow.nodes.humanInputV2.recipients.loadError',
- )
- expect(searchPage).toHaveBeenCalledTimes(2)
- expect(
- screen.queryByText('workflow.nodes.humanInputV2.recipients.noResults'),
- ).not.toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'workflow.common.loadMore' }))
- expect(
- await screen.findByText('workflow.nodes.humanInputV2.recipients.noResults'),
- ).toBeInTheDocument()
- expect(searchPage.mock.calls.map(([, page]) => page)).toEqual([1, 2, 2, 3])
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'workflow.common.loadMore' }),
- ).not.toBeInTheDocument()
- })
-
- it('ignores an older filtered page after the search query changes', async () => {
- const user = userEvent.setup()
- let finishOldPage: (result: {
- data: ContactRecipientOption[]
- page: number
- hasMore: boolean
- }) => void = () => undefined
- const newContact = { ...contact, id: 'new-contact', name: 'Zoe Workspace' }
- const searchPage = vi.fn((query: string, page: number) => {
- if (query === 'Z') return Promise.resolve({ data: [newContact], page: 1, hasMore: false })
- if (page === 1)
- return Promise.resolve({ data: [organizationContact], page: 1, hasMore: true })
- return new Promise<{ data: ContactRecipientOption[]; page: number; hasMore: boolean }>(
- (resolve) => {
- finishOldPage = resolve
- },
- )
- })
- render(<Harness optionProvider={provider({ searchPage })} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await screen.findByRole('button', { name: 'Amanda Lin · [email protected]' })
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
- }),
- )
- await waitFor(() => expect(searchPage).toHaveBeenLastCalledWith('', 2))
- await user.type(
- screen.getByRole('textbox', { name: 'workflow.nodes.humanInputV2.recipients.search' }),
- 'Z',
- )
- expect(
- await screen.findByRole('button', { name: 'Zoe Workspace · [email protected]' }),
- ).toBeInTheDocument()
-
- await act(async () => {
- finishOldPage({ data: [contact], page: 2, hasMore: false })
- })
- expect(
- screen.getByRole('button', { name: 'Zoe Workspace · [email protected]' }),
- ).toBeInTheDocument()
+ it('does not commit an old search result when Enter is pressed during a new keyword debounce', async () => {
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(<Harness observe={observe} />)
+ await openPicker(user)
+ await screen.findByRole('option', { name: /Evan Zhang/ })
+ await user.type(field(), 'Amanda')
+ expect(screen.queryByRole('option', { name: /Evan Zhang/ })).not.toBeInTheDocument()
+ await user.keyboard('{Enter}')
+ expect(observe).not.toHaveBeenCalled()
expect(
- screen.queryByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).not.toBeInTheDocument()
- expect(searchPage).toHaveBeenLastCalledWith('Z', 1)
- })
-
- it('keeps the latest search results when an older response arrives last', async () => {
- const user = userEvent.setup()
- let finishInitial: (options: ContactRecipientOption[]) => void = () => undefined
- const search = vi
- .fn()
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finishInitial = resolve
- }),
- )
- .mockResolvedValue([organizationContact])
- render(<Harness optionProvider={provider({ search })} />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await user.type(
- screen.getByRole('textbox', { name: 'workflow.nodes.humanInputV2.recipients.search' }),
- 'Amanda',
- )
- expect(await screen.findByText('Amanda Lin')).toBeInTheDocument()
- await act(async () => {
- finishInitial([contact])
- })
-
- expect(screen.getByText('Amanda Lin')).toBeInTheDocument()
- expect(screen.queryByText('Evan Zhang')).not.toBeInTheDocument()
- })
-
- it('adds Contact, one-time email, Dynamic Email and Initiator in order', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness observe={observe} availableNodes={[startNode]} />)
-
- const emailInput = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.type(emailInput, '[email protected]{Enter}')
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await user.click(await screen.findByText('Evan Zhang'))
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.insertVariable' }),
- )
- await user.click(within(await screen.findByRole('dialog')).getByText('owner_email'))
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- await user.click(
- screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- }),
- )
-
- expect(observe).toHaveBeenLastCalledWith([
- { type: 'onetime_email', email: '[email protected]' },
- { type: 'contact', contact_id: 'contact-evan' },
- { type: 'dynamic_email', selector: ['start', 'owner_email'] },
- { type: 'initiator' },
- ])
- expect(screen.getByText('Start')).toBeInTheDocument()
- expect(screen.getByText('owner_email')).toBeInTheDocument()
- })
-
- describe('Recipient remove buttons', () => {
- it.each([
- { recipient: { type: 'contact', contact_id: contact.id }, label: 'Evan Zhang' },
- {
- recipient: { type: 'onetime_email', email: '[email protected]' },
- label: '[email protected]',
- },
- { recipient: { type: 'onetime_email', email: 'invalid-email' }, label: 'invalid-email' },
- { recipient: { type: 'dynamic_email', selector: ['start', 'email'] }, label: 'email' },
- { recipient: { type: 'initiator' }, label: 'recipients.type.initiator' },
- { recipient: { type: 'all_workspace_contacts' }, label: 'recipients.allWorkspaceContacts' },
- ] satisfies { recipient: HumanInputV2Recipient; label: string }[])(
- 'removes only the $recipient.type recipient through its named button',
- async ({ recipient, label }) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const retained: HumanInputV2Recipient = {
- type: 'onetime_email',
- email: '[email protected]',
- }
- render(<Harness initial={[recipient, retained]} observe={observe} />)
-
- await user.click(
- await screen.findByRole('button', { name: new RegExp(`recipients\\.remove.*${label}`) }),
- )
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([retained])
- expect(
- screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- ).toHaveFocus()
- expect(screen.queryByRole('dialog', { name: contact.name })).not.toBeInTheDocument()
- },
- )
-
- it('provides a separate removal button that works with touch without opening the contact preview', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'contact', contact_id: contact.id }]} observe={observe} />)
- const chip = await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- const remove = await screen.findByRole('button', { name: /recipients\.remove.*Evan Zhang/ })
- expect(chip).not.toContainElement(remove)
-
- await user.pointer([{ keys: '[TouchA>]', target: remove }, { keys: '[/TouchA]' }])
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([])
- expect(screen.queryByRole('dialog', { name: contact.name })).not.toBeInTheDocument()
- })
-
- it.each(['Backspace', 'Delete'])(
- 'consumes %s on a remove button before workflow shortcuts can process it',
- async (key) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const parentKeyDown = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const remove = screen.getByRole('button', { name: /recipients\.remove/ })
- act(() => remove.focus())
-
- document.addEventListener('keydown', parentKeyDown)
- try {
- await user.keyboard(`{${key}}`)
- } finally {
- document.removeEventListener('keydown', parentKeyDown)
- }
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([])
- expect(parentKeyDown).not.toHaveBeenCalled()
- expect(
- screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- ).toHaveFocus()
- },
- )
-
- it('removes only the chosen duplicate occurrence', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }, { type: 'initiator' }]} observe={observe} />)
-
- await user.click(screen.getAllByRole('button', { name: /recipients\.remove/ })[1]!)
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([{ type: 'initiator' }])
- })
-
- it('does not expose removal buttons for readonly recipients', async () => {
- render(
- <Harness
- readonly
- initial={[
- { type: 'contact', contact_id: contact.id },
- { type: 'onetime_email', email: '[email protected]' },
- { type: 'onetime_email', email: 'invalid-email' },
- { type: 'dynamic_email', selector: ['start', 'email'] },
- { type: 'initiator' },
- { type: 'all_workspace_contacts' },
- ]}
- />,
- )
-
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- expect(screen.queryByRole('button', { name: /recipients\.remove/ })).not.toBeInTheDocument()
- })
- })
-
- describe('Keyboard deletion of a focused recipient', () => {
- it.each(['Backspace', 'Delete'])(
- 'removes only the focused middle recipient with %s and returns focus to the input',
- async (key) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const parentKeyDown = vi.fn()
- const first: HumanInputV2Recipient = { type: 'initiator' }
- const last: HumanInputV2Recipient = { type: 'all_workspace_contacts' }
- render(
- <Harness
- initial={[first, { type: 'onetime_email', email: '[email protected]' }, last]}
- observe={observe}
- />,
- )
- const chip = screen.getByRole('button', { name: '[email protected]' })
- await user.click(chip)
- expect(chip).toHaveFocus()
- expect(observe).not.toHaveBeenCalled()
-
- document.addEventListener('keydown', parentKeyDown)
- try {
- await user.keyboard(`{${key}}`)
- } finally {
- document.removeEventListener('keydown', parentKeyDown)
- }
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([first, last])
- expect(parentKeyDown).not.toHaveBeenCalled()
- expect(
- screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- ).toHaveFocus()
- },
- )
-
- it.each([
- {
- recipient: { type: 'contact', contact_id: contact.id },
- label: 'Evan Zhang · [email protected]',
- },
- {
- recipient: { type: 'contact', contact_id: 'unresolved-contact' },
- label: 'unresolved-contact',
- },
- {
- recipient: { type: 'onetime_email', email: '[email protected]' },
- label: '[email protected]',
- },
- {
- recipient: { type: 'onetime_email', email: 'invalid-email' },
- label: 'invalid-email',
- },
- {
- recipient: { type: 'dynamic_email', selector: ['start', 'email'] },
- label: 'email',
- },
- {
- recipient: { type: 'initiator' },
- label: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- },
- {
- recipient: { type: 'all_workspace_contacts' },
- label: 'workflow.nodes.humanInputV2.recipients.allWorkspaceContacts',
- },
- ] satisfies { recipient: HumanInputV2Recipient; label: string }[])(
- 'selects $label without opening an editor and permits deleting that recipient',
- async ({ recipient, label }) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[recipient]} observe={observe} />)
- const chip = await screen.findByRole('button', { name: label })
-
- await user.click(chip)
-
- expect(chip).toHaveFocus()
- expect(
- screen.queryByRole('group', {
- name: 'workflow.nodes.humanInputV2.recipients.editRecipient',
- }),
- ).not.toBeInTheDocument()
- expect(screen.queryByRole('dialog', { name: contact.name })).not.toBeInTheDocument()
- expect(observe).not.toHaveBeenCalled()
-
- await user.keyboard('{Delete}')
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([])
- },
- )
-
- it.each(['altKey', 'ctrlKey', 'metaKey', 'shiftKey', 'isComposing'])(
- 'does not delete a focused recipient when %s handles the key',
- async (flag) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const chip = screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- })
- await user.click(chip)
-
- expect(fireEvent.keyDown(chip, { key: 'Delete', [flag]: true })).toBe(true)
- expect(observe).not.toHaveBeenCalled()
- expect(chip).toHaveFocus()
- },
- )
-
- it('consumes held-key repeats without deleting the focused recipient', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const parentKeyDown = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const chip = screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- })
- await user.click(chip)
-
- document.addEventListener('keydown', parentKeyDown)
- try {
- expect(fireEvent.keyDown(chip, { key: 'Delete', repeat: true })).toBe(false)
- } finally {
- document.removeEventListener('keydown', parentKeyDown)
- }
- expect(observe).not.toHaveBeenCalled()
- expect(parentKeyDown).not.toHaveBeenCalled()
-
- await user.keyboard('{Delete}')
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([])
- })
-
- it('leaves the previously focused chip intact when Delete is pressed in the main input', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- await user.click(
- screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- }),
- )
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.click(input)
- await user.keyboard('{Delete}')
-
- expect(observe).not.toHaveBeenCalled()
- expect(input).toHaveFocus()
- })
-
- it('removes one selected occurrence of an imported duplicate without clearing both', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }, { type: 'initiator' }]} observe={observe} />)
- const chips = screen.getAllByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- })
-
- await user.click(chips[1]!)
- await user.keyboard('{Delete}')
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([{ type: 'initiator' }])
- expect(
- screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- }),
- ).toBeInTheDocument()
- })
+ contactApi.options.mock.calls.every(
+ ([input]) => !input.query.keyword || input.query.keyword === 'Amanda',
+ ),
+ ).toBe(true)
})
- describe('Backspace in the main recipient input', () => {
- it.each([
- { type: 'contact', contact_id: contact.id },
- { type: 'onetime_email', email: '[email protected]' },
- { type: 'dynamic_email', selector: ['start', 'email'] },
- { type: 'initiator' },
- { type: 'all_workspace_contacts' },
- ] satisfies HumanInputV2Recipient[])(
- 'removes only the preceding $type recipient and keeps input focus',
- async (lastRecipient) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const firstRecipient: HumanInputV2Recipient = {
- type: 'onetime_email',
- email: '[email protected]',
- }
- render(<Harness initial={[firstRecipient, lastRecipient]} observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- await user.click(input)
- await user.keyboard('{Backspace}')
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([firstRecipient])
- expect(input).toHaveFocus()
- expect(input).toHaveValue('')
- },
- )
-
- it.each(['text', ' ', 'selected text'])(
- 'preserves recipients while Backspace deletes the input draft: %j',
- async (draft) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const input = screen.getByRole('textbox', {
- name: 'workflow.nodes.humanInputV2.recipients.placeholder',
- })
- await user.type(input, draft)
- if (draft === 'selected text') {
- act(() => {
- if (input instanceof HTMLInputElement) input.setSelectionRange(0, draft.length)
- })
- }
-
- await user.keyboard('{Backspace}')
-
- expect(input).toHaveValue(draft === 'selected text' ? '' : draft.slice(0, -1))
- expect(observe).not.toHaveBeenCalled()
- },
- )
-
- it.each(['ctrlKey', 'metaKey', 'altKey', 'shiftKey'])(
- 'leaves modified Backspace to the input when %s is held',
- (modifier) => {
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- expect(fireEvent.keyDown(input, { key: 'Backspace', [modifier]: true })).toBe(true)
- expect(observe).not.toHaveBeenCalled()
- },
- )
-
- it('does not delete recipients while an IME composition handles Backspace', () => {
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- expect(fireEvent.keyDown(input, { key: 'Backspace', isComposing: true })).toBe(true)
- expect(observe).not.toHaveBeenCalled()
- })
-
- it('consumes held-key repeats without deleting more recipients', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- initial={[{ type: 'initiator' }, { type: 'onetime_email', email: '[email protected]' }]}
- observe={observe}
- />,
- )
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.click(input)
- await user.keyboard('{Backspace}')
- expect(observe).toHaveBeenCalledExactlyOnceWith([{ type: 'initiator' }])
-
- expect(fireEvent.keyDown(input, { key: 'Backspace', repeat: true })).toBe(false)
- expect(observe).toHaveBeenCalledTimes(1)
- expect(input).toHaveFocus()
- await user.keyboard('{Backspace}')
- expect(observe).toHaveBeenLastCalledWith([])
- })
-
- it('keeps an empty recipient list unchanged', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
-
- await user.click(input)
- await user.keyboard('{Backspace}')
-
- expect(observe).not.toHaveBeenCalled()
- expect(input).toHaveFocus()
- })
-
- it('keeps focus in the main input after closing its search and deleting a recipient', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const input = screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder')
- await user.type(input, 'Evan')
- await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- await user.clear(input)
- await waitFor(() =>
- expect(
- screen.queryByRole('button', { name: 'Evan Zhang · [email protected]' }),
- ).not.toBeInTheDocument(),
- )
- expect(input).toHaveFocus()
-
- await user.keyboard('{Backspace}')
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([])
- expect(input).toHaveFocus()
- })
-
- it('does not remove recipients from the separate picker search', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- initial={[{ type: 'initiator' }, { type: 'onetime_email', email: '[email protected]' }]}
- observe={observe}
- />,
- )
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- const search = screen.getByRole('textbox', {
- name: 'workflow.nodes.humanInputV2.recipients.search',
- })
- await user.click(search)
- await user.keyboard('{Backspace}{Delete}{Escape}')
-
- expect(observe).not.toHaveBeenCalled()
+ it('replaces a conflicting source explicitly instead of adding the same email twice', async () => {
+ contactApi.options.mockResolvedValue({
+ data: [contact, { ...organizationContact, email: contact.email }],
+ total: 2,
+ page: 1,
+ limit: 20,
})
-
- it.each(['Backspace', 'Delete'])(
- 'does not expose a main input or remove readonly recipients with %s',
- async (key) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- initial={[{ type: 'contact', contact_id: contact.id }]}
- readonly
- observe={observe}
- />,
- )
- const chip = await screen.findByRole('button', { name: 'Evan Zhang · [email protected]' })
- expect(
- screen.queryByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- ).not.toBeInTheDocument()
- act(() => chip.focus())
- await user.keyboard(`{${key}}`)
-
- expect(observe).not.toHaveBeenCalled()
- expect(chip).toBeInTheDocument()
- },
- )
- })
-
- it.each([false, true])(
- 'explains an invalid imported email without changing the recipient (readonly=%s)',
- async (readonly) => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- initial={[{ type: 'onetime_email', email: 'invalid-email' }]}
- observe={observe}
- readonly={readonly}
- />,
- )
- const chip = screen.getByRole('button', { name: 'invalid-email' })
-
- await user.hover(chip)
- expect(
- await screen.findByText('workflow.nodes.humanInputV2.recipients.emailInvalidOrDuplicate'),
- ).toBeVisible()
- if (readonly) {
- await user.click(chip)
- expect(
- screen.queryByRole('group', {
- name: 'workflow.nodes.humanInputV2.recipients.editRecipient',
- }),
- ).not.toBeInTheDocument()
- }
- expect(observe).not.toHaveBeenCalled()
- },
- )
-
- it('limits initiator and whole-workspace choices to their designed source tabs', async () => {
- const user = userEvent.setup()
- render(<Harness />)
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- expect(
- screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- }),
- ).toBeInTheDocument()
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.workspace',
- }),
- )
- expect(
- screen.queryByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- }),
- ).not.toBeInTheDocument()
- expect(
- screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.allWorkspaceContacts',
- }),
- ).toBeInTheDocument()
-
- await user.click(
- screen.getByRole('tab', {
- name: 'workflow.nodes.humanInputV2.recipients.contactSource.external',
- }),
- )
- expect(
- screen.queryByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.type.initiator',
- }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.allWorkspaceContacts',
- }),
- ).not.toBeInTheDocument()
- })
-
- it('locks a different contact with a selected email and replaces only that contact from its preview', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- const sameEmailContact: ContactRecipientOption = {
- id: 'contact-beverly',
- name: 'Beverly',
- email: organizationContact.email.toUpperCase(),
- source: 'workspace',
- }
- render(
+ const user = userEvent.setup(),
+ observe = vi.fn()
+ renderContactOwner(
<Harness
- initial={[
- { type: 'onetime_email', email: '[email protected]' },
- { type: 'contact', contact_id: organizationContact.id },
- { type: 'initiator' },
- ]}
- optionProvider={provider({
- resolve: vi.fn(async () => [organizationContact]),
- search: vi.fn(async () => [organizationContact, sameEmailContact]),
- })}
+ initial={[{ type: 'initiator' }, { type: 'contact', contact_id: contact.id }]}
observe={observe}
/>,
)
-
- await screen.findByRole('button', { name: 'Amanda Lin · [email protected]' })
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- const candidate = await screen.findByRole('button', {
- name: 'Beverly · [email protected]',
- })
- expect(candidate).toHaveAttribute('aria-disabled', 'true')
- await user.hover(candidate)
- const preview = await screen.findByRole('dialog', { name: 'Beverly' })
- expect(within(preview).getByText(/recipients\.duplicateSource.*Amanda Lin/)).toBeInTheDocument()
- expect(
- within(preview).getByText('workflow.nodes.humanInputV2.recipients.emailAlreadySelected'),
- ).toBeInTheDocument()
- expect(observe).not.toHaveBeenCalled()
+ await waitFor(() => expect(contactApi.batch).toHaveBeenCalled())
+ await openPicker(user)
+ const row = await screen.findByRole('option', { name: /Amanda Lin/ })
+ expect(row).toHaveAttribute('aria-disabled', 'true')
+ await user.keyboard('{ArrowDown}')
+ await waitFor(() => expect(field()).toHaveAttribute('aria-activedescendant', row.id))
+ await user.tab()
+ await user.tab()
+ const info = screen.getByRole('button', { name: 'contacts.details.title' })
+ expect(info).toHaveFocus()
+ expect(info).toHaveAccessibleDescription(/Amanda Lin/)
+ await user.keyboard('{Enter}')
+ const dialog = await screen.findByRole('dialog', { name: organizationContact.name })
await user.click(
- within(preview).getByRole('button', {
+ within(dialog).getByRole('button', {
name: 'workflow.nodes.humanInputV2.recipients.useThisInstead',
}),
)
-
expect(observe).toHaveBeenLastCalledWith([
- { type: 'onetime_email', email: '[email protected]' },
- { type: 'contact', contact_id: sameEmailContact.id },
{ type: 'initiator' },
+ { type: 'contact', contact_id: organizationContact.id },
])
})
-
- it('prevents canonical email duplicates and preserves imported duplicate rows', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(
- <Harness
- initial={[
- { type: 'initiator' },
- { type: 'initiator' },
- { type: 'onetime_email', email: '[email protected]' },
- ]}
- observe={observe}
- />,
- )
-
- expect(screen.getAllByText('workflow.nodes.humanInputV2.error.recipientInvalid')).toHaveLength(
- 1,
- )
- await user.type(
- screen.getByLabelText('workflow.nodes.humanInputV2.recipients.placeholder'),
- '[email protected]{Enter}',
- )
- expect(screen.getByRole('alert')).toHaveTextContent(
- 'workflow.nodes.humanInputV2.recipients.emailInvalidOrDuplicate',
- )
- expect(observe).not.toHaveBeenCalled()
- })
-
- it('renders deterministic loading, empty and error provider states', async () => {
- const user = userEvent.setup()
- let resolveSearch: (value: ContactRecipientOption[]) => void = () => undefined
- const loadingProvider = provider({
- search: vi.fn(
- () =>
- new Promise<ContactRecipientOption[]>((resolve) => {
- resolveSearch = resolve
- }),
- ),
- })
- const { unmount } = render(<Harness optionProvider={loadingProvider} />)
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- expect(screen.getByRole('status')).toHaveTextContent(
- 'workflow.nodes.humanInputV2.recipients.loading',
- )
- resolveSearch([])
- expect(
- await screen.findByText('workflow.nodes.humanInputV2.recipients.noResults'),
- ).toBeInTheDocument()
- unmount()
-
- render(
- <Harness
- optionProvider={provider({ search: vi.fn(async () => Promise.reject(new Error('mock'))) })}
- />,
- )
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- expect(
- await screen.findByText('workflow.nodes.humanInputV2.recipients.loadError'),
- ).toBeInTheDocument()
- })
-
- it('filters Contact results with the Figma source tabs', async () => {
- const user = userEvent.setup()
- render(
- <Harness
- optionProvider={provider({
- search: vi.fn(async () => [contact, organizationContact]),
- })}
- />,
- )
-
- await user.click(
- screen.getByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- )
- expect(await screen.findByText('Evan Zhang')).toBeInTheDocument()
- await user.click(
- screen.getByRole('tab', {
- name: 'contacts.type.platform',
- }),
- )
-
- expect(screen.queryByText('Evan Zhang')).not.toBeInTheDocument()
- expect(screen.getByText('Amanda Lin')).toBeInTheDocument()
- })
-
- it('adds all workspace contacts once without changing existing recipients', async () => {
- const user = userEvent.setup()
- const observe = vi.fn()
- render(<Harness initial={[{ type: 'initiator' }]} observe={observe} />)
- const openPicker = screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.addContact',
- })
-
- await user.click(openPicker)
- await user.click(
- screen.getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.allWorkspaceContacts',
- }),
- )
-
- expect(observe).toHaveBeenCalledExactlyOnceWith([
- { type: 'initiator' },
- { type: 'all_workspace_contacts' },
- ])
- await user.click(openPicker)
- expect(
- within(screen.getByRole('dialog')).getByRole('button', {
- name: 'workflow.nodes.humanInputV2.recipients.allWorkspaceContacts',
- }),
- ).toBeDisabled()
- expect(observe).toHaveBeenCalledTimes(1)
- })
-
- it('resolves stored contacts and removes nothing in read-only mode', async () => {
- const observe = vi.fn()
- const optionProvider = provider()
- render(
- <Harness
- initial={[
- { type: 'contact', contact_id: 'contact-evan' },
- { type: 'contact', contact_id: 'contact-evan' },
- ]}
- optionProvider={optionProvider}
- observe={observe}
- readonly
- />,
- )
-
- await waitFor(() =>
- expect(screen.getAllByRole('button', { name: 'Evan Zhang · [email protected]' })).toHaveLength(
- 2,
- ),
- )
- expect(optionProvider.resolve).toHaveBeenCalledOnce()
- expect(optionProvider.resolve).toHaveBeenCalledWith({ contact_ids: ['contact-evan'] })
- expect(
- screen.queryByRole('button', { name: 'workflow.nodes.humanInputV2.recipients.addContact' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByLabelText(/workflow\.nodes\.humanInputV2\.recipients\.remove/),
- ).not.toBeInTheDocument()
- expect(observe).not.toHaveBeenCalled()
- })
})
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/debug-mode.tsx b/web/app/components/workflow/nodes/human-input-v2/components/debug-mode.tsx
index 870a2cc9a15..20120940ea0 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/debug-mode.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/debug-mode.tsx
@@ -3,21 +3,16 @@
import type { HumanInputV2DebugChannel, HumanInputV2DebugMode } from '../types'
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
-import { cn } from '@langgenius/dify-ui/cn'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { Switch } from '@langgenius/dify-ui/switch'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ContactChannelIcon } from '@/features/contacts/management/channel-icon'
import { isHumanInputV2DebugChannel } from '../types'
import useConfiguredChannels from '../use-configured-channels'
-// Original stripe background exported from Studio Figma node 25212:78484.
-const debugModeBackground =
- 'data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyMTkuMjQiIGhlaWdodD0iMTE1Ljk2NiIgdmlld0JveD0iMCAwIDEyMTkuMjQgMTE1Ljk2NiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGcgaWQ9IlZlY3RvciIgb3BhY2l0eT0iMC41Ij4KPHBhdGggZD0iTTExMi40MyAwTDExNS45NjYgMy41MzU1M0wzLjUzNTUzIDExNS45NjZMMCAxMTIuNDNMMTEyLjQzIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTEyNi4zOTUgMEwxMjkuOTMxIDMuNTM1NTNMMTcuNTAxIDExNS45NjZMMTMuOTY1NSAxMTIuNDNMMTI2LjM5NSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xNDAuMzYxIDBMMTQzLjg5NyAzLjUzNTUzTDMxLjQ2NjUgMTE1Ljk2NkwyNy45MzEgMTEyLjQzTDE0MC4zNjEgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMTU0LjMyNiAwTDE1Ny44NjIgMy41MzU1M0w0NS40MzIgMTE1Ljk2Nkw0MS44OTY1IDExMi40M0wxNTQuMzI2IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTE2OC4yOTIgMEwxNzEuODI4IDMuNTM1NTNMNTkuMzk3NiAxMTUuOTY2TDU1Ljg2MiAxMTIuNDNMMTY4LjI5MiAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xODIuMjU4IDBMMTg1Ljc5MyAzLjUzNTUzTDczLjM2MzEgMTE1Ljk2Nkw2OS44Mjc1IDExMi40M0wxODIuMjU4IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTE5Ni4yMjMgMEwxOTkuNzU5IDMuNTM1NTNMODcuMzI4NiAxMTUuOTY2TDgzLjc5MyAxMTIuNDNMMTk2LjIyMyAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0yMTAuMTg5IDBMMjEzLjcyNCAzLjUzNTUzTDEwMS4yOTQgMTE1Ljk2Nkw5Ny43NTg1IDExMi40M0wyMTAuMTg5IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTIyNC4xNTQgMEwyMjcuNjkgMy41MzU1M0wxMTUuMjYgMTE1Ljk2NkwxMTEuNzI0IDExMi40M0wyMjQuMTU0IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTIzOC4xMiAwTDI0MS42NTUgMy41MzU1M0wxMjkuMjI1IDExNS45NjZMMTI1LjY5IDExMi40M0wyMzguMTIgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMjUyLjA4NSAwTDI1NS42MjEgMy41MzU1M0wxNDMuMTkxIDExNS45NjZMMTM5LjY1NSAxMTIuNDNMMjUyLjA4NSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0yNjYuMDUxIDBMMjY5LjU4NiAzLjUzNTUzTDE1Ny4xNTYgMTE1Ljk2NkwxNTMuNjIxIDExMi40M0wyNjYuMDUxIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTI4MC4wMTYgMEwyODMuNTUyIDMuNTM1NTNMMTcxLjEyMiAxMTUuOTY2TDE2Ny41ODYgMTEyLjQzTDI4MC4wMTYgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMjkzLjk4MiAwTDI5Ny41MTcgMy41MzU1M0wxODUuMDg3IDExNS45NjZMMTgxLjU1MiAxMTIuNDNMMjkzLjk4MiAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0zMDcuOTQ3IDBMMzExLjQ4MyAzLjUzNTUzTDE5OS4wNTMgMTE1Ljk2NkwxOTUuNTE3IDExMi40M0wzMDcuOTQ3IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTMyMS45MTMgMEwzMjUuNDQ4IDMuNTM1NTNMMjEzLjAxOCAxMTUuOTY2TDIwOS40ODMgMTEyLjQzTDMyMS45MTMgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMzM1Ljg3OCAwTDMzOS40MTQgMy41MzU1M0wyMjYuOTg0IDExNS45NjZMMjIzLjQ0OCAxMTIuNDNMMzM1Ljg3OCAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0zNDkuODQ0IDBMMzUzLjM3OSAzLjUzNTUzTDI0MC45NDkgMTE1Ljk2NkwyMzcuNDE0IDExMi40M0wzNDkuODQ0IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTM2My44MDkgMEwzNjcuMzQ1IDMuNTM1NTNMMjU0LjkxNSAxMTUuOTY2TDI1MS4zNzkgMTEyLjQzTDM2My44MDkgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMzc3Ljc3NSAwTDM4MS4zMSAzLjUzNTUzTDI2OC44OCAxMTUuOTY2TDI2NS4zNDUgMTEyLjQzTDM3Ny43NzUgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMzkxLjc0IDBMMzk1LjI3NiAzLjUzNTUzTDI4Mi44NDYgMTE1Ljk2NkwyNzkuMzEgMTEyLjQzTDM5MS43NCAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik00MDUuNzA2IDBMNDA5LjI0MSAzLjUzNTUzTDI5Ni44MTEgMTE1Ljk2NkwyOTMuMjc2IDExMi40M0w0MDUuNzA2IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTQxOS42NzEgMEw0MjMuMjA3IDMuNTM1NTNMMzEwLjc3NyAxMTUuOTY2TDMwNy4yNDEgMTEyLjQzTDQxOS42NzEgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNDMzLjYzNyAwTDQzNy4xNzIgMy41MzU1M0wzMjQuNzQyIDExNS45NjZMMzIxLjIwNyAxMTIuNDNMNDMzLjYzNyAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik00NDcuNjAyIDBMNDUxLjEzOCAzLjUzNTUzTDMzOC43MDggMTE1Ljk2NkwzMzUuMTcyIDExMi40M0w0NDcuNjAyIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTQ2MS41NjggMEw0NjUuMTAzIDMuNTM1NTNMMzUyLjY3MyAxMTUuOTY2TDM0OS4xMzggMTEyLjQzTDQ2MS41NjggMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNDc1LjUzMyAwTDQ3OS4wNjkgMy41MzU1M0wzNjYuNjM5IDExNS45NjZMMzYzLjEwMyAxMTIuNDNMNDc1LjUzMyAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik00ODkuNDk5IDBMNDkzLjAzNCAzLjUzNTUzTDM4MC42MDQgMTE1Ljk2NkwzNzcuMDY5IDExMi40M0w0ODkuNDk5IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTUwMy40NjQgMEw1MDcgMy41MzU1M0wzOTQuNTcgMTE1Ljk2NkwzOTEuMDM0IDExMi40M0w1MDMuNDY0IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTUxNy40MyAwTDUyMC45NjUgMy41MzU1M0w0MDguNTM1IDExNS45NjZMNDA1IDExMi40M0w1MTcuNDMgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNTMxLjM5NSAwTDUzNC45MzEgMy41MzU1M0w0MjIuNTAxIDExNS45NjZMNDE4Ljk2NSAxMTIuNDNMNTMxLjM5NSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik01NDUuMzYxIDBMNTQ4Ljg5NiAzLjUzNTUzTDQzNi40NjYgMTE1Ljk2Nkw0MzIuOTMxIDExMi40M0w1NDUuMzYxIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTU1OS4zMjYgMEw1NjIuODYyIDMuNTM1NTNMNDUwLjQzMiAxMTUuOTY2TDQ0Ni44OTYgMTEyLjQzTDU1OS4zMjYgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNTczLjI5MiAwTDU3Ni44MjcgMy41MzU1M0w0NjQuMzk3IDExNS45NjZMNDYwLjg2MiAxMTIuNDNMNTczLjI5MiAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik01ODcuMjU3IDBMNTkwLjc5MyAzLjUzNTUzTDQ3OC4zNjMgMTE1Ljk2Nkw0NzQuODI3IDExMi40M0w1ODcuMjU3IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTYwMS4yMjMgMEw2MDQuNzU4IDMuNTM1NTNMNDkyLjMyOCAxMTUuOTY2TDQ4OC43OTMgMTEyLjQzTDYwMS4yMjMgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNjE1LjE4OCAwTDYxOC43MjQgMy41MzU1M0w1MDYuMjk0IDExNS45NjZMNTAyLjc1OCAxMTIuNDNMNjE1LjE4OCAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik02MjkuMTU0IDBMNjMyLjY4OSAzLjUzNTUzTDUyMC4yNTkgMTE1Ljk2Nkw1MTYuNzI0IDExMi40M0w2MjkuMTU0IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTY0My4xMTkgMEw2NDYuNjU1IDMuNTM1NTNMNTM0LjIyNSAxMTUuOTY2TDUzMC42ODkgMTEyLjQzTDY0My4xMTkgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNjU3LjA4NSAwTDY2MC42MiAzLjUzNTUzTDU0OC4xOSAxMTUuOTY2TDU0NC42NTUgMTEyLjQzTDY1Ny4wODUgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNjcxLjA1IDBMNjc0LjU4NiAzLjUzNTUzTDU2Mi4xNTYgMTE1Ljk2Nkw1NTguNjIgMTEyLjQzTDY3MS4wNSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik02ODUuMDE2IDBMNjg4LjU1MiAzLjUzNTUzTDU3Ni4xMjIgMTE1Ljk2Nkw1NzIuNTg2IDExMi40M0w2ODUuMDE2IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTY5OC45ODIgMEw3MDIuNTE3IDMuNTM1NTNMNTkwLjA4NyAxMTUuOTY2TDU4Ni41NTIgMTEyLjQzTDY5OC45ODIgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNzEyLjk0NyAwTDcxNi40ODMgMy41MzU1M0w2MDQuMDUzIDExNS45NjZMNjAwLjUxNyAxMTIuNDNMNzEyLjk0NyAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik03MjYuOTEzIDBMNzMwLjQ0OCAzLjUzNTUzTDYxOC4wMTggMTE1Ljk2Nkw2MTQuNDgzIDExMi40M0w3MjYuOTEzIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTc0MC44NzggMEw3NDQuNDE0IDMuNTM1NTNMNjMxLjk4NCAxMTUuOTY2TDYyOC40NDggMTEyLjQzTDc0MC44NzggMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNNzU0Ljg0NCAwTDc1OC4zNzkgMy41MzU1M0w2NDUuOTQ5IDExNS45NjZMNjQyLjQxNCAxMTIuNDNMNzU0Ljg0NCAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik03NjguODA5IDBMNzcyLjM0NSAzLjUzNTUzTDY1OS45MTUgMTE1Ljk2Nkw2NTYuMzc5IDExMi40M0w3NjguODA5IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTc4Mi43NzUgMEw3ODYuMzEgMy41MzU1M0w2NzMuODggMTE1Ljk2Nkw2NzAuMzQ1IDExMi40M0w3ODIuNzc1IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTc5Ni43NCAwTDgwMC4yNzYgMy41MzU1M0w2ODcuODQ2IDExNS45NjZMNjg0LjMxIDExMi40M0w3OTYuNzQgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNODEwLjcwNiAwTDgxNC4yNDEgMy41MzU1M0w3MDEuODExIDExNS45NjZMNjk4LjI3NiAxMTIuNDNMODEwLjcwNiAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik04MjQuNjcxIDBMODI4LjIwNyAzLjUzNTUzTDcxNS43NzcgMTE1Ljk2Nkw3MTIuMjQxIDExMi40M0w4MjQuNjcxIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTgzOC42MzcgMEw4NDIuMTcyIDMuNTM1NTNMNzI5Ljc0MiAxMTUuOTY2TDcyNi4yMDcgMTEyLjQzTDgzOC42MzcgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNODUyLjYwMiAwTDg1Ni4xMzggMy41MzU1M0w3NDMuNzA4IDExNS45NjZMNzQwLjE3MiAxMTIuNDNMODUyLjYwMiAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik04NjYuNTY4IDBMODcwLjEwMyAzLjUzNTUzTDc1Ny42NzMgMTE1Ljk2Nkw3NTQuMTM4IDExMi40M0w4NjYuNTY4IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTg4MC41MzMgMEw4ODQuMDY5IDMuNTM1NTNMNzcxLjYzOSAxMTUuOTY2TDc2OC4xMDMgMTEyLjQzTDg4MC41MzMgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNODk0LjQ5OSAwTDg5OC4wMzQgMy41MzU1M0w3ODUuNjA0IDExNS45NjZMNzgyLjA2OSAxMTIuNDNMODk0LjQ5OSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik05MDguNDY0IDBMOTEyIDMuNTM1NTNMNzk5LjU3IDExNS45NjZMNzk2LjAzNCAxMTIuNDNMOTA4LjQ2NCAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik05MjIuNDMgMEw5MjUuOTY1IDMuNTM1NTNMODEzLjUzNSAxMTUuOTY2TDgxMCAxMTIuNDNMOTIyLjQzIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTkzNi4zOTUgMEw5MzkuOTMxIDMuNTM1NTNMODI3LjUwMSAxMTUuOTY2TDgyMy45NjUgMTEyLjQzTDkzNi4zOTUgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNOTUwLjM2MSAwTDk1My44OTYgMy41MzU1M0w4NDEuNDY2IDExNS45NjZMODM3LjkzMSAxMTIuNDNMOTUwLjM2MSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik05NjQuMzI2IDBMOTY3Ljg2MiAzLjUzNTUzTDg1NS40MzIgMTE1Ljk2Nkw4NTEuODk2IDExMi40M0w5NjQuMzI2IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTk3OC4yOTIgMEw5ODEuODI3IDMuNTM1NTNMODY5LjM5NyAxMTUuOTY2TDg2NS44NjIgMTEyLjQzTDk3OC4yOTIgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNOTkyLjI1NyAwTDk5NS43OTMgMy41MzU1M0w4ODMuMzYzIDExNS45NjZMODc5LjgyNyAxMTIuNDNMOTkyLjI1NyAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xMDA2LjIyIDBMMTAwOS43NiAzLjUzNTUzTDg5Ny4zMjggMTE1Ljk2Nkw4OTMuNzkzIDExMi40M0wxMDA2LjIyIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTEwMjAuMTkgMEwxMDIzLjcyIDMuNTM1NTNMOTExLjI5NCAxMTUuOTY2TDkwNy43NTggMTEyLjQzTDEwMjAuMTkgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMTAzNC4xNSAwTDEwMzcuNjkgMy41MzU1M0w5MjUuMjU5IDExNS45NjZMOTIxLjcyNCAxMTIuNDNMMTAzNC4xNSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xMDQ4LjEyIDBMMTA1MS42NSAzLjUzNTUzTDkzOS4yMjUgMTE1Ljk2Nkw5MzUuNjg5IDExMi40M0wxMDQ4LjEyIDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTEwNjIuMDggMEwxMDY1LjYyIDMuNTM1NTNMOTUzLjE5IDExNS45NjZMOTQ5LjY1NSAxMTIuNDNMMTA2Mi4wOCAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xMDc2LjA1IDBMMTA3OS41OSAzLjUzNTUzTDk2Ny4xNTYgMTE1Ljk2Nkw5NjMuNjIgMTEyLjQzTDEwNzYuMDUgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMTA5MC4wMiAwTDEwOTMuNTUgMy41MzU1M0w5ODEuMTIxIDExNS45NjZMOTc3LjU4NiAxMTIuNDNMMTA5MC4wMiAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xMTAzLjk4IDBMMTEwNy41MiAzLjUzNTUzTDk5NS4wODcgMTE1Ljk2Nkw5OTEuNTUxIDExMi40M0wxMTAzLjk4IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTExMTcuOTUgMEwxMTIxLjQ4IDMuNTM1NTNMMTAwOS4wNSAxMTUuOTY2TDEwMDUuNTIgMTEyLjQzTDExMTcuOTUgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMTEzMS45MSAwTDExMzUuNDUgMy41MzU1M0wxMDIzLjAyIDExNS45NjZMMTAxOS40OCAxMTIuNDNMMTEzMS45MSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xMTQ1Ljg4IDBMMTE0OS40MSAzLjUzNTUzTDEwMzYuOTggMTE1Ljk2NkwxMDMzLjQ1IDExMi40M0wxMTQ1Ljg4IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTExNTkuODQgMEwxMTYzLjM4IDMuNTM1NTNMMTA1MC45NSAxMTUuOTY2TDEwNDcuNDEgMTEyLjQzTDExNTkuODQgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMTE3My44MSAwTDExNzcuMzQgMy41MzU1M0wxMDY0LjkxIDExNS45NjZMMTA2MS4zOCAxMTIuNDNMMTE3My44MSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjxwYXRoIGQ9Ik0xMTg3Ljc3IDBMMTE5MS4zMSAzLjUzNTUzTDEwNzguODggMTE1Ljk2NkwxMDc1LjM0IDExMi40M0wxMTg3Ljc3IDBaIiBmaWxsPSIjMTAxODI4IiBmaWxsLW9wYWNpdHk9IjAuMDQiLz4KPHBhdGggZD0iTTEyMDEuNzQgMEwxMjA1LjI4IDMuNTM1NTNMMTA5Mi44NSAxMTUuOTY2TDEwODkuMzEgMTEyLjQzTDEyMDEuNzQgMFoiIGZpbGw9IiMxMDE4MjgiIGZpbGwtb3BhY2l0eT0iMC4wNCIvPgo8cGF0aCBkPSJNMTIxNS43MSAwTDEyMTkuMjQgMy41MzU1M0wxMTA2LjgxIDExNS45NjZMMTEwMy4yOCAxMTIuNDNMMTIxNS43MSAwWiIgZmlsbD0iIzEwMTgyOCIgZmlsbC1vcGFjaXR5PSIwLjA0Ii8+CjwvZz4KPC9zdmc+Cg=='
-
type DebugModeProps = {
value: HumanInputV2DebugMode
onChange: (value: HumanInputV2DebugMode) => void
@@ -51,22 +46,14 @@ const DebugMode = ({ value, onChange, readonly, email }: DebugModeProps) => {
}
return (
- <section
+ <div
className="px-4"
aria-describedby={missingSelection || unsupported.length ? errorId : undefined}
>
<div
- className={cn(
- 'relative flex h-9 items-center gap-2 overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg ps-2 pe-2.5 shadow-xs',
- readonly && 'opacity-70',
- )}
+ data-readonly={readonly || undefined}
+ className="relative flex h-9 items-center gap-2 overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg bg-[repeating-linear-gradient(135deg,rgba(16,24,40,0.02)_0_5px,transparent_5px_9.875px)] ps-2 pe-2.5 shadow-xs data-readonly:opacity-70"
>
- <img
- src={debugModeBackground}
- alt=""
- aria-hidden
- className="pointer-events-none absolute top-1/2 left-1/2 h-[115.966px] w-[1219.24px] max-w-none -translate-x-1/2 -translate-y-1/2"
- />
<span className="relative flex size-5 shrink-0 items-center justify-center rounded-md border border-divider-regular bg-components-icon-bg-orange-dark-solid bg-linear-to-br from-components-avatar-bg-mask-stop-0 to-components-avatar-bg-mask-stop-100 text-text-primary-on-surface">
<span className="i-ri-bug-line size-3.5" aria-hidden />
</span>
@@ -76,7 +63,7 @@ const DebugMode = ({ value, onChange, readonly, email }: DebugModeProps) => {
</div>
<Infotip>
<InfotipTrigger
- aria-label={t(($) => $['nodes.humanInputV2.debug.title'], { ns: 'workflow' })}
+ aria-label={t(($) => $['nodes.humanInputV2.debug.sendVia'], { ns: 'workflow' })}
/>
<InfotipContent>
{t(($) => $['nodes.humanInputV2.debug.sendVia'], { ns: 'workflow' })}
@@ -86,38 +73,37 @@ const DebugMode = ({ value, onChange, readonly, email }: DebugModeProps) => {
<Popover open={open} onOpenChange={(nextOpen) => !readonly && setOpen(nextOpen)}>
<PopoverTrigger
render={
- <button
- type="button"
+ <IconButton
+ aria-describedby={selected.length ? `${errorId}-selected` : undefined}
disabled={readonly}
aria-label={t(($) => $['nodes.humanInputV2.debug.configure'], { ns: 'workflow' })}
- className="relative flex h-6 shrink-0 items-center justify-center gap-1 rounded-lg border-0 bg-transparent p-1 text-text-tertiary hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-state-accent-solid disabled:cursor-not-allowed"
+ className="relative h-6 w-auto shrink-0 gap-1 px-1"
>
- {!!selected.length && (
- <span
- role="img"
- aria-label={selected
- .map((channel) =>
- t(($) => $[`nodes.humanInputV2.debug.channel.${channel}`], {
- ns: 'workflow',
- }),
- )
- .join(', ')}
- className="flex items-center gap-1"
- >
- {selected.map((channel) => (
- <ContactChannelIcon key={channel} provider={channel} className="size-4" />
- ))}
- </span>
- )}
- <span className="i-ri-equalizer-2-line size-4" aria-hidden />
- </button>
+ <span className="flex items-center gap-1">
+ {!!selected.length && (
+ <span aria-hidden="true" className="flex items-center gap-1">
+ {selected.map((channel) => (
+ <ContactChannelIcon key={channel} provider={channel} className="size-4" />
+ ))}
+ </span>
+ )}
+ <span className="i-ri-equalizer-2-line size-4" aria-hidden />
+ </span>
+ </IconButton>
}
/>
+ <span className="sr-only" id={`${errorId}-selected`}>
+ {selected
+ .map((channel) =>
+ t(($) => $[`nodes.humanInputV2.debug.channel.${channel}`], { ns: 'workflow' }),
+ )
+ .join(', ')}
+ </span>
<PopoverContent
side="bottom"
align="end"
sideOffset={4}
- className="w-60! bg-components-panel-bg-blur p-1! backdrop-blur-[5px]"
+ className="w-60 bg-components-panel-bg-blur p-1 backdrop-blur-xs"
>
<div className="px-2 pt-1 pb-0.5 system-xs-medium text-text-tertiary">
{t(($) => $['nodes.humanInputV2.debug.sendVia'], { ns: 'workflow' })}
@@ -146,45 +132,41 @@ const DebugMode = ({ value, onChange, readonly, email }: DebugModeProps) => {
ns: 'workflow',
})
return (
- <Tooltip key={channel}>
- <TooltipTrigger
- disabled={!isLastChannel}
- render={
- <label className="flex h-8 cursor-pointer items-center gap-1 rounded-lg px-2 hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-state-accent-solid">
- <Checkbox
- aria-labelledby={`${errorId}-${channel}-label`}
- aria-describedby={isLastChannel ? `${errorId}-keep-channel` : undefined}
- checked={channels.includes(channel)}
- disabled={isLastChannel || readonly}
- onCheckedChange={() => toggleChannel(channel)}
- />
- <ContactChannelIcon provider={channel} className="ms-1 size-4 shrink-0" />
- <span
- id={`${errorId}-${channel}-label`}
- className="shrink-0 system-md-regular text-text-secondary"
- >
- {label}
- </span>
- {channel === 'email' && email && (
- <span
- className="truncate system-xs-regular text-text-tertiary"
- title={email}
- >
- {email}
- </span>
- )}
- </label>
- }
+ <label
+ key={channel}
+ className="flex min-h-8 items-center gap-1 rounded-lg px-2 hover:bg-state-base-hover"
+ >
+ <Checkbox
+ aria-labelledby={`${errorId}-${channel}-label`}
+ aria-describedby={isLastChannel ? `${errorId}-keep-channel` : undefined}
+ checked={channels.includes(channel)}
+ disabled={readonly}
+ aria-disabled={isLastChannel || undefined}
+ onCheckedChange={() => toggleChannel(channel)}
/>
- <TooltipContent
- role="tooltip"
- id={isLastChannel ? `${errorId}-keep-channel` : undefined}
+ <ContactChannelIcon provider={channel} className="ms-1 size-4 shrink-0" />
+ <span
+ id={`${errorId}-${channel}-label`}
+ className="shrink-0 system-md-regular text-text-secondary"
>
- {t(($) => $['nodes.humanInputV2.debug.keepOneChannel'], { ns: 'workflow' })}
- </TooltipContent>
- </Tooltip>
+ {label}
+ </span>
+ {channel === 'email' && email && (
+ <span className="truncate system-xs-regular text-text-tertiary" title={email}>
+ {email}
+ </span>
+ )}
+ </label>
)
})}
+ {selected.length === 1 && (
+ <p
+ id={`${errorId}-keep-channel`}
+ className="px-2 py-1 system-xs-regular text-text-tertiary"
+ >
+ {t(($) => $['nodes.humanInputV2.debug.keepOneChannel'], { ns: 'workflow' })}
+ </p>
+ )}
</PopoverContent>
</Popover>
<div className="relative h-3 w-1.25 shrink-0 border-s border-divider-regular" />
@@ -213,7 +195,7 @@ const DebugMode = ({ value, onChange, readonly, email }: DebugModeProps) => {
})}
</div>
)}
- </section>
+ </div>
)
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/message-template-body.tsx b/web/app/components/workflow/nodes/human-input-v2/components/message-template-body.tsx
index 4af70d2f459..1753a9824aa 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/message-template-body.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/message-template-body.tsx
@@ -1,6 +1,7 @@
import type { RangeSelection } from 'lexical'
import type { ComponentProps } from 'react'
import { Button } from '@langgenius/dify-ui/button'
+import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { mergeRegister } from '@lexical/utils'
import {
@@ -112,22 +113,28 @@ const MessageTemplateBody = ({ nodeId, error, ...props }: MessageTemplateBodyPro
const [toolbar, setToolbar] = useState<HTMLDivElement | null>(null)
const hasRequestURL = getRequestURLCount(props.value ?? '') > 0
return (
- <div
+ <Field
+ name="body"
+ invalid={!!error}
id={`${nodeId}-message-body`}
- role="group"
aria-labelledby={`${nodeId}-message-body-label`}
aria-describedby={`${nodeId}-message-body-hint${error ? ` ${nodeId}-message-body-error` : ''}`}
>
<div className="mb-1 flex min-h-6 items-center justify-between gap-2">
- <span id={`${nodeId}-message-body-label`} className="system-sm-medium text-text-secondary">
+ <FieldLabel
+ id={`${nodeId}-message-body-label`}
+ className="system-sm-medium text-text-secondary"
+ >
{t(($) => $['nodes.humanInputV2.template.body'], { ns: 'workflow' })}
- </span>
+ </FieldLabel>
<div ref={setToolbar} />
</div>
<div className="[&>div>[contenteditable]]:min-h-[118px]">
<MailBodyInput
{...props}
aria-labelledby={`${nodeId}-message-body-label`}
+ aria-describedby={`${nodeId}-message-body-hint${error ? ` ${nodeId}-message-body-error` : ''}`}
+ aria-invalid={!!error}
requestURLSelectable={!hasRequestURL}
>
<InsertRequestURL
@@ -137,19 +144,22 @@ const MessageTemplateBody = ({ nodeId, error, ...props }: MessageTemplateBodyPro
/>
</MailBodyInput>
</div>
- <p id={`${nodeId}-message-body-hint`} className="mt-1.5 system-xs-regular text-text-tertiary">
+ <FieldDescription
+ id={`${nodeId}-message-body-hint`}
+ className="mt-1.5 system-xs-regular text-text-tertiary"
+ >
{t(($) => $['nodes.humanInputV2.template.requestURLHint'], { ns: 'workflow' })}
- </p>
+ </FieldDescription>
{error && (
- <div
+ <FieldError
+ match
id={`${nodeId}-message-body-error`}
- role="alert"
className="mt-1 system-xs-regular text-text-destructive"
>
{error}
- </div>
+ </FieldError>
)}
- </div>
+ </Field>
)
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx b/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx
index 00e04db20b5..4abcd8091ce 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/message-template.tsx
@@ -1,11 +1,24 @@
'use client'
import type { MessageTemplateTestRequest } from '@dify/contracts/api/console/apps/types.gen'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
+import type { MutationKey } from '@tanstack/react-query'
import type { HumanInputV2MessageTemplate } from '../types'
import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
-import { Field, FieldError } from '@langgenius/dify-ui/field'
+import {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogHeaderCloseButton,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Input } from '@langgenius/dify-ui/input'
@@ -20,9 +33,9 @@ import {
SelectValue,
} from '@langgenius/dify-ui/select'
import { Textarea } from '@langgenius/dify-ui/textarea'
-import { useMutation } from '@tanstack/react-query'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { getInputVars } from '@/app/components/base/prompt-editor/constants'
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
@@ -30,7 +43,8 @@ import { useHooksStore } from '@/app/components/workflow/hooks-store'
import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'
import { isENV } from '@/app/components/workflow/nodes/_base/components/variable/utils'
import { VarType } from '@/app/components/workflow/types'
-import { consoleQuery } from '@/service/console'
+import { consoleClient } from '@/service/console'
+import { syncHumanInputDraft } from '../../human-input/shared/sync-draft'
import { isOutput } from '../../human-input/utils'
import { getRequestURLCount } from '../message-template-utils'
import useConfiguredChannels from '../use-configured-channels'
@@ -60,43 +74,37 @@ type MessageTemplateProps = {
availableNodes: Node[]
}
-const MessageTemplate = ({
+const MessageTemplateSession = ({
nodeId,
value,
onChange,
readonly,
availableVars,
availableNodes,
-}: MessageTemplateProps) => {
+ initialShowTest,
+ close,
+ mutationKey,
+}: MessageTemplateProps & {
+ initialShowTest: boolean
+ close: () => void
+ mutationKey: MutationKey
+}) => {
const { t } = useTranslation(['workflow', 'common', 'workflowAgent', 'contacts'])
- const [open, setOpen] = useState(false)
const [draft, setDraft] = useState(value)
- const [submitted, setSubmitted] = useState(false)
const [errors, setErrors] = useState({ subject: false, body: false })
- const [showTest, setShowTest] = useState(false)
+ const [showTest, setShowTest] = useState(initialShowTest)
const [channel, setChannel] = useState<MessageTemplateTestRequest['channel']>()
const configured = useConfiguredChannels()
const selectedChannel =
channel && configured.channels.includes(channel) ? channel : configured.channels[0]
const [testInputs, setTestInputs] = useState<Record<string, string>>({})
- const [testError, setTestError] = useState<string>()
- const [savingForTest, setSavingForTest] = useState(false)
+ const [testInputError, setTestInputError] = useState<{ key: string; message: string }>()
const canRun = useHooksStore((state) => state.accessControl.canRun)
const resource = useAtomValue(editorResourceAtom)
const flowId = resource.kind === 'app' ? resource.appId : undefined
const isChatMode = resource.kind === 'app' && resource.mode === 'advanced-chat'
const { doSyncWorkflowDraft } = useNodesSyncDraft()
- const testMutation = useMutation(
- (isChatMode
- ? consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId
- .messageTemplate.test.post
- : consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.messageTemplate.test
- .post
- ).mutationOptions({ retry: false }),
- )
const canTest = !readonly && canRun && resource.kind === 'app' && !!flowId && !!nodeId
- const pending = savingForTest || testMutation.isPending
- const pendingRef = useRef(false)
const canTestRef = useRef(canTest)
const testContext = `${flowId}:${nodeId}:${isChatMode}:${selectedChannel}`
const testContextRef = useRef(testContext)
@@ -107,6 +115,58 @@ const MessageTemplate = ({
canTestRef.current = false
}
}, [canTest, testContext])
+ const testMutation = useMutation({
+ mutationKey,
+ retry: false,
+ mutationFn: async ({
+ inputs,
+ channel,
+ template,
+ context,
+ }: {
+ inputs: MessageTemplateTestRequest['inputs']
+ channel: MessageTemplateTestRequest['channel']
+ template: HumanInputV2MessageTemplate
+ context: string
+ }) => {
+ if (!flowId || !canTestRef.current) return false
+ onChange({ subject: template.subject, body: template.body })
+ try {
+ await syncHumanInputDraft(doSyncWorkflowDraft)
+ } catch {
+ throw new Error('template-draft-not-saved')
+ }
+ if (!canTestRef.current || testContextRef.current !== context) return false
+ const operation = isChatMode
+ ? consoleClient.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId
+ .messageTemplate.test.post
+ : consoleClient.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.messageTemplate.test
+ .post
+ await operation(
+ { params: { app_id: flowId, node_id: nodeId }, body: { channel, inputs } },
+ { context: { silent: true } },
+ )
+ return true
+ },
+ })
+ const pending = testMutation.isPending
+ const mutationError = testMutation.error
+ ? t(
+ ($) =>
+ $[
+ testMutation.error instanceof Error &&
+ testMutation.error.message === 'template-draft-not-saved'
+ ? 'nodes.humanInputV2.template.testSaveFailed'
+ : typeof testMutation.error === 'object' &&
+ 'status' in testMutation.error &&
+ testMutation.error.status === 501
+ ? 'nodes.humanInputV2.template.testUnavailable'
+ : 'nodes.humanInputV2.template.testFailed'
+ ],
+ { ns: 'workflow' },
+ )
+ : undefined
+
const variables = Array.from(
new Map(
getInputVars(`${draft.subject}\n${draft.body}`)
@@ -121,80 +181,54 @@ const MessageTemplate = ({
]),
).values(),
)
- const triggerRef = useRef<HTMLButtonElement>(null)
- const activeTriggerRef = useRef<HTMLButtonElement | null>(null)
-
- const restoreFocus = () =>
- requestAnimationFrame(() => (activeTriggerRef.current ?? triggerRef.current)?.focus())
- const close = () => {
- if (pendingRef.current) return
- setOpen(false)
- setDraft(value)
- setErrors({ subject: false, body: false })
- restoreFocus()
- }
- const handleOpen = (test = false, trigger = triggerRef.current) => {
- activeTriggerRef.current = trigger
- setDraft(value)
- setErrors({ subject: false, body: false })
- setShowTest(test)
- setChannel(undefined)
- setTestInputs({})
- setTestError(undefined)
- testMutation.reset()
- setOpen(true)
- }
const getBodyError = (body: string) => {
if (!body.trim())
return t(($) => $['nodes.humanInputV2.error.bodyRequired'], { ns: 'workflow' })
const count = getRequestURLCount(body)
- if (count === 0)
+ if (!count)
return t(($) => $['nodes.humanInputV2.error.requestURLRequired'], { ns: 'workflow' })
if (count > 1)
return t(($) => $['nodes.humanInputV2.error.requestURLDuplicate'], { ns: 'workflow' })
- return undefined
}
const validateTemplate = () => {
- const nextErrors = { subject: !draft.subject.trim(), body: !!getBodyError(draft.body) }
- setErrors(nextErrors)
- if (nextErrors.subject || nextErrors.body) {
- requestAnimationFrame(() => {
- if (nextErrors.subject) {
- document.getElementById(`${nodeId}-message-subject`)?.focus()
- return
- }
+ const errors = { subject: !draft.subject.trim(), body: !!getBodyError(draft.body) }
+ setErrors(errors)
+ if (!errors.subject && !errors.body) return true
+ requestAnimationFrame(() => {
+ if (errors.subject) document.getElementById(`${nodeId}-message-subject`)?.focus()
+ else
document
.getElementById(`${nodeId}-message-body`)
- ?.querySelector<HTMLElement>('textarea, [contenteditable="true"]')
+ ?.querySelector<HTMLElement>('[contenteditable="true"], textarea')
?.focus()
- })
- return false
- }
- return true
+ })
+ return false
}
const save = () => {
- if (submitted || readonly || pendingRef.current || !validateTemplate()) return
- setSubmitted(true)
+ if (readonly || pending || !validateTemplate()) return
onChange({ subject: draft.subject, body: draft.body })
- setOpen(false)
- setSubmitted(false)
- restoreFocus()
+ close()
}
const resetTestResult = () => {
- setTestError(undefined)
+ setTestInputError(undefined)
testMutation.reset()
}
- const sendTest = async () => {
- if (!canTest || !flowId || !selectedChannel || pendingRef.current || !validateTemplate()) return
+ const sendTest = () => {
+ if (!canTest || !flowId || !selectedChannel || pending || !validateTemplate()) return
resetTestResult()
const inputs: MessageTemplateTestRequest['inputs'] = {}
for (const variable of variables) {
const raw = testInputs[variable.key]
if (!raw?.trim()) {
- setTestError(
- t(($) => $['nodes.humanInputV2.template.testInputsRequired'], { ns: 'workflow' }),
+ setTestInputError({
+ key: variable.key,
+ message: t(($) => $['nodes.humanInputV2.template.testInputsRequired'], {
+ ns: 'workflow',
+ }),
+ })
+ requestAnimationFrame(() =>
+ document.getElementById(`${nodeId}-test-${variable.key}`)?.focus(),
)
- document.getElementById(`${nodeId}-test-${variable.key}`)?.focus()
return
}
try {
@@ -212,327 +246,335 @@ const MessageTemplate = ({
if (typeof value === 'number' && !Number.isFinite(value)) throw new Error('invalid-number')
inputs[variable.key] = value
} catch {
- setTestError(
- variable.type === VarType.number
- ? t(($) => $['nodes.agent.outputVars.defaultValueNumberInvalid'], {
- ns: 'workflowAgent',
- })
- : t(($) => $['errorMsg.invalidJson'], { ns: 'workflow', field: variable.label }),
+ setTestInputError({
+ key: variable.key,
+ message:
+ variable.type === VarType.number
+ ? t(($) => $['nodes.agent.outputVars.defaultValueNumberInvalid'], {
+ ns: 'workflowAgent',
+ })
+ : t(($) => $['errorMsg.invalidJson'], { ns: 'workflow', field: variable.label }),
+ })
+ requestAnimationFrame(() =>
+ document.getElementById(`${nodeId}-test-${variable.key}`)?.focus(),
)
- document.getElementById(`${nodeId}-test-${variable.key}`)?.focus()
return
}
}
- pendingRef.current = true
- setSavingForTest(true)
- try {
- onChange({ subject: draft.subject, body: draft.body })
- let saved = false
- let failed = false
- const result = await doSyncWorkflowDraft(true, {
- onSuccess: () => {
- saved = true
- },
- onError: () => {
- failed = true
- },
- })
- // The endpoint reads the saved node; a skipped or failed save must not test stale content.
- if (failed || (!saved && result == null)) throw new Error('draft-not-saved')
- } catch {
- setTestError(t(($) => $['nodes.humanInputV2.template.testSaveFailed'], { ns: 'workflow' }))
- pendingRef.current = false
- setSavingForTest(false)
- return
- }
- setSavingForTest(false)
- try {
- if (!canTestRef.current || testContextRef.current !== testContext) return
- await testMutation.mutateAsync({
- params: { app_id: flowId, node_id: nodeId },
- body: { channel: selectedChannel, inputs },
- })
- } catch (error) {
- const unavailable =
- typeof error === 'object' && error !== null && 'status' in error && error.status === 501
- setTestError(
- t(
- ($) =>
- $[
- unavailable
- ? 'nodes.humanInputV2.template.testUnavailable'
- : 'nodes.humanInputV2.template.testFailed'
- ],
- { ns: 'workflow' },
- ),
- )
- } finally {
- pendingRef.current = false
- }
+ testMutation.mutate({ inputs, channel: selectedChannel, template: draft, context: testContext })
}
return (
- <section className="px-4">
- <div className="flex h-9 w-full items-center gap-2 rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg px-2 shadow-xs">
- <span className="flex size-5 shrink-0 items-center justify-center rounded-md border border-divider-regular bg-components-icon-bg-midnight-solid bg-linear-to-br from-components-avatar-bg-mask-stop-0 to-components-avatar-bg-mask-stop-100 text-text-primary-on-surface">
- <span className="i-ri-mail-send-fill size-3.5" aria-hidden />
- </span>
- <div className="flex min-w-0 grow items-center gap-1">
- <button
- ref={triggerRef}
- type="button"
- className="min-w-0 truncate rounded-sm border-0 bg-transparent p-0 text-start system-sm-medium text-text-secondary focus-visible:ring-1 focus-visible:ring-state-accent-solid"
- onClick={() => handleOpen()}
+ <form
+ className="contents"
+ onSubmit={(event) => {
+ event.preventDefault()
+ save()
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>
+ {t(($) => $['nodes.humanInputV2.template.title'], { ns: 'workflow' })}
+ </DialogTitle>
+ <DialogDescription>
+ {t(($) => $['nodes.humanInputV2.template.description'], { ns: 'workflow' })}
+ </DialogDescription>
+ <DialogHeaderCloseButton
+ disabled={pending}
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ />
+ </DialogHeader>
+ <DialogBody className="min-h-65 space-y-5">
+ <Field name="subject" invalid={errors.subject && !draft.subject.trim()}>
+ <FieldLabel
+ htmlFor={`${nodeId}-message-subject`}
+ className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary"
>
- {t(($) => $['nodes.humanInputV2.template.title'], { ns: 'workflow' })}
- </button>
- <Infotip>
- <InfotipTrigger
- aria-label={t(($) => $['nodes.humanInputV2.template.title'], { ns: 'workflow' })}
- />
- <InfotipContent>
- {t(($) => $['nodes.humanInputV2.template.description'], { ns: 'workflow' })}
- </InfotipContent>
- </Infotip>
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {canTest && (
- <IconButton
- aria-label={t(($) => $['nodes.humanInputV2.template.test'], { ns: 'workflow' })}
- onClick={(event) => handleOpen(true, event.currentTarget)}
+ {t(($) => $['nodes.humanInputV2.template.subject'], { ns: 'workflow' })}
+ </FieldLabel>
+ <Input
+ id={`${nodeId}-message-subject`}
+ value={draft.subject}
+ disabled={readonly || pending}
+ aria-invalid={errors.subject && !draft.subject.trim()}
+ aria-describedby={
+ errors.subject && !draft.subject.trim()
+ ? `${nodeId}-message-subject-error`
+ : undefined
+ }
+ onChange={(event) => {
+ resetTestResult()
+ setDraft((current) => ({ ...current, subject: event.target.value }))
+ }}
+ placeholder={t(($) => $['nodes.humanInputV2.template.subjectPlaceholder'], {
+ ns: 'workflow',
+ })}
+ />
+ {errors.subject && !draft.subject.trim() && (
+ <FieldError
+ match
+ id={`${nodeId}-message-subject-error`}
+ className="mt-1 system-xs-regular text-text-destructive"
>
- <span className="i-ri-send-plane-2-line size-4" aria-hidden />
- </IconButton>
+ {t(($) => $['nodes.humanInputV2.error.subjectRequired'], { ns: 'workflow' })}
+ </FieldError>
)}
- <IconButton
- aria-label={t(($) => $['common.configure'], { ns: 'workflow' })}
- onClick={(event) => handleOpen(false, event.currentTarget)}
- >
- <span className="i-ri-equalizer-2-line size-4" aria-hidden />
- </IconButton>
- </div>
- </div>
-
- <Dialog
- open={open}
- onOpenChange={(nextOpen) => {
- if (!nextOpen) close()
- }}
- >
- <DialogContent className="w-[calc(100vw-2rem)]! max-w-[720px]! overflow-hidden!">
- <form
- onSubmit={(event) => {
- event.preventDefault()
- save()
- }}
+ </Field>
+ <MessageTemplateBody
+ nodeId={nodeId}
+ readOnly={readonly || pending}
+ value={draft.body}
+ nodesOutputVars={availableVars}
+ availableNodes={availableNodes}
+ error={errors.body ? getBodyError(draft.body) : undefined}
+ onChange={(body) => {
+ resetTestResult()
+ setDraft((current) => ({ ...current, body }))
+ }}
+ />
+ {showTest && canTest && (
+ <div
+ className="space-y-3 border-t border-divider-subtle pt-4"
+ aria-label={t(($) => $['nodes.humanInputV2.template.test'], { ns: 'workflow' })}
>
- <header className="relative flex h-[78px] items-start ps-6 pe-14 pt-6 pb-3">
- <div className="space-y-1">
- <DialogTitle>
- {t(($) => $['nodes.humanInputV2.template.title'], { ns: 'workflow' })}
- </DialogTitle>
- <p className="system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.template.description'], { ns: 'workflow' })}
- </p>
- </div>
- <IconButton
- size="lg"
- className="absolute inset-e-5 top-5"
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- disabled={pending}
- onClick={close}
- >
- <span className="i-ri-close-line size-4.5" aria-hidden />
- </IconButton>
- </header>
- <div className="max-h-[60vh] min-h-[260px] space-y-5 overflow-y-auto px-6 py-3">
- <Field invalid={errors.subject}>
- <label
- htmlFor={`${nodeId}-message-subject`}
- className="flex h-6 items-center system-sm-medium text-text-secondary"
- >
- {t(($) => $['nodes.humanInputV2.template.subject'], { ns: 'workflow' })}
- </label>
- <Input
- id={`${nodeId}-message-subject`}
- value={draft.subject}
- disabled={readonly || pending}
- onChange={(event) => {
- resetTestResult()
- setDraft((current) => ({ ...current, subject: event.target.value }))
- }}
- placeholder={t(($) => $['nodes.humanInputV2.template.subjectPlaceholder'], {
+ <p className="system-xs-regular text-text-tertiary">
+ {t(($) => $['nodes.humanInputV2.template.testDescription'], { ns: 'workflow' })}
+ </p>
+ <div>
+ <Select<MessageTemplateTestRequest['channel']>
+ value={selectedChannel ?? null}
+ disabled={pending || !configured.channels.length}
+ items={configured.channels.map((value) => ({
+ value,
+ label: t(($) => $[`nodes.humanInputV2.debug.channel.${value}`], {
ns: 'workflow',
- })}
- />
- <FieldError match={errors.subject}>
- {t(($) => $['nodes.humanInputV2.error.subjectRequired'], { ns: 'workflow' })}
- </FieldError>
- </Field>
- <MessageTemplateBody
- nodeId={nodeId}
- readOnly={readonly || pending}
- value={draft.body}
- nodesOutputVars={availableVars}
- availableNodes={availableNodes}
- error={errors.body ? getBodyError(draft.body) : undefined}
- onChange={(body) => {
- resetTestResult()
- if (body !== draft.body) setErrors((current) => ({ ...current, body: true }))
- setDraft((current) => ({ ...current, body }))
+ }),
+ }))}
+ onValueChange={(value) => {
+ if (value) {
+ setChannel(value)
+ resetTestResult()
+ }
}}
- />
- {showTest && canTest && (
- <section
- className="space-y-3 border-t border-divider-subtle pt-4"
- aria-label={t(($) => $['nodes.humanInputV2.template.test'], { ns: 'workflow' })}
- >
- <p className="system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.template.testDescription'], { ns: 'workflow' })}
- </p>
- <div>
- <Select<MessageTemplateTestRequest['channel']>
- value={selectedChannel ?? null}
- disabled={pending || !configured.channels.length}
- items={configured.channels.map((value) => ({
- value,
- label: t(($) => $[`nodes.humanInputV2.debug.channel.${value}`], {
+ >
+ <SelectLabel className="mb-1 block system-xs-medium text-text-secondary">
+ {t(($) => $['nodes.humanInputV2.template.testChannel'], { ns: 'workflow' })}
+ </SelectLabel>
+ <SelectTrigger className="w-full">
+ <SelectValue
+ placeholder={t(($) => $['nodes.humanInputV2.template.notConfigured'], {
+ ns: 'workflow',
+ })}
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {configured.channels.map((value) => (
+ <SelectItem key={value} value={value}>
+ <SelectItemText>
+ {t(($) => $[`nodes.humanInputV2.debug.channel.${value}`], {
ns: 'workflow',
- }),
- }))}
- onValueChange={(value) => {
- if (value) {
- setChannel(value)
- resetTestResult()
- }
- }}
- >
- <SelectLabel className="mb-1 block system-xs-medium text-text-secondary">
- {t(($) => $['nodes.humanInputV2.template.testChannel'], { ns: 'workflow' })}
- </SelectLabel>
- <SelectTrigger className="w-full">
- <SelectValue
- placeholder={t(($) => $['nodes.humanInputV2.template.notConfigured'], {
- ns: 'workflow',
- })}
- />
- </SelectTrigger>
- <SelectContent>
- {configured.channels.map((value) => (
- <SelectItem key={value} value={value}>
- <SelectItemText>
- {t(($) => $[`nodes.humanInputV2.debug.channel.${value}`], {
- ns: 'workflow',
- })}
- </SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- {configured.isPending && (
- <p role="status" className="mt-1 system-xs-regular text-text-tertiary">
- {t(($) => $['imPlatform.loading'], { ns: 'contacts' })}
- </p>
- )}
- {configured.isError && (
- <div role="alert" className="mt-1 system-xs-regular text-text-destructive">
- {t(($) => $['imPlatform.loadError.title'], { ns: 'contacts' })}
- <Button size="small" onClick={() => void configured.refetch()}>
- {t(($) => $['operation.retry'], { ns: 'common' })}
- </Button>
- </div>
- )}
- </div>
- {variables.map((variable) => (
- <div key={variable.key}>
- <label
- htmlFor={`${nodeId}-test-${variable.key}`}
- className="mb-1 block system-xs-medium break-all text-text-secondary"
- >
- {variable.label}
- </label>
- {variable.type === VarType.arrayString ? (
- <Textarea
- id={`${nodeId}-test-${variable.key}`}
- value={testInputs[variable.key] ?? ''}
- disabled={pending}
- placeholder='["value"]'
- onValueChange={(value) => {
- setTestInputs((current) => ({ ...current, [variable.key]: value }))
- resetTestResult()
- }}
- />
- ) : (
- <Input
- id={`${nodeId}-test-${variable.key}`}
- type={
- variable.type === VarType.number
- ? 'number'
- : variable.type === VarType.secret
- ? 'password'
- : 'text'
- }
- step="any"
- value={testInputs[variable.key] ?? ''}
- disabled={pending}
- onChange={(event) => {
- setTestInputs((current) => ({
- ...current,
- [variable.key]: event.target.value,
- }))
- resetTestResult()
- }}
- />
- )}
- </div>
+ })}
+ </SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
))}
- {testError && (
- <p role="alert" className="system-xs-regular text-text-destructive">
- {testError}
- </p>
- )}
- {testMutation.isSuccess && (
- <p role="status" className="system-xs-regular text-text-success">
- {t(($) => $['nodes.humanInputV2.template.testCompleted'], { ns: 'workflow' })}
- </p>
- )}
- <Button onClick={sendTest} loading={pending} disabled={!selectedChannel}>
- {t(($) => $['nodes.humanInputV2.template.saveAndTest'], { ns: 'workflow' })}
+ </SelectContent>
+ </Select>
+ {configured.isPending && (
+ <p role="status" className="mt-1 system-xs-regular text-text-tertiary">
+ {t(($) => $['imPlatform.loading'], { ns: 'contacts' })}
+ </p>
+ )}
+ {configured.isError && (
+ <div role="alert" className="mt-1 system-xs-regular text-text-destructive">
+ {t(($) => $['imPlatform.loadError.title'], { ns: 'contacts' })}
+ <Button size="small" onClick={() => void configured.refetch()}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
</Button>
- </section>
+ </div>
)}
</div>
- <footer className="flex h-[76px] items-center justify-end gap-2 px-6 pt-5 pb-6">
- {canTest && (
- <Button
- className="me-auto"
- disabled={pending}
- aria-expanded={showTest}
- onClick={() => setShowTest(!showTest)}
- >
- <span className="i-ri-send-plane-2-line size-4" aria-hidden />
- {t(($) => $['nodes.humanInputV2.template.test'], { ns: 'workflow' })}
- </Button>
- )}
- <Button className="min-w-18" onClick={close} disabled={pending}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- {!readonly && (
- <Button
- className="min-w-18"
- type="submit"
- variant="primary"
- disabled={submitted || pending}
+ {variables.map((variable) => (
+ <Field
+ key={variable.key}
+ name={variable.key}
+ invalid={testInputError?.key === variable.key}
+ >
+ <FieldLabel
+ htmlFor={`${nodeId}-test-${variable.key}`}
+ className="mb-1 block system-xs-medium break-all text-text-secondary"
>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
+ {variable.label}
+ </FieldLabel>
+ {variable.type === VarType.arrayString ? (
+ <Textarea
+ id={`${nodeId}-test-${variable.key}`}
+ value={testInputs[variable.key] ?? ''}
+ disabled={pending}
+ aria-invalid={testInputError?.key === variable.key}
+ aria-describedby={
+ testInputError?.key === variable.key
+ ? `${nodeId}-test-${variable.key}-error`
+ : undefined
+ }
+ placeholder='["value"]'
+ onValueChange={(value) => {
+ setTestInputs((current) => ({ ...current, [variable.key]: value }))
+ resetTestResult()
+ }}
+ />
+ ) : (
+ <Input
+ id={`${nodeId}-test-${variable.key}`}
+ type={
+ variable.type === VarType.number
+ ? 'number'
+ : variable.type === VarType.secret
+ ? 'password'
+ : 'text'
+ }
+ step="any"
+ value={testInputs[variable.key] ?? ''}
+ disabled={pending}
+ autoComplete={variable.type === VarType.secret ? 'new-password' : 'off'}
+ aria-invalid={testInputError?.key === variable.key}
+ aria-describedby={
+ testInputError?.key === variable.key
+ ? `${nodeId}-test-${variable.key}-error`
+ : undefined
+ }
+ onChange={(event) => {
+ setTestInputs((current) => ({
+ ...current,
+ [variable.key]: event.target.value,
+ }))
+ resetTestResult()
+ }}
+ />
+ )}
+ {testInputError?.key === variable.key && (
+ <FieldError match id={`${nodeId}-test-${variable.key}-error`}>
+ {testInputError.message}
+ </FieldError>
+ )}
+ </Field>
+ ))}
+ {mutationError && (
+ <p role="alert" className="system-xs-regular text-text-destructive">
+ {mutationError}
+ </p>
+ )}
+ {testMutation.isSuccess && testMutation.data && (
+ <p role="status" className="system-xs-regular text-text-success">
+ {t(($) => $['nodes.humanInputV2.template.testCompleted'], { ns: 'workflow' })}
+ </p>
+ )}
+ <Button onClick={sendTest} loading={pending} disabled={!selectedChannel}>
+ {t(($) => $['nodes.humanInputV2.template.saveAndTest'], { ns: 'workflow' })}
+ </Button>
+ </div>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ {canTest && (
+ <Button
+ className="me-auto"
+ disabled={pending}
+ aria-expanded={showTest}
+ onClick={() => setShowTest(!showTest)}
+ >
+ <span className="i-ri-send-plane-2-line size-4" aria-hidden />
+ {t(($) => $['nodes.humanInputV2.template.test'], { ns: 'workflow' })}
+ </Button>
+ )}
+ <DialogClose render={<Button className="min-w-18" disabled={pending} />}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </DialogClose>
+ {!readonly && (
+ <Button className="min-w-18" type="submit" variant="primary" disabled={pending}>
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ )}
+ </DialogFooter>
+ </form>
+ )
+}
+
+const MessageTemplate = (props: MessageTemplateProps) => {
+ const { t } = useTranslation(['workflow', 'common'])
+ const canRun = useHooksStore((state) => state.accessControl.canRun)
+ const resource = useAtomValue(editorResourceAtom)
+ const canTest = !props.readonly && canRun && resource.kind === 'app'
+ const dialogId = useId()
+ const mutationKey = ['human-input-template-test', dialogId]
+ const client = useQueryClient()
+ const actionsRef = useRef<DialogActions | null>(null)
+ return (
+ <Dialog<boolean>
+ actionsRef={actionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && client.isMutating({ mutationKey })) details.cancel()
+ }}
+ >
+ {({ payload }) => (
+ <>
+ <div className="px-4">
+ <div className="flex min-h-9 items-center gap-2 rounded-lg border border-components-panel-border bg-components-panel-on-panel-item-bg px-2 shadow-xs">
+ <span
+ className="i-ri-mail-send-fill size-5 shrink-0 text-text-tertiary"
+ aria-hidden
+ />
+ <DialogTrigger
+ payload={false}
+ className="min-w-0 grow truncate text-start system-sm-medium text-text-secondary"
+ >
+ {t(($) => $['nodes.humanInputV2.template.title'], { ns: 'workflow' })}
+ </DialogTrigger>
+ <Infotip>
+ <InfotipTrigger
+ aria-label={t(($) => $['nodes.humanInputV2.template.description'], {
+ ns: 'workflow',
+ })}
+ />
+ <InfotipContent>
+ {t(($) => $['nodes.humanInputV2.template.description'], { ns: 'workflow' })}
+ </InfotipContent>
+ </Infotip>
+ {canTest && (
+ <DialogTrigger
+ payload
+ render={
+ <IconButton
+ aria-label={t(($) => $['nodes.humanInputV2.template.test'], {
+ ns: 'workflow',
+ })}
+ >
+ <span className="i-ri-send-plane-2-line size-4" aria-hidden />
+ </IconButton>
+ }
+ />
)}
- </footer>
- </form>
- </DialogContent>
- </Dialog>
- </section>
+ <DialogTrigger
+ payload={false}
+ render={
+ <IconButton aria-label={t(($) => $['common.configure'], { ns: 'workflow' })}>
+ <span className="i-ri-equalizer-2-line size-4" aria-hidden />
+ </IconButton>
+ }
+ />
+ </div>
+ </div>
+ <DialogContent className="w-180">
+ <MessageTemplateSession
+ {...props}
+ initialShowTest={payload ?? false}
+ mutationKey={mutationKey}
+ close={() => actionsRef.current?.close()}
+ />
+ </DialogContent>
+ </>
+ )}
+ </Dialog>
)
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/recipient-avatar.tsx b/web/app/components/workflow/nodes/human-input-v2/components/recipient-avatar.tsx
index 604e3a9cb9d..6beebdf283d 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/recipient-avatar.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/recipient-avatar.tsx
@@ -32,6 +32,7 @@ export function RecipientAvatar({ identity, avatar, name, size, className }: Rec
return (
<Avatar
+ aria-hidden="true"
size={size}
className={cn(
'inset-ring-[0.5px] inset-ring-divider-regular',
@@ -39,7 +40,7 @@ export function RecipientAvatar({ identity, avatar, name, size, className }: Rec
className,
)}
>
- {avatar && <AvatarImage key={avatar.split('?')[0]} keepMounted src={avatar} alt={name} />}
+ {avatar && <AvatarImage key={avatar.split('?')[0]} keepMounted src={avatar} alt="" />}
<AvatarFallback
className={cn(
'bg-linear-to-br from-components-avatar-bg-mask-stop-0 to-components-avatar-bg-mask-stop-100 leading-[1.2]',
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/recipient-contact-preview.tsx b/web/app/components/workflow/nodes/human-input-v2/components/recipient-contact-preview.tsx
index 40a7793e54f..11904bbe1af 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/recipient-contact-preview.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/recipient-contact-preview.tsx
@@ -1,122 +1,138 @@
-import type { ReactElement } from 'react'
-import type { ContactRecipientOption } from '../contact-provider'
+import type { ContactOption } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ReactElement, RefObject } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ContactChannelIcon } from '@/features/contacts/management/channel-icon'
+import { getContactChannelLabel } from '@/features/contacts/management/channel-utils'
import { RecipientAvatar } from './recipient-avatar'
type RecipientContactPreviewProps = {
- contact: ContactRecipientOption
+ contact?: ContactOption
children: ReactElement
- selectOnClick?: boolean
- conflictingContact?: ContactRecipientOption
+ conflictingContact?: ContactOption
onReplace?: () => void
+ returnFocus?: RefObject<HTMLElement | null>
}
export function RecipientContactPreview({
contact,
children,
- selectOnClick,
conflictingContact,
onReplace,
+ returnFocus,
}: RecipientContactPreviewProps) {
const { t } = useTranslation(['workflow', 'contacts'])
const [open, setOpen] = useState(false)
- const sourceLabel = (source: ContactRecipientOption['source']) =>
- source === 'organization'
+ const providers = [...(contact?.email ? ['email'] : []), ...new Set(contact?.im_providers ?? [])]
+ const sourceLabel = (source: ContactOption['type']) =>
+ source === 'platform'
? t(($) => $['type.platform'], { ns: 'contacts' })
: t(($) => $[`nodes.humanInputV2.recipients.contactSource.${source}`], { ns: 'workflow' })
return (
- <Popover
- open={open}
- onOpenChange={(nextOpen, details) => {
- if (selectOnClick && details.reason === 'trigger-press') {
- details.cancel()
- setOpen(false)
- return
- }
- setOpen(nextOpen)
- }}
- >
+ <Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger render={children} openOnHover delay={300} closeDelay={150} />
- <PopoverContent
- side="left"
- align="start"
- sideOffset={4}
- className="flex w-60 flex-col gap-2 bg-components-tooltip-bg p-4 backdrop-blur-[5px]"
- >
- <div
- aria-hidden="true"
- className="size-10 shrink-0 rounded-full border-2 border-components-panel-bg"
+ {contact && (
+ <PopoverContent
+ finalFocus={returnFocus}
+ side="left"
+ align="start"
+ sideOffset={4}
+ className="nokey flex w-60 flex-col gap-2 bg-components-tooltip-bg p-4 backdrop-blur-[5px]"
>
- <RecipientAvatar
- identity={contact.id}
- avatar={contact.avatar ?? null}
- name={contact.name}
- size="xl"
- className="size-full inset-ring-[0.5px] inset-ring-divider-regular"
- />
- </div>
- <div className="flex w-full flex-col gap-px">
- <div className="flex items-start gap-1">
- <PopoverTitle className="min-w-0 system-md-medium wrap-anywhere text-text-primary">
- {contact.name}
- </PopoverTitle>
- <span className="mt-0.5 shrink-0 rounded-[5px] bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary inset-ring-1 inset-ring-divider-deep">
- {sourceLabel(contact.source)}
- </span>
+ <div
+ aria-hidden="true"
+ className="size-10 shrink-0 rounded-full border-2 border-components-panel-bg"
+ >
+ <RecipientAvatar
+ identity={contact.id}
+ avatar={contact.avatar_url ?? null}
+ name={contact.name}
+ size="xl"
+ className="size-full inset-ring-[0.5px] inset-ring-divider-regular"
+ />
</div>
- {contact.email && (
- <div className="flex items-center gap-0.5">
- <p className="system-xs-regular wrap-anywhere text-text-tertiary">{contact.email}</p>
- {conflictingContact && (
- <span className="i-ri-lock-line size-3 shrink-0 text-text-tertiary" aria-hidden />
- )}
+ <div className="flex w-full flex-col gap-px">
+ <div className="flex items-start gap-1">
+ <PopoverTitle className="min-w-0 system-md-medium wrap-anywhere text-text-primary">
+ {contact.name}
+ </PopoverTitle>
+ <span className="mt-0.5 shrink-0 rounded-[5px] bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary inset-ring-1 inset-ring-divider-deep">
+ {sourceLabel(contact.type)}
+ </span>
</div>
- )}
- </div>
- {contact.email && (
- <div className="flex size-5 items-center justify-center rounded-[5px] border border-divider-regular bg-components-panel-on-panel-item-bg">
- <ContactChannelIcon provider="email" className="size-3.5" />
- </div>
- )}
- {conflictingContact && (
- <>
- <div className="my-2 h-px w-full bg-divider-subtle" />
- <div className="flex flex-col gap-2">
- <div className="flex flex-col gap-0.5 system-xs-regular">
- <p className="system-xs-medium text-text-secondary">
- {t(($) => $['nodes.humanInputV2.recipients.duplicateSource'], {
- ns: 'workflow',
- name: conflictingContact.name,
- source: sourceLabel(conflictingContact.source),
- })}
- </p>
- <p className="text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.recipients.emailAlreadySelected'], {
- ns: 'workflow',
- })}
+ {contact.email && (
+ <div className="flex items-center gap-0.5">
+ <p className="system-xs-regular wrap-anywhere text-text-tertiary">
+ {contact.email}
</p>
+ {conflictingContact && (
+ <span className="i-ri-lock-line size-3 shrink-0 text-text-tertiary" aria-hidden />
+ )}
</div>
- {onReplace && (
- <Button
- size="small"
- className="self-start"
- onClick={() => {
- setOpen(false)
- onReplace()
- }}
+ )}
+ </div>
+ {providers.length > 0 && (
+ <div
+ role="group"
+ aria-label={t(($) => $['details.channels'], { ns: 'contacts' })}
+ className="flex flex-wrap gap-1"
+ >
+ {providers.map((provider) => (
+ <span
+ key={provider}
+ role="img"
+ aria-label={
+ provider === 'email'
+ ? t(($) => $['directory.channel.email'], { ns: 'contacts' })
+ : getContactChannelLabel(provider)
+ }
+ className="flex size-5 items-center justify-center rounded-[5px] border border-divider-regular bg-components-panel-on-panel-item-bg"
>
- {t(($) => $['nodes.humanInputV2.recipients.useThisInstead'], { ns: 'workflow' })}
- </Button>
- )}
+ <ContactChannelIcon provider={provider} className="size-3.5" />
+ </span>
+ ))}
</div>
- </>
- )}
- </PopoverContent>
+ )}
+ {conflictingContact && (
+ <>
+ <div className="my-2 h-px w-full bg-divider-subtle" />
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-0.5 system-xs-regular">
+ <p className="system-xs-medium text-text-secondary">
+ {t(($) => $['nodes.humanInputV2.recipients.duplicateSource'], {
+ ns: 'workflow',
+ name: conflictingContact.name,
+ source: sourceLabel(conflictingContact.type),
+ })}
+ </p>
+ <p className="text-text-tertiary">
+ {t(($) => $['nodes.humanInputV2.recipients.emailAlreadySelected'], {
+ ns: 'workflow',
+ })}
+ </p>
+ </div>
+ {onReplace && (
+ <Button
+ size="small"
+ className="self-start"
+ onClick={() => {
+ setOpen(false)
+ onReplace()
+ }}
+ >
+ {t(($) => $['nodes.humanInputV2.recipients.useThisInstead'], {
+ ns: 'workflow',
+ })}
+ </Button>
+ )}
+ </div>
+ </>
+ )}
+ </PopoverContent>
+ )}
</Popover>
)
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/components/recipients.tsx b/web/app/components/workflow/nodes/human-input-v2/components/recipients.tsx
index c9bf92d389f..e825dd14217 100644
--- a/web/app/components/workflow/nodes/human-input-v2/components/recipients.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/components/recipients.tsx
@@ -1,36 +1,54 @@
'use client'
-import type { KeyboardEvent } from 'react'
-import type { ContactRecipientOption, ContactRecipientOptionProvider } from '../contact-provider'
+import type { ContactOption } from '@dify/contracts/api/console/workspaces/types.gen'
import type { HumanInputV2Recipient } from '../types'
-import type { Node, ValueSelector, Var } from '@/app/components/workflow/types'
+import type { Node, Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
+import {
+ Combobox,
+ ComboboxChip,
+ ComboboxChipRemove,
+ ComboboxChips,
+ ComboboxInput,
+ ComboboxInputGroup,
+ ComboboxItem,
+ ComboboxItemIndicator,
+ ComboboxList,
+ ComboboxPopup,
+ ComboboxPortal,
+ ComboboxPositioner,
+ ComboboxStatus,
+ ComboboxTrigger,
+ ComboboxValue,
+ createComboboxItems,
+} from '@langgenius/dify-ui/combobox'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
-import { Input } from '@langgenius/dify-ui/input'
-import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { useQuery } from '@tanstack/react-query'
+import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
+import { skipToken, useInfiniteQuery, useQuery } from '@tanstack/react-query'
+import { useDebounce } from 'ahooks'
import { useAtomValue } from 'jotai'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { WorkspaceAvatar } from '@/app/components/base/workspace-avatar'
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
import { VariableLabelInEditor } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
import { VarType } from '@/app/components/workflow/types'
-import { currentWorkspaceAtom, isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'
+import {
+ currentWorkspaceAtom,
+ currentWorkspaceIdAtom,
+ isCurrentWorkspaceManagerAtom,
+} from '@/context/workspace-state'
import { selectIMCentrallyManaged } from '@/features/contacts/im-capability'
import { consoleQuery } from '@/service/console'
-import { useContactRecipientOptionProvider } from '../contact-provider'
+import { getContactRecipientQueryOptions } from '../contact-queries'
import {
addRecipient,
findConflictingContact,
getRecipientCanonicalKey,
getRecipientValidationError,
hasDuplicateRecipients,
- removeRecipient,
replaceContactRecipient,
} from '../recipient-utils'
import { RecipientAvatar } from './recipient-avatar'
@@ -41,273 +59,210 @@ type RecipientsProps = {
value: HumanInputV2Recipient[]
onChange: (value: HumanInputV2Recipient[]) => void
readonly: boolean
- provider?: ContactRecipientOptionProvider
- workspace?: { name: string; contactCount?: number }
availableNodes?: Node[]
}
-
-const getOptionLabel = (option: ContactRecipientOption) =>
- option.email ? `${option.name} · ${option.email}` : option.name
-
-type ContactSourceFilter = 'all' | ContactRecipientOption['source']
-
-const contactSourceFilters: ContactSourceFilter[] = ['all', 'workspace', 'organization', 'external']
+type SourceFilter = 'all' | 'workspace' | 'organization' | 'external'
+type RecipientItem = {
+ key: string
+ label: string
+ recipient: HumanInputV2Recipient
+ contact?: ContactOption
+}
+const sourceFilters: SourceFilter[] = ['all', 'workspace', 'organization', 'external']
+const getContactLabel = (contact: ContactOption) =>
+ contact.email ? `${contact.name} · ${contact.email}` : contact.name
const RecipientsContent = ({
nodeId,
value,
onChange,
readonly,
- provider,
- workspace,
availableNodes = [],
-}: RecipientsProps & { provider: ContactRecipientOptionProvider }) => {
- const { t } = useTranslation(['workflow', 'contacts'])
+ workspaceId,
+ workspace,
+}: RecipientsProps & {
+ workspaceId: string
+ workspace: { name: string; contactCount?: number }
+}) => {
+ const { t } = useTranslation(['workflow', 'contacts', 'common'])
const [open, setOpen] = useState(false)
- const [searchFromInput, setSearchFromInput] = useState(false)
const [query, setQuery] = useState('')
- const [options, setOptions] = useState<ContactRecipientOption[]>([])
- const [sourceFilter, setSourceFilter] = useState<ContactSourceFilter>('all')
- const centrallyManagedQuery = useQuery(
- consoleQuery.features.get.queryOptions({
- select: selectIMCentrallyManaged,
- retry: false,
- }),
- )
- const centrallyManaged = centrallyManagedQuery.isSuccess && centrallyManagedQuery.data === true
- const availableSourceFilters = contactSourceFilters.filter(
- (filter) => filter !== 'organization' || centrallyManaged,
- )
- const activeSourceFilter =
- sourceFilter === 'organization' && !centrallyManaged ? 'all' : sourceFilter
- const [resolvedOptions, setResolvedOptions] = useState<ContactRecipientOption[]>([])
- const [loading, setLoading] = useState(false)
- const [loadError, setLoadError] = useState(false)
- const [searchPage, setSearchPage] = useState(1)
- const [hasMore, setHasMore] = useState(false)
- const [loadingMore, setLoadingMore] = useState(false)
- const searchRequestRef = useRef(0)
- const searchQueryRef = useRef('')
- const [emailDraft, setEmailDraft] = useState('')
+ const keyword = useDebounce(query.trim(), { wait: 300 })
+ const isDebouncing = keyword !== query.trim()
+ const [source, setSource] = useState<SourceFilter>('all')
const [emailError, setEmailError] = useState(false)
- const firstOptionRef = useRef<HTMLButtonElement>(null)
- const recipientInputRef = useRef<HTMLInputElement>(null)
+ const [highlighted, setHighlighted] = useState<string>()
+ const [previewContact, setPreviewContact] = useState<ContactOption>()
+ const inputRef = useRef<HTMLInputElement>(null)
const variableTriggerRef = useRef<HTMLButtonElement>(null)
-
- const selectedKeys = useMemo(
- () => new Set(value.map(getRecipientCanonicalKey).filter((key): key is string => !!key)),
- [value],
+ const contactIds = value.flatMap((recipient) =>
+ recipient.type === 'contact' ? [recipient.contact_id] : [],
)
- const resolvedMap = useMemo(
- () => new Map(resolvedOptions.map((option) => [option.id, option])),
- [resolvedOptions],
+ const resolved = useQuery(getContactRecipientQueryOptions(workspaceId, contactIds))
+ const features = useQuery(
+ consoleQuery.features.get.queryOptions({ select: selectIMCentrallyManaged, retry: false }),
)
- const visibleOptions = useMemo(
- () =>
- activeSourceFilter === 'all'
- ? options
- : options.filter((option) => option.source === activeSourceFilter),
- [options, activeSourceFilter],
+ const centrallyManaged = features.isSuccess && features.data
+ const activeSource = source === 'organization' && !centrallyManaged ? 'all' : source
+ const operation = consoleQuery.workspaces.current.humanInput.v2.contactOptions.get
+ const searchInput = workspaceId
+ ? (page: number) => ({ query: { keyword, page, limit: 20 } })
+ : skipToken
+ const search = useInfiniteQuery(
+ operation.infiniteOptions({
+ input: searchInput,
+ queryKey: [
+ ...operation.infiniteKey({ input: searchInput, initialPageParam: 1 }),
+ { workspaceId },
+ ],
+ initialPageParam: 1,
+ getNextPageParam: (page) => (page.page * page.limit < page.total ? page.page + 1 : undefined),
+ enabled: open,
+ context: { silent: true },
+ retry: false,
+ }),
)
- const recipientRows = useMemo(() => {
- const occurrences = new Map<string, number>()
- return value.map((recipient, index) => {
- const baseKey =
- getRecipientCanonicalKey(recipient) ?? `${recipient.type}:${JSON.stringify(recipient)}`
- const occurrence = occurrences.get(baseKey) ?? 0
- occurrences.set(baseKey, occurrence + 1)
- return { recipient, index, key: `${baseKey}:${occurrence}` }
- })
- }, [value])
-
- useEffect(() => {
- const ids = [
- ...new Set(
- value
- .filter(
- (recipient): recipient is Extract<HumanInputV2Recipient, { type: 'contact' }> =>
- recipient.type === 'contact',
+ const { selectedItems, results, itemMap, items } = useMemo(() => {
+ const contacts = search.data?.pages.flatMap((page) => page.data) ?? []
+ const selectedContacts = resolved.data?.data ?? []
+ const contactMap = new Map(
+ [...contacts, ...selectedContacts].map((contact) => [contact.id, contact]),
+ )
+ const labelFor = (recipient: HumanInputV2Recipient) => {
+ switch (recipient.type) {
+ case 'contact':
+ return contactMap.has(recipient.contact_id)
+ ? getContactLabel(contactMap.get(recipient.contact_id)!)
+ : resolved.isSuccess
+ ? t(($) => $['details.notFound'], { ns: 'contacts' })
+ : t(
+ ($) =>
+ $[
+ resolved.isError
+ ? 'nodes.humanInputV2.recipients.loadError'
+ : 'nodes.humanInputV2.recipients.loading'
+ ],
+ { ns: 'workflow' },
+ )
+ case 'initiator':
+ return t(($) => $['nodes.humanInputV2.recipients.type.initiator'], { ns: 'workflow' })
+ case 'all_workspace_contacts':
+ return (
+ workspace.name ||
+ t(($) => $['nodes.humanInputV2.recipients.allWorkspaceContacts'], { ns: 'workflow' })
)
- .map((recipient) => recipient.contact_id),
- ),
- ]
- if (!ids.length) return
-
- let active = true
- provider
- .resolve({ contact_ids: ids })
- .then((result) => {
- if (active) setResolvedOptions(result)
- })
- .catch(() => {
- if (active)
- setResolvedOptions((current) => current.filter((option) => ids.includes(option.id)))
- })
- return () => {
- active = false
+ case 'onetime_email':
+ return recipient.email
+ case 'dynamic_email':
+ return [
+ availableNodes.find((node) => node.id === recipient.selector[0])?.data.title,
+ ...recipient.selector.slice(1),
+ ]
+ .filter(Boolean)
+ .join(' / ')
+ }
}
- }, [provider, value])
-
- const loadOptions = useCallback(
- async (nextQuery: string, page = 1) => {
- const requestId = ++searchRequestRef.current
- searchQueryRef.current = nextQuery
- setLoading(page === 1)
- setLoadingMore(page > 1)
- setLoadError(false)
- if (page === 1) {
- setOptions([])
- setHasMore(false)
+ const occurrences = new Map<string, number>()
+ const selectedItems: RecipientItem[] = value.map((recipient, index) => {
+ const canonical = getRecipientCanonicalKey(recipient) ?? `invalid:${index}`
+ const occurrence = occurrences.get(canonical) ?? 0
+ occurrences.set(canonical, occurrence + 1)
+ return {
+ key: occurrence ? `${canonical}:duplicate:${occurrence}` : canonical,
+ label: labelFor(recipient),
+ recipient,
+ contact: recipient.type === 'contact' ? contactMap.get(recipient.contact_id) : undefined,
}
- try {
- const result = provider.searchPage
- ? await provider.searchPage(nextQuery, page)
- : { data: await provider.search(nextQuery), page: 1, hasMore: false }
- if (requestId !== searchRequestRef.current) return
- setOptions((current) =>
- page === 1
- ? result.data
- : [
- ...new Map(
- [...current, ...result.data].map((option) => [option.id, option]),
- ).values(),
- ],
+ })
+ const specialRecipients: HumanInputV2Recipient[] =
+ activeSource === 'all'
+ ? [{ type: 'initiator' }, { type: 'all_workspace_contacts' }]
+ : activeSource === 'workspace'
+ ? [{ type: 'all_workspace_contacts' }]
+ : []
+ const results: RecipientItem[] = [
+ ...contacts
+ .filter(
+ (contact) =>
+ activeSource === 'all' ||
+ contact.type === (activeSource === 'organization' ? 'platform' : activeSource),
)
- setSearchPage(result.page)
- setHasMore(result.hasMore)
- } catch {
- if (requestId !== searchRequestRef.current) return
- setLoadError(true)
- } finally {
- if (requestId === searchRequestRef.current) {
- setLoading(false)
- setLoadingMore(false)
- }
- }
- },
- [provider],
- )
-
- const loadMore = () => {
- if (!hasMore || loading || loadingMore) return
- void loadOptions(searchQueryRef.current, searchPage + 1)
- }
-
- useEffect(() => {
- // The editor-safe endpoint paginates all sources together. Keep looking until the
- // selected source has a result, or the server confirms that no later page exists.
- if (
- !open ||
- activeSourceFilter === 'all' ||
- visibleOptions.length > 0 ||
- !hasMore ||
- loading ||
- loadingMore ||
- loadError
- )
- return
-
- void loadOptions(searchQueryRef.current, searchPage + 1)
+ .map((contact) => ({
+ key: `contact:${contact.id}`,
+ label: getContactLabel(contact),
+ recipient: { type: 'contact' as const, contact_id: contact.id },
+ contact,
+ })),
+ ...specialRecipients
+ .filter(
+ (recipient) =>
+ !query.trim() ||
+ labelFor(recipient).toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()),
+ )
+ .map((recipient) => ({ key: recipient.type, label: labelFor(recipient), recipient })),
+ ]
+ const itemMap = new Map([...results, ...selectedItems].map((item) => [item.key, item]))
+ const items = createComboboxItems([...itemMap.values()], {
+ getValue: (item) => item.key,
+ getLabel: (item) => item.label,
+ })
+ return { selectedItems, results, itemMap, items }
}, [
- hasMore,
- loadError,
- loadOptions,
- loading,
- loadingMore,
- open,
- searchPage,
- activeSourceFilter,
- visibleOptions.length,
+ search.data,
+ resolved.data,
+ resolved.isSuccess,
+ resolved.isError,
+ value,
+ activeSource,
+ query,
+ availableNodes,
+ t,
+ workspace.name,
])
-
- const handleOpenChange = (nextOpen: boolean) => {
+ const selectedContacts = selectedItems.flatMap((item) => (item.contact ? [item.contact] : []))
+ const selectedKeys = selectedItems.map((item) => item.key)
+ const previewConflict =
+ previewContact &&
+ findConflictingContact(
+ value,
+ { id: previewContact.id, email: previewContact.email ?? '' },
+ selectedContacts.map((contact) => ({ ...contact, email: contact.email ?? '' })),
+ )
+ const commit = (next: HumanInputV2Recipient[]) => {
if (readonly) return
- setOpen(nextOpen)
- if (nextOpen) {
- setSearchFromInput(false)
- setQuery('')
- setSourceFilter('all')
- void loadOptions('')
- }
- }
-
- const add = (recipient: HumanInputV2Recipient) => {
- if (recipient.type === 'contact') {
- const option = options.find((option) => option.id === recipient.contact_id)
- if (option && findConflictingContact(value, option, resolvedOptions)) return
- }
- const nextValue = addRecipient(value, recipient)
- if (recipient.type === 'contact') {
- const option = options.find((option) => option.id === recipient.contact_id)
- if (option) {
- setResolvedOptions((current) => [
- ...current.filter((item) => item.id !== option.id),
- option,
- ])
- }
- }
- if (nextValue !== value) onChange(nextValue)
- setEmailDraft('')
+ onChange(next)
setQuery('')
setEmailError(false)
setOpen(false)
}
-
- const replaceContact = (previousContactId: string, nextContact: ContactRecipientOption) => {
- const nextValue = replaceContactRecipient(value, previousContactId, nextContact.id)
- if (nextValue === value) return
- setResolvedOptions((current) => [
- ...current.filter((item) => item.id !== previousContactId && item.id !== nextContact.id),
- nextContact,
- ])
- onChange(nextValue)
- setEmailDraft('')
- setQuery('')
- setEmailError(false)
- setOpen(false)
- }
-
- const addOneTimeEmail = () => {
- const recipients: HumanInputV2Recipient[] = emailDraft.split(',').map((email) => ({
- type: 'onetime_email',
- email: email.trim(),
- }))
- const invalid = recipients.some((recipient) => !!getRecipientValidationError(recipient))
- const duplicate =
- hasDuplicateRecipients(recipients) ||
- recipients.some((recipient) => selectedKeys.has(getRecipientCanonicalKey(recipient) || ''))
- setEmailError(invalid || duplicate)
- if (invalid || duplicate) return
- onChange([...value, ...recipients])
- setEmailDraft('')
- setQuery('')
- setOpen(false)
- }
-
- const getRecipientLabel = (recipient: HumanInputV2Recipient) => {
- if (recipient.type === 'all_workspace_contacts')
- return (
- workspace?.name ||
- t(($) => $['nodes.humanInputV2.recipients.allWorkspaceContacts'], { ns: 'workflow' })
- )
- if (recipient.type === 'initiator')
- return t(($) => $['nodes.humanInputV2.recipients.type.initiator'], { ns: 'workflow' })
- if (recipient.type === 'contact')
- return resolvedMap.get(recipient.contact_id)
- ? getOptionLabel(resolvedMap.get(recipient.contact_id)!)
- : recipient.contact_id
- if (recipient.type === 'dynamic_email') {
- const node = availableNodes.find((node) => node.id === recipient.selector[0])
- return (
- node ? [node.data.title, ...recipient.selector.slice(1)] : recipient.selector.slice(1)
- ).join(' / ')
+ const addEmail = () => {
+ const additions: HumanInputV2Recipient[] = query
+ .split(',')
+ .map((email) => ({ type: 'onetime_email', email: email.trim() }))
+ if (
+ additions.some((recipient) => getRecipientValidationError(recipient)) ||
+ hasDuplicateRecipients([...value, ...additions])
+ ) {
+ setEmailError(true)
+ inputRef.current?.focus()
+ return
}
- return recipient.email
+ commit([...value, ...additions])
+ inputRef.current?.focus()
}
+ const infoName = (name: string) =>
+ t(($) => $['nodes.humanInputV2.recipients.contactInfo'], { ns: 'workflow', name })
+ const inputHint = t(($) => $['nodes.humanInputV2.recipients.selectionHint'], {
+ ns: 'workflow',
+ count: value.length,
+ })
+ const invalidMessage = t(($) => $['nodes.humanInputV2.error.recipientInvalid'], {
+ ns: 'workflow',
+ })
return (
- <section className="px-4 pt-2" aria-labelledby={`${nodeId}-recipients-label`}>
- <div className="mb-1 flex h-6 items-center gap-0.5">
+ <div className="nokey px-4 pt-2">
+ <div className="mb-1 flex min-h-6 items-center gap-0.5">
<h3
id={`${nodeId}-recipients-label`}
className="system-sm-semibold-uppercase text-text-secondary"
@@ -316,674 +271,570 @@ const RecipientsContent = ({
</h3>
<Infotip>
<InfotipTrigger
- aria-label={t(($) => $['nodes.humanInputV2.recipients.title'], { ns: 'workflow' })}
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.help'], { ns: 'workflow' })}
/>
<InfotipContent>
{t(($) => $['nodes.humanInputV2.recipients.help'], { ns: 'workflow' })}
</InfotipContent>
</Infotip>
</div>
-
- <div
- className={cn(
- 'min-h-20 rounded-lg bg-components-input-bg-normal focus-within:ring-1 focus-within:ring-components-input-border-active',
- readonly && 'opacity-70',
- )}
- >
- <div
- className="flex min-h-11 flex-wrap content-start items-start gap-1 px-2 pt-2 pb-0.5"
- aria-live="polite"
- >
- {recipientRows.map(({ recipient, index, key }) => {
- const contact =
- recipient.type === 'contact' ? resolvedMap.get(recipient.contact_id) : undefined
- const invalidEmail =
- recipient.type === 'onetime_email' && !!getRecipientValidationError(recipient)
- const invalid =
- !!getRecipientValidationError(recipient) ||
- (hasDuplicateRecipients(value) &&
- value.findIndex(
- (item) => getRecipientCanonicalKey(item) === getRecipientCanonicalKey(recipient),
- ) !== index)
- const chipClassName = cn(
- 'flex h-5 max-w-full items-center gap-1 rounded-full bg-components-badge-white-to-dark p-0.5 system-xs-regular text-text-primary shadow-xs inset-ring-[0.5px] inset-ring-components-panel-border-subtle',
- (recipient.type === 'initiator' || recipient.type === 'all_workspace_contacts') &&
- 'bg-util-colors-indigo-indigo-100 font-medium text-util-colors-indigo-indigo-700 inset-ring-util-colors-indigo-indigo-200',
- recipient.type === 'dynamic_email' &&
- 'rounded-[5px] bg-util-colors-blue-blue-50 text-text-accent',
- invalid && 'bg-state-destructive-hover text-text-destructive',
- !readonly &&
- 'focus-within:bg-util-colors-blue-blue-50 focus-within:inset-ring-1 focus-within:inset-ring-state-accent-solid',
- )
- const label = contact ? getOptionLabel(contact) : getRecipientLabel(recipient)
- const removeChip = () => {
- onChange(removeRecipient(value, index))
- setSearchFromInput(true)
- setOpen(false)
- recipientInputRef.current?.focus()
- }
- const handleChipKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
- if (
- event.nativeEvent.isComposing ||
- event.altKey ||
- event.ctrlKey ||
- event.metaKey ||
- event.shiftKey ||
- (event.key !== 'Backspace' && event.key !== 'Delete')
+ <Combobox<string, true, RecipientItem>
+ multiple
+ modal={false}
+ readOnly={readonly}
+ items={items}
+ filteredItems={isDebouncing ? [] : results}
+ filter={null}
+ value={selectedKeys}
+ inputValue={query}
+ open={open}
+ onOpenChange={(next) => {
+ if (!readonly) {
+ setOpen(next)
+ if (!next) setQuery('')
+ }
+ }}
+ onInputValueChange={(next, details) => {
+ if (details.reason === 'input-change') setPreviewContact(undefined)
+ setQuery(next)
+ setEmailError(false)
+ }}
+ onItemHighlighted={(key) => {
+ setHighlighted(key)
+ if (key !== undefined) setPreviewContact(itemMap.get(key)?.contact)
+ }}
+ onValueChange={(next, details) => {
+ if (readonly || details.reason === 'escape-key') {
+ details.cancel()
+ return
+ }
+ const added = next.find((key) => !selectedKeys.includes(key))
+ if (added) {
+ const item = itemMap.get(added)
+ if (!item) return
+ if (
+ item.contact &&
+ findConflictingContact(
+ value,
+ { id: item.contact.id, email: item.contact.email ?? '' },
+ selectedContacts.map((contact) => ({ ...contact, email: contact.email ?? '' })),
)
- return
- event.preventDefault()
- event.stopPropagation()
- if (event.repeat) return
- removeChip()
- }
- const chipContent = (
- <>
- {invalidEmail && (
- <span
- className="i-ri-error-warning-fill size-4 shrink-0 text-text-destructive"
- aria-hidden
- />
- )}
- {recipient.type === 'onetime_email' && !invalidEmail && (
- <RecipientAvatar
- identity={recipient.email.trim().toLowerCase()}
- avatar={null}
- name={recipient.email}
- size="xxs"
- className="[&>span]:text-[10px]"
- />
- )}
- {(recipient.type === 'initiator' ||
- recipient.type === 'all_workspace_contacts') && (
- <span className="flex size-4 shrink-0 items-center justify-center rounded-full bg-util-colors-indigo-indigo-500 text-text-primary-on-surface">
- {recipient.type === 'all_workspace_contacts' && workspace?.name ? (
- <WorkspaceAvatar
- name={workspace.name}
- size="xs"
- className="size-4 rounded-full"
- />
- ) : (
- <span
- className={cn(
- 'size-3',
- recipient.type === 'initiator'
- ? 'i-ri-user-follow-line'
- : 'i-ri-group-line',
- )}
- aria-hidden
- />
- )}
- </span>
- )}
- {contact ? (
- <>
- <span aria-hidden="true" className="flex shrink-0">
- <RecipientAvatar
- identity={contact.id}
- avatar={contact.avatar ?? null}
- name={contact.name}
- size="xxs"
- className="[&>span]:text-[10px]"
- />
- </span>
- <span className="max-w-[260px] truncate px-0.5">{contact.name}</span>
- </>
- ) : recipient.type === 'dynamic_email' ? (
- <VariableLabelInEditor
- variables={recipient.selector}
- nodeType={
- availableNodes.find((node) => node.id === recipient.selector[0])?.data.type
- }
- nodeTitle={
- availableNodes.find((node) => node.id === recipient.selector[0])?.data.title
- }
- />
- ) : (
- <span className="max-w-[260px] truncate px-0.5">
- {getRecipientLabel(recipient)}
- </span>
- )}
- {recipient.type === 'all_workspace_contacts' &&
- workspace?.contactCount !== undefined && (
- <span className="pe-1 text-text-tertiary">{workspace.contactCount}</span>
- )}
- {invalid && (
- <span className="sr-only">
- {t(($) => $['nodes.humanInputV2.error.recipientInvalid'], {
- ns: 'workflow',
- })}
- </span>
- )}
- </>
)
- const chip =
- readonly && !contact && !invalidEmail ? (
- <span className="flex min-w-0 items-center gap-1">{chipContent}</span>
- ) : (
- <button
- type="button"
- aria-label={label}
- aria-keyshortcuts={readonly ? undefined : 'Backspace Delete'}
- className="flex min-w-0 items-center gap-1 rounded-[inherit] border-0 text-start focus-visible:ring-1 focus-visible:ring-state-accent-solid"
- onKeyDown={readonly ? undefined : handleChipKeyDown}
- >
- {chipContent}
- </button>
- )
- const preview = invalidEmail ? (
- <Tooltip>
- <TooltipTrigger render={chip} />
- <TooltipContent>
- {t(($) => $['nodes.humanInputV2.recipients.emailInvalidOrDuplicate'], {
- ns: 'workflow',
- })}
- </TooltipContent>
- </Tooltip>
- ) : contact ? (
- <RecipientContactPreview contact={contact} selectOnClick={!readonly}>
- {chip}
- </RecipientContactPreview>
- ) : (
- chip
+ return
+ commit(addRecipient(value, item.recipient))
+ } else {
+ onChange(
+ selectedItems.filter((item) => next.includes(item.key)).map((item) => item.recipient),
)
- return (
- <span key={key} className={chipClassName}>
- {preview}
+ if (details.reason !== 'item-press') setOpen(false)
+ }
+ }}
+ >
+ <ComboboxInputGroup className="min-h-20 flex-col items-stretch py-2 data-readonly:opacity-70">
+ <ComboboxValue<string, true>>
+ {() => (
+ <ComboboxChips
+ aria-label={
+ value.length
+ ? t(($) => $['nodes.humanInputV2.recipients.title'], { ns: 'workflow' })
+ : undefined
+ }
+ >
+ {selectedItems.map((item, index) => {
+ const recipient = item.recipient
+ const invalid =
+ !!getRecipientValidationError(recipient) ||
+ value.findIndex(
+ (other) =>
+ getRecipientCanonicalKey(other) === getRecipientCanonicalKey(recipient),
+ ) !== index ||
+ (recipient.type === 'contact' &&
+ resolved.isSuccess &&
+ !(resolved.data?.data ?? []).some(
+ (contact) => contact.id === recipient.contact_id,
+ ))
+ return (
+ <ComboboxChip
+ key={item.key}
+ onKeyDown={(event) => {
+ // The chip owns keys only while the chip itself is focused. Its
+ // information button and portalled content own their own commands.
+ if (event.target !== event.currentTarget) event.preventBaseUIHandler()
+ }}
+ onFocus={() => {
+ setPreviewContact(item.contact)
+ }}
+ aria-label={item.label}
+ aria-description={
+ readonly
+ ? undefined
+ : t(($) => $['nodes.humanInputV2.recipients.removeHint'], {
+ ns: 'workflow',
+ })
+ }
+ aria-invalid={invalid || undefined}
+ aria-describedby={
+ [
+ invalid ? `${nodeId}-invalid-${index}` : undefined,
+ recipient.type === 'contact' && !item.contact
+ ? `${nodeId}-contact-${index}`
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined
+ }
+ className="rounded-full aria-invalid:bg-state-destructive-hover aria-invalid:text-text-destructive data-[recipient-type=all_workspace_contacts]:bg-util-colors-indigo-indigo-100 data-[recipient-type=all_workspace_contacts]:text-util-colors-indigo-indigo-700 data-[recipient-type=dynamic_email]:bg-util-colors-blue-blue-50 data-[recipient-type=dynamic_email]:text-text-accent data-[recipient-type=initiator]:bg-util-colors-indigo-indigo-100 data-[recipient-type=initiator]:text-util-colors-indigo-indigo-700"
+ data-recipient-type={recipient.type}
+ >
+ {recipient.type === 'initiator' && (
+ <span
+ className="flex size-4 shrink-0 items-center justify-center rounded-full bg-util-colors-indigo-indigo-500 text-text-primary-on-surface"
+ aria-hidden
+ >
+ <span className="i-ri-user-follow-line size-3" />
+ </span>
+ )}
+ {recipient.type === 'onetime_email' && !invalid && (
+ <RecipientAvatar
+ identity={recipient.email.trim().toLocaleLowerCase()}
+ name={recipient.email}
+ size="xxs"
+ />
+ )}
+ {invalid && (
+ <span className="i-ri-error-warning-fill size-3.5 shrink-0" aria-hidden />
+ )}
+ {item.contact && (
+ <RecipientAvatar
+ identity={item.contact.id}
+ name={item.contact.name}
+ avatar={item.contact.avatar_url}
+ size="xxs"
+ />
+ )}
+ {recipient.type === 'all_workspace_contacts' && workspace.name && (
+ <span aria-hidden>
+ <WorkspaceAvatar name={workspace.name} size="xs" />
+ </span>
+ )}
+ {recipient.type === 'dynamic_email' ? (
+ <VariableLabelInEditor
+ variables={recipient.selector}
+ nodeType={
+ availableNodes.find((node) => node.id === recipient.selector[0])?.data
+ .type
+ }
+ nodeTitle={
+ availableNodes.find((node) => node.id === recipient.selector[0])?.data
+ .title
+ }
+ />
+ ) : (
+ <span className="max-w-65 truncate">
+ {item.contact?.name ?? item.label}
+ </span>
+ )}
+ {recipient.type === 'all_workspace_contacts' &&
+ workspace.contactCount !== undefined && (
+ <span>{workspace.contactCount}</span>
+ )}
+ {invalid && (
+ <span id={`${nodeId}-invalid-${index}`} className="sr-only">
+ {invalidMessage}
+ </span>
+ )}
+ {recipient.type === 'contact' && !item.contact && (
+ <span id={`${nodeId}-contact-${index}`} className="sr-only">
+ {recipient.contact_id}
+ </span>
+ )}
+ {item.contact && (
+ <RecipientContactPreview contact={item.contact}>
+ <IconButton size="xs" aria-label={infoName(item.contact.name)}>
+ <span className="i-ri-information-line size-3" aria-hidden />
+ </IconButton>
+ </RecipientContactPreview>
+ )}
+ {!readonly && (
+ <ComboboxChipRemove
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.remove'], {
+ ns: 'workflow',
+ recipient: item.label,
+ })}
+ />
+ )}
+ </ComboboxChip>
+ )
+ })}
{!readonly && (
- <IconButton
- size="xs"
- className="shrink-0"
- aria-label={t(($) => $['nodes.humanInputV2.recipients.remove'], {
+ <ComboboxInput
+ ref={inputRef}
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.placeholder'], {
ns: 'workflow',
- recipient: label,
})}
- aria-keyshortcuts="Backspace Delete"
- onKeyDown={handleChipKeyDown}
- onClick={(event) => {
- event.stopPropagation()
- removeChip()
+ aria-describedby={`${nodeId}-selection-hint${emailError ? ` ${nodeId}-recipient-email-error` : ''}`}
+ aria-invalid={emailError}
+ placeholder={
+ value.length
+ ? ''
+ : t(($) => $['nodes.humanInputV2.recipients.placeholder'], {
+ ns: 'workflow',
+ })
+ }
+ className="min-w-4 py-0.5"
+ onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing) return
+ // oxlint-disable-next-line typescript/no-deprecated -- Safari can report 229 without isComposing while confirming IME text.
+ if (event.nativeEvent.keyCode === 229) return
+ if (event.key === '/' && !query.trim()) {
+ event.preventDefault()
+ variableTriggerRef.current?.click()
+ }
+ if (
+ event.key === 'Enter' &&
+ query.trim() &&
+ (!open || !highlighted) &&
+ !event.defaultPrevented
+ ) {
+ event.preventDefault()
+ const candidate =
+ !query.includes(',') &&
+ !isDebouncing &&
+ !search.isFetching &&
+ !search.isError &&
+ results.find(
+ (item) =>
+ !value.some(
+ (recipient) =>
+ getRecipientCanonicalKey(recipient) ===
+ getRecipientCanonicalKey(item.recipient),
+ ) &&
+ (!query.includes('@') ||
+ item.contact?.email?.toLocaleLowerCase() ===
+ query.trim().toLocaleLowerCase()),
+ )
+ if (
+ candidate &&
+ (!candidate.contact ||
+ !findConflictingContact(
+ value,
+ { id: candidate.contact.id, email: candidate.contact.email ?? '' },
+ selectedContacts.map((contact) => ({
+ ...contact,
+ email: contact.email ?? '',
+ })),
+ ))
+ )
+ commit(addRecipient(value, candidate.recipient))
+ else addEmail()
+ }
}}
- >
- <span aria-hidden className="i-ri-close-line size-3" />
- </IconButton>
+ />
)}
- </span>
- )
- })}
- {!readonly && (
- <>
- <Input
- ref={recipientInputRef}
- aria-label={t(($) => $['nodes.humanInputV2.recipients.placeholder'], {
- ns: 'workflow',
- })}
- value={emailDraft}
- onChange={(event) => {
- const nextQuery = event.target.value
- setEmailDraft(nextQuery)
- setQuery(nextQuery)
- setEmailError(false)
- setSearchFromInput(true)
- setSourceFilter('all')
- setOpen(!!nextQuery.trim())
- if (nextQuery.trim()) void loadOptions(nextQuery)
- else {
- searchRequestRef.current += 1
- searchQueryRef.current = ''
- setOptions([])
- setLoading(false)
- setLoadingMore(false)
- setLoadError(false)
- setHasMore(false)
- }
- }}
- onKeyDown={(event) => {
- if (readonly || event.nativeEvent.isComposing) return
- if (
- event.key === 'Backspace' &&
- !event.altKey &&
- !event.ctrlKey &&
- !event.metaKey &&
- !event.shiftKey &&
- emailDraft === '' &&
- value.length > 0
- ) {
- event.preventDefault()
- event.stopPropagation()
- if (event.repeat) return
- const lastIndex = value.length - 1
- onChange(removeRecipient(value, lastIndex))
- setSearchFromInput(true)
- setOpen(false)
- return
- }
- if (event.key === '/' && !emailDraft.trim()) {
- event.preventDefault()
- variableTriggerRef.current?.click()
- return
- }
- if (event.key === 'ArrowDown' && open) {
- event.preventDefault()
- firstOptionRef.current?.focus()
- }
- if (event.key === 'Escape') setOpen(false)
- if (event.key === 'Enter') {
- event.preventDefault()
- const searchValue = emailDraft.trim().toLowerCase()
- if (!searchValue) return
- const option =
- !searchValue.includes(',') &&
- !loading &&
- !loadError &&
- searchQueryRef.current === emailDraft &&
- visibleOptions.find(
- (option) =>
- !selectedKeys.has(`contact:${option.id}`) &&
- !findConflictingContact(value, option, resolvedOptions) &&
- (!searchValue.includes('@') ||
- option.email.toLowerCase() === searchValue),
- )
- if (option) add({ type: 'contact', contact_id: option.id })
- else addOneTimeEmail()
- }
- }}
- placeholder={
- value.length
- ? ''
- : t(($) => $['nodes.humanInputV2.recipients.placeholder'], {
- ns: 'workflow',
- })
- }
- aria-invalid={emailError}
- aria-describedby={emailError ? `${nodeId}-recipient-email-error` : undefined}
- // oxlint-disable-next-line shadcn/no-restyle -- The enclosing recipient editor paints the shared focus ring around its chips and input.
- className="h-5 w-0 min-w-4 grow basis-4 rounded-none border-0 bg-transparent px-1 py-0 shadow-none hover:bg-transparent focus:bg-transparent focus:shadow-none focus:ring-0"
- />
- {emailDraft.includes('@') && (
- <Button size="small" onClick={addOneTimeEmail}>
- {t(($) => $['nodes.humanInputV2.recipients.addEmail'], { ns: 'workflow' })}
- </Button>
- )}
- </>
+ </ComboboxChips>
+ )}
+ </ComboboxValue>
+ <p id={`${nodeId}-selection-hint`} className="sr-only">
+ {inputHint}
+ </p>
+ {emailError && (
+ <p
+ id={`${nodeId}-recipient-email-error`}
+ role="alert"
+ className="px-1 system-xs-regular text-text-destructive"
+ >
+ {t(($) => $['nodes.humanInputV2.recipients.emailInvalidOrDuplicate'], {
+ ns: 'workflow',
+ })}
+ </p>
+ )}
+ {!value.length && readonly && (
+ <p className="px-1 system-xs-regular text-text-tertiary">
+ {t(($) => $['nodes.humanInputV2.recipients.empty'], { ns: 'workflow' })}
+ </p>
)}
- </div>
- {emailError && (
- <div
- id={`${nodeId}-recipient-email-error`}
- role="alert"
- className="px-3 pb-1 system-xs-regular text-text-destructive"
- >
- {t(($) => $['nodes.humanInputV2.recipients.emailInvalidOrDuplicate'], {
- ns: 'workflow',
- })}
- </div>
- )}
- {!value.length && readonly && (
- <div className="px-3 py-2 system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.recipients.empty'], { ns: 'workflow' })}
- </div>
- )}
- {!readonly && (
- <div className="flex min-h-9 items-center gap-1 py-1.5 ps-1.5 pe-2.5">
- <Popover open={open} onOpenChange={handleOpenChange}>
- <PopoverTrigger
+ {!readonly && (
+ <div className="flex items-center gap-1 pt-1">
+ <ComboboxTrigger
render={
<Button
variant="ghost"
size="small"
- className="gap-1 ps-1.25 pe-1.5 text-text-tertiary"
+ onClick={() => {
+ inputRef.current?.focus()
+ }}
>
<span className="i-ri-account-circle-line size-3.5" aria-hidden />
{t(($) => $['nodes.humanInputV2.recipients.addContact'], { ns: 'workflow' })}
</Button>
}
/>
- <PopoverContent
- initialFocus={searchFromInput ? false : undefined}
- finalFocus={searchFromInput ? recipientInputRef : undefined}
- side="bottom"
- align="start"
- sideOffset={4}
- className="w-80 bg-components-panel-bg-blur p-0 backdrop-blur-[5px]"
+ <Popover
+ onOpenChange={(next) => {
+ if (next) setOpen(false)
+ }}
>
- {!searchFromInput && (
- <div className="px-2 pt-2 pb-1">
- <InputGroup className="h-8">
- <InputGroupAddon className="ps-1.75 pe-1.25">
- <span
- className="i-ri-search-line size-4 text-components-input-text-placeholder"
- aria-hidden
- />
- </InputGroupAddon>
- <InputGroupInput
- aria-label={t(($) => $['nodes.humanInputV2.recipients.search'], {
- ns: 'workflow',
- })}
- value={query}
- onChange={(event) => {
- setQuery(event.target.value)
- void loadOptions(event.target.value)
- }}
- onKeyDown={(event) => {
- if (event.nativeEvent.isComposing) return
- if (event.key === 'ArrowDown') {
- event.preventDefault()
- firstOptionRef.current?.focus()
- }
- if (event.key === 'Enter') {
- const option = visibleOptions.find(
- (option) =>
- !selectedKeys.has(`contact:${option.id}`) &&
- !findConflictingContact(value, option, resolvedOptions),
- )
- if (option) add({ type: 'contact', contact_id: option.id })
- }
- if (event.key === 'Escape') setOpen(false)
- }}
- placeholder={t(
- ($) => $['nodes.humanInputV2.recipients.searchPlaceholder'],
- {
- ns: 'workflow',
- },
- )}
- />
- </InputGroup>
- </div>
- )}
- <div
- className="flex gap-0.5 overflow-x-auto px-2 py-1"
- role="tablist"
- aria-label={t(($) => $['nodes.humanInputV2.recipients.contactSourceLabel'], {
+ <PopoverTrigger
+ render={
+ <IconButton
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.contactSourceLabel'], {
+ ns: 'workflow',
+ })}
+ >
+ <span className="i-ri-filter-3-line size-4" aria-hidden />
+ </IconButton>
+ }
+ />
+ <PopoverContent>
+ <SegmentedControl<SourceFilter>
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.contactSourceLabel'], {
+ ns: 'workflow',
+ })}
+ value={activeSource}
+ onValueChange={(next) => {
+ setSource(next)
+ setPreviewContact(undefined)
+ }}
+ className="m-1 shrink-0 overflow-x-auto"
+ >
+ {sourceFilters
+ .filter((filter) => filter !== 'organization' || centrallyManaged)
+ .map((filter) => (
+ <SegmentedControlItem key={filter} value={filter}>
+ {filter === 'organization'
+ ? t(($) => $['type.platform'], { ns: 'contacts' })
+ : t(($) => $[`nodes.humanInputV2.recipients.contactSource.${filter}`], {
+ ns: 'workflow',
+ })}
+ </SegmentedControlItem>
+ ))}
+ </SegmentedControl>
+ </PopoverContent>
+ </Popover>
+ <RecipientContactPreview
+ contact={previewContact}
+ returnFocus={inputRef}
+ conflictingContact={
+ previewConflict
+ ? selectedContacts.find((contact) => contact.id === previewConflict.id)
+ : undefined
+ }
+ onReplace={
+ previewConflict && previewContact
+ ? () => {
+ commit(
+ replaceContactRecipient(value, previewConflict.id, previewContact.id),
+ )
+ inputRef.current?.focus()
+ }
+ : undefined
+ }
+ >
+ <IconButton
+ disabled={!previewContact}
+ focusableWhenDisabled
+ aria-label={t(($) => $['details.title'], { ns: 'contacts' })}
+ aria-describedby={`${nodeId}-preview-contact`}
+ >
+ <span className="i-ri-information-line size-4" aria-hidden />
+ </IconButton>
+ </RecipientContactPreview>
+ <span id={`${nodeId}-preview-contact`} className="sr-only">
+ {previewContact ? getContactLabel(previewContact) : inputHint}
+ </span>
+ <VarReferencePicker
+ nodeId={nodeId}
+ readonly={readonly}
+ value={[]}
+ isShowNodeName
+ filterVar={(variable: Var) =>
+ variable.type === VarType.string || variable.type === VarType.secret
+ }
+ trigger={
+ <Button ref={variableTriggerRef} variant="ghost" size="small">
+ <span
+ className="i-custom-vender-line-others-global-variable size-3.5"
+ aria-hidden
+ />
+ {t(($) => $['nodes.humanInputV2.recipients.insertVariable'], {
+ ns: 'workflow',
+ })}
+ </Button>
+ }
+ onChange={(selector) => {
+ if (Array.isArray(selector))
+ commit(addRecipient(value, { type: 'dynamic_email', selector }))
+ }}
+ />
+ {!open && query.includes('@') && (
+ <Button size="small" onClick={addEmail}>
+ {t(($) => $['nodes.humanInputV2.recipients.addEmail'], { ns: 'workflow' })}
+ </Button>
+ )}
+ <Infotip>
+ <InfotipTrigger
+ className="ms-auto"
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.inputHelp'], {
ns: 'workflow',
})}
- >
- {availableSourceFilters.map((filter) => (
- <button
- key={filter}
- type="button"
- role="tab"
- aria-selected={activeSourceFilter === filter}
- className={cn(
- 'shrink-0 rounded-md border-0 bg-transparent px-2 py-1 system-xs-medium text-text-tertiary focus-visible:ring-1 focus-visible:ring-state-accent-solid',
- activeSourceFilter === filter &&
- 'bg-state-base-hover-alt text-text-primary',
- )}
- onClick={() => setSourceFilter(filter)}
- >
+ />
+ <InfotipContent>
+ {t(($) => $['nodes.humanInputV2.recipients.inputHelp'], { ns: 'workflow' })}
+ </InfotipContent>
+ </Infotip>
+ </div>
+ )}
+ </ComboboxInputGroup>
+ <ComboboxPortal>
+ <ComboboxPositioner align="start">
+ <ComboboxPopup>
+ <SegmentedControl<SourceFilter>
+ aria-label={t(($) => $['nodes.humanInputV2.recipients.contactSourceLabel'], {
+ ns: 'workflow',
+ })}
+ value={activeSource}
+ onValueChange={(next) => {
+ setSource(next)
+ setPreviewContact(undefined)
+ }}
+ className="m-1 shrink-0 overflow-x-auto"
+ >
+ {sourceFilters
+ .filter((filter) => filter !== 'organization' || centrallyManaged)
+ .map((filter) => (
+ <SegmentedControlItem key={filter} value={filter}>
{filter === 'organization'
? t(($) => $['type.platform'], { ns: 'contacts' })
: t(($) => $[`nodes.humanInputV2.recipients.contactSource.${filter}`], {
ns: 'workflow',
})}
- </button>
+ </SegmentedControlItem>
))}
- </div>
- <div className="max-h-84 overflow-y-auto p-1" aria-live="polite">
- {loading && (
- <div role="status" className="p-3 system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.recipients.loading'], { ns: 'workflow' })}
- </div>
- )}
- {!loading && loadError && (
- <div role="alert" className="p-3 system-xs-regular text-text-destructive">
- {t(($) => $['nodes.humanInputV2.recipients.loadError'], { ns: 'workflow' })}
- </div>
- )}
- {!loading && !loadError && !visibleOptions.length && !hasMore && (
- <div className="p-3 system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.recipients.noResults'], { ns: 'workflow' })}
- </div>
- )}
- {!loading &&
- visibleOptions.map((option, index) => {
- const added = selectedKeys.has(`contact:${option.id}`)
- const conflict = findConflictingContact(value, option, resolvedOptions)
- const conflictingContact = conflict ? resolvedMap.get(conflict.id) : undefined
- return (
- <RecipientContactPreview
- key={option.id}
- contact={option}
- conflictingContact={conflictingContact}
- onReplace={
- conflictingContact
- ? () => replaceContact(conflictingContact.id, option)
- : undefined
- }
- >
- <button
- aria-label={getOptionLabel(option)}
- ref={
- index ===
- visibleOptions.findIndex(
- (item) =>
- !selectedKeys.has(`contact:${item.id}`) &&
- !findConflictingContact(value, item, resolvedOptions),
- )
- ? firstOptionRef
- : undefined
- }
- type="button"
- disabled={added}
- aria-disabled={!!conflictingContact || undefined}
- className="flex min-h-10 w-full items-center gap-2 rounded-lg border-0 bg-transparent py-1 ps-2 pe-3 text-start hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-state-accent-solid"
- onClick={() => {
- if (!conflictingContact)
- add({ type: 'contact', contact_id: option.id })
- }}
- >
- <RecipientAvatar
- identity={option.id}
- avatar={option.avatar ?? null}
- name={option.name}
- size="sm"
- className={cn(
- 'inset-ring-[0.5px] inset-ring-divider-regular [&>span]:text-[13px] [&>span]:font-semibold',
- (added || conflictingContact) && 'opacity-50',
- )}
- />
- <span
- className={cn(
- 'min-w-0 grow',
- (added || conflictingContact) && 'opacity-50',
- )}
- >
- <span className="block truncate system-sm-medium text-text-secondary">
- {option.name}
- </span>
- <span className="block truncate system-xs-regular text-text-tertiary">
- {option.email}
- </span>
- </span>
- {added && (
- <span className="system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.recipients.added'], {
- ns: 'workflow',
- })}
- </span>
- )}
- {conflictingContact && (
- <span
- className="i-ri-lock-line size-3 shrink-0 text-text-tertiary"
- aria-hidden
- />
- )}
- </button>
- </RecipientContactPreview>
- )
- })}
- {hasMore && !loading && (
- <Button
- size="small"
- loading={loadingMore}
- disabled={loadingMore}
- onClick={loadMore}
- >
- {t(($) => $['common.loadMore'], { ns: 'workflow' })}
- </Button>
- )}
- {(activeSourceFilter === 'all' || activeSourceFilter === 'workspace') && (
- <div className="my-1 h-px bg-divider-subtle" />
- )}
- {activeSourceFilter === 'all' && (
- <button
- type="button"
- aria-label={t(($) => $['nodes.humanInputV2.recipients.type.initiator'], {
+ </SegmentedControl>
+ <ComboboxStatus>
+ {isDebouncing || search.isPending
+ ? t(($) => $['nodes.humanInputV2.recipients.loading'], { ns: 'workflow' })
+ : search.isError
+ ? t(($) => $['nodes.humanInputV2.recipients.loadError'], { ns: 'workflow' })
+ : t(($) => $['nodes.humanInputV2.recipients.resultCount'], {
ns: 'workflow',
+ count: results.length,
})}
- disabled={selectedKeys.has('initiator')}
- className="flex min-h-10 w-full items-center gap-2 rounded-lg border-0 bg-transparent py-1 ps-2 pe-3 text-start hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-state-accent-solid disabled:opacity-50"
- onClick={() => add({ type: 'initiator' })}
+ </ComboboxStatus>
+ <ComboboxList<RecipientItem>>
+ {(item) => {
+ const added = value.some(
+ (recipient) =>
+ getRecipientCanonicalKey(recipient) ===
+ getRecipientCanonicalKey(item.recipient),
+ )
+ const conflict =
+ item.contact &&
+ findConflictingContact(
+ value,
+ { id: item.contact.id, email: item.contact.email ?? '' },
+ selectedContacts.map((contact) => ({
+ ...contact,
+ email: contact.email ?? '',
+ })),
+ )
+ return (
+ <ComboboxItem<string>
+ key={item.key}
+ value={item.key}
+ disabled={added || !!conflict}
+ className="min-w-0 grow"
>
- <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-util-colors-indigo-indigo-500 text-text-primary-on-surface">
- <span className="i-ri-user-follow-line size-4" aria-hidden />
- </span>
- <span className="min-w-0 grow">
- <span className="block system-sm-medium text-util-colors-indigo-indigo-700">
- {t(($) => $['nodes.humanInputV2.recipients.type.initiator'], {
- ns: 'workflow',
- })}
- </span>
- <span className="block system-xs-regular text-text-tertiary">
- {t(($) => $['nodes.humanInputV2.recipients.initiator'], {
- ns: 'workflow',
- })}
- </span>
- </span>
- </button>
- )}
- {(activeSourceFilter === 'all' || activeSourceFilter === 'workspace') && (
- <button
- type="button"
- aria-label={t(
- ($) => $['nodes.humanInputV2.recipients.allWorkspaceContacts'],
- {
- ns: 'workflow',
- },
- )}
- disabled={selectedKeys.has('all_workspace_contacts')}
- className="flex min-h-10 w-full items-center gap-2 rounded-lg border-0 bg-transparent py-1 ps-2 pe-3 text-start hover:bg-state-base-hover focus-visible:ring-1 focus-visible:ring-state-accent-solid disabled:opacity-50"
- onClick={() => add({ type: 'all_workspace_contacts' })}
- >
- <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-util-colors-indigo-indigo-500 text-text-primary-on-surface">
- {workspace?.name ? (
- <WorkspaceAvatar
- name={workspace.name}
+ <span className="flex min-w-0 items-center gap-2">
+ {item.contact && (
+ <RecipientAvatar
+ identity={item.contact.id}
+ name={item.contact.name}
+ avatar={item.contact.avatar_url}
size="sm"
- className="rounded-full"
/>
- ) : (
- <span className="i-ri-group-line size-4" aria-hidden />
)}
- </span>
- <span className="min-w-0 grow">
- <span className="block system-sm-medium text-util-colors-indigo-indigo-700">
- {workspace?.name ||
- t(($) => $['nodes.humanInputV2.recipients.allWorkspaceContacts'], {
- ns: 'workflow',
- })}
- {workspace?.contactCount !== undefined && (
- <span className="ms-0.5 inline-flex min-w-4 items-center justify-center rounded-[5px] bg-components-badge-bg-dimm px-1 py-0.5 align-middle system-2xs-medium-uppercase text-text-tertiary inset-ring-1 inset-ring-divider-deep">
- {workspace.contactCount}
+ <span className="min-w-0">
+ <span className="block truncate system-sm-medium">
+ {item.contact?.name ?? item.label}
+ </span>
+ {item.contact?.email && (
+ <span className="block truncate system-xs-regular text-text-tertiary">
+ {item.contact.email}
</span>
)}
</span>
- <span className="block system-xs-regular text-text-tertiary">
- {t(
- ($) =>
- $['nodes.humanInputV2.recipients.allWorkspaceContactsDescription'],
- { ns: 'workflow' },
- )}
- </span>
+ {conflict && (
+ <span className="sr-only">
+ {t(($) => $['nodes.humanInputV2.recipients.emailAlreadySelected'], {
+ ns: 'workflow',
+ })}
+ </span>
+ )}
</span>
- </button>
- )}
- </div>
- </PopoverContent>
- </Popover>
-
- <VarReferencePicker
- nodeId={nodeId}
- readonly={readonly}
- value={[]}
- isShowNodeName
- filterVar={(variable: Var) =>
- variable.type === VarType.string || variable.type === VarType.secret
- }
- trigger={
+ <ComboboxItemIndicator />
+ </ComboboxItem>
+ )
+ }}
+ </ComboboxList>
+ {query.includes('@') && (
+ <Button size="small" onClick={addEmail}>
+ {t(($) => $['nodes.humanInputV2.recipients.addEmail'], { ns: 'workflow' })}
+ </Button>
+ )}
+ {search.isError && (
+ <Button size="small" onClick={() => void search.refetch()}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ )}
+ {(search.hasNextPage || (search.data?.pages.length ?? 0) > 1) && (
<Button
- ref={variableTriggerRef}
- variant="ghost"
size="small"
- className="gap-1 ps-1.25 pe-1.5 text-text-tertiary"
+ loading={search.isFetchingNextPage}
+ aria-disabled={!search.hasNextPage || search.isFetchingNextPage}
+ onClick={() => {
+ if (search.hasNextPage && !search.isFetchingNextPage)
+ void search.fetchNextPage()
+ }}
>
- <span
- className="i-custom-vender-line-others-global-variable size-3.5"
- aria-hidden
- />
- {t(($) => $['nodes.humanInputV2.recipients.insertVariable'], { ns: 'workflow' })}
+ {t(($) => $['common.loadMore'], { ns: 'workflow' })}
</Button>
- }
- onChange={(selector) => {
- if (!Array.isArray(selector)) return
- const next = addRecipient(value, {
- type: 'dynamic_email',
- selector: selector as ValueSelector,
- })
- if (next !== value) onChange(next)
- }}
- />
- <div className="ms-auto flex shrink-0 items-center gap-1">
- <Infotip>
- <InfotipTrigger
- aria-label={t(($) => $['nodes.humanInputV2.recipients.title'], {
- ns: 'workflow',
- })}
- />
- <InfotipContent>
- {t(($) => $['nodes.humanInputV2.recipients.inputHelp'], { ns: 'workflow' })}
- </InfotipContent>
- </Infotip>
- </div>
- </div>
- )}
- </div>
- </section>
+ )}
+ </ComboboxPopup>
+ </ComboboxPositioner>
+ </ComboboxPortal>
+ </Combobox>
+ </div>
)
}
-const RuntimeRecipients = (props: RecipientsProps) => {
- const { provider, workspaceId } = useContactRecipientOptionProvider()
+const Recipients = (props: RecipientsProps) => {
+ const workspaceId = useAtomValue(currentWorkspaceIdAtom)
const workspace = useAtomValue(currentWorkspaceAtom)
- const canManageContacts = useAtomValue(isCurrentWorkspaceManagerAtom)
- const input = { query: { group: 'workspace' as const, page: 1, limit: 1 } }
- const contactsQuery = consoleQuery.workspaces.current.humanInput.v2.contacts.get
- const count = useQuery({
- ...contactsQuery.queryOptions({
+ const canManage = useAtomValue(isCurrentWorkspaceManagerAtom)
+ const operation = consoleQuery.workspaces.current.humanInput.v2.contacts.get
+ const input =
+ workspaceId && canManage
+ ? { query: { group: 'workspace' as const, page: 1, limit: 1 } }
+ : skipToken
+ const count = useQuery(
+ operation.queryOptions({
input,
- queryKey: [...contactsQuery.queryKey({ input }), { workspaceId }],
+ queryKey: [...operation.queryKey({ input }), { workspaceId }],
+ select: (response) => response.total,
context: { silent: true },
+ retry: false,
}),
- enabled: Boolean(workspaceId) && canManageContacts,
- select: (response) => response.total,
- retry: false,
- })
+ )
return (
<RecipientsContent
key={workspaceId}
{...props}
readonly={props.readonly || !workspaceId}
- provider={provider}
- workspace={{ name: workspace.name, contactCount: canManageContacts ? count.data : undefined }}
+ workspaceId={workspaceId}
+ workspace={{ name: workspace.name, contactCount: canManage ? count.data : undefined }}
/>
)
}
-const Recipients = (props: RecipientsProps) =>
- props.provider ? (
- <RecipientsContent {...props} provider={props.provider} />
- ) : (
- <RuntimeRecipients {...props} />
- )
-
export default Recipients
diff --git a/web/app/components/workflow/nodes/human-input-v2/contact-provider.ts b/web/app/components/workflow/nodes/human-input-v2/contact-provider.ts
deleted file mode 100644
index 3fffcf14d41..00000000000
--- a/web/app/components/workflow/nodes/human-input-v2/contact-provider.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import type { ContactOption } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { QueryClient } from '@tanstack/react-query'
-import { useQueryClient } from '@tanstack/react-query'
-import { useAtomValue } from 'jotai'
-import { useMemo } from 'react'
-import { currentWorkspaceIdAtom } from '@/context/workspace-state'
-import { consoleQuery } from '@/service/console'
-
-export type ContactRecipientOption = {
- id: string
- name: string
- email: string
- avatar?: string
- source: 'workspace' | 'organization' | 'external'
-}
-
-export type ContactRecipientOptionProvider = {
- search: (query: string) => Promise<ContactRecipientOption[]>
- searchPage?: (
- query: string,
- page: number,
- ) => Promise<{
- data: ContactRecipientOption[]
- page: number
- hasMore: boolean
- }>
- resolve: (query: { contact_ids: string[] }) => Promise<ContactRecipientOption[]>
-}
-
-const toRecipientOption = (contact: ContactOption): ContactRecipientOption => ({
- id: contact.id,
- name: contact.name,
- email: contact.email ?? '',
- avatar: contact.avatar_url ?? undefined,
- source: contact.type === 'platform' ? 'organization' : contact.type,
-})
-
-export function createContactRecipientOptionProvider(
- workspaceId: string,
- queryClient: QueryClient,
-): ContactRecipientOptionProvider {
- const contactOptions = consoleQuery.workspaces.current.humanInput.v2.contactOptions
- const searchPage = async (keyword: string, page: number) => {
- if (!workspaceId) return { data: [], page, hasMore: false }
- const input = { query: { keyword: keyword.trim(), page, limit: 20 } }
- const response = await queryClient.query(
- contactOptions.get.queryOptions({
- input,
- queryKey: [...contactOptions.get.queryKey({ input }), { workspaceId }],
- staleTime: 0,
- }),
- )
- return {
- data: response.data.map(toRecipientOption),
- page: response.page,
- hasMore: response.page * response.limit < response.total,
- }
- }
-
- return {
- searchPage,
- async search(keyword) {
- return (await searchPage(keyword, 1)).data
- },
- async resolve({ contact_ids }) {
- if (!workspaceId || !contact_ids.length) return []
- const input = { query: { contact_ids: [...new Set(contact_ids)].sort() } }
- const response = await queryClient.query(
- contactOptions.batch.get.queryOptions({
- input,
- queryKey: [...contactOptions.batch.get.queryKey({ input }), { workspaceId }],
- staleTime: 0,
- }),
- )
- return response.data.map(toRecipientOption)
- },
- }
-}
-
-export function useContactRecipientOptionProvider() {
- const workspaceId = useAtomValue(currentWorkspaceIdAtom)
- const queryClient = useQueryClient()
- const provider = useMemo(
- () => createContactRecipientOptionProvider(workspaceId, queryClient),
- [workspaceId, queryClient],
- )
- return { provider, workspaceId }
-}
diff --git a/web/app/components/workflow/nodes/human-input-v2/contact-queries.ts b/web/app/components/workflow/nodes/human-input-v2/contact-queries.ts
new file mode 100644
index 00000000000..9c234524e03
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input-v2/contact-queries.ts
@@ -0,0 +1,22 @@
+import { skipToken } from '@tanstack/react-query'
+import { consoleQuery } from '@/service/console'
+
+// The node card, editor and publish check must observe the same authoritative lookup.
+export function getContactRecipientQueryOptions(
+ workspaceId: string,
+ contactIds: readonly string[],
+) {
+ const operation = consoleQuery.workspaces.current.humanInput.v2.contactOptions.batch.get
+ const input =
+ workspaceId && contactIds.length
+ ? { query: { contact_ids: [...new Set(contactIds)].sort() } }
+ : skipToken
+
+ return operation.queryOptions({
+ input,
+ queryKey: [...operation.queryKey({ input }), { workspaceId }],
+ staleTime: 0,
+ retry: false,
+ context: { silent: true },
+ })
+}
diff --git a/web/app/components/workflow/nodes/human-input-v2/default.ts b/web/app/components/workflow/nodes/human-input-v2/default.ts
index 00fcab6db31..e5a1d767da4 100644
--- a/web/app/components/workflow/nodes/human-input-v2/default.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/default.ts
@@ -34,7 +34,15 @@ const nodeDefault: NodeDefault<HumanInputV2NodeType> = {
timeout: 36,
timeout_unit: 'hour',
},
- checkValid(payload, t: TFunction<['workflow']>) {
+ checkValid(
+ payload,
+ t: TFunction<['workflow']>,
+ moreDataForCheckValid?: {
+ resolvedContactIds?: ReadonlySet<string>
+ contactLookupFailed?: boolean
+ },
+ ) {
+ const { resolvedContactIds, contactLookupFailed } = moreDataForCheckValid ?? {}
let errorMessage = ''
if (!ENABLE_HITL_IM)
errorMessage = t(($) => $['nodes.humanInputV2.disabled'], { ns: 'workflow' })
@@ -44,6 +52,21 @@ const nodeDefault: NodeDefault<HumanInputV2NodeType> = {
errorMessage = t(($) => $['nodes.humanInputV2.error.recipientRequired'], { ns: 'workflow' })
else if (payload.recipients_spec.some(getRecipientValidationError))
errorMessage = t(($) => $['nodes.humanInputV2.error.recipientInvalid'], { ns: 'workflow' })
+ else if (
+ contactLookupFailed &&
+ payload.recipients_spec.some((recipient) => recipient.type === 'contact')
+ )
+ errorMessage = t(($) => $['nodes.humanInputV2.error.recipientVerificationFailed'], {
+ ns: 'workflow',
+ })
+ else if (
+ resolvedContactIds &&
+ payload.recipients_spec.some(
+ (recipient) =>
+ recipient.type === 'contact' && !resolvedContactIds.has(recipient.contact_id),
+ )
+ )
+ errorMessage = t(($) => $['nodes.humanInputV2.error.recipientInvalid'], { ns: 'workflow' })
else if (hasDuplicateRecipients(payload.recipients_spec))
errorMessage = t(($) => $['nodes.humanInputV2.error.recipientDuplicate'], { ns: 'workflow' })
else if (!payload.message_template.subject.trim())
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/README.md b/web/app/components/workflow/nodes/human-input-v2/migration/README.md
index ecb459cb6ff..e2b96399c01 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/README.md
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/README.md
@@ -2,7 +2,7 @@
This module owns the frontend rollout policy, one-call batch migration orchestration, response validation, and application of legacy Human Input migration results.
-The provider uses the generated `consoleClient.workspaces.current.humanInput.v2.nodeDataMigration.post` endpoint. The server owns recipient conversion, legacy aliases, and lossless-conversion blockers. The HTTP compatibility DTO accepts raw historical delivery JSON; its generated schema documents only canonical delivery methods, so the adapter preserves historical input at that boundary. Successful responses are validated with the generated schema and normalized through the shared paragraph/select/file/file-list editor adapter. HTTP 400 migration failures become node-scoped blockers; other failures leave the graph untouched.
+The executor adapter uses the generated `consoleClient.workspaces.current.humanInput.v2.nodeDataMigration.post` endpoint. The server owns recipient conversion, legacy aliases, and lossless-conversion blockers. The HTTP compatibility DTO accepts raw historical delivery JSON; its generated schema documents only canonical delivery methods, so the adapter preserves historical input at that boundary. Successful responses are validated with the generated schema and normalized through the shared paragraph/select/file/file-list editor adapter. HTTP 400 migration failures become node-scoped blockers; other failures leave the graph untouched.
The executor sends the whole eligible batch and verifies that every requested node appears exactly once as v2 data before applying anything. A changed migration candidate, added legacy node, or lost editing permission cancels the attempt. Unrelated node, layout, and edge edits made while the request is pending are retained.
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/executor.spec.ts b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/executor.spec.ts
index c7df7e60aac..3ce0434574d 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/executor.spec.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/executor.spec.ts
@@ -445,26 +445,28 @@ describe('Human Input migration executor', () => {
expect(harness.saveHistory).not.toHaveBeenCalled()
})
- it('maps the server invalid-default-value blocker from an HTTP response', async () => {
+ it('maps the server invalid-default-value blocker from the generated client error', async () => {
const harness = createHarness({ nodes: [createLegacyNode('a')], edges: [] })
harness.post.mockRejectedValueOnce(
- new Response(
- JSON.stringify({
- message: 'Human Input node-data migration failed.',
- status: 400,
- code: 'hitl_node_data_migration_failure',
- blockers: [
- {
- code: 'invalid-default-value',
- node_id: 'a',
- node_title: 'Approval',
- method_id: null,
- value: 'default_value',
- },
- ],
- }),
- { status: 400 },
- ),
+ new ORPCError('BAD_REQUEST', {
+ status: 400,
+ data: {
+ body: {
+ message: 'Human Input node-data migration failed.',
+ status: 400,
+ code: 'hitl_node_data_migration_failure',
+ blockers: [
+ {
+ code: 'invalid-default-value',
+ node_id: 'a',
+ node_title: 'Approval',
+ method_id: null,
+ value: 'default_value',
+ },
+ ],
+ },
+ },
+ }),
)
expect(await executeHumanInputV2Migration(harness.dependencies)).toEqual({
status: 'blocked',
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/locales.spec.ts b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/locales.spec.ts
index 305cca74d17..6d22dad1a77 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/locales.spec.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/locales.spec.ts
@@ -1,10 +1,51 @@
+import i18next from 'i18next'
import { describe, expect, it } from 'vitest'
+import { loadI18nResource } from '@/i18n/load-resource'
+import { supportedLocales } from '@/i18n/locale'
import enUS from '@/i18n/locales/en-US/workflow.json'
import zhHans from '@/i18n/locales/zh-Hans/workflow.json'
const MIGRATION_PREFIX = 'nodes.humanInputMigration.'
+const HUMAN_INPUT_KEYS = Object.keys(enUS).filter(
+ (key) =>
+ [
+ 'blocks.human-input-v2',
+ 'blocksAbout.human-input-v2',
+ 'changeHistory.humanInputMigration',
+ ].includes(key) ||
+ ['nodes.humanInput.output.', MIGRATION_PREFIX, 'nodes.humanInputV2.'].some((prefix) =>
+ key.startsWith(prefix),
+ ),
+)
describe('Human Input migration locales', () => {
+ it.each(supportedLocales)('loads every Human Input workflow string in %s', async (locale) => {
+ const [{ default: workflow }, { default: workflowHumanInput }] = await Promise.all([
+ loadI18nResource(locale, 'workflow'),
+ loadI18nResource(locale, 'workflowHumanInput'),
+ ])
+ const i18n = i18next.createInstance()
+ await i18n.init({
+ lng: locale,
+ fallbackLng: false,
+ keySeparator: false,
+ resources: { [locale]: { workflow, workflowHumanInput } },
+ })
+
+ for (const key of HUMAN_INPUT_KEYS)
+ expect(i18n.getResource(locale, 'workflow', key), key).toEqual(expect.stringMatching(/\S/))
+
+ expect(
+ i18n.getResource(locale, 'workflowHumanInput', 'nodes.humanInput.userActions.defaultTitle'),
+ ).toEqual(expect.stringMatching(/\S/))
+ expect(
+ i18n.t(($) => $['nodes.humanInput.userActions.defaultTitle'], {
+ ns: 'workflowHumanInput',
+ index: 3,
+ }),
+ ).toContain('3')
+ })
+
it('defines every migration string in English and Simplified Chinese', () => {
const englishKeys = Object.keys(enUS)
.filter((key) => key.startsWith(MIGRATION_PREFIX))
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-banner.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-banner.spec.tsx
index a829fffea8b..2aee93faaa1 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-banner.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-banner.spec.tsx
@@ -15,17 +15,13 @@ describe('Human Input migration banner', () => {
/>,
)
- expect(
- screen.getByRole('complementary', {
- name: 'workflow.nodes.humanInputMigration.banner.ariaLabel',
- }),
- ).toBeInTheDocument()
+ expect(screen.queryByRole('complementary')).not.toBeInTheDocument()
expect(
screen.getByText('workflow.nodes.humanInputMigration.banner.description'),
).toBeInTheDocument()
expect(
screen.getByRole('link', {
- name: 'workflow.nodes.humanInputMigration.banner.learnMore',
+ name: /workflow.nodes.humanInputMigration.banner.learnMore/,
}),
).toHaveAttribute('href', 'https://docs.example/human-input')
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-dialog.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-dialog.spec.tsx
index c16492e8a0e..5bbd458580d 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-dialog.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/migration-dialog.spec.tsx
@@ -76,9 +76,12 @@ describe('Human Input migration dialog', () => {
expect(onConfirm).toHaveBeenCalledTimes(1)
expect(
- screen.getByRole('button', { name: /workflow.nodes.humanInputMigration.action.migrating/ }),
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),
).toHaveAttribute('aria-disabled', 'true')
- expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
await user.keyboard('{Escape}')
expect(screen.getByRole('alertdialog')).toBeInTheDocument()
})
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/policy.spec.ts b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/policy.spec.ts
index 48f9ab8c0e2..5dcf79e0aea 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/policy.spec.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/policy.spec.ts
@@ -7,6 +7,8 @@ import {
canInsertHumanInputNodes,
classifyHumanInputVersion,
getHumanInputCreationPolicy,
+ getHumanInputInsertionBlocker,
+ getHumanInputNodesInsertionBlocker,
HumanInputVersionKind,
isLegacyHumanInputNodeData,
} from '../policy'
@@ -147,3 +149,17 @@ describe('Human Input migration policy', () => {
expect(canInsertHumanInput([legacy], BlockEnum.HumanInput)).toBe(false)
})
})
+
+it('distinguishes unsupported versions, migration requirements and incompatible version mixes', () => {
+ expect(getHumanInputInsertionBlocker([node()], BlockEnum.HumanInputV2)).toBe('migration-required')
+ expect(getHumanInputInsertionBlocker([node('2')], BlockEnum.HumanInput)).toBe(
+ 'incompatible-versions',
+ )
+ expect(getHumanInputInsertionBlocker([], BlockEnum.HumanInput, data('3'))).toBe(
+ 'unsupported-version',
+ )
+ expect(getHumanInputNodesInsertionBlocker([], [node(), node('2')])).toBe('incompatible-versions')
+ releaseGate.enabled = false
+ expect(getHumanInputInsertionBlocker([], BlockEnum.HumanInputV2)).toBe('disabled')
+ expect(getHumanInputInsertionBlocker([], BlockEnum.Code)).toBeUndefined()
+})
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx
index 4b5eff74d91..d0da1d5e91a 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/__tests__/provider.spec.tsx
@@ -165,9 +165,7 @@ it('migrates the real graph through one shared dialog and updates the insertion
const edges = view.graph().edges
expect(screen.getByText('insertion-blocked')).toBeInTheDocument()
expect(
- screen.getByRole('complementary', {
- name: 'workflow.nodes.humanInputMigration.banner.ariaLabel',
- }),
+ screen.getByText('workflow.nodes.humanInputMigration.banner.description'),
).toBeInTheDocument()
await confirmMigration(user)
expect(await screen.findByText('insertion-enabled')).toBeInTheDocument()
@@ -254,7 +252,10 @@ it('starts only one migration when confirmation is double-clicked during a draft
await user.dblClick(
screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),
)
- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'workflow.nodes.humanInputMigration.action.migrate' }),
+ ).toHaveAttribute('aria-disabled', 'true')
expect(view.graph().nodes[0]!.data.version).toBe('2')
expect(postMigration).toHaveBeenCalledTimes(1)
expect(sync).toHaveBeenCalledTimes(1)
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/executor.ts b/web/app/components/workflow/nodes/human-input-v2/migration/executor.ts
index 3705eb3e588..6d3afaf0c49 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/executor.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/executor.ts
@@ -24,16 +24,12 @@ import {
} from './policy'
import { HumanInputMigrationBlockerCode } from './types'
-/** The backend owns legacy alias handling and recipient conversion. */
export const createHumanInputMigrationApi = (
client: typeof consoleClient.workspaces.current.humanInput.v2.nodeDataMigration = consoleClient
.workspaces.current.humanInput.v2.nodeDataMigration,
): HumanInputMigrationApi => ({
async migrate(request) {
try {
- // The HTTP compatibility DTO accepts raw historical delivery JSON, while its
- // generated schema documents canonical methods only. Preserve aliases and
- // unsupported methods here so backend preflight can report precise blockers.
const body = request as Parameters<typeof client.post>[0]['body']
const response = zNodeDataMigrationResponse.parse(
await client.post({ body }, { context: { silent: true } }),
@@ -43,8 +39,6 @@ export const createHumanInputMigrationApi = (
data: response.data.map(({ node_id, node_data }) => {
if (node_data.version !== '2') throw new Error('human-input-migration-invalid-response')
const inputs = (node_data.inputs ?? []).map(normalizeHumanInputFormInput)
- // The editor uses TS enums for common node fields whose generated DTO
- // counterparts are string literals. All remote fields were validated above.
const data = {
...node_data,
type: BlockEnum.HumanInput,
@@ -59,18 +53,8 @@ export const createHumanInputMigrationApi = (
}),
}
} catch (error) {
- const status =
- error instanceof Response || error instanceof ORPCError ? error.status : undefined
- if (status !== 400) throw error
- const data: unknown =
- error instanceof Response
- ? await error
- .clone()
- .json()
- .catch(() => undefined)
- : error instanceof ORPCError
- ? error.data
- : undefined
+ if (!(error instanceof ORPCError) || error.status !== 400) throw error
+ const data: unknown = error.data
const body = data && typeof data === 'object' && 'body' in data ? data.body : data
const failure = zNodeDataMigrationFailureResponse.safeParse(body)
if (!failure.success || !failure.data.blockers.length) throw error
@@ -191,7 +175,6 @@ export const executeHumanInputV2Migration = async ({
return { ...node, data: { ...extensions, ...cloneDeep(data) } }
}),
}
- // Capture exactly what was applied so rollback never overwrites later edits.
const appliedData = new Map(
migratedGraph.nodes
.filter((node) => originalData.has(node.id))
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/insertion-feedback.ts b/web/app/components/workflow/nodes/human-input-v2/migration/insertion-feedback.ts
new file mode 100644
index 00000000000..e291b0eaf8e
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/insertion-feedback.ts
@@ -0,0 +1,17 @@
+import type { TFunction } from 'i18next'
+import type { HumanInputInsertionBlocker } from './policy'
+import { toast } from '@/app/notifications'
+
+const reasonKeys = {
+ disabled: 'nodes.humanInputV2.disabled',
+ 'unsupported-version': 'nodes.humanInputMigration.blocker.unsupportedVersion',
+ 'migration-required': 'nodes.humanInputMigration.disabledReason',
+ 'incompatible-versions': 'nodes.humanInputMigration.incompatibleVersions',
+} as const
+
+export const notifyHumanInputInsertionBlocked = (
+ reason: HumanInputInsertionBlocker,
+ t: TFunction<['workflow']>,
+) => {
+ toast.warning(t(($) => $[reasonKeys[reason]], { ns: 'workflow' }))
+}
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/migration-banner.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/migration-banner.tsx
index 17e4ee3d8b8..06743b96619 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/migration-banner.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/migration-banner.tsx
@@ -15,15 +15,12 @@ const HumanInputMigrationBanner = ({
helpLink,
onMigrate,
}: HumanInputMigrationBannerProps) => {
- const { t } = useTranslation(['workflow'])
+ const { t } = useTranslation(['workflow', 'common'])
return (
- <aside
- aria-label={t(($) => $['nodes.humanInputMigration.banner.ariaLabel'], { ns: 'workflow' })}
- className="pointer-events-auto flex w-full min-w-0 items-center justify-center gap-2 rounded-lg border-[0.5px] border-components-badge-status-light-warning-halo bg-state-warning-hover px-3 py-2 shadow-xs"
- >
+ <div className="pointer-events-auto flex w-full min-w-0 flex-wrap items-center justify-center gap-2 rounded-lg border-[0.5px] border-components-badge-status-light-warning-halo bg-state-warning-hover px-3 py-2 shadow-xs">
<BlockIcon size="sm" className="shrink-0" type={BlockEnum.HumanInputV2} />
- <div className="min-w-0 truncate system-xs-regular text-text-secondary">
+ <div className="min-w-0 flex-1 system-xs-regular text-text-secondary">
{t(($) => $['nodes.humanInputMigration.banner.description'], { ns: 'workflow' })}
</div>
{helpLink && (
@@ -34,6 +31,10 @@ const HumanInputMigrationBanner = ({
className="inline-flex h-6 shrink-0 items-center gap-0.5 rounded-md px-1.5 system-xs-medium text-text-secondary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
{t(($) => $['nodes.humanInputMigration.banner.learnMore'], { ns: 'workflow' })}
+ <span className="sr-only">
+ {' '}
+ ({t(($) => $['operation.openInNewTab'], { ns: 'common' })})
+ </span>
<span aria-hidden className="i-ri-external-link-line size-3.5" />
</a>
)}
@@ -43,7 +44,7 @@ const HumanInputMigrationBanner = ({
<span aria-hidden className="i-ri-arrow-right-line size-3.5" />
</Button>
)}
- </aside>
+ </div>
)
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/migration-dialog.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/migration-dialog.tsx
index 58f66e7755e..89cd1a3816d 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/migration-dialog.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/migration-dialog.tsx
@@ -1,13 +1,14 @@
import {
AlertDialog,
+ AlertDialogBody,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
+ AlertDialogHeader,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
-import { Button } from '@langgenius/dify-ui/button'
import { memo, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
@@ -39,8 +40,8 @@ const HumanInputMigrationDialog = ({
return (
<AlertDialog open={open} onOpenChange={handleOpenChange}>
- <AlertDialogContent className="w-[480px] max-w-[calc(100vw-2rem)]">
- <div className="px-6 pt-6">
+ <AlertDialogContent className="w-120 max-w-[calc(100vw-2rem)]">
+ <AlertDialogHeader>
<AlertDialogTitle>
{t(($) => $['nodes.humanInputMigration.dialog.title'], {
ns: 'workflow',
@@ -62,32 +63,28 @@ const HumanInputMigrationDialog = ({
</span>
</AlertDialogDescription>
</div>
+ </AlertDialogHeader>
+ <AlertDialogBody>
{error && (
<div
role="alert"
- className="bg-background-default-destructive mt-3 rounded-lg px-3 py-2 system-xs-regular text-text-destructive"
+ className="mt-3 rounded-lg bg-state-destructive-hover px-3 py-2 system-xs-regular text-text-destructive"
>
{error}
</div>
)}
- </div>
+ </AlertDialogBody>
<AlertDialogFooter>
- {pending ? (
- <Button disabled>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
- ) : (
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- )}
+ <AlertDialogCancelButton disabled={pending} focusableWhenDisabled>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
<AlertDialogConfirmButton
tone="default"
loading={pending}
disabled={pending}
onClick={onConfirm}
>
- {pending
- ? t(($) => $['nodes.humanInputMigration.action.migrating'], { ns: 'workflow' })
- : t(($) => $['nodes.humanInputMigration.action.migrate'], { ns: 'workflow' })}
+ {t(($) => $['nodes.humanInputMigration.action.migrate'], { ns: 'workflow' })}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/policy.ts b/web/app/components/workflow/nodes/human-input-v2/migration/policy.ts
index 1341b1d5741..de4e0a03752 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/policy.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/policy.ts
@@ -121,3 +121,35 @@ export const canInsertHumanInputNodes = (
if (hasIncomingV2 && hasIncomingLegacy) return false
return humanInputNodes.every((node) => canInsertHumanInput(nodes, node.data.type, node.data))
}
+
+export type HumanInputInsertionBlocker =
+ | 'disabled'
+ | 'unsupported-version'
+ | 'migration-required'
+ | 'incompatible-versions'
+
+export const getHumanInputInsertionBlocker = (
+ nodes: Pick<Node, 'data'>[],
+ nodeType: BlockEnum,
+ data?: Pick<CommonNodeType, 'type'> & { version?: unknown },
+): HumanInputInsertionBlocker | undefined => {
+ if (canInsertHumanInput(nodes, nodeType, data)) return undefined
+ if (data?.version !== undefined && data.version !== '1' && data.version !== '2')
+ return 'unsupported-version'
+ if (!ENABLE_HITL_IM) return 'disabled'
+ if (nodes.some((node) => classifyHumanInputVersion(node.data) === HumanInputVersionKind.V2))
+ return 'incompatible-versions'
+ return 'migration-required'
+}
+
+export const getHumanInputNodesInsertionBlocker = (
+ nodes: Pick<Node, 'data'>[],
+ incomingNodes: Pick<Node, 'data'>[],
+): HumanInputInsertionBlocker | undefined => {
+ if (canInsertHumanInputNodes(nodes, incomingNodes)) return undefined
+ for (const node of incomingNodes) {
+ const blocker = getHumanInputInsertionBlocker(nodes, node.data.type, node.data)
+ if (blocker) return blocker
+ }
+ return 'incompatible-versions'
+}
diff --git a/web/app/components/workflow/nodes/human-input-v2/migration/provider.tsx b/web/app/components/workflow/nodes/human-input-v2/migration/provider.tsx
index 1cb20f3510c..5458f6a19c2 100644
--- a/web/app/components/workflow/nodes/human-input-v2/migration/provider.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/migration/provider.tsx
@@ -1,6 +1,7 @@
import type { PropsWithChildren } from 'react'
import type { HumanInputMigrationBlocker } from './types'
import type { Edge, Node } from '@/app/components/workflow/types'
+import { useMutation } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNodes, useStoreApi } from 'reactflow'
@@ -12,8 +13,8 @@ import {
WorkflowHistoryEvent,
} from '@/app/components/workflow/hooks/use-workflow-history'
import { BlockEnum } from '@/app/components/workflow/types'
-import { toast } from '@/app/notifications'
import { ENABLE_HITL_IM } from '@/config'
+import { syncHumanInputDraft } from '../../human-input/shared/sync-draft'
import { HumanInputMigrationContext } from './context'
import { createHumanInputMigrationApi, executeHumanInputV2Migration } from './executor'
import HumanInputMigrationBanner from './migration-banner'
@@ -53,24 +54,6 @@ const getBlockerTranslationKey = (
}
}
-const syncDraftOnce = async (
- doSyncWorkflowDraft: ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft'],
-) => {
- let saved = false
- let failed = false
- const result = await doSyncWorkflowDraft(true, {
- onSuccess: () => {
- saved = true
- },
- onError: () => {
- failed = true
- },
- })
- // Read-only, unloaded, and non-persisting collaboration paths can settle with
- // no save. Completion alone must not turn an unsaved migration into success.
- if (failed || (!saved && result == null)) throw new Error('human-input-migration-sync-failed')
-}
-
const ActiveHumanInputMigrationProvider = ({
children,
canEdit,
@@ -83,9 +66,6 @@ const ActiveHumanInputMigrationProvider = ({
const { saveStateToHistory } = useWorkflowHistory()
const { nodesMap } = useNodesMetaData()
const [dialogOpen, setDialogOpen] = useState(false)
- const [pending, setPending] = useState(false)
- const [error, setError] = useState<string>()
- const pendingRef = useRef(false)
const canApplyRef = useRef(canEdit)
useEffect(() => {
canApplyRef.current = canEdit
@@ -100,17 +80,6 @@ const ActiveHumanInputMigrationProvider = ({
)
const helpLink = nodesMap?.[BlockEnum.HumanInputV2]?.metaData.helpLinkUri
- const openMigrationDialog = useCallback(() => {
- if (!canEdit || !policy.hasLegacyHumanInput) return
- setError(undefined)
- setDialogOpen(true)
- }, [canEdit, policy.hasLegacyHumanInput])
-
- const handleDialogOpenChange = useCallback((open: boolean) => {
- setDialogOpen(open)
- if (!open) setError(undefined)
- }, [])
-
const migrationApi = useMemo(() => createHumanInputMigrationApi(), [])
const replaceGraph = useCallback(
@@ -120,14 +89,9 @@ const ActiveHumanInputMigrationProvider = ({
[collaborativeWorkflow],
)
- const handleConfirm = useCallback(async () => {
- if (pendingRef.current || !canEdit) return
- pendingRef.current = true
- setPending(true)
- setError(undefined)
-
- try {
- const result = await executeHumanInputV2Migration({
+ const migration = useMutation({
+ mutationFn: () =>
+ executeHumanInputV2Migration({
getGraph: () => {
const state = store.getState()
return { nodes: state.getNodes() as Node[], edges: state.edges as Edge[] }
@@ -135,61 +99,53 @@ const ActiveHumanInputMigrationProvider = ({
canApply: () => canApplyRef.current,
migrationApi,
replaceGraph,
- syncDraft: () => syncDraftOnce(doSyncWorkflowDraft),
+ syncDraft: () => syncHumanInputDraft(doSyncWorkflowDraft),
saveHistory: (migratedNodeIds) =>
saveStateToHistory(WorkflowHistoryEvent.HumanInputMigration, {
nodeId: migratedNodeIds[0],
}),
- })
-
- if (result.status === 'blocked') {
- const firstBlocker = result.blockers[0]
- if (!firstBlocker) throw new Error('human-input-migration-invalid-response')
- const reason =
- firstBlocker.code === HumanInputMigrationBlockerCode.UnsupportedInputType
- ? t(($) => $['nodes.humanInputMigration.blocker.unsupportedInputType'], {
- ns: 'workflow',
- field: firstBlocker.value,
- })
- : t(($) => $[getBlockerTranslationKey(firstBlocker.code)], { ns: 'workflow' })
- const message = t(($) => $['nodes.humanInputMigration.error.blocked'], {
- ns: 'workflow',
- nodeTitle: firstBlocker.nodeTitle,
- reason,
- })
- setError(message)
- toast.error(message)
- return
- }
-
- if (result.status === 'graph-changed') {
- const message = t(($) => $['nodes.humanInputMigration.error.graphChanged'], {
- ns: 'workflow',
- })
- setError(message)
- toast.error(message)
- return
- }
-
- if (result.status === 'sync-error') {
- const message = t(($) => $['nodes.humanInputMigration.error.sync'], { ns: 'workflow' })
- setError(message)
- toast.error(message)
- return
- }
-
- setDialogOpen(false)
- if (result.status === 'success')
- toast.success(t(($) => $['nodes.humanInputMigration.success'], { ns: 'workflow' }))
- } catch {
- const message = t(($) => $['nodes.humanInputMigration.error.preflight'], { ns: 'workflow' })
- setError(message)
- toast.error(message)
- } finally {
- pendingRef.current = false
- setPending(false)
- }
- }, [canEdit, doSyncWorkflowDraft, migrationApi, replaceGraph, saveStateToHistory, store, t])
+ }),
+ onSuccess: (result) => {
+ if (result.status === 'success' || result.status === 'noop') setDialogOpen(false)
+ },
+ })
+ const { reset, mutate, isPending: pending } = migration
+ const openMigrationDialog = useCallback(() => {
+ if (!canEdit || !policy.hasLegacyHumanInput) return
+ reset()
+ setDialogOpen(true)
+ }, [canEdit, policy.hasLegacyHumanInput, reset])
+ const handleDialogOpenChange = (open: boolean) => {
+ if (pending) return
+ setDialogOpen(open)
+ if (!open) reset()
+ }
+ const result = migration.data
+ const error = migration.isError
+ ? t(($) => $['nodes.humanInputMigration.error.preflight'], { ns: 'workflow' })
+ : result?.status === 'blocked'
+ ? (() => {
+ const blocker = result.blockers[0]
+ if (!blocker)
+ return t(($) => $['nodes.humanInputMigration.error.preflight'], { ns: 'workflow' })
+ const reason =
+ blocker.code === HumanInputMigrationBlockerCode.UnsupportedInputType
+ ? t(($) => $['nodes.humanInputMigration.blocker.unsupportedInputType'], {
+ ns: 'workflow',
+ field: blocker.value,
+ })
+ : t(($) => $[getBlockerTranslationKey(blocker.code)], { ns: 'workflow' })
+ return t(($) => $['nodes.humanInputMigration.error.blocked'], {
+ ns: 'workflow',
+ nodeTitle: blocker.nodeTitle,
+ reason,
+ })
+ })()
+ : result?.status === 'graph-changed'
+ ? t(($) => $['nodes.humanInputMigration.error.graphChanged'], { ns: 'workflow' })
+ : result?.status === 'sync-error'
+ ? t(($) => $['nodes.humanInputMigration.error.sync'], { ns: 'workflow' })
+ : undefined
const contextValue = useMemo(
() => ({ policy, canEdit, pending, helpLink, openMigrationDialog }),
@@ -209,12 +165,14 @@ const ActiveHumanInputMigrationProvider = ({
</div>
)}
<HumanInputMigrationDialog
- open={dialogOpen && policy.hasLegacyHumanInput}
+ open={dialogOpen && (policy.hasLegacyHumanInput || pending)}
pending={pending}
nodeCount={legacyNodeCount}
error={error}
onOpenChange={handleDialogOpenChange}
- onConfirm={handleConfirm}
+ onConfirm={() => {
+ if (canEdit && !pending) mutate()
+ }}
/>
</HumanInputMigrationContext>
)
diff --git a/web/app/components/workflow/nodes/human-input-v2/node.tsx b/web/app/components/workflow/nodes/human-input-v2/node.tsx
index 95634acf296..c54d7718750 100644
--- a/web/app/components/workflow/nodes/human-input-v2/node.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/node.tsx
@@ -1,24 +1,20 @@
-import type { ContactRecipientOption, ContactRecipientOptionProvider } from './contact-provider'
import type { HumanInputV2NodeType } from './types'
import type { NodeProps } from '@/app/components/workflow/types'
-import { cn } from '@langgenius/dify-ui/cn'
-import { useEffect, useMemo, useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { useAtomValue } from 'jotai'
+import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import HumanInputNodeBranches from '@/app/components/workflow/nodes/human-input/shared/node-branches'
import { ENABLE_HITL_IM } from '@/config'
-import { useContactRecipientOptionProvider } from './contact-provider'
+import { currentWorkspaceIdAtom } from '@/context/workspace-state'
+import { getContactRecipientQueryOptions } from './contact-queries'
import { HumanInputV2Disabled } from './disabled'
import { deriveRecipientSummary } from './recipient-utils'
-const HumanInputV2NodeContent = ({
- provider,
- ...props
-}: NodeProps<HumanInputV2NodeType> & {
- provider: ContactRecipientOptionProvider
-}) => {
+const HumanInputV2NodeContent = (props: NodeProps<HumanInputV2NodeType>) => {
const { t } = useTranslation(['workflow'])
const { data } = props
- const [contacts, setContacts] = useState<ContactRecipientOption[]>([])
+ const workspaceId = useAtomValue(currentWorkspaceIdAtom)
const contactIds = useMemo(
() => [
...new Set(
@@ -30,26 +26,12 @@ const HumanInputV2NodeContent = ({
[data.recipients_spec],
)
- useEffect(() => {
- if (!contactIds.length) return
-
- let active = true
- void provider
- .resolve({ contact_ids: contactIds })
- .then((options) => {
- if (active) setContacts(options)
- })
- .catch(() => {
- if (active) setContacts([])
- })
- return () => {
- active = false
- }
- }, [contactIds, provider])
-
+ const contacts = useQuery(getContactRecipientQueryOptions(workspaceId, contactIds))
const summary = deriveRecipientSummary(
data.recipients_spec,
- new Map(contacts.map((contact) => [contact.id, contact.name])),
+ contacts.isSuccess
+ ? new Map(contacts.data.data.map((contact) => [contact.id, contact.name]))
+ : undefined,
)
const summaryLabel = (() => {
@@ -98,7 +80,7 @@ const HumanInputV2NodeContent = ({
return (
<>
- <div className="space-y-0.5 py-1">
+ <div className="space-y-0.5 py-1" aria-busy={contactIds.length > 0 && contacts.isPending}>
{summary.state !== 'empty' && (
<div className="px-2.5 py-0.5 system-2xs-medium-uppercase text-text-tertiary">
{t(($) => $['nodes.humanInputV2.recipients.title'], { ns: 'workflow' })}
@@ -106,15 +88,8 @@ const HumanInputV2NodeContent = ({
)}
<div className="px-2.5">
<div
- className={cn(
- 'flex min-h-6 items-center gap-1 rounded-md px-1.5 py-1 system-xs-regular',
- summary.state === 'empty' &&
- 'bg-state-warning-hover px-2 text-text-warning ring-[0.5px] ring-state-warning-active',
- summary.state === 'invalid' &&
- 'bg-state-destructive-hover text-text-destructive-secondary',
- (summary.state === 'configured' || summary.state === 'overflow') &&
- 'bg-workflow-block-parma-bg text-text-secondary',
- )}
+ data-state={summary.state}
+ className="flex min-h-6 items-center gap-1 rounded-md px-1.5 py-1 system-xs-regular data-[state=configured]:bg-workflow-block-parma-bg data-[state=configured]:text-text-secondary data-[state=empty]:bg-state-warning-hover data-[state=empty]:px-2 data-[state=empty]:text-text-warning data-[state=empty]:ring-[0.5px] data-[state=empty]:ring-state-warning-active data-[state=invalid]:bg-state-destructive-hover data-[state=invalid]:text-text-destructive-secondary data-[state=overflow]:bg-workflow-block-parma-bg data-[state=overflow]:text-text-secondary"
>
{summary.state === 'invalid' && (
<span className="i-ri-alert-line size-4 shrink-0" aria-hidden />
@@ -128,11 +103,6 @@ const HumanInputV2NodeContent = ({
)
}
-const EnabledHumanInputV2Node = (props: NodeProps<HumanInputV2NodeType>) => {
- const { provider, workspaceId } = useContactRecipientOptionProvider()
- return <HumanInputV2NodeContent key={workspaceId} {...props} provider={provider} />
-}
-
export const HumanInputV2Node = (props: NodeProps<HumanInputV2NodeType>) => {
if (!ENABLE_HITL_IM) {
return (
@@ -143,5 +113,5 @@ export const HumanInputV2Node = (props: NodeProps<HumanInputV2NodeType>) => {
)
}
- return <EnabledHumanInputV2Node {...props} />
+ return <HumanInputV2NodeContent {...props} />
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/panel.tsx b/web/app/components/workflow/nodes/human-input-v2/panel.tsx
index d4afe7d6133..e9bbcaee9e3 100644
--- a/web/app/components/workflow/nodes/human-input-v2/panel.tsx
+++ b/web/app/components/workflow/nodes/human-input-v2/panel.tsx
@@ -63,7 +63,12 @@ const HumanInputV2PanelContent = ({ id, data }: NodePanelProps<HumanInputV2NodeT
<div className="px-4 py-2">
<Separator className="my-0 bg-divider-subtle" />
</div>
- <HumanInputSharedPanelSections id={id} config={config} />
+ <HumanInputSharedPanelSections
+ id={id}
+ config={config}
+ availableVars={availableVars}
+ availableNodes={availableNodesWithParent}
+ />
</div>
)
}
diff --git a/web/app/components/workflow/nodes/human-input-v2/recipient-utils.ts b/web/app/components/workflow/nodes/human-input-v2/recipient-utils.ts
index e216b2e10f8..f6f3425a7cf 100644
--- a/web/app/components/workflow/nodes/human-input-v2/recipient-utils.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/recipient-utils.ts
@@ -93,13 +93,6 @@ export function updateRecipient(
return recipients.map((item, itemIndex) => (itemIndex === index ? recipient : item))
}
-export function removeRecipient(
- recipients: HumanInputV2Recipient[],
- index: number,
-): HumanInputV2Recipient[] {
- return recipients.filter((_, itemIndex) => itemIndex !== index)
-}
-
export type RecipientSummary = {
state: 'empty' | 'configured' | 'overflow' | 'invalid'
contactCount: number
@@ -113,7 +106,7 @@ export type RecipientSummary = {
export function deriveRecipientSummary(
recipients: HumanInputV2Recipient[],
- contactLabels: ReadonlyMap<string, string> = new Map(),
+ contactLabels?: ReadonlyMap<string, string>,
visibleLimit = 3,
): RecipientSummary {
if (!recipients.length) {
@@ -139,8 +132,8 @@ export function deriveRecipientSummary(
if (getRecipientValidationError(recipient)) invalid = true
if (recipient.type === 'contact') {
contactCount += 1
- const label = contactLabels.get(recipient.contact_id)
- if (!label) invalid = true
+ const label = contactLabels?.get(recipient.contact_id)
+ if (contactLabels && !contactLabels.has(recipient.contact_id)) invalid = true
return label || recipient.contact_id || 'contact'
}
if (recipient.type === 'dynamic_email') {
diff --git a/web/app/components/workflow/nodes/human-input-v2/use-config.ts b/web/app/components/workflow/nodes/human-input-v2/use-config.ts
index d05ba531485..0efd0d179d4 100644
--- a/web/app/components/workflow/nodes/human-input-v2/use-config.ts
+++ b/web/app/components/workflow/nodes/human-input-v2/use-config.ts
@@ -10,8 +10,6 @@ import useHumanInputSharedConfig from '../human-input/shared/use-config'
const useHumanInputV2Config = (id: string, payload: HumanInputV2NodeType) => {
const removedInputsRef = useRef(new Map<string, Map<string, FormInputItem>>())
- // Older drafts can retain input definitions after losing their body placeholders.
- // Restore the existing controls without replacing their options or output identities.
const missingPlaceholders = payload.inputs
.map((input) => `{{#$output.${input.output_variable_name}#}}`)
.filter((placeholder) => !payload.form_content.includes(placeholder))
@@ -51,7 +49,6 @@ const useHumanInputV2Config = (id: string, payload: HumanInputV2NodeType) => {
removedInputs.set(input.output_variable_name, input)
return false
})
- // Lexical undo restores the body token; retain its original field definition too.
for (const [name, input] of removedInputs) {
if (
value.includes(`{{#$output.${name}#}}`) &&
@@ -68,7 +65,6 @@ const useHumanInputV2Config = (id: string, payload: HumanInputV2NodeType) => {
const handleFormInputsChange = useCallback((inputs: FormInputItem[]) => {
const config = configRef.current
if (config.readOnly) return
- // Existing editor blocks can still hold the definitions from before a keyboard deletion.
config.handleFormInputsChange(
inputs.filter((input) =>
config.inputs.form_content.includes(`{{#$output.${input.output_variable_name}#}}`),
diff --git a/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx
index e91319bad13..127950e916d 100644
--- a/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx
@@ -276,6 +276,36 @@ describe('DSL Import with Human Input Node', () => {
})
})
+ it.each([
+ ['id', undefined, 'emptyActionId'],
+ ['id', null, 'emptyActionId'],
+ ['title', undefined, 'emptyActionTitle'],
+ ['title', null, 'emptyActionTitle'],
+ ])('validates historical action %s = %s without throwing', (field, value, error) => {
+ const action = { id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary }
+ Reflect.set(action, field, value)
+ const payload: HumanInputNodeType = {
+ type: BlockEnum.HumanInput,
+ title: 'Legacy approval',
+ desc: '',
+ delivery_methods: [{ id: 'web', type: DeliveryMethodType.WebApp, enabled: true }],
+ form_content: '',
+ inputs: [],
+ user_actions: [action],
+ timeout: 3,
+ timeout_unit: 'day',
+ }
+ expect(
+ humanInputDefault.checkValid(
+ payload,
+ withSelectorKey((key: string) => key, 'workflow'),
+ ),
+ ).toMatchObject({
+ isValid: false,
+ errorMessage: `nodes.humanInput.errorMsg.${error}`,
+ })
+ })
+
it('ignores incomplete email configuration when that delivery method is disabled', () => {
const payload = createHumanInputNode({
delivery_methods: [
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx
index 8113ee0d043..af40c7dbf32 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content-preview.hitl-v2.spec.tsx
@@ -1,8 +1,8 @@
-import { act, screen } from '@testing-library/react'
+import { act, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createNode } from '../../../../__tests__/fixtures'
import { renderWorkflowComponent } from '../../../../__tests__/workflow-test-env'
-import FormContentPreview from '../form-content-preview'
+import FormContentPreview, { FormContentPreviewTrigger } from '../form-content-preview'
const preview = vi.hoisted(() => vi.fn())
vi.mock('@/service/console', async (importOriginal) => {
@@ -27,13 +27,20 @@ const renderPreview = (
options: Parameters<typeof renderWorkflowComponent>[1] = {},
readOnly = false,
) =>
- renderWorkflowComponent(<FormContentPreview {...props} readOnly={readOnly} />, {
- ...options,
- initialStoreState: {
- panelWidth: 320,
- nodes: [createNode({ id: 'node-1', data: { title: 'Classifier' } })],
+ renderWorkflowComponent(
+ readOnly ? (
+ <FormContentPreview {...props} readOnly />
+ ) : (
+ <FormContentPreviewTrigger {...props} />
+ ),
+ {
+ ...options,
+ initialStoreState: {
+ panelWidth: 320,
+ nodes: [createNode({ id: 'node-1', data: { title: 'Classifier' } })],
+ },
},
- })
+ )
it('waits for the saved workflow before displaying the real server markdown', async () => {
let finishSave!: () => void
@@ -42,16 +49,31 @@ it('waits for the saved workflow before displaying the real server markdown', as
})
preview.mockResolvedValue({ form_content: 'Resolved server preview', inputs: [], actions: [] })
renderPreview({ hooksStoreProps: { doSyncWorkflowDraft: () => saving } })
- expect(screen.getByRole('status')).toHaveTextContent('common.loading')
+ const status = screen.getByRole('status')
+ expect(status).toBeEmptyDOMElement()
+ await userEvent.setup().click(
+ screen.getByRole('button', {
+ name: 'workflowHumanInput.nodes.humanInput.formContent.preview',
+ }),
+ )
+ expect(status).toHaveTextContent('common.loading')
+ expect(within(status).queryByRole('button')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeEnabled()
expect(preview).not.toHaveBeenCalled()
expect(screen.queryByText(props.content)).not.toBeInTheDocument()
await act(async () => finishSave())
- expect(await screen.findByText('Resolved server preview')).toBeInTheDocument()
+ expect(
+ await screen.findByText('Resolved server preview', {}, { timeout: 5000 }),
+ ).toBeInTheDocument()
expect(screen.queryByText(props.content)).not.toBeInTheDocument()
- expect(preview).toHaveBeenCalledExactlyOnceWith({
- params: { app_id: 'app-1', node_id: 'node-1' },
- body: { inputs: {} },
- })
+ expect(preview).toHaveBeenCalledExactlyOnceWith(
+ {
+ params: { app_id: 'app-1', node_id: 'node-1' },
+ body: { inputs: {} },
+ },
+ { context: { silent: true } },
+ )
+ expect(status).toBeEmptyDOMElement()
})
it('shows a server failure and retries without presenting local content as the result', async () => {
@@ -62,7 +84,10 @@ it('shows a server failure and retries without presenting local content as the r
renderPreview({
hooksStoreProps: { doSyncWorkflowDraft: async () => ({ hash: 'saved', updatedAt: 1 }) },
})
- expect(await screen.findByText('Server preview failed')).toBeInTheDocument()
+ await user.click(
+ screen.getByRole('button', { name: 'workflowHumanInput.nodes.humanInput.formContent.preview' }),
+ )
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.error')
expect(screen.queryByText(props.content)).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
expect(await screen.findByText('Retried preview')).toBeInTheDocument()
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.hitl-v2.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.hitl-v2.spec.tsx
index 6da4fb7991f..40c2a676153 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.hitl-v2.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/single-run-form.hitl-v2.spec.tsx
@@ -39,7 +39,7 @@ const createFormData = (overrides: Partial<HumanInputFormData> = {}): HumanInput
})
describe('SingleRunForm', () => {
- it('restores the submit action and keeps entered values after a server failure', async () => {
+ it('reports a failed submission inline and keeps entered values for a retry', async () => {
const user = userEvent.setup()
const onSubmit = vi
.fn()
@@ -50,12 +50,14 @@ describe('SingleRunForm', () => {
await user.type(screen.getByRole('textbox', { name: 'review' }), 'Keep this answer')
await user.click(screen.getByRole('button', { name: 'Approve' }))
await waitFor(() => expect(screen.getByRole('button', { name: 'Approve' })).toBeEnabled())
- expect(mockToastError).toHaveBeenCalledWith('Submission unavailable')
+ expect(mockToastError).not.toHaveBeenCalled()
+ expect(screen.getByRole('alert')).toHaveTextContent('common.api.actionFailed')
expect(screen.getByRole('textbox', { name: 'review' })).toHaveValue('Keep this answer')
await user.click(screen.getByRole('button', { name: 'Approve' }))
expect(onSubmit).toHaveBeenLastCalledWith({
action: 'approve',
inputs: { review: 'Keep this answer' },
})
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument())
})
})
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
index 4cc218d5706..6695094d1f2 100644
--- 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
@@ -1,6 +1,5 @@
import type { ReactNode } from 'react'
import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'
-import { cn } from '@langgenius/dify-ui/cn'
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'
@@ -15,6 +14,8 @@ type MailBodyInputProps = {
children?: ReactNode
requestURLSelectable?: boolean
'aria-labelledby'?: string
+ 'aria-describedby'?: string
+ 'aria-invalid'?: boolean
}
const MailBodyInput = ({
@@ -26,19 +27,19 @@ const MailBodyInput = ({
children,
requestURLSelectable = true,
'aria-labelledby': ariaLabelledby,
+ 'aria-describedby': ariaDescribedBy,
+ 'aria-invalid': ariaInvalid,
}: MailBodyInputProps) => {
const { t } = useTranslation(['workflow'])
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',
- )}
+ wrapperClassName="w-full rounded-lg border border-transparent bg-components-input-bg-normal px-2 py-1 focus-within:border-components-input-border-active focus-within:bg-components-input-bg-active focus-within:shadow-xs hover:border-components-input-border-hover hover:bg-components-input-bg-hover"
className="min-h-32"
editable={!readOnly}
aria-labelledby={ariaLabelledby}
+ aria-describedby={ariaDescribedBy}
+ aria-invalid={ariaInvalid}
value={value}
requestURLBlock={{
show: true,
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
index 2d8eda9d692..a93544be3a9 100644
--- 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
@@ -1,20 +1,23 @@
'use client'
import type { FC } from 'react'
import type { FormInputItem, UserAction } from '../types'
-import { zFormInputConfig, zUserActionConfig } from '@dify/contracts/api/web/zod.gen'
+import { zFormInputConfig, zUserActionConfig } from '@dify/contracts/api/console/apps/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { useMutation } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge'
import { getButtonStyle } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
import { Markdown } from '@/app/components/base/markdown'
+import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'
import { useStore } from '@/app/components/workflow/store'
import useNodes from '@/app/components/workflow/store/workflow/use-nodes'
import { consoleClient } from '@/service/console'
+import { HumanInputDraftSyncError, syncHumanInputDraft } from '../shared/sync-draft'
import { normalizeHumanInputFormInput } from '../shared/types'
import { Note, rehypeNotes, rehypeVariable, Variable } from './variable-in-markdown'
@@ -114,106 +117,146 @@ const FormContentPreview: FC<FormContentPreviewProps> = ({
)
}
-const ServerFormContentPreview = (props: FormContentPreviewProps & { nodeId: string }) => {
+type PreviewTriggerProps = Omit<FormContentPreviewProps, 'onClose' | 'readOnly'>
+
+const PreviewButton = ({
+ open,
+ onClick,
+ buttonRef,
+}: {
+ open: boolean
+ onClick: () => void
+ buttonRef: React.RefObject<HTMLButtonElement | null>
+}) => {
+ const { t } = useTranslation(['workflowHumanInput'])
+ return (
+ <Button
+ ref={buttonRef}
+ variant="ghost"
+ size="small"
+ aria-pressed={open}
+ className="flex items-center px-2 aria-pressed:bg-state-accent-active aria-pressed:text-text-accent"
+ onClick={onClick}
+ >
+ <span className="i-ri-eye-line size-3.5" aria-hidden />
+ <span className="system-xs-medium">
+ {t(($) => $['nodes.humanInput.formContent.preview'], { ns: 'workflowHumanInput' })}
+ </span>
+ </Button>
+ )
+}
+
+const ServerPreviewTrigger = ({ nodeId }: PreviewTriggerProps & { nodeId: string }) => {
const { t } = useTranslation(['workflow', 'common'])
const resource = useAtomValue(editorResourceAtom)
- const app = resource.kind === 'app' ? { id: resource.appId, mode: resource.mode } : undefined
const { doSyncWorkflowDraft } = useNodesSyncDraft()
const panelWidth = useStore((state) => state.panelWidth)
- const [result, setResult] = React.useState<{
- requestKey: string
- data?: Pick<FormContentPreviewProps, 'content' | 'formInputs' | 'userActions'>
- error?: string
- }>()
- const [attempt, retry] = React.useReducer((value) => value + 1, 0)
- const requestKey = JSON.stringify([app?.id, app?.mode, props.nodeId, attempt])
- const data = result?.requestKey === requestKey ? result.data : undefined
- const error = result?.requestKey === requestKey ? result.error : undefined
- React.useEffect(() => {
- let cancelled = false
- const load = async () => {
- if (!app?.id) throw new Error(t(($) => $.error, { ns: 'common' }))
- if (!props.readOnly) {
- let saved = false
- let failed = false
- const result = await doSyncWorkflowDraft(true, {
- onSuccess: () => {
- saved = true
- },
- onError: () => {
- failed = true
- },
- })
- if (failed || (!saved && result == null))
- throw new Error(
- t(($) => $['nodes.humanInputV2.template.testSaveFailed'], { ns: 'workflow' }),
- )
- }
- if (cancelled) return
+ const [open, setOpen] = React.useState(false)
+ const buttonRef = React.useRef<HTMLButtonElement>(null)
+ const preview = useMutation({
+ mutationFn: async () => {
+ if (resource.kind !== 'app') throw new Error('Missing application')
+ await syncHumanInputDraft(doSyncWorkflowDraft)
const api =
- app.mode === 'workflow'
+ resource.mode === 'workflow'
? consoleClient.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form
: consoleClient.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form
- const response = await api.preview.post({
- params: { app_id: app.id, node_id: props.nodeId },
- body: { inputs: {} },
- })
- if (!cancelled)
- setResult({
- requestKey,
- data: {
- content: response.form_content,
- formInputs: (response.inputs ?? []).map((input) =>
- normalizeHumanInputFormInput(zFormInputConfig.parse(input)),
- ),
- userActions: (response.actions ?? []).map((action) => {
- const parsed = zUserActionConfig.parse(action)
- return { ...parsed, button_style: parsed.button_style ?? 'default' }
- }),
- },
- })
- }
- load().catch((error) => {
- if (!cancelled)
- setResult({
- requestKey,
- error: error instanceof Error ? error.message : t(($) => $.error, { ns: 'common' }),
- })
- })
- return () => {
- cancelled = true
+ const response = await api.preview.post(
+ {
+ params: { app_id: resource.appId, node_id: nodeId },
+ body: { inputs: {} },
+ },
+ { context: { silent: true } },
+ )
+ return {
+ content: response.form_content,
+ formInputs: (response.inputs ?? []).map((input) =>
+ normalizeHumanInputFormInput(zFormInputConfig.parse(input)),
+ ),
+ userActions: (response.actions ?? []).map((action) => {
+ const parsed = zUserActionConfig.parse(action)
+ return { ...parsed, button_style: parsed.button_style ?? 'default' }
+ }),
+ }
+ },
+ })
+ const close = () => {
+ setOpen(false)
+ preview.reset()
+ buttonRef.current?.focus()
+ }
+ const toggle = () => {
+ if (open) close()
+ else {
+ setOpen(true)
+ preview.mutate()
}
- }, [app?.id, app?.mode, props.nodeId, props.readOnly, doSyncWorkflowDraft, requestKey, t])
- if (data) return <FormContentPreview {...data} onClose={props.onClose} />
+ }
return (
- <div
- role="status"
- className="fixed top-28 z-10 w-150 rounded-2xl border border-components-panel-border bg-components-panel-bg p-4 shadow-xl"
- style={{ right: panelWidth + 8 }}
- >
- <div className="flex items-center justify-between gap-4">
- <span>{error ?? t(($) => $.loading, { ns: 'common' })}</span>
- <IconButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- onClick={props.onClose}
- >
- <span aria-hidden className="i-ri-close-line size-5" />
- </IconButton>
- </div>
- {error && (
- <Button className="mt-3" onClick={retry}>
- {t(($) => $['operation.retry'], { ns: 'common' })}
- </Button>
- )}
- </div>
+ <>
+ <p role="status" className="sr-only">
+ {open && preview.isPending ? t(($) => $.loading, { ns: 'common' }) : ''}
+ </p>
+ <PreviewButton open={open} onClick={toggle} buttonRef={buttonRef} />
+ {open &&
+ (preview.data ? (
+ <FormContentPreview {...preview.data} onClose={close} />
+ ) : (
+ <div
+ className="fixed top-28 z-10 w-150 rounded-2xl border border-components-panel-border bg-components-panel-bg p-4 shadow-xl"
+ style={{ right: panelWidth + 8 }}
+ >
+ <div className="flex items-center justify-between gap-4">
+ {preview.isError ? (
+ <p role="alert">
+ {preview.error instanceof HumanInputDraftSyncError
+ ? t(($) => $['nodes.humanInputV2.template.testSaveFailed'], { ns: 'workflow' })
+ : t(($) => $.error, { ns: 'common' })}
+ </p>
+ ) : (
+ <SkeletonContainer aria-hidden className="grow">
+ <SkeletonRectangle className="h-4 w-1/3" />
+ <SkeletonRectangle className="h-16 w-full" />
+ </SkeletonContainer>
+ )}
+ <IconButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ onClick={close}
+ >
+ <span aria-hidden className="i-ri-close-line size-5" />
+ </IconButton>
+ </div>
+ {preview.isError && (
+ <Button className="mt-3" onClick={() => preview.mutate()}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ )}
+ </div>
+ ))}
+ </>
+ )
+}
+
+const LocalPreviewTrigger = (props: PreviewTriggerProps) => {
+ const [open, setOpen] = React.useState(false)
+ const buttonRef = React.useRef<HTMLButtonElement>(null)
+ const close = () => {
+ setOpen(false)
+ buttonRef.current?.focus()
+ }
+ return (
+ <>
+ <PreviewButton open={open} onClick={() => setOpen(!open)} buttonRef={buttonRef} />
+ {open && <FormContentPreview {...props} onClose={close} />}
+ </>
)
}
-const HumanInputFormContentPreview = (props: FormContentPreviewProps) =>
- props.nodeId && !props.readOnly ? (
- <ServerFormContentPreview {...props} nodeId={props.nodeId} />
+export const FormContentPreviewTrigger = (props: PreviewTriggerProps) =>
+ props.nodeId ? (
+ <ServerPreviewTrigger key={props.nodeId} {...props} nodeId={props.nodeId} />
) : (
- <FormContentPreview {...props} />
+ <LocalPreviewTrigger {...props} />
)
-export default React.memo(HumanInputFormContentPreview)
+export default React.memo(FormContentPreview)
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
index e0470f020e0..808b6cdc431 100644
--- 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
@@ -21,7 +21,6 @@ import {
initializeInputs,
splitByOutputVar,
} from '@/app/components/base/chat/chat/answer/human-input-content/utils'
-import { toast } from '@/app/notifications'
type Props = Readonly<{
nodeName: string
@@ -43,7 +42,7 @@ const FormContent = ({ nodeName, data, showBackButton, handleBack, onSubmit }: P
const renderedFormInputs = getRenderedFormInputs(data.inputs, data.form_content)
const defaultInputs = initializeInputs(renderedFormInputs, data.resolved_default_values || {})
const [inputs, setInputs] = useState(defaultInputs)
- const [isSubmitting, setIsSubmitting] = useState(false)
+ const [submission, setSubmission] = useState<'idle' | 'submitting' | 'failed'>('idle')
const handleInputsChange = (name: string, value: HumanInputFieldValue) => {
setInputs((prev) => ({
@@ -55,13 +54,12 @@ const FormContent = ({ nodeName, data, showBackButton, handleBack, onSubmit }: P
const hasEmptySelectOrFileInput = hasInvalidSelectOrFileInput(renderedFormInputs, inputs)
const submit = async (actionID: string) => {
- setIsSubmitting(true)
+ setSubmission('submitting')
try {
await onSubmit?.({ inputs, action: actionID })
- } catch (error) {
- toast.error(error instanceof Error ? error.message : t(($) => $.error, { ns: 'common' }))
- } finally {
- setIsSubmitting(false)
+ setSubmission('idle')
+ } catch {
+ setSubmission('failed')
}
}
@@ -73,7 +71,7 @@ const FormContent = ({ nodeName, data, showBackButton, handleBack, onSubmit }: P
<BreadcrumbItem className="shrink-0">
<button
type="button"
- className="flex cursor-pointer items-center gap-1 rounded-sm text-left system-sm-semibold-uppercase text-text-accent focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ className="flex cursor-pointer items-center gap-1 rounded-sm text-start system-sm-semibold-uppercase text-text-accent focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
onClick={handleBack}
>
<span className="i-ri-arrow-left-line size-4" aria-hidden />
@@ -102,11 +100,16 @@ const FormContent = ({ nodeName, data, showBackButton, handleBack, onSubmit }: P
onInputChange={handleInputsChange}
/>
))}
+ {submission === 'failed' && (
+ <p role="alert" className="system-sm-regular text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ )}
<div className="flex flex-wrap gap-1 py-1">
{data.actions.map((action: UserAction) => (
<Button
key={action.id}
- disabled={isSubmitting || hasEmptySelectOrFileInput}
+ disabled={submission === 'submitting' || hasEmptySelectOrFileInput}
variant={getButtonStyle(action.button_style)}
onClick={() => submit(action.id)}
>
diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.hitl-v2.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.hitl-v2.spec.ts
index 55aa97b6e79..21379acd57f 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.hitl-v2.spec.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.hitl-v2.spec.ts
@@ -144,19 +144,15 @@ describe('human-input/hooks/use-single-run-form-params', () => {
act(() => subject.result.current.form.forms[0]!.onChange({ topic: 'saved' }))
expect(subject.result.current.runInputData).toEqual({ topic: 'saved' })
- let request!: Promise<void>
act(() => {
- request = subject.result.current.form.handleShowGeneratedForm(
- subject.result.current.runInputData,
- )
+ subject.result.current.form.handleShowGeneratedForm(subject.result.current.runInputData)
})
- expect(subject.result.current.form.isGeneratingForm).toBe(true)
+ await waitFor(() => expect(subject.result.current.form.isGeneratingForm).toBe(true))
expect(mockFetchHumanInputNodeStepRunForm).not.toHaveBeenCalled()
await act(async () => {
resolveSave({ hash: 'saved', updatedAt: 1 })
- await request
})
- expect(subject.result.current.form.showGeneratedForm).toBe(true)
+ await waitFor(() => expect(subject.result.current.form.showGeneratedForm).toBe(true))
expect(subject.result.current.form.formData).toEqual(mockFormData)
expect(mockFetchHumanInputNodeStepRunForm).toHaveBeenCalledExactlyOnceWith(
'/apps/app-1/workflows/draft/human-input/nodes/node-1/form',
@@ -171,8 +167,8 @@ describe('human-input/hooks/use-single-run-form-params', () => {
)
await act(async () => subject.result.current.form.handleShowGeneratedForm({}))
expect(mockFetchHumanInputNodeStepRunForm).not.toHaveBeenCalled()
- expect(subject.result.current.form.showGeneratedForm).toBe(false)
- expect(subject.result.current.form.isGeneratingForm).toBe(false)
+ await waitFor(() => expect(subject.result.current.form.showGeneratedForm).toBe(false))
+ await waitFor(() => expect(subject.result.current.form.isGeneratingForm).toBe(false))
expect(mockToastError).toHaveBeenCalledWith('nodes.humanInputV2.template.testSaveFailed')
})
@@ -180,11 +176,13 @@ describe('human-input/hooks/use-single-run-form-params', () => {
mockFetchHumanInputNodeStepRunForm.mockRejectedValueOnce(new Error('Preview unavailable'))
const subject = renderSubject(createPayload())
await act(async () => subject.result.current.form.handleShowGeneratedForm({}))
- expect(subject.result.current.form.showGeneratedForm).toBe(false)
- expect(subject.result.current.form.isGeneratingForm).toBe(false)
- expect(mockToastError).toHaveBeenCalledWith('Preview unavailable')
+ await waitFor(() => expect(subject.result.current.form.showGeneratedForm).toBe(false))
+ await waitFor(() => expect(subject.result.current.form.isGeneratingForm).toBe(false))
+ expect(mockToastError).not.toHaveBeenCalled()
await act(async () => subject.result.current.form.handleShowGeneratedForm({}))
- expect(subject.result.current.form.formData?.form_content).toBe('Rendered content')
+ await waitFor(() =>
+ expect(subject.result.current.form.formData?.form_content).toBe('Rendered content'),
+ )
})
it('normalizes nullable server defaults and rejects malformed response fields', async () => {
@@ -207,8 +205,8 @@ describe('human-input/hooks/use-single-run-form-params', () => {
inputs: [{ type: 'unknown' }],
})
await act(async () => subject.result.current.form.handleShowGeneratedForm({}))
- expect(subject.result.current.form.showGeneratedForm).toBe(false)
- expect(subject.result.current.form.isGeneratingForm).toBe(false)
+ await waitFor(() => expect(subject.result.current.form.showGeneratedForm).toBe(false))
+ await waitFor(() => expect(subject.result.current.form.isGeneratingForm).toBe(false))
})
it.each([undefined, '2'] as const)(
@@ -271,18 +269,18 @@ describe('human-input/hooks/use-single-run-form-params', () => {
}),
)
const subject = renderSubject(payload)
- let oldRequest!: Promise<void>
act(() => {
- oldRequest = subject.result.current.form.handleShowGeneratedForm({ topic: 'old' })
+ subject.result.current.form.handleShowGeneratedForm({ topic: 'old' })
})
setSingleRunOpen(subject, payload, false)
setSingleRunOpen(subject, payload, true)
await act(async () => subject.result.current.form.handleShowGeneratedForm({ topic: 'new' }))
await act(async () => {
resolveOld({ ...mockFormData, form_content: 'Old response' })
- await oldRequest
})
- expect(subject.result.current.form.formData?.form_content).toBe('Rendered content')
+ await waitFor(() =>
+ expect(subject.result.current.form.formData?.form_content).toBe('Rendered content'),
+ )
await act(async () =>
subject.result.current.form.handleSubmitHumanInputForm({
action: 'approve',
@@ -299,9 +297,20 @@ describe('human-input/hooks/use-single-run-form-params', () => {
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
- const { withConsoleResponses } = await import('@/test/console/service-responses')
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
return {
...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post': (input: {
+ params: { app_id: string; node_id: string }
+ body: unknown
+ }) =>
+ mockFetchHumanInputNodeStepRunForm(
+ `/apps/${input.params.app_id}/workflows/draft/human-input/nodes/${input.params.node_id}/form`,
+ input.body,
+ ),
+ }),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post': (input: {
params: { app_id: string; node_id: string }
diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
index 09c3260bcec..e2c66fe9aa4 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
@@ -4,7 +4,7 @@ import type { WorkflowAppMode } from '@/app/components/apps/app-type'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { InputVar } from '@/app/components/workflow/types'
import type { HumanInputFormData } from '@/types/workflow'
-import { act } from '@testing-library/react'
+import { act, waitFor } from '@testing-library/react'
import { renderWorkflowFlowHook as renderHookWithConsoleQuery } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'
@@ -274,7 +274,7 @@ describe('human-input/hooks/use-single-run-form-params', () => {
})
expect(previewInputs).toHaveProperty('ignored', undefined)
- expect(result.current.showGeneratedForm).toBe(true)
+ await waitFor(() => expect(result.current.showGeneratedForm).toBe(true))
expect(previewForm).toHaveBeenCalledWith(
'/console/api/apps/app-1/workflows/draft/human-input/nodes/node-1/form/preview',
{
@@ -331,7 +331,7 @@ describe('human-input/hooks/use-single-run-form-params', () => {
result.current.handleHideGeneratedForm()
})
- expect(result.current.showGeneratedForm).toBe(false)
+ await waitFor(() => expect(result.current.showGeneratedForm).toBe(false))
})
it('should use the advanced-chat endpoint for chatflow form previews', async () => {
@@ -362,6 +362,7 @@ describe('human-input/hooks/use-single-run-form-params', () => {
)
expect(previewForm).toHaveBeenCalledTimes(1)
+ await waitFor(() => expect(result.current.formData).not.toBeNull())
await act(async () => {
await result.current.handleSubmitHumanInputForm({
inputs: undefined,
@@ -420,6 +421,7 @@ describe('human-input/hooks/use-single-run-form-params', () => {
await result.current.handleFetchFormContent({})
})
+ await waitFor(() => expect(result.current.formData).not.toBeNull())
expect(result.current.formData).toMatchObject({
inputs: [
{ type: 'paragraph', default: { type: 'constant', selector: [], value: '' } },
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
index f690df9f137..7274ba775f7 100644
--- 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
@@ -2,23 +2,24 @@ import type { HumanInputSharedNodeType } from '../shared/types'
import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
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 { zFormInputConfig, zUserActionConfig } from '@dify/contracts/api/console/apps/zod.gen'
import { useMutation } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { getProcessedHumanInputFormInputs } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'
import { toast } from '@/app/notifications'
-import { consoleQuery } from '@/service/console'
+import { consoleClient, consoleQuery } from '@/service/console'
import useNodeCrud from '../../_base/hooks/use-node-crud'
import { isHumanInputV2NodeData } from '../../human-input-v2/types'
import { selectHumanInputFormPreview } from '../query-select'
+import { HumanInputDraftSyncError, syncHumanInputDraft } from '../shared/sync-draft'
import { getHumanInputFormDependencySelectors, isOutput } from '../utils'
const i18nPrefix = 'nodes.humanInput'
+const EMPTY_REQUEST_INPUTS: Record<string, string> = {}
type Params = {
id: string
@@ -35,16 +36,6 @@ const useSingleRunFormParams = ({
getInputVars,
setRunInputData,
}: Params) => {
- const { mutateAsync: previewWorkflowForm } = useMutation(
- consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(
- { context: { silent: true } },
- ),
- )
- const { mutateAsync: previewChatflowForm } = useMutation(
- consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(
- { context: { silent: true } },
- ),
- )
const { mutateAsync: submitWorkflowForm } = useMutation(
consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(
{ context: { silent: true } },
@@ -58,11 +49,6 @@ const useSingleRunFormParams = ({
const { t } = useTranslation(['workflow', 'workflowHumanInput', 'common'])
const { inputs } = useNodeCrud<HumanInputSharedNodeType>(id, payload)
const { doSyncWorkflowDraft } = useNodesSyncDraft()
- const [showGeneratedForm, setShowGeneratedForm] = useState(false)
- const [formData, setFormData] = useState<HumanInputFormData | null>(null)
- const [requiredInputs, setRequiredInputs] = useState<Record<string, string>>({})
- const [isGeneratingForm, setIsGeneratingForm] = useState(false)
- const generationSequenceRef = useRef(0)
const generatedInputs = useMemo(() => {
const formInputDependencyInputs = getHumanInputFormDependencySelectors(inputs.inputs).map(
(selector) => `{{#${selector.join('.')}#}}`,
@@ -89,7 +75,6 @@ const useSingleRunFormParams = ({
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('.')
@@ -101,86 +86,44 @@ const useSingleRunFormParams = ({
const appId = resource.kind === 'app' ? resource.appId : undefined
const isWorkflowMode = resource.kind === 'app' && resource.mode === 'workflow'
const isV2 = isHumanInputV2NodeData(payload)
- const [formSession, setFormSession] = useState({ appId, id, isSingleRun: payload._isSingleRun })
- if (
- formSession.appId !== appId ||
- formSession.id !== id ||
- formSession.isSingleRun !== payload._isSingleRun
- ) {
- setFormSession({ appId, id, isSingleRun: payload._isSingleRun })
- setShowGeneratedForm(false)
- setIsGeneratingForm(false)
- setFormData(null)
- setRequiredInputs({})
- }
- const generationSessionRef = useRef({ appId, id, isSingleRun: payload._isSingleRun })
- const isMountedRef = useRef(false)
- // The child form can generate automatically in its mount effect. Invalidate
- // the previous session before that effect, without cancelling StrictMode replays.
- useLayoutEffect(() => {
- isMountedRef.current = true
- const previous = generationSessionRef.current
- if (
- previous.appId !== appId ||
- previous.id !== id ||
- previous.isSingleRun !== payload._isSingleRun
- ) {
- generationSequenceRef.current += 1
- }
- generationSessionRef.current = { appId, id, isSingleRun: payload._isSingleRun }
- return () => {
- isMountedRef.current = false
- }
- }, [appId, id, payload._isSingleRun])
- const handleFetchFormContent = useCallback(
- async (values: Record<string, string>) => {
- if (!appId) return null
- const generation = ++generationSequenceRef.current
- if (isV2) {
- let saved = false
- let failed = false
- const result = await doSyncWorkflowDraft(true, {
- onSuccess: () => {
- saved = true
- },
- onError: () => {
- failed = true
- },
- })
- if (!isMountedRef.current || generation !== generationSequenceRef.current) return null
- if (failed || (!saved && result == null))
- throw new Error(
- t(($) => $['nodes.humanInputV2.template.testSaveFailed'], { ns: 'workflow' }),
- )
- }
- const requestParamsObj = Object.fromEntries(
+ const generation = useMutation({
+ mutationKey: ['human-input-preview', appId, id],
+ mutationFn: async (values: Record<string, string>) => {
+ if (!appId) throw new Error('Missing application')
+ if (isV2) await syncHumanInputDraft(doSyncWorkflowDraft)
+ const requestInputs = Object.fromEntries(
Object.entries(values).filter(([, value]) => value !== undefined),
)
- const previewForm = isWorkflowMode ? previewWorkflowForm : previewChatflowForm
- const response = await previewForm({
+ const api = isWorkflowMode
+ ? consoleClient.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form
+ : consoleClient.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form
+ const response = await api.preview.post({
params: { app_id: appId, node_id: id },
- body: { inputs: requestParamsObj },
+ body: { inputs: requestInputs },
})
- if (!isMountedRef.current || generation !== generationSequenceRef.current) return null
- const data = selectHumanInputFormPreview({
- ...response,
- inputs: response.inputs?.map((input) => zFormInputConfig.parse(input)),
- actions: response.actions?.map((action) => zUserActionConfig.parse(action)),
- })
- setFormData(data)
- setRequiredInputs(requestParamsObj)
- return data
+ return {
+ formData: selectHumanInputFormPreview({
+ ...response,
+ inputs: response.inputs?.map((input) => zFormInputConfig.parse(input)),
+ actions: response.actions?.map((action) => zUserActionConfig.parse(action)),
+ }),
+ requestInputs,
+ }
},
- [
- appId,
- id,
- isWorkflowMode,
- previewWorkflowForm,
- previewChatflowForm,
- isV2,
- doSyncWorkflowDraft,
- t,
- ],
+ onError: (error) => {
+ if (error instanceof HumanInputDraftSyncError)
+ toast.error(t(($) => $['nodes.humanInputV2.template.testSaveFailed'], { ns: 'workflow' }))
+ },
+ })
+ const { mutate: generate, mutateAsync: generateAsync, reset: resetGeneration } = generation
+ useEffect(() => {
+ if (payload._isSingleRun === false) resetGeneration()
+ }, [payload._isSingleRun, resetGeneration])
+ const formData = generation.data?.formData ?? null
+ const requiredInputs = generation.data?.requestInputs ?? EMPTY_REQUEST_INPUTS
+ const handleFetchFormContent = useCallback(
+ async (values: Record<string, string>) => (await generateAsync(values)).formData,
+ [generateAsync],
)
const handleSubmitHumanInputForm = useCallback(
@@ -213,33 +156,22 @@ const useSingleRunFormParams = ({
],
)
- const handleShowGeneratedForm = async (formValue: Record<string, string>) => {
- if (!appId) return
- const generation = generationSequenceRef.current + 1
- setIsGeneratingForm(true)
- try {
- const form = await handleFetchFormContent(formValue)
- if (form && generation === generationSequenceRef.current) setShowGeneratedForm(true)
- } catch (error) {
- if (!isMountedRef.current || generation !== generationSequenceRef.current) return
- toast.error(error instanceof Error ? error.message : t(($) => $.error, { ns: 'common' }))
- } finally {
- if (isMountedRef.current && generation === generationSequenceRef.current)
- setIsGeneratingForm(false)
- }
- }
-
- const handleHideGeneratedForm = () => {
- generationSequenceRef.current += 1
- setShowGeneratedForm(false)
- setIsGeneratingForm(false)
- }
+ const handleShowGeneratedForm = useCallback(
+ (values: Record<string, string>) => {
+ if (!appId) return
+ generate(values)
+ },
+ [appId, generate],
+ )
+ const handleHideGeneratedForm = useCallback(() => {
+ resetGeneration()
+ }, [resetGeneration])
return {
forms,
- isGeneratingForm,
+ isGeneratingForm: generation.isPending,
getDependentVars,
- showGeneratedForm,
+ showGeneratedForm: generation.isSuccess && Boolean(formData),
handleShowGeneratedForm,
handleHideGeneratedForm,
formData,
diff --git a/web/app/components/workflow/nodes/human-input/panel.tsx b/web/app/components/workflow/nodes/human-input/panel.tsx
index 7558d5e3052..89e77c5d2e6 100644
--- a/web/app/components/workflow/nodes/human-input/panel.tsx
+++ b/web/app/components/workflow/nodes/human-input/panel.tsx
@@ -52,7 +52,12 @@ const Panel: FC<NodePanelProps<HumanInputNodeType>> = ({ id, data }) => {
<div className="px-4 py-2">
<Separator className="my-0 bg-divider-subtle" />
</div>
- <HumanInputSharedPanelSections id={id} config={config} />
+ <HumanInputSharedPanelSections
+ id={id}
+ config={config}
+ availableVars={availableVars}
+ availableNodes={availableNodesWithParent}
+ />
</div>
)
}
diff --git a/web/app/components/workflow/nodes/human-input/shared/__tests__/panel-sections.spec.tsx b/web/app/components/workflow/nodes/human-input/shared/__tests__/panel-sections.spec.tsx
index a3070353311..76dc984c975 100644
--- a/web/app/components/workflow/nodes/human-input/shared/__tests__/panel-sections.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/shared/__tests__/panel-sections.spec.tsx
@@ -18,7 +18,7 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', ()
// Keep the action list and its inputs real; the rich form editor is unrelated to action editing.
vi.mock('../../components/form-content', () => ({ default: () => null }))
-vi.mock('../../components/form-content-preview', () => ({ default: () => null }))
+vi.mock('../../components/form-content-preview', () => ({ FormContentPreviewTrigger: () => null }))
const initialActions: UserAction[] = [
{ id: 'approve', title: 'Approve', button_style: UserActionButtonType.Primary },
@@ -57,7 +57,14 @@ const ActionPanel = ({ actions: startingActions = initialActions }: { actions?:
handleFormInputItemRemove: vi.fn(),
}
- return <HumanInputSharedPanelSections id="human-input" config={config} />
+ return (
+ <HumanInputSharedPanelSections
+ id="human-input"
+ config={config}
+ availableVars={[]}
+ availableNodes={[]}
+ />
+ )
}
const getActionIds = () =>
@@ -161,3 +168,21 @@ describe('HumanInputSharedPanelSections action editing', () => {
expect(getActionTitles()[0]).toHaveValue('Approve')
})
})
+
+it.each([0, 1, 2])(
+ 'keeps keyboard focus on a surviving action after deleting row %s',
+ async (index) => {
+ const user = userEvent.setup()
+ render(<ActionPanel />)
+ const expected = initialActions[index === 2 ? 1 : index + 1]!.id
+ await user.click(screen.getAllByRole('button', { name: 'common.operation.delete' })[index]!)
+ expect(screen.getByDisplayValue(expected)).toHaveFocus()
+ },
+)
+
+it('returns focus to Add when the last action is removed', async () => {
+ const user = userEvent.setup()
+ render(<ActionPanel actions={[initialActions[0]!]} />)
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ expect(screen.getByRole('button', { name: 'common.operation.add' })).toHaveFocus()
+})
diff --git a/web/app/components/workflow/nodes/human-input/shared/default-utils.ts b/web/app/components/workflow/nodes/human-input/shared/default-utils.ts
index 70b175ebbd8..f76915efa89 100644
--- a/web/app/components/workflow/nodes/human-input/shared/default-utils.ts
+++ b/web/app/components/workflow/nodes/human-input/shared/default-utils.ts
@@ -24,14 +24,14 @@ export const getHumanInputSharedValidationError = (
return t(($) => $['nodes.humanInput.errorMsg.noUserActions'], { ns: 'workflow' })
if (new Set(payload.user_actions.map((action) => action.id)).size !== payload.user_actions.length)
return t(($) => $['nodes.humanInput.errorMsg.duplicateActionId'], { ns: 'workflow' })
- if (payload.user_actions.some((action) => !action.id.trim()))
+ if (payload.user_actions.some((action) => !action.id?.trim()))
return t(($) => $['nodes.humanInput.errorMsg.emptyActionId'], { ns: 'workflow' })
if (payload.user_actions.some((action) => action.id === HUMAN_INPUT_TIMEOUT_HANDLE))
return t(($) => $['nodes.humanInput.errorMsg.reservedActionId'], {
ns: 'workflow',
id: HUMAN_INPUT_TIMEOUT_HANDLE,
})
- if (payload.user_actions.some((action) => !action.title.trim()))
+ if (payload.user_actions.some((action) => !action.title?.trim()))
return t(($) => $['nodes.humanInput.errorMsg.emptyActionTitle'], { ns: 'workflow' })
return ''
}
diff --git a/web/app/components/workflow/nodes/human-input/shared/panel-sections.tsx b/web/app/components/workflow/nodes/human-input/shared/panel-sections.tsx
index 035a6df7b03..11465fee757 100644
--- a/web/app/components/workflow/nodes/human-input/shared/panel-sections.tsx
+++ b/web/app/components/workflow/nodes/human-input/shared/panel-sections.tsx
@@ -1,22 +1,19 @@
import type { FormInputItem, HumanInputSharedNodeType, UserAction } from './types'
-import type { Var } from '@/app/components/workflow/types'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
+import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { useBoolean } from 'ahooks'
import copy from 'copy-to-clipboard'
-import { useCallback, useId } from 'react'
+import { useId, useLayoutEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
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 { toast } from '@/app/notifications'
import { isHumanInputV2NodeData } from '../../human-input-v2/types'
import FormContent from '../components/form-content'
-import FormContentPreview from '../components/form-content-preview'
+import { FormContentPreviewTrigger } from '../components/form-content-preview'
import TimeoutInput from '../components/timeout'
import UserActionItem from '../components/user-action'
import { UserActionButtonType } from './types'
@@ -48,11 +45,15 @@ export type HumanInputSharedPanelConfig<T extends HumanInputSharedNodeType> = {
type HumanInputSharedPanelSectionsProps<T extends HumanInputSharedNodeType> = {
id: string
config: HumanInputSharedPanelConfig<T>
+ availableVars: NodeOutPutVar[]
+ availableNodes: Node[]
}
const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
id,
config,
+ availableVars,
+ availableNodes,
}: HumanInputSharedPanelSectionsProps<T>) => {
const { t } = useTranslation(['workflow', 'workflowHumanInput', 'common', 'share'])
const actionsLabelId = useId()
@@ -72,23 +73,21 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
structuredOutputCollapsed,
setStructuredOutputCollapsed,
} = config
- const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {
- onlyLeafNodeVar: false,
- filterVar: (varPayload: Var) => {
- const supportedVariableTypes: readonly VarType[] = [
- VarType.string,
- VarType.number,
- VarType.secret,
- VarType.arrayString,
- ]
- return supportedVariableTypes.includes(varPayload.type)
- },
- })
const [isExpandFormContent, { toggle: toggleExpandFormContent }] = useBoolean(false)
- const [isPreview, { toggle: togglePreview, setFalse: hidePreview }] = useBoolean(false)
const nodePanelWidth = useStore((state) => state.nodePanelWidth)
- const onAddUserAction = useCallback(() => {
+ const addActionRef = useRef<HTMLButtonElement>(null)
+ const actionsRef = useRef<HTMLDivElement>(null)
+ const actionFocusRef = useRef<number | undefined>(undefined)
+ useLayoutEffect(() => {
+ const index = actionFocusRef.current
+ if (index === undefined) return
+ actionFocusRef.current = undefined
+ const input = actionsRef.current?.children[index]?.querySelector<HTMLInputElement>('input')
+ if (input) input.focus()
+ else addActionRef.current?.focus()
+ }, [inputs.user_actions])
+ const onAddUserAction = () => {
const existingIds = new Set(inputs.user_actions.map((action) => action.id))
let index = inputs.user_actions.length + 1
while (existingIds.has(`action_${index}`)) index += 1
@@ -100,16 +99,13 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
}),
button_style: UserActionButtonType.Default,
})
- }, [handleUserActionAdd, inputs.user_actions, t])
+ }
return (
<>
<div
- className={cn(
- 'px-4 py-2',
- isExpandFormContent &&
- 'fixed inset-e-1 top-61 bottom-2 z-10 flex flex-col rounded-b-2xl bg-components-panel-bg',
- )}
+ data-expanded={isExpandFormContent || undefined}
+ className="px-4 py-2 data-expanded:fixed data-expanded:inset-e-1 data-expanded:top-61 data-expanded:bottom-2 data-expanded:z-10 data-expanded:flex data-expanded:flex-col data-expanded:rounded-b-2xl data-expanded:bg-components-panel-bg"
style={{ width: isExpandFormContent ? nodePanelWidth : '100%' }}
>
<div className="mb-1 flex shrink-0 items-center justify-between">
@@ -129,42 +125,31 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
</div>
{!readOnly && (
<div className="flex items-center">
- <Button
- variant="ghost"
- size="small"
- className={cn(
- 'flex items-center px-2',
- isPreview && 'bg-state-accent-active text-text-accent',
- )}
- onClick={togglePreview}
- >
- <span className="i-ri-eye-line size-3.5" aria-hidden />
- <span className="system-xs-medium">
- {t(($) => $[`${i18nPrefix}.formContent.preview`], { ns: 'workflowHumanInput' })}
- </span>
- </Button>
+ <FormContentPreviewTrigger
+ content={inputs.form_content}
+ formInputs={inputs.inputs}
+ userActions={inputs.user_actions}
+ nodeId={isHumanInputV2NodeData(inputs) ? id : undefined}
+ />
<div className="mx-2 h-3 w-px bg-divider-regular" />
<div className="flex items-center space-x-1">
- <button
+ <IconButton
type="button"
aria-label={t(($) => $['operation.copy'], { ns: 'common' })}
- className="flex size-6 cursor-pointer items-center justify-center rounded-md border-none bg-transparent p-0 hover:bg-components-button-ghost-bg-hover focus-visible:ring-1 focus-visible:ring-components-button-secondary-accent-border"
onClick={() => {
copy(inputs.form_content)
toast.success(t(($) => $['actionMsg.copySuccessfully'], { ns: 'common' }))
}}
>
<span className="i-ri-clipboard-line size-4 text-text-secondary" aria-hidden />
- </button>
- <button
+ </IconButton>
+ <IconButton
type="button"
aria-label={t(($) => $[isExpandFormContent ? 'chat.collapse' : 'chat.expand'], {
ns: 'share',
})}
- className={cn(
- 'flex size-6 cursor-pointer items-center justify-center rounded-md border-none bg-transparent p-0 text-text-secondary hover:bg-components-button-ghost-bg-hover focus-visible:ring-1 focus-visible:ring-components-button-secondary-accent-border',
- isExpandFormContent && 'bg-state-accent-active text-text-accent',
- )}
+ data-expanded={isExpandFormContent || undefined}
+ className="text-text-secondary data-expanded:bg-state-accent-active data-expanded:text-text-accent"
onClick={toggleExpandFormContent}
>
{isExpandFormContent ? (
@@ -172,7 +157,7 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
) : (
<span className="i-ri-expand-diagonal-line size-4" aria-hidden />
)}
- </button>
+ </IconButton>
</div>
</div>
)}
@@ -188,7 +173,7 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
onFormInputItemRemove={handleFormInputItemRemove}
isExpand={isExpandFormContent}
availableVars={availableVars}
- availableNodes={availableNodesWithParent}
+ availableNodes={availableNodes}
readonly={readOnly}
/>
</div>
@@ -209,6 +194,7 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
{!readOnly && (
<div className="flex items-center px-1">
<IconButton
+ ref={addActionRef}
aria-label={t(($) => $['operation.add'], { ns: 'common' })}
onClick={onAddUserAction}
>
@@ -223,15 +209,20 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
</div>
)}
{!!inputs.user_actions.length && (
- <div className="space-y-2">
+ <div ref={actionsRef} className="space-y-2">
{inputs.user_actions.map((action, index) => (
<UserActionItem
- // Action IDs are editable; keep each input mounted while its ID changes.
// oxlint-disable-next-line react/no-array-index-key -- Editable action IDs cannot provide stable keys while typing.
key={`${id}-${index}`}
data={action}
onChange={(data) => handleUserActionChange(index, data)}
- onDelete={handleUserActionDelete}
+ onDelete={(actionId) => {
+ actionFocusRef.current = Math.max(
+ 0,
+ Math.min(index, inputs.user_actions.length - 2),
+ )
+ handleUserActionDelete(actionId)
+ }}
readonly={readOnly}
/>
))}
@@ -277,17 +268,6 @@ const HumanInputSharedPanelSections = <T extends HumanInputSharedNodeType>({
description={t(($) => $[`${i18nPrefix}.output.renderedContent`], { ns: 'workflow' })}
/>
</OutputVars>
-
- {isPreview && (
- <FormContentPreview
- content={inputs.form_content}
- formInputs={inputs.inputs}
- userActions={inputs.user_actions}
- onClose={hidePreview}
- nodeId={isHumanInputV2NodeData(inputs) ? id : undefined}
- readOnly={readOnly}
- />
- )}
</>
)
}
diff --git a/web/app/components/workflow/nodes/human-input/shared/sync-draft.ts b/web/app/components/workflow/nodes/human-input/shared/sync-draft.ts
new file mode 100644
index 00000000000..1192afd0df5
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/shared/sync-draft.ts
@@ -0,0 +1,24 @@
+import type { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'
+
+export class HumanInputDraftSyncError extends Error {
+ constructor() {
+ super('Human Input draft could not be saved')
+ this.name = 'HumanInputDraftSyncError'
+ }
+}
+
+export const syncHumanInputDraft = async (
+ syncDraft: ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft'],
+): Promise<void> => {
+ let saved = false
+ let failed = false
+ const result = await syncDraft(true, {
+ onSuccess: () => {
+ saved = true
+ },
+ onError: () => {
+ failed = true
+ },
+ })
+ if (failed || (!saved && result == null)) throw new HumanInputDraftSyncError()
+}
diff --git a/web/app/components/workflow/nodes/human-input/shared/use-form-content.ts b/web/app/components/workflow/nodes/human-input/shared/use-form-content.ts
index afe080a3e99..1d956ce2b22 100644
--- a/web/app/components/workflow/nodes/human-input/shared/use-form-content.ts
+++ b/web/app/components/workflow/nodes/human-input/shared/use-form-content.ts
@@ -8,10 +8,8 @@ const useHumanInputFormContent = <T extends HumanInputSharedNodeType>(id: string
const [editorKey, setEditorKey] = useState(0)
const { inputs, setInputs } = useNodeCrud<T>(id, payload)
const { handleOutVarRenameChange } = useWorkflow()
- // Existing Lexical blocks retain callbacks, so edits must read the latest node data.
const inputsRef = useRef(inputs)
- // Refresh before FormContent's passive effect persists newly inserted fields.
useLayoutEffect(() => {
inputsRef.current = inputs
}, [inputs])
diff --git a/web/app/components/workflow/panel/__tests__/human-input-form-list.spec.tsx b/web/app/components/workflow/panel/__tests__/human-input-form-list.spec.tsx
index eaad61c9977..44f81dd958d 100644
--- a/web/app/components/workflow/panel/__tests__/human-input-form-list.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/human-input-form-list.spec.tsx
@@ -148,6 +148,7 @@ describe('HumanInputFormList', () => {
reason: 'updated reason',
},
action: 'approve',
+ form_version: undefined,
})
})
@@ -176,6 +177,7 @@ describe('HumanInputFormList', () => {
expect(onSubmit).toHaveBeenCalledWith('token-1', {
inputs: { reason: 'first decision' },
action: 'approve',
+ form_version: undefined,
})
rerender(
@@ -186,6 +188,7 @@ describe('HumanInputFormList', () => {
expect(onSubmit).toHaveBeenLastCalledWith('token-2', {
inputs: { reason: 'second decision' },
action: 'approve',
+ form_version: undefined,
})
})
@@ -238,6 +241,7 @@ describe('HumanInputFormList', () => {
expect(onSubmit).toHaveBeenCalledExactlyOnceWith('token-1', {
inputs: { reason: 'prefill' },
action: 'approve',
+ form_version: '1',
})
})
})
diff --git a/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx b/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx
index 5fdde67cdca..b452aa27c97 100644
--- a/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/workflow-preview.hitl-v2.spec.tsx
@@ -104,8 +104,8 @@ describe('WorkflowPreview HITL submission versions', () => {
},
})
- await user.type(screen.getByRole('textbox', { name: 'name' }), 'Ada')
- await user.type(screen.getByRole('textbox', { name: 'reason' }), 'Ready to ship')
+ await user.type(screen.getByRole('textbox', { name: 'Name' }), 'Ada')
+ await user.type(screen.getByRole('textbox', { name: 'Reason' }), 'Ready to ship')
await user.click(screen.getByRole('button', { name: 'Approve' }))
await waitFor(() =>
@@ -114,8 +114,10 @@ describe('WorkflowPreview HITL submission versions', () => {
{
inputs: { name: 'Ada', reason: 'Ready to ship' },
action: 'approve',
+ form_version: version,
},
version,
+ { silent: true },
),
)
},
diff --git a/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx b/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
index 22b63f38a63..1f795f583c0 100644
--- a/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
@@ -206,7 +206,7 @@ it('opens pending human input on pause and submits the token with the entered re
})
expect(screen.getByText('Need Approval')).toBeInTheDocument()
expect(await screen.findByText('Already approved', {}, { timeout: 5000 })).toBeInTheDocument()
- await user.type(screen.getByRole('textbox', { name: 'reason' }), 'Looks good')
+ await user.type(screen.getByRole('textbox', { name: 'Before' }), 'Looks good')
await user.click(screen.getByRole('button', { name: 'Approve' }))
await waitFor(() =>
expect(mockSubmitHumanInputForm).toHaveBeenCalledWith(
@@ -214,8 +214,10 @@ it('opens pending human input on pause and submits the token with the entered re
{
inputs: { reason: 'Looks good' },
action: 'approve',
+ form_version: undefined,
},
undefined,
+ { silent: true },
),
)
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
index e0eca04a07f..a103ca2dc5c 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
@@ -258,12 +258,13 @@ describe('useChat – handleSubmitHumanInputForm', () => {
await result.current.handleSubmitHumanInputForm('nested-token', {
action: 'approve',
inputs: {},
+ form_version: version,
})
})
expect(mockSubmitHumanInputForm).toHaveBeenCalledWith(
'nested-token',
- { action: 'approve', inputs: {} },
+ { action: 'approve', inputs: {}, form_version: version },
version,
)
},
diff --git a/web/app/components/workflow/panel/workflow-preview.tsx b/web/app/components/workflow/panel/workflow-preview.tsx
index b18295c070b..1cefd9abaca 100644
--- a/web/app/components/workflow/panel/workflow-preview.tsx
+++ b/web/app/components/workflow/panel/workflow-preview.tsx
@@ -10,6 +10,7 @@ import ReasoningPanel from '@/app/components/base/chat/chat/answer/reasoning-pan
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import ResizeHandle from '@/app/components/base/resize-handle'
import { toast } from '@/app/notifications'
+import { ENABLE_HITL_IM } from '@/config'
import { submitHumanInputForm } from '@/service/workflow'
import { editorAppIdAtom } from '../editor-resource/state'
import { useWorkflowInteractions } from '../hooks/use-workflow-panel-interactions'
@@ -102,7 +103,12 @@ const WorkflowPreview = () => {
const handleSubmitHumanInputForm = useCallback(
async (formToken: string, formData: HumanInputFormSubmitData) => {
const form = humanInputFormDataList?.find((item) => item.form_token === formToken)
- await submitHumanInputForm(formToken, formData, form?.form_version)
+ await submitHumanInputForm(
+ formToken,
+ formData,
+ form?.form_version,
+ ENABLE_HITL_IM ? { silent: true } : undefined,
+ )
},
[humanInputFormDataList],
)
diff --git a/web/app/components/workflow/utils/elk-layout.ts b/web/app/components/workflow/utils/elk-layout.ts
index e52b596ce81..ec6ed9c1223 100644
--- a/web/app/components/workflow/utils/elk-layout.ts
+++ b/web/app/components/workflow/utils/elk-layout.ts
@@ -10,6 +10,7 @@ import {
NODE_LAYOUT_VERTICAL_PADDING,
} from '@/app/components/workflow/constants'
import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'
+import { HUMAN_INPUT_TIMEOUT_HANDLE } from '@/app/components/workflow/nodes/human-input/shared/constants'
import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'
import { BlockEnum } from '@/app/components/workflow/types'
@@ -317,8 +318,8 @@ const sortHumanInputOutEdges = (humanInputNode: Node, outEdges: Edge[]): Edge[]
if (handleA && handleB) {
const userActions = (humanInputNode.data as HumanInputSharedNodeType).user_actions || []
- if (handleA === '__timeout') return 1
- if (handleB === '__timeout') return -1
+ if (handleA === HUMAN_INPUT_TIMEOUT_HANDLE) return 1
+ if (handleB === HUMAN_INPUT_TIMEOUT_HANDLE) return -1
const indexA = userActions.findIndex((action) => action.id === handleA)
const indexB = userActions.findIndex((action) => action.id === handleB)
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
index 5078248b712..25bf7141687 100644
--- a/web/app/layout.tsx
+++ b/web/app/layout.tsx
@@ -74,9 +74,9 @@ export default async function RootLayout({ children }: { children: React.ReactNo
const dehydratedState = errorDocument ? undefined : dehydrateSystemFeatures()
return (
- <html lang={locale} dir={dir(locale)} suppressHydrationWarning>
+ <html lang={locale} dir={dir(locale)} {...datasetMap} suppressHydrationWarning>
<head>{!errorDocument && <ReactScanLoader />}</head>
- <body className="bg-background-body" {...datasetMap}>
+ <body className="bg-background-body">
{!errorDocument && <CloudAnalytics />}
<div className="isolate">
<JotaiProvider>
diff --git a/web/env.ts b/web/env.ts
index fff13955e5c..d65438099fe 100644
--- a/web/env.ts
+++ b/web/env.ts
@@ -212,155 +212,152 @@ export const env = createEnv({
experimental__runtimeEnv: {
NEXT_PUBLIC_ALLOW_EMBED: isServer
? process.env.NEXT_PUBLIC_ALLOW_EMBED
- : getRuntimeEnvFromBody('allowEmbed'),
+ : getRuntimeEnv('allowEmbed'),
NEXT_PUBLIC_ALLOW_INLINE_STYLES: isServer
? process.env.NEXT_PUBLIC_ALLOW_INLINE_STYLES
- : getRuntimeEnvFromBody('allowInlineStyles'),
+ : getRuntimeEnv('allowInlineStyles'),
NEXT_PUBLIC_ALLOW_UNSAFE_DATA_SCHEME: isServer
? process.env.NEXT_PUBLIC_ALLOW_UNSAFE_DATA_SCHEME
- : getRuntimeEnvFromBody('allowUnsafeDataScheme'),
+ : getRuntimeEnv('allowUnsafeDataScheme'),
NEXT_PUBLIC_AMPLITUDE_API_KEY: isServer
? process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY
- : getRuntimeEnvFromBody('amplitudeApiKey'),
+ : getRuntimeEnv('amplitudeApiKey'),
NEXT_PUBLIC_API_PREFIX: isServer
? process.env.NEXT_PUBLIC_API_PREFIX
- : getRuntimeEnvFromBody('apiPrefix'),
- NEXT_PUBLIC_BASE_PATH: isServer
- ? process.env.NEXT_PUBLIC_BASE_PATH
- : getRuntimeEnvFromBody('basePath'),
+ : getRuntimeEnv('apiPrefix'),
+ NEXT_PUBLIC_BASE_PATH: isServer ? process.env.NEXT_PUBLIC_BASE_PATH : getRuntimeEnv('basePath'),
NEXT_PUBLIC_BATCH_CONCURRENCY: isServer
? process.env.NEXT_PUBLIC_BATCH_CONCURRENCY
- : getRuntimeEnvFromBody('batchConcurrency'),
+ : getRuntimeEnv('batchConcurrency'),
NEXT_PUBLIC_COOKIE_DOMAIN: isServer
? process.env.NEXT_PUBLIC_COOKIE_DOMAIN
- : getRuntimeEnvFromBody('cookieDomain'),
+ : getRuntimeEnv('cookieDomain'),
NEXT_PUBLIC_COOKIEYES_SITE_KEY: isServer
? process.env.NEXT_PUBLIC_COOKIEYES_SITE_KEY
- : getRuntimeEnvFromBody('cookieyesSiteKey'),
+ : getRuntimeEnv('cookieyesSiteKey'),
NEXT_PUBLIC_CSP_WHITELIST: isServer
? process.env.NEXT_PUBLIC_CSP_WHITELIST
- : getRuntimeEnvFromBody('cspWhitelist'),
+ : getRuntimeEnv('cspWhitelist'),
NEXT_PUBLIC_DEPLOY_ENV: isServer
? process.env.NEXT_PUBLIC_DEPLOY_ENV
- : getRuntimeEnvFromBody('deployEnv'),
+ : getRuntimeEnv('deployEnv'),
NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON: isServer
? process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON
- : getRuntimeEnvFromBody('disableUploadImageAsIcon'),
+ : getRuntimeEnv('disableUploadImageAsIcon'),
NEXT_PUBLIC_ENABLE_ACCESS_TOKEN: isServer
? process.env.NEXT_PUBLIC_ENABLE_ACCESS_TOKEN
- : getRuntimeEnvFromBody('enableAccessToken'),
+ : getRuntimeEnv('enableAccessToken'),
NEXT_PUBLIC_ENABLE_AGENT_V2: isServer
? process.env.NEXT_PUBLIC_ENABLE_AGENT_V2
- : getRuntimeEnvFromBody('enableAgentV2'),
+ : getRuntimeEnv('enableAgentV2'),
NEXT_PUBLIC_ENABLE_AGENT_V2_IN_CHATFLOW: isServer
? process.env.NEXT_PUBLIC_ENABLE_AGENT_V2_IN_CHATFLOW
- : getRuntimeEnvFromBody('enableAgentV2InChatflow'),
+ : getRuntimeEnv('enableAgentV2InChatflow'),
NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW: isServer
? process.env.NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW
- : getRuntimeEnvFromBody('enableFeaturePreview'),
+ : getRuntimeEnv('enableFeaturePreview'),
NEXT_PUBLIC_ENABLE_HITL_IM: isServer
- ? // Read at server startup rather than inlining a public env value at build time.
- Reflect.get(process.env, 'NEXT_PUBLIC_ENABLE_HITL_IM')
- : getRuntimeEnvFromBody('enableHitlIm'),
+ ? process.env.NEXT_PUBLIC_ENABLE_HITL_IM
+ : getRuntimeEnv('enableHitlIm'),
NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX: isServer
? process.env.NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX
- : getRuntimeEnvFromBody('enableSingleDollarLatex'),
+ : getRuntimeEnv('enableSingleDollarLatex'),
NEXT_PUBLIC_ENABLE_WEBSITE_FIRECRAWL: isServer
? process.env.NEXT_PUBLIC_ENABLE_WEBSITE_FIRECRAWL
- : getRuntimeEnvFromBody('enableWebsiteFirecrawl'),
+ : getRuntimeEnv('enableWebsiteFirecrawl'),
NEXT_PUBLIC_ENABLE_WEBSITE_JINAREADER: isServer
? process.env.NEXT_PUBLIC_ENABLE_WEBSITE_JINAREADER
- : getRuntimeEnvFromBody('enableWebsiteJinareader'),
+ : getRuntimeEnv('enableWebsiteJinareader'),
NEXT_PUBLIC_ENABLE_WEBSITE_WATERCRAWL: isServer
? process.env.NEXT_PUBLIC_ENABLE_WEBSITE_WATERCRAWL
- : getRuntimeEnvFromBody('enableWebsiteWatercrawl'),
+ : getRuntimeEnv('enableWebsiteWatercrawl'),
NEXT_PUBLIC_INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH: isServer
? process.env.NEXT_PUBLIC_INDEXING_MAX_SEGMENTATION_TOKENS_LENGTH
- : getRuntimeEnvFromBody('indexingMaxSegmentationTokensLength'),
+ : getRuntimeEnv('indexingMaxSegmentationTokensLength'),
NEXT_PUBLIC_IS_MARKETPLACE: isServer
? process.env.NEXT_PUBLIC_IS_MARKETPLACE
- : getRuntimeEnvFromBody('isMarketplace'),
+ : getRuntimeEnv('isMarketplace'),
NEXT_PUBLIC_LOOP_NODE_MAX_COUNT: isServer
? process.env.NEXT_PUBLIC_LOOP_NODE_MAX_COUNT
- : getRuntimeEnvFromBody('loopNodeMaxCount'),
+ : getRuntimeEnv('loopNodeMaxCount'),
NEXT_PUBLIC_MARKDOWN_FORM_FIELD_NAME_EXTRA_CHARS: isServer
? process.env.NEXT_PUBLIC_MARKDOWN_FORM_FIELD_NAME_EXTRA_CHARS
- : getRuntimeEnvFromBody('markdownFormFieldNameExtraChars'),
+ : getRuntimeEnv('markdownFormFieldNameExtraChars'),
NEXT_PUBLIC_MARKDOWN_FORM_FIELD_NAME_MAX_LENGTH: isServer
? process.env.NEXT_PUBLIC_MARKDOWN_FORM_FIELD_NAME_MAX_LENGTH
- : getRuntimeEnvFromBody('markdownFormFieldNameMaxLength'),
+ : getRuntimeEnv('markdownFormFieldNameMaxLength'),
NEXT_PUBLIC_MARKETPLACE_API_PREFIX: isServer
? process.env.NEXT_PUBLIC_MARKETPLACE_API_PREFIX
- : getRuntimeEnvFromBody('marketplaceApiPrefix'),
+ : getRuntimeEnv('marketplaceApiPrefix'),
NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: isServer
? process.env.NEXT_PUBLIC_MARKETPLACE_URL_PREFIX
- : getRuntimeEnvFromBody('marketplaceUrlPrefix'),
+ : getRuntimeEnv('marketplaceUrlPrefix'),
NEXT_PUBLIC_MAX_ITERATIONS_NUM: isServer
? process.env.NEXT_PUBLIC_MAX_ITERATIONS_NUM
- : getRuntimeEnvFromBody('maxIterationsNum'),
+ : getRuntimeEnv('maxIterationsNum'),
NEXT_PUBLIC_MAX_PARALLEL_LIMIT: isServer
? process.env.NEXT_PUBLIC_MAX_PARALLEL_LIMIT
- : getRuntimeEnvFromBody('maxParallelLimit'),
+ : getRuntimeEnv('maxParallelLimit'),
NEXT_PUBLIC_MAX_TOOLS_NUM: isServer
? process.env.NEXT_PUBLIC_MAX_TOOLS_NUM
- : getRuntimeEnvFromBody('maxToolsNum'),
+ : getRuntimeEnv('maxToolsNum'),
NEXT_PUBLIC_MAX_TREE_DEPTH: isServer
? process.env.NEXT_PUBLIC_MAX_TREE_DEPTH
- : getRuntimeEnvFromBody('maxTreeDepth'),
+ : getRuntimeEnv('maxTreeDepth'),
NEXT_PUBLIC_PUBLIC_API_PREFIX: isServer
? process.env.NEXT_PUBLIC_PUBLIC_API_PREFIX
- : getRuntimeEnvFromBody('publicApiPrefix'),
+ : getRuntimeEnv('publicApiPrefix'),
NEXT_PUBLIC_SENTRY_DSN: isServer
? process.env.NEXT_PUBLIC_SENTRY_DSN
- : getRuntimeEnvFromBody('sentryDsn'),
+ : getRuntimeEnv('sentryDsn'),
NEXT_PUBLIC_SITE_ABOUT: isServer
? process.env.NEXT_PUBLIC_SITE_ABOUT
- : getRuntimeEnvFromBody('siteAbout'),
+ : getRuntimeEnv('siteAbout'),
NEXT_PUBLIC_SOCKET_URL: isServer
? process.env.NEXT_PUBLIC_SOCKET_URL
- : getRuntimeEnvFromBody('socketUrl'),
+ : getRuntimeEnv('socketUrl'),
NEXT_PUBLIC_SUPPORT_EMAIL_ADDRESS: isServer
? process.env.NEXT_PUBLIC_SUPPORT_EMAIL_ADDRESS
- : getRuntimeEnvFromBody('supportEmailAddress'),
+ : getRuntimeEnv('supportEmailAddress'),
NEXT_PUBLIC_SUPPORT_MAIL_LOGIN: isServer
? process.env.NEXT_PUBLIC_SUPPORT_MAIL_LOGIN
- : getRuntimeEnvFromBody('supportMailLogin'),
+ : getRuntimeEnv('supportMailLogin'),
NEXT_PUBLIC_TEXT_GENERATION_TIMEOUT_MS: isServer
? process.env.NEXT_PUBLIC_TEXT_GENERATION_TIMEOUT_MS
- : getRuntimeEnvFromBody('textGenerationTimeoutMs'),
+ : getRuntimeEnv('textGenerationTimeoutMs'),
NEXT_PUBLIC_TOP_K_MAX_VALUE: isServer
? process.env.NEXT_PUBLIC_TOP_K_MAX_VALUE
- : getRuntimeEnvFromBody('topKMaxValue'),
+ : getRuntimeEnv('topKMaxValue'),
NEXT_PUBLIC_TURNSTILE_SITE_KEY: isServer
? process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY
- : getRuntimeEnvFromBody('turnstileSiteKey'),
+ : getRuntimeEnv('turnstileSiteKey'),
NEXT_PUBLIC_UPLOAD_IMAGE_AS_ICON: isServer
? process.env.NEXT_PUBLIC_UPLOAD_IMAGE_AS_ICON
- : getRuntimeEnvFromBody('uploadImageAsIcon'),
+ : getRuntimeEnv('uploadImageAsIcon'),
NEXT_PUBLIC_WEB_PREFIX: isServer
? process.env.NEXT_PUBLIC_WEB_PREFIX
- : getRuntimeEnvFromBody('webPrefix'),
+ : getRuntimeEnv('webPrefix'),
NEXT_PUBLIC_WORKFLOW_GENERATION_TIMEOUT_MS: isServer
? process.env.NEXT_PUBLIC_WORKFLOW_GENERATION_TIMEOUT_MS
- : getRuntimeEnvFromBody('workflowGenerationTimeoutMs'),
+ : getRuntimeEnv('workflowGenerationTimeoutMs'),
NEXT_PUBLIC_ZENDESK_FIELD_ID_EMAIL: isServer
? process.env.NEXT_PUBLIC_ZENDESK_FIELD_ID_EMAIL
- : getRuntimeEnvFromBody('zendeskFieldIdEmail'),
+ : getRuntimeEnv('zendeskFieldIdEmail'),
NEXT_PUBLIC_ZENDESK_FIELD_ID_ENVIRONMENT: isServer
? process.env.NEXT_PUBLIC_ZENDESK_FIELD_ID_ENVIRONMENT
- : getRuntimeEnvFromBody('zendeskFieldIdEnvironment'),
+ : getRuntimeEnv('zendeskFieldIdEnvironment'),
NEXT_PUBLIC_ZENDESK_FIELD_ID_PLAN: isServer
? process.env.NEXT_PUBLIC_ZENDESK_FIELD_ID_PLAN
- : getRuntimeEnvFromBody('zendeskFieldIdPlan'),
+ : getRuntimeEnv('zendeskFieldIdPlan'),
NEXT_PUBLIC_ZENDESK_FIELD_ID_VERSION: isServer
? process.env.NEXT_PUBLIC_ZENDESK_FIELD_ID_VERSION
- : getRuntimeEnvFromBody('zendeskFieldIdVersion'),
+ : getRuntimeEnv('zendeskFieldIdVersion'),
NEXT_PUBLIC_ZENDESK_FIELD_ID_WORKSPACE_ID: isServer
? process.env.NEXT_PUBLIC_ZENDESK_FIELD_ID_WORKSPACE_ID
- : getRuntimeEnvFromBody('zendeskFieldIdWorkspaceId'),
+ : getRuntimeEnv('zendeskFieldIdWorkspaceId'),
NEXT_PUBLIC_ZENDESK_WIDGET_KEY: isServer
? process.env.NEXT_PUBLIC_ZENDESK_WIDGET_KEY
- : getRuntimeEnvFromBody('zendeskWidgetKey'),
+ : getRuntimeEnv('zendeskWidgetKey'),
},
emptyStringAsUndefined: true,
})
@@ -374,19 +371,20 @@ function getDatasetAttributeName(envKey: ClientEnvKey) {
}
/**
- * Browser-only function to get runtime env value from HTML body dataset.
+ * Browser-only function to get runtime env value from the root element dataset.
+ * The root element exists before streamed body content, so module-level reads are safe.
*/
-function getRuntimeEnvFromBody(key: DatasetKey) {
+function getRuntimeEnv(key: DatasetKey) {
if (typeof window === 'undefined') {
- throw new TypeError('getRuntimeEnvFromBody can only be called in the browser')
+ throw new TypeError('getRuntimeEnv can only be called in the browser')
}
- const value = document.body.dataset[key]
+ const value = document.documentElement.dataset[key]
return value || undefined
}
/**
- * Server-only function to get dataset map for embedding into the HTML body.
+ * Server-only function to get dataset map for embedding into the root HTML element.
*/
export function getDatasetMap() {
if (isClient) {
diff --git a/web/features/contacts/im-capability.ts b/web/features/contacts/im-capability.ts
index fe0cfb537d9..2e0e2d3fc0e 100644
--- a/web/features/contacts/im-capability.ts
+++ b/web/features/contacts/im-capability.ts
@@ -1,5 +1,4 @@
import type { GetFeaturesResponse } from '@dify/contracts/api/console/features/types.gen'
export const selectIMCentrallyManaged = (features: GetFeaturesResponse) =>
- // Older feature contracts omit this capability; only an explicit backend true enables it.
- 'im_centrally_managed' in features && features.im_centrally_managed === true
+ features.im_centrally_managed
diff --git a/web/features/contacts/im-platform/README.md b/web/features/contacts/im-platform/README.md
index 59166ade7c5..f851a7c9373 100644
--- a/web/features/contacts/im-platform/README.md
+++ b/web/features/contacts/im-platform/README.md
@@ -1,39 +1,21 @@
-# Contacts IM Platform
-
-Organization-scoped IM platform binding and directory-sync UI for the Contacts domain.
-
-## Mount Points
-
-- CE / SaaS workspace management mounts this feature from `app/components/header/account-setting`.
-- Centrally managed deployments do not expose this workspace binding entry. The Account Settings shell checks `im_centrally_managed` from `/features` before mounting the feature.
-- `features/agent-v2/roster` is intentionally outside this feature boundary and must not import or mount Contacts IM platform UI.
-
-The entry requires the dedicated `NEXT_PUBLIC_ENABLE_HITL_IM` release gate to be
-`true` and `im_centrally_managed` to be `false`. The release gate defaults to
-`false`, independently of `NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW`. Disabled or
-unavailable entries also reject the IM platform settings deep link. Changing the
-release gate requires restarting Web and reloading the page. Turning it off also
-restores legacy V1 editing/form entry points and disables V2 editors, migration,
-and approval entry points. Saved V2 data and channel credentials are preserved;
-V2 tokens are never sent through legacy V1 transports.
-
-## Internal Modules
-
-- `types.ts` defines provider, connection, sync, command, pagination, and safe-error contracts.
-- `repository.ts` defines the replaceable frontend data boundary.
-- `__tests__/fixtures/scenarios.ts` owns named deterministic fixtures and consistency validation.
-- `__tests__/fixtures/repository.ts` owns in-memory mutations and explicitly controlled sync transitions.
-- `composition.tsx` injects Organization context and the runtime API repository adapter.
-- `hooks.ts` is the only React Query access layer used by feature components.
-- `management-surface.tsx` owns binding status, provider selection, diagnostics, and confirmations.
-- `binding-dialog.tsx` and `provider-form-adapters.ts` own credential and mock OAuth flows.
-- `sync-section.tsx` owns manual-trigger eligibility, active-run recovery, and summary presentation.
-- `sync-details-dialog.tsx` owns the URL-addressable, filtered, paginated, read-only result view.
-- `sync-run-url-state.ts` keeps the selected run in the `sync_run_id` query parameter.
-- `account-setting-page.tsx` is the workspace-managed settings composition root.
-
-## External Modules
-
-- `app/components/header/account-setting`
-- `config`
-- `@tanstack/react-query`
+# Workspace channels
+
+The Account Settings Channels tab configures Email and IM delivery and inspects directory synchronization. It is available only to workspace managers when `NEXT_PUBLIC_ENABLE_HITL_IM` is true and `/features.im_centrally_managed` is false. The release flag defaults to false; disabling it preserves saved channels and credentials and restores the existing V1 entry points.
+
+## Data ownership
+
+The surface uses generated `consoleQuery.workspaces.current.humanInput.v2` options. Channel lists and provider definitions are loaded at the page owner. Redacted channel details are requested when a configuration session opens. Shared mutation defaults own generated-key invalidation; the feature has no repository, DTO status mirror, or private cache namespace.
+
+`credentials.ts` owns credential draft payload shaping and saved redaction metadata. Optional credentials can be retained, replaced, or explicitly cleared. Successful saves and closing clear typed secrets; rejected writes keep the draft available for correction. Credential mutations have zero cache retention and reset after completion. Generated mutations receive typed payloads while pending; the outer orchestration mutation receives credentials through a ref rather than mutation variables.
+
+The configuration and sync-detail sessions mount inside `DialogContent`. Their roots remain mounted while closing, and the subject survives until the closing lifecycle completes. `callback-setup.tsx` displays each provider's actual webhook URL and provider-specific setup destination.
+
+## Directory synchronization
+
+The server exposes the latest run only. The selected run ID and result filter are stored with nuqs in `sync_run_id` and `sync_result`. A different latest ID is reported as changed rather than displayed under the requested identity. The summary polls only queued/running runs and refreshes related generated caches on an observed active-to-terminal transition.
+
+The result view consumes generated run/result types directly. CSV export requests up to 100 rows per page and verifies the latest run before and after the complete export. It never invents contact email, actor, partial-success, or OAuth fields absent from the contract.
+
+## Verification
+
+Feature tests exercise real generated clients and query policies with mocked HTTP responses, retaining the actual dialogs, forms, and URL-state owner. The API's generated types determine valid scenarios. No production mock repository or mock-only status is shipped.
diff --git a/web/features/contacts/im-platform/__tests__/credential-session.spec.tsx b/web/features/contacts/im-platform/__tests__/credential-session.spec.tsx
new file mode 100644
index 00000000000..f04db1aa53e
--- /dev/null
+++ b/web/features/contacts/im-platform/__tests__/credential-session.spec.tsx
@@ -0,0 +1,64 @@
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { ContactImBindingContent } from '../binding-dialog'
+import { providerMetadata } from '../credentials'
+import { ContactEmailConfigContent } from '../email-config-dialog'
+
+vi.mock('@/context/i18n', async (original) => ({
+ ...(await original<typeof import('@/context/i18n')>()),
+ useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,
+}))
+
+it.each(['feishu', 'resend'] as const)(
+ 'keeps the %s credential draft until the closing content session unmounts',
+ async (provider) => {
+ const user = userEvent.setup()
+ const client = new QueryClient()
+ const close = vi.fn()
+ const metadata = providerMetadata[provider]
+ const definition = {
+ provider,
+ displayName: metadata.name,
+ requiredFields: metadata.fields,
+ }
+ const content = (open: boolean) => (
+ <QueryClientProvider client={client}>
+ <Dialog open={open}>
+ <DialogContent>
+ {provider === 'feishu' ? (
+ <ContactImBindingContent
+ integration={null}
+ provider={definition}
+ replaceActiveProvider={false}
+ onOpenChange={close}
+ />
+ ) : (
+ <ContactEmailConfigContent
+ integration={null}
+ provider={definition}
+ onOpenChange={close}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
+ </QueryClientProvider>
+ )
+ const view = render(content(true))
+ const label =
+ provider === 'feishu'
+ ? 'contacts.imPlatform.bindingDialog.field.secret'
+ : 'contacts.imPlatform.email.apiKey'
+ const input = await screen.findByLabelText(label)
+ await user.type(input, 'unsaved-secret')
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ expect(close).toHaveBeenCalledWith(false)
+ expect(input).toHaveValue('unsaved-secret')
+ view.rerender(content(false))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ view.rerender(content(true))
+ expect(await screen.findByLabelText(label)).toHaveValue('')
+ client.clear()
+ },
+)
diff --git a/web/features/contacts/im-platform/__tests__/credentials.spec.ts b/web/features/contacts/im-platform/__tests__/credentials.spec.ts
new file mode 100644
index 00000000000..88a196fd927
--- /dev/null
+++ b/web/features/contacts/im-platform/__tests__/credentials.spec.ts
@@ -0,0 +1,113 @@
+import type { ContactImProvider } from '../types'
+import {
+ createCredentialsFor,
+ emailSettingsFor,
+ toDetailView,
+ updateCredentialsFor,
+ updateEmailSettingsFor,
+} from '../credentials'
+import { ContactImRepositoryErrorCode } from '../types'
+import { channelSummary, emailDetail, imDetail } from './fixtures/channel-client'
+
+const values = {
+ appId: ' app-id ',
+ clientId: ' client-id ',
+ corpId: ' corp-id ',
+ agentId: ' agent-id ',
+ tenantId: ' tenant-id ',
+ signingSecret: ' signing-secret ',
+ botToken: ' bot-token ',
+ appToken: ' app-token ',
+ verificationToken: ' token ',
+ encryptKey: ' encryption ',
+ senderEmail: ' [email protected] ',
+ senderName: ' Approvals ',
+}
+
+it.each<ContactImProvider>([
+ 'resend',
+ 'feishu',
+ 'lark',
+ 'slack',
+ 'ding_talk',
+ 'ms_teams',
+ 'we_com',
+])('builds the generated %s credential shape and trims user input', (provider) => {
+ const result = createCredentialsFor({ provider, secret: ' new-secret ', values })
+ expect(result.provider).toBe(provider)
+ const strings = Object.values(result).filter((value) => typeof value === 'string')
+ strings.forEach((value) => expect(value).toBe(value.trim()))
+ expect(result).toEqual(
+ expect.objectContaining(
+ provider === 'resend'
+ ? { api_key: 'new-secret' }
+ : provider === 'we_com'
+ ? { secret: 'new-secret' }
+ : provider === 'feishu' || provider === 'lark'
+ ? { app_id: 'app-id', app_secret: 'new-secret' }
+ : { client_secret: 'new-secret' },
+ ),
+ )
+})
+
+it.each<ContactImProvider>([
+ 'resend',
+ 'feishu',
+ 'lark',
+ 'slack',
+ 'ding_talk',
+ 'ms_teams',
+ 'we_com',
+])('retains redacted %s credentials with the generated unchanged sentinel', (provider) => {
+ const result = updateCredentialsFor({ provider, values: {} })
+ for (const [key, value] of Object.entries(result))
+ if (key !== 'provider') expect(value).toEqual({ type: 'unchanged' })
+})
+
+it('clears only explicitly selected optional credentials', () => {
+ expect(
+ updateCredentialsFor({ provider: 'feishu', values: {}, clearedFields: ['encryptKey'] }),
+ ).toMatchObject({ encrypt_key: null, verification_token: { type: 'unchanged' } })
+ expect(() =>
+ updateCredentialsFor({ provider: 'feishu', values: {}, clearedFields: ['secret'] }),
+ ).toThrow(ContactImRepositoryErrorCode.InvalidCommand)
+})
+
+it('requires fresh credentials on initial connection', () => {
+ expect(() => createCredentialsFor({ provider: 'feishu', values: { appId: 'app-1' } })).toThrow(
+ ContactImRepositoryErrorCode.RequiredFieldsMissing,
+ )
+})
+
+it('preserves email settings independently from its saved secret', () => {
+ expect(emailSettingsFor({ provider: 'resend', values })).toEqual({
+ sender_email: '[email protected]',
+ sender_name: 'Approvals',
+ })
+ expect(updateEmailSettingsFor({ provider: 'resend', values: {} })).toEqual({
+ sender_email: { type: 'unchanged' },
+ sender_name: { type: 'unchanged' },
+ })
+})
+
+it.each<ContactImProvider>(['feishu', 'lark', 'slack', 'ding_talk', 'ms_teams', 'we_com'])(
+ 'projects %s redaction metadata without ever putting saved secrets into form values',
+ (provider) => {
+ const summary = channelSummary({ provider })
+ const result = toDetailView(imDetail(summary))
+ expect(result.id).toBe(summary.id)
+ expect(result.status).toBe(summary.status)
+ expect(result.configuredFields).toContain('secret')
+ expect(result.configuredValues).not.toHaveProperty('secret')
+ expect(result.configuredValues).not.toHaveProperty('signingSecret')
+ },
+)
+
+it('projects the actual email sender identity', () => {
+ const result = toDetailView(emailDetail(channelSummary({ provider: 'resend', kind: 'email' })))
+ expect(result.configuredValues).toEqual({
+ senderEmail: '[email protected]',
+ senderName: 'Approvals',
+ })
+ expect(result.secretConfigured).toBe(true)
+})
diff --git a/web/features/contacts/im-platform/__tests__/email-config-dialog.spec.tsx b/web/features/contacts/im-platform/__tests__/email-config-dialog.spec.tsx
new file mode 100644
index 00000000000..76c27548287
--- /dev/null
+++ b/web/features/contacts/im-platform/__tests__/email-config-dialog.spec.tsx
@@ -0,0 +1,237 @@
+import type { ContactImIntegrationView } from '../types'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { providerMetadata, toDetailView } from '../credentials'
+import { ContactEmailConfigContent } from '../email-config-dialog'
+import { channelSummary, emailDetail } from './fixtures/channel-client'
+import { json } from './fixtures/http'
+
+const network = vi.hoisted(() => ({
+ handle: vi.fn<(request: Request) => Promise<Response> | Response>(),
+}))
+vi.mock('@/service/base', async () => {
+ const { httpErrorFromResponse } = await import('@/service/http-error')
+ return {
+ request: async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const response = await network.handle(options.request)
+ if (!response.ok) throw await httpErrorFromResponse(response)
+ return response
+ },
+ }
+})
+vi.mock('@/utils/client', () => ({ isClient: true, isServer: false }))
+vi.mock('@/context/i18n', async (original) => ({
+ ...(await original<typeof import('@/context/i18n')>()),
+ useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,
+}))
+
+const email = channelSummary({ id: 'channel-email', kind: 'email', provider: 'resend' })
+const clients: QueryClient[] = []
+const apiPath = '/workspaces/current/human-input/v2/channels/email'
+const saveLabel = 'contacts.imPlatform.action.save'
+const testLabel = 'contacts.imPlatform.action.testConnection'
+const secretLabel = 'contacts.imPlatform.email.apiKey'
+
+function EmailSession({ integration }: { integration: ContactImIntegrationView | null }) {
+ const [open, setOpen] = useState(true)
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent>
+ <ContactEmailConfigContent
+ integration={integration}
+ provider={{
+ provider: 'resend',
+ displayName: 'Email',
+ requiredFields: providerMetadata.resend.fields,
+ }}
+ onOpenChange={setOpen}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function renderEmail(
+ integration: ContactImIntegrationView | null = toDetailView(emailDetail(email)),
+) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ })
+ clients.push(client)
+ render(
+ <QueryClientProvider client={client}>
+ <EmailSession integration={integration} />
+ </QueryClientProvider>,
+ )
+}
+
+function requests(method: string, ending: string) {
+ return network.handle.mock.calls
+ .map(([request]) => request)
+ .filter(
+ (request) => request.method === method && new URL(request.url).pathname.endsWith(ending),
+ )
+}
+
+beforeEach(() => {
+ network.handle.mockImplementation((request) => {
+ const path = new URL(request.url).pathname
+ if (path.endsWith('/test'))
+ return json({ status: 'connected', status_description: 'Connected' })
+ if (request.method === 'GET') return json(emailDetail(email))
+ return json({ summary: email })
+ })
+})
+afterEach(() => clients.splice(0).forEach((client) => client.clear()))
+
+it('tests a new Email draft without saving it, then creates the channel on save', async () => {
+ const user = userEvent.setup()
+ renderEmail(null)
+ await user.type(
+ await screen.findByLabelText('contacts.imPlatform.email.senderEmail'),
+ )
+ await user.type(screen.getByLabelText('contacts.imPlatform.email.senderName'), ' Approvals ')
+ await user.type(screen.getByLabelText(secretLabel), ' new-api-key ')
+ await user.click(screen.getByRole('button', { name: testLabel }))
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent('contacts.imPlatform.email.testSucceeded'),
+ )
+ const [testRequest] = requests('POST', `${apiPath}/test`)
+ expect(await testRequest?.json()).toEqual({
+ sender_email: '[email protected]',
+ sender_name: 'Approvals',
+ credentials: { provider: 'resend', api_key: 'new-api-key' },
+ })
+ expect(requests('POST', apiPath)).toHaveLength(0)
+ expect(screen.getByLabelText(secretLabel)).toHaveValue(' new-api-key ')
+
+ await user.click(screen.getByRole('button', { name: saveLabel }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ const [saveRequest] = requests('POST', apiPath)
+ expect(await saveRequest?.json()).toEqual({
+ sender_email: '[email protected]',
+ sender_name: 'Approvals',
+ credentials: { provider: 'resend', api_key: 'new-api-key' },
+ })
+})
+
+it('retains a saved API key for connection tests and updates while invalidating stale test success', async () => {
+ const user = userEvent.setup()
+ renderEmail()
+ await user.click(await screen.findByRole('button', { name: testLabel }))
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent('contacts.imPlatform.email.testSucceeded'),
+ )
+ const [testRequest] = requests('POST', `${apiPath}/${email.id}/test`)
+ expect(await testRequest?.json()).toEqual({
+ expected_config_version: email.config_version,
+ sender_email: '[email protected]',
+ sender_name: 'Approvals',
+ credentials: { provider: 'resend', api_key: { type: 'unchanged' } },
+ })
+
+ const name = screen.getByLabelText('contacts.imPlatform.email.senderName')
+ await user.clear(name)
+ await user.type(name, 'New sender')
+ expect(screen.getByRole('status')).toBeEmptyDOMElement()
+ await user.click(screen.getByRole('button', { name: saveLabel }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ const [saveRequest] = requests('PUT', `${apiPath}/${email.id}`)
+ expect(await saveRequest?.json()).toEqual({
+ expected_config_version: email.config_version,
+ sender_email: '[email protected]',
+ sender_name: 'New sender',
+ credentials: { provider: 'resend', api_key: { type: 'unchanged' } },
+ })
+})
+
+it('shows a failed provider test, keeps the draft, and lets corrected credentials be tested again', async () => {
+ let connected = false
+ network.handle.mockImplementation(() =>
+ json({
+ status: connected ? 'connected' : 'invalid_credentials',
+ status_description: connected ? 'Connected' : 'The API key was rejected',
+ }),
+ )
+ const user = userEvent.setup()
+ renderEmail()
+ const secret = await screen.findByLabelText(secretLabel)
+ await user.type(secret, 'rejected-key')
+ await user.click(screen.getByRole('button', { name: testLabel }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('The API key was rejected')
+ expect(secret).toHaveValue('rejected-key')
+ expect(screen.getByRole('status')).toBeEmptyDOMElement()
+
+ connected = true
+ await user.clear(secret)
+ await user.type(secret, 'corrected-key')
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: testLabel }))
+ await waitFor(() =>
+ expect(screen.getByRole('status')).toHaveTextContent('contacts.imPlatform.email.testSucceeded'),
+ )
+ const testRequests = requests('POST', `${apiPath}/${email.id}/test`)
+ expect(testRequests).toHaveLength(2)
+ expect(await testRequests[1]?.json()).toMatchObject({
+ credentials: { api_key: 'corrected-key' },
+ })
+ expect(requests('PUT', `${apiPath}/${email.id}`)).toHaveLength(0)
+})
+
+it('preserves a rejected Email save for correction and retries with the current sender and secret', async () => {
+ let rejectSave = true
+ network.handle.mockImplementation((request) => {
+ if (request.method === 'GET') return json(emailDetail(email))
+ return rejectSave
+ ? json({ code: 'bad_request', message: 'Sender domain is not verified' }, 400)
+ : json({ summary: email })
+ })
+ const user = userEvent.setup()
+ renderEmail()
+ const secret = await screen.findByLabelText(secretLabel)
+ await user.type(secret, 'retry-key')
+ await user.click(screen.getByRole('button', { name: saveLabel }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('Sender domain is not verified')
+ expect(secret).toHaveValue('retry-key')
+
+ rejectSave = false
+ const sender = screen.getByLabelText('contacts.imPlatform.email.senderEmail')
+ await user.clear(sender)
+ await user.type(sender, '[email protected]')
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: saveLabel }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ const saves = requests('PUT', `${apiPath}/${email.id}`)
+ expect(saves).toHaveLength(2)
+ expect(await saves[1]?.json()).toMatchObject({
+ sender_email: '[email protected]',
+ credentials: { api_key: 'retry-key' },
+ })
+})
+
+it('clears the API key and prevents duplicate writes when save succeeds but fresh details cannot load', async () => {
+ network.handle.mockImplementation((request) =>
+ request.method === 'GET'
+ ? json({ code: 'unavailable', message: 'Details unavailable' }, 503)
+ : json({ summary: email }),
+ )
+ const user = userEvent.setup()
+ renderEmail()
+ const secret = await screen.findByLabelText(secretLabel)
+ await user.type(secret, 'saved-key')
+ await user.click(screen.getByRole('button', { name: saveLabel }))
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.bindingDialog.savedDetailsUnavailable',
+ )
+ expect(secret).toHaveValue('')
+ expect(secret).toBeDisabled()
+ expect(screen.getByRole('button', { name: saveLabel })).toBeDisabled()
+ expect(screen.getByRole('button', { name: testLabel })).toBeDisabled()
+ expect(requests('PUT', `${apiPath}/${email.id}`)).toHaveLength(1)
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+})
diff --git a/web/features/contacts/im-platform/__tests__/fixtures/channel-client.ts b/web/features/contacts/im-platform/__tests__/fixtures/channel-client.ts
index 07cb369b654..f13392d2194 100644
--- a/web/features/contacts/im-platform/__tests__/fixtures/channel-client.ts
+++ b/web/features/contacts/im-platform/__tests__/fixtures/channel-client.ts
@@ -1,52 +1,8 @@
-import type { ChannelSummary } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { createContactImApiRepository } from '../../repository'
-
-type ChannelApiClient = NonNullable<Parameters<typeof createContactImApiRepository>[1]>
-type EmailDetail = Awaited<ReturnType<ChannelApiClient['channels']['email']['byChannelId']['get']>>
-type ImDetail = Awaited<ReturnType<ChannelApiClient['channels']['im']['byChannelId']['get']>>
-
-export function createChannelClient() {
- const client = {
- channelProviders: { get: vi.fn<ChannelApiClient['channelProviders']['get']>() },
- channels: {
- get: vi.fn<ChannelApiClient['channels']['get']>(),
- email: {
- post: vi.fn<ChannelApiClient['channels']['email']['post']>(),
- test: { post: vi.fn<ChannelApiClient['channels']['email']['test']['post']>() },
- byChannelId: {
- get: vi.fn<ChannelApiClient['channels']['email']['byChannelId']['get']>(),
- put: vi.fn<ChannelApiClient['channels']['email']['byChannelId']['put']>(),
- delete: vi.fn<ChannelApiClient['channels']['email']['byChannelId']['delete']>(),
- test: {
- post: vi.fn<ChannelApiClient['channels']['email']['byChannelId']['test']['post']>(),
- },
- },
- },
- im: {
- post: vi.fn<ChannelApiClient['channels']['im']['post']>(),
- test: { post: vi.fn<ChannelApiClient['channels']['im']['test']['post']>() },
- byChannelId: {
- get: vi.fn<ChannelApiClient['channels']['im']['byChannelId']['get']>(),
- put: vi.fn<ChannelApiClient['channels']['im']['byChannelId']['put']>(),
- delete: vi.fn<ChannelApiClient['channels']['im']['byChannelId']['delete']>(),
- test: {
- post: vi.fn<ChannelApiClient['channels']['im']['byChannelId']['test']['post']>(),
- },
- replacement: {
- post: vi.fn<ChannelApiClient['channels']['im']['byChannelId']['replacement']['post']>(),
- },
- },
- },
- },
- } satisfies ChannelApiClient
- client.channels.email.byChannelId.get.mockImplementation(async ({ params }) =>
- emailDetail(channelSummary({ id: params.channel_id, kind: 'email', provider: 'resend' })),
- )
- client.channels.im.byChannelId.get.mockImplementation(async ({ params }) =>
- imDetail(channelSummary({ id: params.channel_id })),
- )
- return client
-}
+import type {
+ ChannelSummary,
+ EmailChannelDetailResponse as EmailDetail,
+ ImChannelDetailResponse as ImDetail,
+} from '@dify/contracts/api/console/workspaces/types.gen'
export function channelSummary(overrides: Partial<ChannelSummary> = {}): ChannelSummary {
return {
diff --git a/web/features/contacts/im-platform/__tests__/fixtures/http.ts b/web/features/contacts/im-platform/__tests__/fixtures/http.ts
new file mode 100644
index 00000000000..09887aa9480
--- /dev/null
+++ b/web/features/contacts/im-platform/__tests__/fixtures/http.ts
@@ -0,0 +1,54 @@
+import type { ImSyncRun } from '@dify/contracts/api/console/workspaces/types.gen'
+import { channelSummary, emailDetail, imDetail } from './channel-client'
+
+export const channel = channelSummary({
+ provider: 'feishu',
+ display_identifier: 'saved-tenant',
+ id: 'channel-1',
+})
+export const providers = {
+ email_providers: [{ provider: 'resend' }],
+ im_providers: [
+ { provider: 'feishu' },
+ { provider: 'lark' },
+ { provider: 'slack' },
+ { provider: 'ding_talk' },
+ { provider: 'ms_teams' },
+ { provider: 'we_com' },
+ ],
+}
+export const syncRun = (overrides: Partial<ImSyncRun> = {}): ImSyncRun => ({
+ id: 'run-1',
+ channel_id: channel.id,
+ channel_config_version: 1,
+ provider: 'feishu',
+ started_at: 1,
+ finished_at: 2,
+ status: 'succeeded',
+ result_counts: { added: 0, not_matched: 0, failed: 0, removed: 0, skipped: 0 },
+ ...overrides,
+})
+export const json = (data: unknown, status = 200) =>
+ new Response(JSON.stringify(data), { status, headers: { 'content-type': 'application/json' } })
+export function defaultResponse(request: Request) {
+ const url = new URL(request.url)
+ if (url.pathname.endsWith('/channel-providers')) return json(providers)
+ if (url.pathname.endsWith('/channels')) return json({ channels: [channel] })
+ if (url.pathname.endsWith('/channels/im/channel-1'))
+ return json(request.method === 'GET' ? imDetail(channel) : { summary: channel })
+ if (url.pathname.endsWith('/channels/email/channel-email'))
+ return json(
+ request.method === 'GET'
+ ? emailDetail(channelSummary({ id: 'channel-email', kind: 'email', provider: 'resend' }))
+ : { summary: channelSummary({ id: 'channel-email', kind: 'email', provider: 'resend' }) },
+ )
+ if (url.pathname.endsWith('/im-sync-runs/latest')) return json({ run: syncRun() })
+ if (url.pathname.endsWith('/im-sync-runs/latest/results'))
+ return json({
+ data: [],
+ total: 0,
+ limit: Number(url.searchParams.get('limit')),
+ page: Number(url.searchParams.get('page')),
+ })
+ throw new Error(`Unexpected request: ${request.method} ${request.url}`)
+}
diff --git a/web/features/contacts/im-platform/__tests__/fixtures/repository.ts b/web/features/contacts/im-platform/__tests__/fixtures/repository.ts
deleted file mode 100644
index f7d01b91b3a..00000000000
--- a/web/features/contacts/im-platform/__tests__/fixtures/repository.ts
+++ /dev/null
@@ -1,488 +0,0 @@
-import type { ContactsImPlatformOrganizationContext } from '../../context'
-import type { ContactImPlatformRepository } from '../../repository'
-import type {
- AuthorizeContactImProviderCommand,
- ContactImIntegrationView,
- ContactImOrganizationCommand,
- ContactImPage,
- ContactImProviderCommand,
- ContactImProviderDefinition,
- ContactImSyncItemView,
- ContactImSyncRunView,
- ListContactImSyncItemsInput,
- SaveContactImCredentialsCommand,
- TestContactImConnectionCommand,
-} from '../../types'
-import type { ContactImMockScenario, ContactImMockScenarioSeed } from './scenarios'
-import {
- ContactImAuthMode,
- ContactImConnectionStatus,
- ContactImProvider,
- ContactImProviderAvailability,
- ContactImProviderField,
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
- ContactImSyncStatus,
-} from '../../types'
-import {
- countContactImSyncItems,
- createDefaultTransitionFinal,
- createEmptyContactImSyncCounts,
- getContactImMockScenarioSeed,
- ContactImMockScenario as MockScenario,
- validateContactImMockScenarioSeed,
-} from './scenarios'
-
-type LoadBarrier = {
- promise: Promise<void>
- release: () => void
-}
-
-const clone = <T>(value: T): T => structuredClone(value)
-
-const createLoadBarrier = (): LoadBarrier => {
- let release: () => void = () => undefined
- const promise = new Promise<void>((resolve) => {
- release = resolve
- })
-
- return { promise, release }
-}
-
-class InMemoryContactImPlatformRepository implements ContactImPlatformRepository {
- readonly queryKey: string
- private loadBarrier: LoadBarrier | null
- private seed: ContactImMockScenarioSeed
-
- constructor(seed: ContactImMockScenarioSeed) {
- validateContactImMockScenarioSeed(seed)
- this.seed = clone(seed)
- this.loadBarrier = seed.pendingInitialLoad ? createLoadBarrier() : null
- this.queryKey = `mock:${seed.organization.organizationId}:${seed.scenario}:${seed.organization.canManage ? 'manager' : 'viewer'}`
- }
-
- private assertOrganization(organizationId: string) {
- if (organizationId !== this.seed.organization.organizationId)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
- }
-
- private assertCanManage() {
- if (!this.seed.organization.canManage)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
- }
-
- private getProvider(providerId: ContactImProviderDefinition['provider']) {
- const provider = this.seed.providers.find((item) => item.provider === providerId)
-
- if (!provider) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- if (provider.availability !== ContactImProviderAvailability.Available)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ProviderUnavailable)
-
- return provider
- }
-
- private getIntegration(provider: ContactImProvider) {
- return this.seed.integrations.find((integration) => integration.provider === provider)
- }
-
- private assertProviderReplacement(provider: ContactImProvider, replaceActiveProvider: boolean) {
- if (provider === ContactImProvider.Email) return
-
- const activeProvider = this.seed.integrations.find(
- (integration) => integration.provider !== ContactImProvider.Email,
- )?.provider
-
- if (activeProvider && activeProvider !== provider && !replaceActiveProvider)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ActiveProviderExists)
- }
-
- private removeReplacedProvider(provider: ContactImProvider, replaceActiveProvider: boolean) {
- if (provider === ContactImProvider.Email || !replaceActiveProvider) return
-
- this.seed.integrations = this.seed.integrations.filter(
- (integration) =>
- integration.provider === ContactImProvider.Email || integration.provider === provider,
- )
- }
-
- private upsertIntegration(integration: ContactImIntegrationView) {
- const index = this.seed.integrations.findIndex(
- (current) => current.provider === integration.provider,
- )
-
- if (index === -1) this.seed.integrations.push(integration)
- else this.seed.integrations[index] = integration
- }
-
- private validateCredentials(
- provider: ContactImProviderDefinition,
- command: Pick<
- SaveContactImCredentialsCommand,
- 'provider' | 'retainSecret' | 'secret' | 'values' | 'clearedFields'
- >,
- replaceActiveProvider = false,
- ) {
- const currentIntegration = replaceActiveProvider
- ? undefined
- : this.getIntegration(command.provider)
- const configuredFields = new Set(currentIntegration?.configuredFields)
- if (currentIntegration?.secretConfigured) configuredFields.add(ContactImProviderField.Secret)
- for (const { field } of provider.requiredFields) {
- if (field !== ContactImProviderField.Secret && currentIntegration?.configuredValues[field])
- configuredFields.add(field)
- }
- for (const field of command.clearedFields ?? []) {
- const definition = provider.requiredFields.find((item) => item.field === field)
- if (!definition || definition.required)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
- }
- const retainingCurrentSecret = Boolean(currentIntegration?.secretConfigured)
- const hasReplacementSecret = Boolean(command.secret?.trim())
- const missingRequiredField = provider.requiredFields.some((definition) => {
- if (!definition.required) return false
- if (definition.field === ContactImProviderField.Secret)
- return !retainingCurrentSecret && !hasReplacementSecret
- return !(command.values[definition.field]?.trim() || configuredFields.has(definition.field))
- })
-
- if (missingRequiredField)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.RequiredFieldsMissing)
-
- return {
- currentIntegration,
- configuredFields,
- secretConfigured: retainingCurrentSecret || hasReplacementSecret,
- }
- }
-
- private async waitForInitialLoad() {
- if (this.loadBarrier) await this.loadBarrier.promise
- }
-
- releaseInitialLoad() {
- this.loadBarrier?.release()
- this.loadBarrier = null
- }
-
- toJSON() {
- return this.queryKey
- }
-
- async getIntegrations(organizationId: string) {
- this.assertOrganization(organizationId)
- await this.waitForInitialLoad()
-
- if (this.seed.failures.permissionLoad)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PermissionLoadFailed)
-
- if (this.seed.failures.integrationLoad)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.IntegrationLoadFailed)
-
- const providerOrder = new Map(
- this.seed.providers.map((provider, index) => [provider.provider, index]),
- )
- return clone(
- [...this.seed.integrations].sort(
- (left, right) =>
- (providerOrder.get(left.provider) ?? 0) - (providerOrder.get(right.provider) ?? 0),
- ),
- )
- }
-
- async getProviderDefinitions(organizationId: string) {
- this.assertOrganization(organizationId)
- await this.waitForInitialLoad()
-
- if (this.seed.failures.providerLoad)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ProviderLoadFailed)
-
- return clone(this.seed.providers)
- }
-
- async saveCredentials(command: SaveContactImCredentialsCommand) {
- this.assertOrganization(command.organizationId)
- this.assertCanManage()
- const provider = this.getProvider(command.provider)
- this.assertProviderReplacement(command.provider, command.replaceActiveProvider)
-
- if (provider.authMode !== ContactImAuthMode.Credentials)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- const { currentIntegration, configuredFields, secretConfigured } = this.validateCredentials(
- provider,
- command,
- command.replaceActiveProvider,
- )
-
- if (this.seed.failures.save)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed)
-
- const configuredValues = { ...currentIntegration?.configuredValues }
- for (const { field, secret: isSecret } of provider.requiredFields) {
- if (field === ContactImProviderField.Secret) continue
- const value = command.values[field]
- if (!value?.trim()) continue
- configuredFields.add(field)
- if (!isSecret) configuredValues[field] = value.trim()
- }
- if (secretConfigured) configuredFields.add(ContactImProviderField.Secret)
- for (const field of command.clearedFields ?? []) {
- configuredFields.delete(field)
- if (field !== ContactImProviderField.Secret) delete configuredValues[field]
- }
- const displayIdentifier =
- configuredValues.senderEmail ??
- configuredValues.appId ??
- configuredValues.clientId ??
- configuredValues.tenantId ??
- currentIntegration?.displayIdentifier ??
- null
- const integration: ContactImIntegrationView = {
- canManage: this.seed.organization.canManage,
- capabilities: clone(provider.capabilities),
- channelKind: provider.channelKind,
- configuredValues,
- configuredFields: [...configuredFields],
- displayIdentifier,
- lastCheckedAt: null,
- lastSync: currentIntegration?.lastSync ?? null,
- organizationId: this.seed.organization.organizationId,
- provider: command.provider,
- secretConfigured,
- status: ContactImConnectionStatus.Configured,
- statusReason: null,
- }
- this.removeReplacedProvider(command.provider, command.replaceActiveProvider)
- this.upsertIntegration(integration)
-
- return clone(integration)
- }
-
- async authorizeProvider(command: AuthorizeContactImProviderCommand) {
- this.assertOrganization(command.organizationId)
- this.assertCanManage()
- const provider = this.getProvider(command.provider)
- this.assertProviderReplacement(command.provider, command.replaceActiveProvider)
-
- if (provider.authMode !== ContactImAuthMode.OAuth)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- if (this.seed.failures.authorization)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed)
-
- const currentIntegration = this.getIntegration(command.provider)
- const integration: ContactImIntegrationView = {
- canManage: this.seed.organization.canManage,
- capabilities: clone(provider.capabilities),
- channelKind: provider.channelKind,
- configuredValues: currentIntegration?.configuredValues ?? {},
- displayIdentifier: 'oauth-workspace',
- lastCheckedAt: '2026-07-17T06:12:00.000Z',
- lastSync: currentIntegration?.lastSync ?? null,
- organizationId: this.seed.organization.organizationId,
- provider: command.provider,
- secretConfigured: false,
- status: ContactImConnectionStatus.Connected,
- statusReason: null,
- }
- this.removeReplacedProvider(command.provider, command.replaceActiveProvider)
- this.upsertIntegration(integration)
-
- return clone(integration)
- }
-
- async testConnection(command: TestContactImConnectionCommand) {
- this.assertOrganization(command.organizationId)
- this.assertCanManage()
- const provider = this.getProvider(command.provider)
-
- if (provider.authMode !== ContactImAuthMode.Credentials)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- const { currentIntegration, configuredFields, secretConfigured } = this.validateCredentials(
- provider,
- command,
- )
-
- if (this.seed.failures.connectionTest)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed)
-
- const configuredValues = { ...currentIntegration?.configuredValues }
- for (const { field, secret: isSecret } of provider.requiredFields) {
- if (field === ContactImProviderField.Secret) continue
- const value = command.values[field]?.trim()
- if (!value) continue
- configuredFields.add(field)
- if (!isSecret) configuredValues[field] = value
- }
- if (secretConfigured) configuredFields.add(ContactImProviderField.Secret)
- for (const field of command.clearedFields ?? []) {
- configuredFields.delete(field)
- if (field !== ContactImProviderField.Secret) delete configuredValues[field]
- }
- const testedIntegration: ContactImIntegrationView = {
- canManage: this.seed.organization.canManage,
- capabilities: clone(provider.capabilities),
- channelKind: provider.channelKind,
- configuredValues,
- configuredFields: [...configuredFields],
- displayIdentifier:
- configuredValues.senderEmail ?? currentIntegration?.displayIdentifier ?? null,
- lastCheckedAt: '2026-07-17T06:14:00.000Z',
- lastSync: currentIntegration?.lastSync ?? null,
- organizationId: this.seed.organization.organizationId,
- provider: provider.provider,
- secretConfigured,
- status: ContactImConnectionStatus.Connected,
- statusReason: null,
- }
- return clone(testedIntegration)
- }
-
- async disconnect(command: ContactImProviderCommand) {
- this.assertOrganization(command.organizationId)
- this.assertCanManage()
-
- if (this.seed.failures.disconnect)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed)
-
- this.seed.integrations = this.seed.integrations.filter(
- (integration) => integration.provider !== command.provider,
- )
-
- return this.getIntegrations(command.organizationId)
- }
-
- async getActiveSync(organizationId: string) {
- this.assertOrganization(organizationId)
- const activeRun = Object.values(this.seed.runs).find(
- (run) =>
- run.status === ContactImSyncStatus.Queued || run.status === ContactImSyncStatus.Running,
- )
-
- return activeRun ? clone(activeRun) : null
- }
-
- async startSync(command: ContactImOrganizationCommand) {
- this.assertOrganization(command.organizationId)
- this.assertCanManage()
-
- const syncIntegration = this.seed.integrations.find(
- (integration) =>
- integration.status === ContactImConnectionStatus.Connected &&
- integration.capabilities.directorySync,
- )
- if (!syncIntegration) {
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncNotAllowed)
- }
-
- if (await this.getActiveSync(command.organizationId))
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncAlreadyRunning)
-
- if (this.seed.failures.syncStart)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed)
-
- const id = `mock-sync-${this.seed.nextSyncNumber}`
- this.seed.nextSyncNumber += 1
- const run: ContactImSyncRunView = {
- completedAt: null,
- counts: createEmptyContactImSyncCounts(),
- durationMs: null,
- id,
- safeError: null,
- startedAt: '2026-07-17T06:20:00.000Z',
- startedBy: 'Workspace admin',
- status: ContactImSyncStatus.Queued,
- }
- this.seed.itemsByRun[id] = []
- this.seed.runs[id] = run
- this.seed.transitionFinals[id] = createDefaultTransitionFinal()
-
- return clone(run)
- }
-
- async advanceSync(runId: string) {
- const run = this.seed.runs[runId]
-
- if (!run) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
-
- if (run.status === ContactImSyncStatus.Queued) {
- run.status = ContactImSyncStatus.Running
- return clone(run)
- }
-
- if (run.status !== ContactImSyncStatus.Running) return clone(run)
-
- const final = this.seed.transitionFinals[runId] ?? createDefaultTransitionFinal()
- run.completedAt = '2026-07-17T06:22:04.000Z'
- run.counts = countContactImSyncItems(final.items)
- run.durationMs = 124000
- run.safeError = final.safeError
- run.status = final.status
- this.seed.itemsByRun[runId] = clone(final.items)
- const syncIntegration = this.seed.integrations.find(
- (integration) => integration.capabilities.directorySync,
- )
- if (syncIntegration) syncIntegration.lastSync = clone(run)
- delete this.seed.transitionFinals[runId]
-
- return clone(run)
- }
-
- async getSyncRun(runId: string) {
- const run = this.seed.runs[runId]
-
- if (!run) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
-
- if (this.seed.failures.detailRunId === runId)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.DetailLoadFailed)
-
- return clone(run)
- }
-
- async getSyncItems(
- input: ListContactImSyncItemsInput,
- ): Promise<ContactImPage<ContactImSyncItemView>> {
- const run = this.seed.runs[input.runId]
-
- if (!run) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
-
- if (this.seed.failures.detailRunId === input.runId)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.DetailLoadFailed)
-
- if (input.cursor && this.seed.failures.pageCursor === input.cursor)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
-
- const start = input.cursor ? Number.parseInt(input.cursor, 10) : 0
- if (!Number.isFinite(start) || start < 0)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- const pageSize = Math.min(Math.max(input.pageSize ?? 20, 1), 50)
- const filteredItems = (this.seed.itemsByRun[input.runId] ?? []).filter(
- (item) => !input.result || item.result === input.result,
- )
- const items = filteredItems.slice(start, start + pageSize)
- const nextStart = start + items.length
-
- return {
- items: clone(items),
- nextCursor: nextStart < filteredItems.length ? String(nextStart) : null,
- }
- }
-
- getDebugSnapshot() {
- return clone(this.seed)
- }
-}
-
-export const createContactImMockRepository = ({
- organization,
- scenario = MockScenario.Connected,
-}: {
- organization: ContactsImPlatformOrganizationContext
- scenario?: ContactImMockScenario
-}) => new InMemoryContactImPlatformRepository(getContactImMockScenarioSeed(scenario, organization))
-
-export const createContactImMockRepositoryFromSeed = (seed: ContactImMockScenarioSeed) =>
- new InMemoryContactImPlatformRepository(seed)
diff --git a/web/features/contacts/im-platform/__tests__/fixtures/scenarios.ts b/web/features/contacts/im-platform/__tests__/fixtures/scenarios.ts
deleted file mode 100644
index be5728ea48b..00000000000
--- a/web/features/contacts/im-platform/__tests__/fixtures/scenarios.ts
+++ /dev/null
@@ -1,553 +0,0 @@
-import type { ContactsImPlatformOrganizationContext } from '../../context'
-import type {
- ContactImIntegrationView,
- ContactImProviderDefinition,
- ContactImSafeReason,
- ContactImSyncCounts,
- ContactImSyncItemView,
- ContactImSyncRunView,
- ContactImSyncStatus,
-} from '../../types'
-import {
- ContactChannelKind,
- ContactImAuthMode,
- ContactImConnectionStatus,
- ContactImProvider,
- ContactImProviderAvailability,
- ContactImProviderField,
- ContactImStatusReason,
- ContactImSyncResult,
- ContactImUnavailableReason,
- ContactImSafeReason as SafeReason,
- ContactImSyncStatus as SyncStatus,
-} from '../../types'
-
-type ValueOf<T> = T[keyof T]
-
-export const ContactImMockScenario = {
- ActiveSync: 'active_sync',
- AuthorizationFailure: 'authorization_failure',
- CallbackError: 'callback_error',
- ChannelsConfigured: 'channels_configured',
- Configured: 'configured',
- Connected: 'connected',
- ConnectionError: 'connection_error',
- ConnectionTestFailure: 'connection_test_failure',
- DetailFailure: 'detail_failure',
- DisconnectFailure: 'disconnect_failure',
- EmailConnectionTestFailure: 'email_connection_test_failure',
- LoadFailure: 'load_failure',
- Loading: 'loading',
- NoPermission: 'no_permission',
- PageFailure: 'page_failure',
- PaginatedResults: 'paginated_results',
- PermissionIssue: 'permission_issue',
- PermissionLoadFailure: 'permission_load_failure',
- ProviderUnavailable: 'provider_unavailable',
- SaveFailure: 'save_failure',
- SyncFailure: 'sync_failure',
- SyncPartialSuccess: 'sync_partial_success',
- SyncStartFailure: 'sync_start_failure',
- SyncSuccess: 'sync_success',
- NotConfigured: 'not_configured',
-} as const
-
-export type ContactImMockScenario = ValueOf<typeof ContactImMockScenario>
-
-type ContactImMockFailurePlan = {
- authorization: boolean
- connectionTest: boolean
- detailRunId: string | null
- disconnect: boolean
- integrationLoad: boolean
- pageCursor: string | null
- permissionLoad: boolean
- providerLoad: boolean
- save: boolean
- syncStart: boolean
-}
-
-export type ContactImMockTransitionFinal = {
- items: ContactImSyncItemView[]
- safeError: ContactImSafeReason | null
- status: Extract<ContactImSyncStatus, 'success' | 'partial_success' | 'failure'>
-}
-
-export type ContactImMockScenarioSeed = {
- failures: ContactImMockFailurePlan
- integrations: ContactImIntegrationView[]
- itemsByRun: Record<string, ContactImSyncItemView[]>
- nextSyncNumber: number
- organization: ContactsImPlatformOrganizationContext
- pendingInitialLoad: boolean
- providers: ContactImProviderDefinition[]
- runs: Record<string, ContactImSyncRunView>
- scenario: ContactImMockScenario
- transitionFinals: Record<string, ContactImMockTransitionFinal>
-}
-
-export const createEmptyContactImSyncCounts = (): ContactImSyncCounts => ({
- [ContactImSyncResult.CreatedBinding]: 0,
- [ContactImSyncResult.Failed]: 0,
- [ContactImSyncResult.Matched]: 0,
- [ContactImSyncResult.Skipped]: 0,
- [ContactImSyncResult.Unmatched]: 0,
- [ContactImSyncResult.UpdatedBinding]: 0,
-})
-
-export const countContactImSyncItems = (items: ContactImSyncItemView[]): ContactImSyncCounts => {
- const counts = createEmptyContactImSyncCounts()
-
- for (const item of items) counts[item.result] = (counts[item.result] ?? 0) + 1
-
- return counts
-}
-
-const clone = <T>(value: T): T => structuredClone(value)
-
-const createProviderDefinitions = (): ContactImProviderDefinition[] => [
- {
- authMode: ContactImAuthMode.Credentials,
- availability: ContactImProviderAvailability.Available,
- callbackUrl: null,
- capabilities: { directorySync: false },
- channelKind: ContactChannelKind.Email,
- displayName: 'Email',
- provider: ContactImProvider.Email,
- requiredFields: [
- { field: ContactImProviderField.SenderEmail, required: true },
- { field: ContactImProviderField.Secret, required: true },
- ],
- unavailableReason: null,
- },
- {
- authMode: ContactImAuthMode.Credentials,
- availability: ContactImProviderAvailability.Available,
- callbackUrl: 'https://example.dify.test/contacts/im/slack/callback',
- capabilities: { directorySync: true },
- channelKind: ContactChannelKind.Im,
- displayName: 'Slack',
- provider: ContactImProvider.Slack,
- requiredFields: [
- { field: ContactImProviderField.AppId, required: true },
- { field: ContactImProviderField.Secret, required: true },
- ],
- unavailableReason: null,
- },
- {
- authMode: ContactImAuthMode.Credentials,
- availability: ContactImProviderAvailability.Available,
- callbackUrl: 'https://example.dify.test/contacts/im/feishu/callback',
- capabilities: { directorySync: true },
- channelKind: ContactChannelKind.Im,
- displayName: 'Feishu',
- provider: ContactImProvider.Feishu,
- requiredFields: [
- { field: ContactImProviderField.AppId, required: true },
- { field: ContactImProviderField.Secret, required: true },
- ],
- unavailableReason: null,
- },
- {
- authMode: ContactImAuthMode.Credentials,
- availability: ContactImProviderAvailability.Available,
- callbackUrl: 'https://example.dify.test/contacts/im/dingtalk/callback',
- capabilities: { directorySync: false },
- channelKind: ContactChannelKind.Im,
- displayName: 'DingTalk',
- provider: ContactImProvider.DingTalk,
- requiredFields: [
- { field: ContactImProviderField.ClientId, required: true },
- { field: ContactImProviderField.Secret, required: true },
- ],
- unavailableReason: null,
- },
-]
-
-const createIntegration = (
- organization: ContactsImPlatformOrganizationContext,
- provider: ContactImProviderDefinition,
- status: Exclude<ContactImIntegrationView['status'], 'not_configured'>,
- {
- configuredValues = {},
- displayIdentifier = null,
- lastCheckedAt = null,
- secretConfigured = false,
- }: {
- configuredValues?: ContactImIntegrationView['configuredValues']
- displayIdentifier?: string | null
- lastCheckedAt?: string | null
- secretConfigured?: boolean
- } = {},
-): ContactImIntegrationView => ({
- canManage: organization.canManage,
- capabilities: clone(provider.capabilities),
- channelKind: provider.channelKind,
- configuredValues: clone(configuredValues),
- displayIdentifier,
- lastCheckedAt,
- lastSync: null,
- organizationId: organization.organizationId,
- provider: provider.provider,
- secretConfigured,
- status,
- statusReason: null,
-})
-
-const createFailurePlan = (): ContactImMockFailurePlan => ({
- authorization: false,
- connectionTest: false,
- detailRunId: null,
- disconnect: false,
- integrationLoad: false,
- pageCursor: null,
- permissionLoad: false,
- providerLoad: false,
- save: false,
- syncStart: false,
-})
-
-const createBaseSeed = (
- organization: ContactsImPlatformOrganizationContext,
- scenario: ContactImMockScenario,
-): ContactImMockScenarioSeed => ({
- failures: createFailurePlan(),
- integrations: [],
- itemsByRun: {},
- nextSyncNumber: 1,
- organization: clone(organization),
- pendingInitialLoad: false,
- providers: createProviderDefinitions(),
- runs: {},
- scenario,
- transitionFinals: {},
-})
-
-const configureSlack = (
- seed: ContactImMockScenarioSeed,
- status: Exclude<ContactImIntegrationView['status'], 'not_configured'>,
-) => {
- const slack = seed.providers.find((provider) => provider.provider === ContactImProvider.Slack)
-
- if (!slack) throw new Error('Slack provider definition is required')
-
- seed.integrations = seed.integrations.filter(
- (integration) => integration.provider !== ContactImProvider.Slack,
- )
- seed.integrations.push(
- createIntegration(seed.organization, slack, status, {
- configuredValues: { appId: 'A012••••89' },
- displayIdentifier: 'A012••••89',
- lastCheckedAt: '2026-07-17T05:42:00.000Z',
- secretConfigured: true,
- }),
- )
-}
-
-const setSlackStatusReason = (seed: ContactImMockScenarioSeed, reason: ContactImStatusReason) => {
- const slack = seed.integrations.find(
- (integration) => integration.provider === ContactImProvider.Slack,
- )
-
- if (!slack) throw new Error('Configured Slack integration is required')
- slack.statusReason = reason
-}
-
-const configureEmail = (seed: ContactImMockScenarioSeed) => {
- const email = seed.providers.find((provider) => provider.provider === ContactImProvider.Email)
-
- if (!email) throw new Error('Email provider definition is required')
-
- seed.integrations = seed.integrations.filter(
- (integration) => integration.provider !== ContactImProvider.Email,
- )
- seed.integrations.push(
- createIntegration(seed.organization, email, ContactImConnectionStatus.Connected, {
- configuredValues: {
- senderEmail: '[email protected]',
- senderName: 'Acme',
- },
- displayIdentifier: '[email protected]',
- lastCheckedAt: '2026-07-17T05:40:00.000Z',
- secretConfigured: true,
- }),
- )
-}
-
-const createItem = (
- id: string,
- result: ContactImSyncItemView['result'],
- options: {
- matched?: boolean
- missingEmail?: boolean
- reason?: ContactImSafeReason | null
- } = {},
-): ContactImSyncItemView => ({
- id,
- matchedContact:
- options.matched === false
- ? null
- : {
- email: `contact-${id}@example.test`,
- id: `contact-${id}`,
- name: `Contact ${id}`,
- },
- platformIdentity: {
- displayName: `Member ${id}`,
- email: options.missingEmail ? null : `member-${id}@example.test`,
- platformUserId: `platform-${id}`,
- },
- result,
- safeReason: options.reason ?? null,
-})
-
-const createSuccessItems = (): ContactImSyncItemView[] => [
- createItem('matched-1', ContactImSyncResult.Matched),
- createItem('created-1', ContactImSyncResult.CreatedBinding),
- createItem('updated-1', ContactImSyncResult.UpdatedBinding),
-]
-
-const createPartialItems = (): ContactImSyncItemView[] => [
- ...createSuccessItems(),
- createItem('unmatched-1', ContactImSyncResult.Unmatched, {
- matched: false,
- reason: SafeReason.NoMatchingContact,
- }),
- createItem('skipped-1', ContactImSyncResult.Skipped, {
- matched: false,
- missingEmail: true,
- reason: SafeReason.MissingEmail,
- }),
- createItem('failed-1', ContactImSyncResult.Failed, {
- matched: false,
- reason: SafeReason.ContactUpdateFailed,
- }),
-]
-
-const createRun = (
- id: string,
- status: ContactImSyncStatus,
- items: ContactImSyncItemView[],
- safeError: ContactImSafeReason | null = null,
-): ContactImSyncRunView => ({
- completedAt:
- status === SyncStatus.Queued || status === SyncStatus.Running
- ? null
- : '2026-07-17T06:02:04.000Z',
- counts: countContactImSyncItems(items),
- durationMs: status === SyncStatus.Queued || status === SyncStatus.Running ? null : 124000,
- id,
- safeError,
- startedAt: '2026-07-17T06:00:00.000Z',
- startedBy: 'Workspace admin',
- status,
-})
-
-const addCompletedRun = (
- seed: ContactImMockScenarioSeed,
- id: string,
- status: Extract<ContactImSyncStatus, 'success' | 'partial_success' | 'failure'>,
- items: ContactImSyncItemView[],
- safeError: ContactImSafeReason | null = null,
-) => {
- const run = createRun(id, status, items, safeError)
- seed.itemsByRun[id] = clone(items)
- seed.runs[id] = run
- const syncIntegration = seed.integrations.find(
- (integration) => integration.capabilities.directorySync,
- )
- if (syncIntegration) syncIntegration.lastSync = clone(run)
-}
-
-const addActiveRun = (seed: ContactImMockScenarioSeed) => {
- const id = 'mock-active-sync'
- const run = createRun(id, SyncStatus.Queued, [])
- seed.itemsByRun[id] = []
- seed.runs[id] = run
- seed.transitionFinals[id] = {
- items: createPartialItems(),
- safeError: null,
- status: SyncStatus.PartialSuccess,
- }
-}
-
-const assertCountAgreement = (run: ContactImSyncRunView, items: ContactImSyncItemView[]) => {
- const actual = countContactImSyncItems(items)
-
- for (const result of Object.values(ContactImSyncResult)) {
- if (run.counts[result] !== actual[result])
- throw new Error(`Sync summary counts do not match detail items for run ${run.id}`)
- }
-}
-
-export const validateContactImMockScenarioSeed = (seed: ContactImMockScenarioSeed) => {
- const configuredProviders = new Set<ContactImProvider>()
- let activeImProvider: ContactImProvider | null = null
-
- for (const integration of seed.integrations) {
- if (configuredProviders.has(integration.provider))
- throw new Error(`Provider ${integration.provider} has more than one active configuration`)
- if (integration.status === ContactImConnectionStatus.NotConfigured)
- throw new Error('Configured channel collection cannot contain a not-configured entry')
- if (integration.provider !== ContactImProvider.Email) {
- if (activeImProvider) throw new Error('Only one active IM provider configuration is allowed')
- activeImProvider = integration.provider
- }
- configuredProviders.add(integration.provider)
- }
-
- for (const [runId, run] of Object.entries(seed.runs))
- assertCountAgreement(run, seed.itemsByRun[runId] ?? [])
-
- for (const [runId, final] of Object.entries(seed.transitionFinals)) {
- const finalRun = createRun(runId, final.status, final.items, final.safeError)
- assertCountAgreement(finalRun, final.items)
- }
-
- for (const integration of seed.integrations) {
- if (integration.lastSync && !seed.runs[integration.lastSync.id])
- throw new Error('Latest sync must reference a run in the same scenario')
- }
-}
-
-export const getContactImMockScenarioSeed = (
- scenario: ContactImMockScenario,
- organization: ContactsImPlatformOrganizationContext,
-): ContactImMockScenarioSeed => {
- const seed = createBaseSeed(organization, scenario)
-
- switch (scenario) {
- case ContactImMockScenario.Loading:
- seed.pendingInitialLoad = true
- break
- case ContactImMockScenario.LoadFailure:
- seed.failures.integrationLoad = true
- break
- case ContactImMockScenario.PermissionLoadFailure:
- seed.failures.permissionLoad = true
- break
- case ContactImMockScenario.NoPermission:
- seed.organization.canManage = false
- break
- case ContactImMockScenario.ProviderUnavailable: {
- const provider = seed.providers.find(
- (definition) => definition.provider === ContactImProvider.DingTalk,
- )
- if (provider) {
- provider.availability = ContactImProviderAvailability.Unavailable
- provider.unavailableReason = ContactImUnavailableReason.DeploymentUnsupported
- }
- break
- }
- case ContactImMockScenario.NotConfigured:
- break
- case ContactImMockScenario.ChannelsConfigured:
- configureEmail(seed)
- configureSlack(seed, ContactImConnectionStatus.Connected)
- break
- case ContactImMockScenario.Configured:
- configureSlack(seed, ContactImConnectionStatus.Configured)
- break
- case ContactImMockScenario.Connected:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- break
- case ContactImMockScenario.PermissionIssue:
- configureSlack(seed, ContactImConnectionStatus.PermissionIssue)
- setSlackStatusReason(seed, ContactImStatusReason.MissingDirectoryPermission)
- break
- case ContactImMockScenario.CallbackError:
- configureSlack(seed, ContactImConnectionStatus.CallbackError)
- setSlackStatusReason(seed, ContactImStatusReason.CallbackMismatch)
- break
- case ContactImMockScenario.ConnectionError:
- configureSlack(seed, ContactImConnectionStatus.ConnectionError)
- setSlackStatusReason(seed, ContactImStatusReason.ProviderRequestFailed)
- break
- case ContactImMockScenario.SaveFailure:
- seed.failures.save = true
- break
- case ContactImMockScenario.AuthorizationFailure:
- seed.failures.authorization = true
- break
- case ContactImMockScenario.ConnectionTestFailure:
- configureSlack(seed, ContactImConnectionStatus.Configured)
- seed.failures.connectionTest = true
- break
- case ContactImMockScenario.EmailConnectionTestFailure:
- configureEmail(seed)
- seed.failures.connectionTest = true
- break
- case ContactImMockScenario.DisconnectFailure:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- seed.failures.disconnect = true
- break
- case ContactImMockScenario.SyncStartFailure:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- seed.failures.syncStart = true
- break
- case ContactImMockScenario.ActiveSync:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- addActiveRun(seed)
- break
- case ContactImMockScenario.SyncSuccess:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- addCompletedRun(seed, 'mock-sync-success', SyncStatus.Success, createSuccessItems())
- break
- case ContactImMockScenario.SyncPartialSuccess:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- addCompletedRun(seed, 'mock-sync-partial', SyncStatus.PartialSuccess, createPartialItems())
- break
- case ContactImMockScenario.SyncFailure:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- addCompletedRun(
- seed,
- 'mock-sync-failure',
- SyncStatus.Failure,
- [],
- SafeReason.ProviderRequestFailed,
- )
- break
- case ContactImMockScenario.DetailFailure:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- addCompletedRun(
- seed,
- 'mock-sync-detail-failure',
- SyncStatus.PartialSuccess,
- createPartialItems(),
- )
- seed.failures.detailRunId = 'mock-sync-detail-failure'
- break
- case ContactImMockScenario.PaginatedResults: {
- configureSlack(seed, ContactImConnectionStatus.Connected)
- const items = [
- ...createPartialItems(),
- createItem('unmatched-2', ContactImSyncResult.Unmatched, {
- matched: false,
- reason: SafeReason.NoMatchingContact,
- }),
- createItem('matched-2', ContactImSyncResult.Matched),
- ]
- addCompletedRun(seed, 'mock-sync-paginated', SyncStatus.PartialSuccess, items)
- break
- }
- case ContactImMockScenario.PageFailure:
- configureSlack(seed, ContactImConnectionStatus.Connected)
- addCompletedRun(
- seed,
- 'mock-sync-page-failure',
- SyncStatus.PartialSuccess,
- createPartialItems(),
- )
- seed.failures.pageCursor = '2'
- break
- }
-
- validateContactImMockScenarioSeed(seed)
- return clone(seed)
-}
-
-export const createDefaultTransitionFinal = (): ContactImMockTransitionFinal => ({
- items: createPartialItems(),
- safeError: null,
- status: SyncStatus.PartialSuccess,
-})
diff --git a/web/features/contacts/im-platform/__tests__/management-surface.spec.tsx b/web/features/contacts/im-platform/__tests__/management-surface.spec.tsx
index 5578012d282..da5b26c206a 100644
--- a/web/features/contacts/im-platform/__tests__/management-surface.spec.tsx
+++ b/web/features/contacts/im-platform/__tests__/management-surface.spec.tsx
@@ -1,2110 +1,636 @@
-import type { ReactNode } from 'react'
-import type { ContactImPlatformRepository } from '../repository'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import copy from 'copy-to-clipboard'
-import { ContactsImPlatformProvider } from '../composition'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { consoleQuery } from '@/service/console'
+import { ContactsImPlatformRuntimeProvider } from '../composition'
import { ContactsImPlatformManagementSurface } from '../management-surface'
-import { createContactImApiRepository } from '../repository'
-import {
- ContactImConnectionStatus,
- ContactImProvider,
- ContactImProviderField,
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
-} from '../types'
-import { channelSummary, createChannelClient, imDetail } from './fixtures/channel-client'
-import { createContactImMockRepository } from './fixtures/repository'
-import { ContactImMockScenario } from './fixtures/scenarios'
+import { channelSummary, emailDetail } from './fixtures/channel-client'
+import { channel, defaultResponse, json, providers, syncRun } from './fixtures/http'
-const mockNavigation = vi.hoisted(() => ({
- replace: vi.fn(),
- searchParams: new URLSearchParams(),
+const network = vi.hoisted(() => ({
+ handle: vi.fn<(request: Request) => Promise<Response> | Response>(),
}))
-
-vi.mock('@/next/navigation', () => ({
- usePathname: () => '/contacts/settings',
- useRouter: () => ({ replace: mockNavigation.replace }),
- useSearchParams: () => mockNavigation.searchParams,
-}))
-
-vi.mock('copy-to-clipboard', () => ({
- default: vi.fn(() => true),
-}))
-
-vi.mock('@/context/i18n', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/context/i18n')>()),
- useDocLink: () => (path: string) => `https://docs.dify.ai/en/cloud${path}`,
-}))
-
-const organization = {
- canManage: true,
- organizationId: 'org-surface',
- workspaceId: 'workspace-surface',
-}
-
-const renderSurface = ({
- canManage = true,
- workspaceId = organization.workspaceId,
- repository,
- scenario = ContactImMockScenario.NotConfigured,
-}: {
- canManage?: boolean
- workspaceId?: string
- repository?: ContactImPlatformRepository
- scenario?: ContactImMockScenario
-} = {}) => {
- const scopedOrganization = { ...organization, canManage, workspaceId }
- const scopedRepository =
- repository ??
- createContactImMockRepository({
- organization: scopedOrganization,
- scenario,
- })
- const queryClient = new QueryClient({
- defaultOptions: {
- mutations: { retry: false },
- queries: { retry: false },
- },
- })
- const wrapper = ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <ContactsImPlatformProvider organization={scopedOrganization} repository={scopedRepository}>
- {children}
- </ContactsImPlatformProvider>
- </QueryClientProvider>
- )
-
+vi.mock('@/service/base', async () => {
+ const { httpErrorFromResponse } = await import('@/service/http-error')
return {
- queryClient,
- repository: scopedRepository,
- ...render(<ContactsImPlatformManagementSurface />, { wrapper }),
+ request: async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const response = await network.handle(options.request)
+ if (!response.ok) throw await httpErrorFromResponse(response)
+ return response
+ },
}
+})
+vi.mock('@/utils/client', () => ({ isClient: true, isServer: false }))
+vi.mock('@/context/i18n', async (original) => ({
+ ...(await original<typeof import('@/context/i18n')>()),
+ useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,
+}))
+const clients: QueryClient[] = []
+function renderSurface(canManage = true) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ })
+ clients.push(client)
+ render(
+ <QueryClientProvider client={client}>
+ <NuqsTestingAdapter>
+ <ContactsImPlatformRuntimeProvider
+ organization={{ canManage, organizationId: 'workspace-1', workspaceId: 'workspace-1' }}
+ >
+ <ContactsImPlatformManagementSurface />
+ </ContactsImPlatformRuntimeProvider>
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
+ )
+ return client
}
-
+const calls = (ending: string, method = 'GET') =>
+ network.handle.mock.calls
+ .map(([request]) => request)
+ .filter(
+ (request) => new URL(request.url).pathname.endsWith(ending) && request.method === method,
+ )
beforeEach(() => {
- mockNavigation.replace.mockReset()
- mockNavigation.searchParams = new URLSearchParams()
+ network.handle.mockImplementation(defaultResponse)
})
-
-describe('Contacts IM platform management surface', () => {
- it('shows a dedicated loading state without treating it as not configured', () => {
- renderSurface({ scenario: ContactImMockScenario.Loading })
-
- expect(screen.getByRole('status', { name: 'contacts.imPlatform.loading' })).toBeInTheDocument()
- expect(screen.queryByText('contacts.imPlatform.status.not_configured')).not.toBeInTheDocument()
- })
-
- it('shows a load failure with a retry action', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface({ scenario: ContactImMockScenario.LoadFailure })
- const getIntegrations = vi.spyOn(repository, 'getIntegrations')
-
- expect(await screen.findByText('contacts.imPlatform.loadError.title')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.loadError.retry' }))
-
- expect(getIntegrations).toHaveBeenCalledTimes(1)
- })
-
- it('does not downgrade a permission-load failure to not configured', async () => {
- renderSurface({ scenario: ContactImMockScenario.PermissionLoadFailure })
-
- expect(await screen.findByText('contacts.imPlatform.loadError.title')).toBeInTheDocument()
- expect(screen.queryByText('contacts.imPlatform.status.not_configured')).not.toBeInTheDocument()
- })
-
- it('shows all providers for the empty state', async () => {
- renderSurface()
-
- expect(
- await screen.findByRole('heading', { name: 'contacts.imPlatform.title' }),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('heading', { name: 'contacts.imPlatform.chooseProvider', level: 3 }),
- ).toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.chooseProvider' }),
- ).not.toBeInTheDocument()
- expect(screen.getByText('Email')).toBeInTheDocument()
- expect(screen.getByText('Slack')).toBeInTheDocument()
- expect(screen.getByText('Feishu')).toBeInTheDocument()
- expect(screen.getByText('DingTalk')).toBeInTheDocument()
- })
-
- it('shows the existing permission notice without querying restricted channel data', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const getIntegrations = vi.spyOn(repository, 'getIntegrations')
- const getProviderDefinitions = vi.spyOn(repository, 'getProviderDefinitions')
- const getActiveSync = vi.spyOn(repository, 'getActiveSync')
- renderSurface({ canManage: false, repository })
-
- expect(await screen.findByText('contacts.imPlatform.permission.title')).toBeInTheDocument()
- expect(screen.queryByRole('button')).not.toBeInTheDocument()
- expect(screen.queryByText('contacts.imPlatform.loadError.title')).not.toBeInTheDocument()
- expect(getIntegrations).not.toHaveBeenCalled()
- expect(getProviderDefinitions).not.toHaveBeenCalled()
- expect(getActiveSync).not.toHaveBeenCalled()
- })
-
- it('waits for a workspace before requesting channel configuration', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const getIntegrations = vi.spyOn(repository, 'getIntegrations')
- const getProviderDefinitions = vi.spyOn(repository, 'getProviderDefinitions')
- renderSurface({ workspaceId: '', repository })
-
- expect(
- await screen.findByRole('status', { name: 'contacts.imPlatform.loading' }),
- ).toBeInTheDocument()
- expect(screen.queryByText('contacts.imPlatform.permission.title')).not.toBeInTheDocument()
- expect(getIntegrations).not.toHaveBeenCalled()
- expect(getProviderDefinitions).not.toHaveBeenCalled()
- })
-
- it('disables an unavailable provider and presents its safe reason', async () => {
- renderSurface({ scenario: ContactImMockScenario.ProviderUnavailable })
-
- expect(
- await screen.findByText(
- 'contacts.imPlatform.provider.unavailableReason.deployment_unsupported',
- ),
- ).toBeInTheDocument()
- expect(screen.getByRole('button', { name: /DingTalk.*unavailable/i })).toBeDisabled()
- })
-
- it.each([
- [ContactImMockScenario.Configured, ContactImConnectionStatus.Configured],
- [ContactImMockScenario.Connected, ContactImConnectionStatus.Connected],
- [ContactImMockScenario.PermissionIssue, ContactImConnectionStatus.PermissionIssue],
- [ContactImMockScenario.CallbackError, ContactImConnectionStatus.CallbackError],
- [ContactImMockScenario.ConnectionError, ContactImConnectionStatus.ConnectionError],
- ])('presents the %s connection state', async (scenario, status) => {
- renderSurface({ scenario })
-
- expect(await screen.findAllByText(`contacts.imPlatform.status.${status}`)).not.toHaveLength(0)
- })
-
- it('shows configured channels before the remaining connect options', async () => {
- renderSurface({ scenario: ContactImMockScenario.ChannelsConfigured })
-
- expect(await screen.findByText(/contacts\.imPlatform\.email\.summary/)).toBeInTheDocument()
- expect(screen.getByRole('group', { name: 'Email' })).toBeInTheDocument()
- expect(screen.getByRole('group', { name: 'Slack' })).toBeInTheDocument()
- expect(screen.getByText('contacts.imPlatform.connectMore')).toBeInTheDocument()
- expect(
- within(screen.getByRole('group', { name: 'Feishu' })).getByRole('button', {
- name: /Feishu.*replace/i,
- }),
- ).toBeEnabled()
- })
-
- it('shows the sender email without including the sender name in the channel summary', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.ChannelsConfigured,
- })
- const integrations = await repository.getIntegrations(organization.organizationId)
- vi.spyOn(repository, 'getIntegrations').mockResolvedValue(
- integrations.map((integration) =>
- integration.provider === ContactImProvider.Email
- ? { ...integration, displayIdentifier: 'Acme [email protected]' }
- : integration,
- ),
- )
- renderSurface({ repository })
-
- const channel = await screen.findByRole('group', { name: 'Email' })
- expect(
- within(channel).getByText('contacts.imPlatform.email.summary:{"email":"[email protected]"}'),
- ).toBeInTheDocument()
- expect(channel).not.toHaveTextContent('Acme')
- })
-
- it('shows Slack connection status instead of presenting a client ID as a token', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const integrations = await repository.getIntegrations(organization.organizationId)
- vi.spyOn(repository, 'getIntegrations').mockResolvedValue(
- integrations.map((integration) => ({
- ...integration,
- displayIdentifier: '11264416750647.11695819675697',
- })),
- )
- renderSurface({ repository })
-
- const channel = await screen.findByRole('group', { name: 'Slack' })
- expect(within(channel).getByText('contacts.imPlatform.status.connected')).toBeInTheDocument()
- expect(channel).not.toHaveTextContent('11264416750647.11695819675697')
- })
-
- it('collapses only the remaining connect options and restores them when expanded', async () => {
- const user = userEvent.setup()
- renderSurface({ scenario: ContactImMockScenario.ChannelsConfigured })
-
- const trigger = await screen.findByRole('button', {
- name: 'contacts.imPlatform.connectMore',
- })
- expect(trigger).toHaveAttribute('aria-expanded', 'true')
- expect(screen.getByRole('group', { name: 'Feishu' })).toBeVisible()
- expect(screen.getByRole('group', { name: 'DingTalk' })).toBeVisible()
-
- await user.click(trigger)
-
- expect(trigger).toHaveAttribute('aria-expanded', 'false')
- await waitFor(() => {
- expect(screen.queryByRole('group', { name: 'Feishu' })).not.toBeInTheDocument()
- expect(screen.queryByRole('group', { name: 'DingTalk' })).not.toBeInTheDocument()
- })
- expect(screen.getByRole('group', { name: 'Email' })).toBeVisible()
- expect(screen.getByRole('group', { name: 'Slack' })).toBeVisible()
- expect(screen.getByRole('button', { name: 'contacts.imPlatform.action.syncNow' })).toBeVisible()
-
- await user.click(trigger)
-
- expect(trigger).toHaveAttribute('aria-expanded', 'true')
- expect(await screen.findByRole('group', { name: 'Feishu' })).toBeVisible()
- expect(screen.getByRole('group', { name: 'DingTalk' })).toBeVisible()
- })
+afterEach(() => clients.splice(0).forEach((client) => client.clear()))
+
+it('loads the generated summary once without fetching every channel detail', async () => {
+ renderSurface()
+ expect(await screen.findByRole('group', { name: 'Feishu' })).toHaveTextContent('saved-tenant')
+ expect(calls('/channels')).toHaveLength(1)
+ expect(calls('/channel-providers')).toHaveLength(1)
+ expect(calls('/channels/im/channel-1')).toHaveLength(0)
})
-describe('Contacts IM platform binding flows', () => {
- it('does not offer a provider placeholder callback before the channel is saved', async () => {
- const user = userEvent.setup()
- renderSurface()
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
-
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- ).not.toBeInTheDocument()
- expect(
- screen.getByRole('link', { name: 'contacts.imPlatform.bindingDialog.openSetupGuide' }),
- ).toHaveAttribute('href', 'https://docs.slack.dev/interactivity/handling-user-interaction/')
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- ).toBeInTheDocument()
- })
-
- it('associates required credential errors with their fields', async () => {
- const user = userEvent.setup()
- renderSurface()
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(screen.getAllByText('contacts.imPlatform.bindingDialog.required')).toHaveLength(2)
- const appId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret')
- expect(appId).toHaveAttribute('aria-invalid', 'true')
- expect(secret).toHaveAttribute('aria-invalid', 'true')
- expect(appId).toHaveAccessibleDescription('contacts.imPlatform.bindingDialog.required')
- expect(secret).toHaveAccessibleDescription('contacts.imPlatform.bindingDialog.required')
- })
-
- it('opens the dialog and restores focus to the provider trigger', async () => {
- const user = userEvent.setup()
- renderSurface()
- const trigger = await screen.findByRole('button', { name: /Slack.*connect/i })
- await user.click(trigger)
-
- expect(screen.getByRole('dialog')).toBeVisible()
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- await waitFor(() => expect(trigger).toHaveFocus())
- })
-
- it('submits a complete credential form from the keyboard', async () => {
- const user = userEvent.setup()
- renderSurface()
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'keyboard-app',
- )
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret')
- await user.type(secret, 'keyboard-secret')
- secret.focus()
- await user.keyboard('{Enter}')
-
- await waitFor(() => {
- expect(screen.getByRole('group', { name: 'Slack' })).toHaveTextContent(
- 'contacts.imPlatform.status.configured',
- )
- })
- })
-
- it('saves credentials, clears the secret, and advances to configured', async () => {
- const user = userEvent.setup()
- const { container } = renderSurface()
- const submittedSecret = 'surface-secret-must-disappear'
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'app-surface',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- submittedSecret,
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- await waitFor(() => {
- expect(screen.getByRole('group', { name: 'Slack' })).toHaveTextContent(
- 'contacts.imPlatform.status.configured',
- )
- })
- expect(screen.queryByDisplayValue(submittedSecret)).not.toBeInTheDocument()
- expect(container.innerHTML).not.toContain(submittedSecret)
- })
-
- it('connects Feishu with application credentials without invoking OAuth', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface()
- const authorize = vi.spyOn(repository, 'authorizeProvider')
- const save = vi.spyOn(repository, 'saveCredentials')
- await user.click(await screen.findByRole('button', { name: /Feishu.*connect/i }))
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.action.authorize' }),
- ).not.toBeInTheDocument()
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'feishu-app',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
- 'feishu-test-secret',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(await screen.findByText('contacts.imPlatform.status.configured')).toBeInTheDocument()
- expect(authorize).not.toHaveBeenCalled()
- expect(save).toHaveBeenCalledWith(
- expect.objectContaining({
- provider: ContactImProvider.Feishu,
- secret: 'feishu-test-secret',
- values: { appId: 'feishu-app' },
- }),
- )
- })
-
- it('retains credential inputs after a save failure until the dialog is closed', async () => {
- const user = userEvent.setup()
- renderSurface({ scenario: ContactImMockScenario.SaveFailure })
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- const appId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret')
- await user.type(appId, 'safe-app-id')
- await user.type(secret, 'retain-on-failure')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(
- await screen.findByText('contacts.imPlatform.bindingDialog.saveFailed'),
- ).toBeInTheDocument()
- expect(appId).toHaveValue('safe-app-id')
- expect(secret).toHaveValue('retain-on-failure')
-
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- await user.click(screen.getByRole('button', { name: /Slack.*connect/i }))
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- ).toHaveValue('')
- })
-
- it('requires confirmation before replacing the active IM binding', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface({ scenario: ContactImMockScenario.Connected })
- await user.click(await screen.findByRole('button', { name: /Feishu.*replace/i }))
-
- expect(screen.getByRole('alertdialog')).toBeInTheDocument()
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
-
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'replacement-app',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
- 'replacement-test-secret',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- await waitFor(async () => {
- const integrations = await repository.getIntegrations(organization.organizationId)
- expect(integrations.map(({ provider }) => provider)).toEqual([ContactImProvider.Feishu])
- })
- })
+it('does not fetch or expose channels to a non-manager', () => {
+ renderSurface(false)
+ expect(screen.queryByRole('group', { name: 'Feishu' })).not.toBeInTheDocument()
+ expect(network.handle).not.toHaveBeenCalled()
+})
- it('prevents duplicate credential submissions while the mutation is pending', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface()
- let resolveSave:
- | ((value: Awaited<ReturnType<typeof repository.saveCredentials>>) => void)
- | null = null
- const saveCredentials = vi.spyOn(repository, 'saveCredentials').mockImplementation(
- () =>
- new Promise((resolve) => {
- resolveSave = resolve
- }),
- )
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'pending-app',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- 'pending-secret',
- )
- const saveButton = screen.getByRole('button', {
+it('uses saved redacted metadata for an update and keeps generated cache invalidation', async () => {
+ const user = userEvent.setup()
+ const client = renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ const appId = await within(dialog).findByLabelText(
+ 'contacts.imPlatform.bindingDialog.field.appId',
+ )
+ await user.clear(appId)
+ await user.type(appId, 'updated-app')
+ await user.click(
+ within(dialog).getByRole('button', {
name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
- })
- await user.click(saveButton)
-
- expect(saveButton).toHaveAttribute('aria-disabled', 'true')
- await user.click(saveButton)
- expect(saveCredentials).toHaveBeenCalledTimes(1)
-
- await act(async () => {
- const resolvedRepository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Configured,
- })
- const integration = (await resolvedRepository.getIntegrations(organization.organizationId))[0]
- if (!integration) throw new Error('Pending save test requires a configured integration')
- resolveSave?.(integration)
- })
- })
-
- it('never pre-fills an already configured secret', async () => {
- const user = userEvent.setup()
- renderSurface({ scenario: ContactImMockScenario.Configured })
- await user.click(
- within(await screen.findByRole('group', { name: 'Slack' })).getByRole('button', {
- name: /contacts\.imPlatform\.action\.configureChannel/,
- }),
- )
-
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- ).toHaveValue('')
- expect(
- screen.getByText('contacts.imPlatform.bindingDialog.secretConfigured'),
- ).toBeInTheDocument()
- })
-
- it('uses the dedicated Resend form for the Email channel', async () => {
- const user = userEvent.setup()
- renderSurface()
- const emailCard = await screen.findByRole('group', { name: 'Email' })
-
- await user.click(within(emailCard).getByRole('button'))
-
- expect(
- screen.getByRole('heading', { name: 'contacts.imPlatform.email.title' }),
- ).toBeInTheDocument()
- expect(screen.getByLabelText('contacts.imPlatform.email.provider')).toHaveValue('Resend')
- expect(screen.getByLabelText('contacts.imPlatform.email.provider')).toBeDisabled()
- expect(screen.getByLabelText('contacts.imPlatform.email.senderEmail')).toBeRequired()
- expect(screen.getByLabelText('contacts.imPlatform.email.senderName')).toBeRequired()
- expect(screen.getByLabelText('contacts.imPlatform.email.apiKey')).toBeRequired()
- expect(screen.getByRole('link', { name: 'contacts.imPlatform.learnMore' })).toHaveAttribute(
- 'href',
- 'https://docs.dify.ai/en/cloud/use-dify/nodes/human-input',
- )
- })
-
- it('tests a valid Email configuration without closing the dialog or retaining the API key', async () => {
- const user = userEvent.setup()
- const { queryClient, repository } = renderSurface()
- const testConnection = vi.spyOn(repository, 'testConnection')
- const submittedApiKey = 'resend-test-key'
- await user.click(
- within(await screen.findByRole('group', { name: 'Email' })).getByRole('button'),
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.email.senderEmail'),
- )
- await user.type(screen.getByLabelText('contacts.imPlatform.email.senderName'), 'Approvals')
- await user.type(screen.getByLabelText('contacts.imPlatform.email.apiKey'), submittedApiKey)
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
-
- expect(await screen.findByText('contacts.imPlatform.email.testSucceeded')).toBeInTheDocument()
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- expect(testConnection).toHaveBeenCalledTimes(1)
- expect(JSON.stringify(queryClient.getMutationCache().getAll())).not.toContain(submittedApiKey)
- })
-
- it.each(['testConnection', 'saveCredentials'] as const)(
- 'displays the provider error code when Email %s fails',
- async (operation) => {
- const user = userEvent.setup()
- const { repository } = renderSurface()
- const message =
- 'The submitted credentials are invalid. Provider error code: restricted_api_key.'
- vi.spyOn(repository, operation).mockRejectedValue(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed, message),
- )
- await user.click(
- within(await screen.findByRole('group', { name: 'Email' })).getByRole('button'),
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.email.senderEmail'),
- )
- await user.type(screen.getByLabelText('contacts.imPlatform.email.senderName'), 'Approvals')
- await user.type(screen.getByLabelText('contacts.imPlatform.email.apiKey'), 'resend-test-key')
- await user.click(
- screen.getByRole('button', {
- name:
- operation === 'testConnection'
- ? 'contacts.imPlatform.action.testConnection'
- : 'contacts.imPlatform.action.save',
- }),
- )
-
- expect(await screen.findByRole('alert')).toHaveTextContent(message)
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- },
+ }),
)
-
- it('saves Email as a configured channel and never exposes the submitted API key', async () => {
- const user = userEvent.setup()
- const { container, repository } = renderSurface()
- const submittedApiKey = 'resend-save-key'
- await user.click(
- within(await screen.findByRole('group', { name: 'Email' })).getByRole('button'),
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.email.senderEmail'),
- )
- await user.type(screen.getByLabelText('contacts.imPlatform.email.senderName'), 'Approvals')
- await user.type(screen.getByLabelText('contacts.imPlatform.email.apiKey'), submittedApiKey)
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.save' }))
-
- expect(await screen.findByText(/contacts\.imPlatform\.email\.summary/)).toBeInTheDocument()
- expect(screen.queryByDisplayValue(submittedApiKey)).not.toBeInTheDocument()
- expect(container.innerHTML).not.toContain(submittedApiKey)
- expect(
- JSON.stringify(await repository.getIntegrations(organization.organizationId)),
- ).not.toContain(submittedApiKey)
- })
-
- it('shows separate accessible Configure and Delete actions for every configured channel', async () => {
- renderSurface({ scenario: ContactImMockScenario.ChannelsConfigured })
-
- for (const provider of ['Email', 'Slack']) {
- const providerCard = await screen.findByRole('group', { name: provider })
-
- expect(
- within(providerCard).getByRole('button', {
- name: /contacts\.imPlatform\.action\.configureChannel/,
- }),
- ).toBeEnabled()
- expect(
- within(providerCard).getByRole('button', {
- name: /contacts\.imPlatform\.action\.deleteChannel/,
- }),
- ).toBeEnabled()
- expect(within(providerCard).getAllByRole('button')).toHaveLength(2)
- }
- })
-
- it('opens the matching configuration form from a configured channel action', async () => {
- const user = userEvent.setup()
- renderSurface({ scenario: ContactImMockScenario.ChannelsConfigured })
- const emailCard = await screen.findByRole('group', { name: 'Email' })
-
- await user.click(
- within(emailCard).getByRole('button', {
- name: /contacts\.imPlatform\.action\.configureChannel/,
- }),
- )
-
- expect(
- screen.getByRole('heading', { name: 'contacts.imPlatform.email.title' }),
- ).toBeInTheDocument()
- expect(screen.getByLabelText('contacts.imPlatform.email.senderEmail')).toHaveValue(
- )
- expect(screen.getByLabelText('contacts.imPlatform.email.apiKey')).toHaveValue('')
- })
-
- it('cancels channel deletion without mutating and restores focus to Delete', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface({ scenario: ContactImMockScenario.ChannelsConfigured })
- const disconnect = vi.spyOn(repository, 'disconnect')
- const emailCard = await screen.findByRole('group', { name: 'Email' })
- const deleteButton = within(emailCard).getByRole('button', {
- name: /contacts\.imPlatform\.action\.deleteChannel/,
- })
-
- await user.click(deleteButton)
- expect(screen.getByRole('alertdialog')).toBeInTheDocument()
- expect(disconnect).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
-
- expect(disconnect).not.toHaveBeenCalled()
- expect(screen.getByRole('group', { name: 'Email' })).toBeInTheDocument()
- await waitFor(() => expect(deleteButton).toHaveFocus())
- })
-
- it('deletes only the confirmed channel and returns it to the connect list', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface({ scenario: ContactImMockScenario.ChannelsConfigured })
- const slackCard = await screen.findByRole('group', { name: 'Slack' })
-
- await user.click(
- within(slackCard).getByRole('button', {
- name: /contacts\.imPlatform\.action\.deleteChannel/,
- }),
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.delete.confirm' }))
-
- await waitFor(async () => {
- const integrations = await repository.getIntegrations(organization.organizationId)
- expect(integrations.some(({ provider }) => provider === ContactImProvider.Slack)).toBe(false)
- })
- expect(
- within(screen.getByRole('group', { name: 'Slack' })).getByRole('button', {
- name: /Slack.*contacts\.imPlatform\.action\.connect/,
- }),
- ).toBeEnabled()
- expect(screen.getByRole('group', { name: 'Email' })).toBeInTheDocument()
- })
-
- it('keeps the channel and confirmation open when deletion fails', async () => {
- const user = userEvent.setup()
- const { repository } = renderSurface({ scenario: ContactImMockScenario.DisconnectFailure })
- const slackCard = await screen.findByRole('group', { name: 'Slack' })
-
- await user.click(
- within(slackCard).getByRole('button', {
- name: /contacts\.imPlatform\.action\.deleteChannel/,
- }),
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.delete.confirm' }))
-
- expect(await screen.findByText('contacts.imPlatform.delete.failed')).toBeInTheDocument()
- expect(screen.getByRole('alertdialog')).toBeInTheDocument()
- expect(
- (await repository.getIntegrations(organization.organizationId)).some(
- ({ provider }) => provider === ContactImProvider.Slack,
- ),
- ).toBe(true)
- })
+ await waitFor(() => expect(calls('/channels/im/channel-1', 'PUT')).toHaveLength(1))
+ const request = calls('/channels/im/channel-1', 'PUT')[0]
+ if (!request) throw new Error('Expected the saved channel request')
+ const payload = await request.json()
+ expect(payload).toMatchObject({
+ credentials: { app_id: 'updated-app', app_secret: { type: 'unchanged' } },
+ expected_config_version: channel.config_version,
+ })
+ await waitFor(() => expect(calls('/channels').length).toBeGreaterThan(1))
+ expect(
+ client.getQueryData(consoleQuery.workspaces.current.humanInput.v2.channels.get.queryKey()),
+ ).toEqual({ channels: [channel] })
})
-describe('Replacing a tenant in the configured IM provider', () => {
- const setupChannel = (provider: 'feishu' | 'slack' = 'feishu') => {
- const client = createChannelClient()
- const current = channelSummary({ provider, id: 'current-channel' })
- const replacement = channelSummary({
- provider,
- id: 'replacement-channel',
- config_version: 'replacement-version',
- webhook_url: 'https://example.test/replacement-callback',
- })
- client.channelProviders.get.mockResolvedValue({
- email_providers: [],
- im_providers: [{ provider, connection_mode: 'custom_app' }],
- })
- client.channels.get.mockResolvedValue({ channels: [current] })
- client.channels.im.byChannelId.get.mockImplementation(async ({ params }) =>
- imDetail(params.channel_id === replacement.id ? replacement : current),
- )
- client.channels.im.byChannelId.put.mockRejectedValue(
- Response.json(
- { code: 'replacement_required', message: 'Explicit replacement required' },
- { status: 409 },
- ),
- )
- client.channels.im.byChannelId.replacement.post.mockImplementation(async () => {
- client.channels.get.mockResolvedValue({ channels: [replacement] })
- return { summary: replacement }
- })
- const repository = createContactImApiRepository(organization, client)
- vi.spyOn(repository, 'getActiveSync').mockResolvedValue(null)
- renderSurface({ repository })
- return { client, current, replacement }
- }
-
- const editFeishuTenant = async (user: ReturnType<typeof userEvent.setup>) => {
- await user.click(
- within(await screen.findByRole('group', { name: 'Feishu' })).getByRole('button', {
- name: /contacts\.imPlatform\.action\.configureChannel/,
- }),
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- await user.clear(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'))
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'new-tenant-app',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
- 'new-tenant-secret',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- }
-
- it('offers explicit same-provider tenant replacement and saves the new channel callback', async () => {
- const user = userEvent.setup()
- const { client, replacement } = setupChannel()
- await editFeishuTenant(user)
-
- expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
- expect(client.channels.im.byChannelId.replacement.post).not.toHaveBeenCalled()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
-
- expect(await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback')).toHaveValue(
- replacement.webhook_url,
- )
- expect(client.channels.im.byChannelId.replacement.post).toHaveBeenCalledExactlyOnceWith(
- {
- params: { channel_id: 'current-channel' },
- body: {
- expected_config_version: 'snapshot-version',
- credentials: {
- provider: 'feishu',
- app_id: 'new-tenant-app',
- app_secret: 'new-tenant-secret',
- encrypt_key: null,
- verification_token: null,
- },
- },
- },
- { context: { silent: true } },
- )
- expect(screen.queryByDisplayValue('new-tenant-secret')).not.toBeInTheDocument()
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledTimes(1)
- })
-
- it('cancels tenant replacement without mutating and saves a corrected same-tenant draft normally', async () => {
- const user = userEvent.setup()
- const { client, current } = setupChannel()
- await editFeishuTenant(user)
- await user.click(
- within(await screen.findByRole('alertdialog')).getByRole('button', {
- name: 'common.operation.cancel',
- }),
- )
-
- expect(client.channels.im.byChannelId.replacement.post).not.toHaveBeenCalled()
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret')).toHaveValue(
- 'new-tenant-secret',
- )
- const appId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')
- await user.clear(appId)
- await user.type(appId, 'corrected-same-tenant-app')
- client.channels.im.byChannelId.put.mockResolvedValue({ summary: current })
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback')).toHaveValue(
- current.webhook_url,
- )
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledTimes(2)
- expect(client.channels.im.byChannelId.replacement.post).not.toHaveBeenCalled()
- })
-
- it('requires complete fresh Slack credentials after confirming replacement and keeps them after a version conflict', async () => {
- const user = userEvent.setup()
- const { client } = setupChannel('slack')
- await user.click(
- within(await screen.findByRole('group', { name: 'Slack' })).getByRole('button', {
- name: /contacts\.imPlatform\.action\.configureChannel/,
- }),
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.botToken'),
- 'new-tenant-bot-token',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- await user.click(
- within(await screen.findByRole('alertdialog')).getByRole('button', {
- name: 'contacts.imPlatform.replacement.confirm',
- }),
- )
-
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret')
- const signingSecret = screen.getByLabelText(
- 'contacts.imPlatform.bindingDialog.field.signingSecret',
- )
- expect(secret).toBeRequired()
- expect(signingSecret).toBeRequired()
- expect(client.channels.im.byChannelId.replacement.post).not.toHaveBeenCalled()
- await user.type(secret, 'new-client-secret')
- await user.type(signingSecret, 'new-signing-secret')
- client.channels.im.byChannelId.replacement.post.mockRejectedValue(
- Response.json(
- { code: 'provider_configuration_updated', message: 'Configuration updated' },
- { status: 409 },
- ),
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- await user.click(
- within(await screen.findByRole('alertdialog')).getByRole('button', {
- name: 'contacts.imPlatform.replacement.confirm',
- }),
- )
+it('keeps corrected credentials after a rejected save', async () => {
+ network.handle.mockImplementation((request) =>
+ request.method === 'PUT'
+ ? json({ code: 'bad_request', message: 'Invalid credentials' }, 400)
+ : defaultResponse(request),
+ )
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ const secret = await within(dialog).findByLabelText(
+ 'contacts.imPlatform.bindingDialog.field.secret',
+ )
+ await user.type(secret, 'retry-secret')
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
+ }),
+ )
+ expect(await within(dialog).findByRole('alert')).toBeInTheDocument()
+ expect(secret).toHaveValue('retry-secret')
+})
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.configurationUpdated',
- )
- expect(secret).toHaveValue('new-client-secret')
- expect(signingSecret).toHaveValue('new-signing-secret')
- expect(client.channels.im.byChannelId.replacement.post).toHaveBeenCalledExactlyOnceWith(
- {
- params: { channel_id: 'current-channel' },
- body: {
- expected_config_version: 'snapshot-version',
- credentials: {
- provider: 'slack',
- client_id: 'client-1',
- client_secret: 'new-client-secret',
- signing_secret: 'new-signing-secret',
- bot_token: 'new-tenant-bot-token',
- app_token: null,
- },
+it('confirms tenant replacement once and includes the saved identity in its title', async () => {
+ network.handle.mockImplementation((request) => {
+ if (request.method === 'PUT')
+ return json(
+ {
+ code: 'replacement_required',
+ message: 'Replace tenant',
+ current_config_version: channel.config_version,
},
- },
- { context: { silent: true } },
- )
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledTimes(1)
+ 409,
+ )
+ if (request.url.endsWith('/replacement')) return json({ summary: channel })
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ const app = await within(dialog).findByLabelText('contacts.imPlatform.bindingDialog.field.appId')
+ await user.clear(app)
+ await user.type(app, 'different-tenant')
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
+ }),
+ )
+ const confirmation = await screen.findByRole('alertdialog')
+ expect(confirmation).toHaveAccessibleName(
+ /contacts\.imPlatform\.bindingDialog\.replaceTenantTitle.*saved-tenant/,
+ )
+ await user.click(
+ within(confirmation).getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
+ )
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ await user.type(
+ within(dialog).getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
+ 'fresh-secret',
+ )
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
+ }),
+ )
+ await waitFor(() => expect(calls('/replacement', 'POST')).toHaveLength(1))
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})
-describe('Contacts IM platform manual sync', () => {
- it('enables manual sync only for a manageable connected provider with directory capability', async () => {
- renderSurface({ scenario: ContactImMockScenario.Connected })
-
- const syncButton = await screen.findByRole('button', {
- name: 'contacts.imPlatform.action.syncNow',
- })
- await waitFor(() => expect(syncButton).toBeEnabled())
+it('clears an unsaved credential session after closing and reopening', async () => {
+ const user = userEvent.setup()
+ renderSurface()
+ const configure = await screen.findByRole('button', {
+ name: /contacts\.imPlatform\.action\.configureChannel/,
})
-
- it.each([[ContactImMockScenario.Configured, 'contacts.imPlatform.sync.notConnected', true]])(
- 'blocks sync for %s and explains why',
- async (scenario, reason, canManage) => {
- renderSurface({ canManage, scenario })
-
- expect(await screen.findByText(reason)).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.syncNow' }),
- ).toBeDisabled()
- },
+ await user.click(configure)
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
)
-
- it('blocks sync when the connected provider lacks directory capability', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const integrations = await repository.getIntegrations(organization.organizationId)
- vi.spyOn(repository, 'getIntegrations').mockResolvedValue(
- integrations.map((integration) => ({
- ...integration,
- capabilities: { directorySync: false },
- })),
- )
- renderSurface({ repository })
-
- expect(await screen.findByText('contacts.imPlatform.sync.unsupported')).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.syncNow' }),
- ).toBeDisabled()
- })
-
- it('restores an existing active run without starting another one', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.ActiveSync,
- })
- const startSync = vi.spyOn(repository, 'startSync')
- renderSurface({ repository })
-
- expect(await screen.findByText('contacts.imPlatform.sync.status.queued')).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.syncing' }),
- ).toBeDisabled()
- expect(startSync).not.toHaveBeenCalled()
- })
-
- it('prevents duplicate sync starts while the mutation is pending', async () => {
- const user = userEvent.setup()
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- let resolveStart: ((value: Awaited<ReturnType<typeof repository.startSync>>) => void) | null =
- null
- const startSyncImplementation = repository.startSync.bind(repository)
- const startSync = vi.spyOn(repository, 'startSync').mockImplementation(async (command) => {
- const run = await startSyncImplementation(command)
- return new Promise((resolve) => {
- resolveStart = resolve
- void run
- })
- })
- renderSurface({ repository })
- const syncButton = await screen.findByRole('button', {
- name: 'contacts.imPlatform.action.syncNow',
- })
-
- await user.click(syncButton)
- expect(syncButton).toHaveAttribute('aria-disabled', 'true')
- await user.click(syncButton)
- expect(startSync).toHaveBeenCalledTimes(1)
-
- await act(async () => resolveStart?.(await repository.getSyncRun('mock-sync-1')))
- })
-
- it('keeps sync retryable after a start failure', async () => {
- const user = userEvent.setup()
- renderSurface({ scenario: ContactImMockScenario.SyncStartFailure })
- const syncButton = await screen.findByRole('button', {
- name: 'contacts.imPlatform.action.syncNow',
- })
- await waitFor(() => expect(syncButton).toBeEnabled())
- await user.click(syncButton)
-
- expect(await screen.findByText('contacts.imPlatform.sync.startFailed')).toBeInTheDocument()
- await waitFor(() => expect(syncButton).toBeEnabled())
- })
-
- it.each([
- [ContactImMockScenario.SyncSuccess, 'contacts.imPlatform.sync.status.success'],
- [ContactImMockScenario.SyncPartialSuccess, 'contacts.imPlatform.sync.status.partial_success'],
- [ContactImMockScenario.SyncFailure, 'contacts.imPlatform.sync.status.failure'],
- ])('presents the latest %s summary', async (scenario, statusLabel) => {
- renderSurface({ scenario })
-
- expect(await screen.findByText(statusLabel)).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.viewDetails' }),
- ).toBeEnabled()
- })
-
- it('restores sync details from sync_run_id and removes it when closed', async () => {
- const user = userEvent.setup()
- mockNavigation.searchParams = new URLSearchParams({
- sync_run_id: 'mock-sync-success',
- })
- renderSurface({ scenario: ContactImMockScenario.SyncSuccess })
-
- expect(
- await screen.findByRole('heading', { name: 'contacts.imPlatform.details.title' }),
- ).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
-
- expect(mockNavigation.replace).toHaveBeenCalledWith('/contacts/settings', { scroll: false })
- })
-
- it('restores focus to the details trigger after closing the overlay', async () => {
- const user = userEvent.setup()
- renderSurface({ scenario: ContactImMockScenario.SyncSuccess })
- const trigger = await screen.findByRole('button', {
- name: 'contacts.imPlatform.action.viewDetails',
- })
- await user.click(trigger)
- expect(await screen.findByRole('dialog')).toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
- await waitFor(() => expect(trigger).toHaveFocus())
- })
+ const app = await within(dialog).findByLabelText('contacts.imPlatform.bindingDialog.field.appId')
+ await user.clear(app)
+ await user.type(app, 'unsaved')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(configure)
+ const reopened = await screen.findByRole('dialog')
+ await user.click(
+ within(reopened).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ expect(
+ await within(reopened).findByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
+ ).toHaveValue('app-1')
})
-describe('Contacts channel credential API contracts', () => {
- const createApiShapeRepository = async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.ChannelsConfigured,
- })
- const definitions = await repository.getProviderDefinitions(organization.organizationId)
- vi.spyOn(repository, 'getProviderDefinitions').mockResolvedValue(
- definitions.map((definition) => ({
- ...definition,
- requiresFreshCredentials: false,
- callbackUrl: null,
- requiredFields:
- definition.provider === ContactImProvider.Slack
- ? [
- { field: ContactImProviderField.ClientId, required: true },
- { field: ContactImProviderField.Secret, required: true, secret: true },
- { field: ContactImProviderField.SigningSecret, required: true, secret: true },
- { field: ContactImProviderField.BotToken, required: true, secret: true },
- { field: ContactImProviderField.AppToken, required: false, secret: true },
- ]
- : definition.provider === ContactImProvider.Feishu
- ? [
- { field: ContactImProviderField.AppId, required: true },
- { field: ContactImProviderField.Secret, required: true, secret: true },
- {
- field: ContactImProviderField.VerificationToken,
- required: false,
- secret: true,
- },
- { field: ContactImProviderField.EncryptKey, required: false, secret: true },
- ]
- : definition.requiredFields,
- })),
- )
- const integrations = (await repository.getIntegrations(organization.organizationId)).map(
- (integration) => ({
- ...integration,
- channelId: `${integration.provider}-channel`,
- configVersion: 'version-at-open',
- configuredFields:
- integration.provider === ContactImProvider.Slack
- ? [
- ContactImProviderField.ClientId,
- ContactImProviderField.Secret,
- ContactImProviderField.SigningSecret,
- ContactImProviderField.BotToken,
- ContactImProviderField.AppToken,
- ]
- : [
- ContactImProviderField.SenderEmail,
- ContactImProviderField.SenderName,
- ContactImProviderField.Secret,
- ],
- callbackUrl:
- integration.provider === ContactImProvider.Slack
- ? 'https://example.dify.test/actual-webhook'
- : null,
- configuredValues:
- integration.provider === ContactImProvider.Email ? integration.configuredValues : {},
- }),
- )
- vi.spyOn(repository, 'getIntegrations').mockResolvedValue(integrations)
- const slack = integrations.find(
- (integration) => integration.provider === ContactImProvider.Slack,
- )
- if (!slack) throw new Error('Configured Slack fixture is required')
- return { repository, slack }
- }
-
- const fillSlackCredentials = async (user: ReturnType<typeof userEvent.setup>) => {
- for (const [field, value] of [
- ['clientId', 'slack-client'],
- ['clientSecret', 'test-client-secret'],
- ['signingSecret', 'test-signing-secret'],
- ['botToken', 'xoxb-test-only'],
- ]) {
- const input = screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`)
- await user.clear(input)
- await user.type(input, value!)
- }
- }
+it('renders Email provider as static text and gives changing actions stable names', async () => {
+ const email = channelSummary({ id: 'channel-email', kind: 'email', provider: 'resend' })
+ network.handle.mockImplementation((request) => {
+ if (request.url.endsWith('/channels')) return json({ channels: [email] })
+ if (request.url.endsWith('/channel-providers')) return json(providers)
+ if (request.url.endsWith('/channels/email/channel-email')) return json(emailDetail(email))
+ return defaultResponse(request)
+ })
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ expect(await within(dialog).findByText('Resend')).toBeVisible()
+ expect(
+ within(dialog).queryByRole('textbox', { name: 'contacts.imPlatform.email.provider' }),
+ ).not.toBeInTheDocument()
+ expect(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.action.save' }),
+ ).toHaveAttribute('aria-labelledby')
+ expect(within(dialog).getByRole('status')).toBeEmptyDOMElement()
+})
- const openConfigured = async (user: ReturnType<typeof userEvent.setup>, provider: string) => {
- await user.click(
- within(await screen.findByRole('group', { name: provider })).getByRole('button', {
- name: /contacts\.imPlatform\.action\.configureChannel/,
- }),
- )
- }
+it('keeps sync action focused while the server run is queued', async () => {
+ network.handle.mockImplementation((request) =>
+ request.method === 'POST' && request.url.endsWith('/im-sync-runs')
+ ? json({ run: syncRun({ status: 'queued', finished_at: null }) })
+ : defaultResponse(request),
+ )
+ const user = userEvent.setup()
+ renderSurface()
+ const button = await screen.findByRole('button', { name: 'contacts.imPlatform.action.syncNow' })
+ await waitFor(() => expect(button).toBeEnabled())
+ await user.click(button)
+ expect(
+ await screen.findByRole('button', { name: 'contacts.imPlatform.action.syncing' }),
+ ).toHaveFocus()
+ expect(button).toHaveAttribute('aria-disabled', 'true')
+})
- const createSavedFeishuRepository = async () => {
- const { repository, slack } = await createApiShapeRepository()
- const feishu = {
- ...slack,
- provider: ContactImProvider.Feishu,
- channelId: 'feishu-channel',
- callbackUrl: 'https://example.dify.test/feishu-webhook',
- configuredValues: { appId: 'saved-feishu-app' },
- configuredFields: [
- ContactImProviderField.AppId,
- ContactImProviderField.Secret,
- ContactImProviderField.VerificationToken,
- ContactImProviderField.EncryptKey,
- ],
- }
- vi.mocked(repository.getIntegrations).mockResolvedValue([feishu])
- return { repository, feishu }
- }
+it('does not invalidate completed sync data merely when opening the surface', async () => {
+ const client = renderSurface()
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
+ await screen.findByRole('button', { name: 'contacts.imPlatform.action.syncNow' })
+ await waitFor(() => expect(calls('/im-sync-runs/latest')).toHaveLength(1))
+ expect(invalidate).not.toHaveBeenCalled()
+})
- it('clears and locks Feishu credential drafts when saving succeeded but loading the saved details failed', async () => {
- const user = userEvent.setup()
- const { repository } = await createSavedFeishuRepository()
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValue(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.SavedDetailsUnavailable),
- )
- const testConnection = vi.spyOn(repository, 'testConnection')
- renderSurface({ repository })
- await openConfigured(user, 'Feishu')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- for (const field of ['secret', 'verificationToken', 'encryptKey'])
- await user.type(
- screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`),
- `saved-${field}`,
- )
- const saveButton = screen.getByRole('button', {
+it('shows a version conflict without offering a destructive tenant replacement', async () => {
+ network.handle.mockImplementation((request) =>
+ request.method === 'PUT'
+ ? json(
+ { code: 'provider_configuration_updated', message: 'Configuration changed', status: 409 },
+ 409,
+ )
+ : defaultResponse(request),
+ )
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ await user.type(
+ await within(dialog).findByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
+ '-changed',
+ )
+ await user.click(
+ within(dialog).getByRole('button', {
name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
- })
- const testButton = screen.getByRole('button', {
- name: 'contacts.imPlatform.action.testConnection',
- })
- await user.click(saveButton)
-
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.savedDetailsUnavailable',
- )
- expect(
- screen.queryByText('contacts.imPlatform.bindingDialog.saveFailed'),
- ).not.toBeInTheDocument()
- for (const field of ['secret', 'verificationToken', 'encryptKey']) {
- const input = screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`)
- expect(input).toHaveValue('')
- expect(input).toBeDisabled()
- }
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')).toBeDisabled()
- expect(saveButton).toBeDisabled()
- expect(testButton).toBeDisabled()
- await user.click(saveButton)
- await user.click(testButton)
- expect(save).toHaveBeenCalledTimes(1)
- expect(testConnection).not.toHaveBeenCalled()
- expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeEnabled()
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- })
+ }),
+ )
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.configurationUpdated',
+ )
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ expect(calls('/replacement', 'POST')).toHaveLength(0)
+})
- it('clears and locks the Email API key after saving when the saved channel details are unavailable', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValue(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.SavedDetailsUnavailable),
- )
- const testConnection = vi.spyOn(repository, 'testConnection')
- renderSurface({ repository })
- await openConfigured(user, 'Email')
- const apiKey = screen.getByLabelText('contacts.imPlatform.email.apiKey')
- await user.type(apiKey, 'already-persisted-resend-key')
- const saveButton = screen.getByRole('button', { name: 'contacts.imPlatform.action.save' })
- const testButton = screen.getByRole('button', {
- name: 'contacts.imPlatform.action.testConnection',
- })
- await user.click(saveButton)
+it('allows starting the first sync after the generated latest endpoint returns 404', async () => {
+ network.handle.mockImplementation((request) =>
+ request.url.endsWith('/latest')
+ ? json({ code: 'not_found', message: 'No sync yet' }, 404)
+ : defaultResponse(request),
+ )
+ renderSurface()
+ const button = await screen.findByRole('button', { name: 'contacts.imPlatform.action.syncNow' })
+ await waitFor(() => expect(button).toBeEnabled())
+ expect(await screen.findByText('contacts.imPlatform.sync.noRuns')).toBeVisible()
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+})
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.savedDetailsUnavailable',
- )
- expect(apiKey).toHaveValue('')
- for (const field of ['apiKey', 'senderEmail', 'senderName'])
- expect(screen.getByLabelText(`contacts.imPlatform.email.${field}`)).toBeDisabled()
- expect(saveButton).toBeDisabled()
- expect(testButton).toBeDisabled()
- await user.click(saveButton)
- await user.click(testButton)
- expect(save).toHaveBeenCalledTimes(1)
- expect(testConnection).not.toHaveBeenCalled()
- expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeEnabled()
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- })
+it('refreshes related generated caches on an actual running-to-terminal transition', async () => {
+ const client = renderSurface()
+ await screen.findByRole('button', { name: 'contacts.imPlatform.action.viewDetails' })
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
+ const latestKey = consoleQuery.workspaces.current.humanInput.v2.imSyncRuns.latest.get.queryKey()
+ await act(async () => {
+ client.setQueryData(latestKey, {
+ run: syncRun({ id: 'new-run', status: 'running', finished_at: null }),
+ })
+ })
+ await screen.findByRole('button', { name: 'contacts.imPlatform.action.syncing' })
+ expect(invalidate).not.toHaveBeenCalled()
+ await act(async () => {
+ client.setQueryData(latestKey, { run: syncRun({ id: 'new-run', status: 'succeeded' }) })
+ })
+ await waitFor(() =>
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: consoleQuery.workspaces.current.humanInput.v2.contacts.key(),
+ }),
+ )
+})
- it('explains a different-organization credential conflict and preserves the editable draft', async () => {
- const user = userEvent.setup()
- const { repository, feishu } = await createSavedFeishuRepository()
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValueOnce(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.ReplacementRequired),
- )
- .mockResolvedValue(feishu)
- renderSurface({ repository })
- await openConfigured(user, 'Feishu')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- const appId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret')
- await user.clear(appId)
- await user.type(appId, 'different-organization-app')
- await user.type(secret, 'correctable-app-secret')
- const saveButton = screen.getByRole('button', {
+it('continues to saved callbacks without rewriting unchanged credentials', async () => {
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ await user.click(
+ await within(dialog).findByRole('button', {
name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
- })
- await user.click(saveButton)
-
- await user.click(
- within(await screen.findByRole('alertdialog')).getByRole('button', {
- name: 'common.operation.cancel',
- }),
- )
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.replacementRequired',
- )
- expect(screen.queryByText('contacts.imPlatform.configurationUpdated')).not.toBeInTheDocument()
- expect(appId).toHaveValue('different-organization-app')
- expect(appId).toBeEnabled()
- expect(secret).toHaveValue('correctable-app-secret')
- expect(secret).toBeEnabled()
- expect(saveButton).toBeEnabled()
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- ).toBeEnabled()
- await user.clear(appId)
- await user.type(appId, 'corrected-organization-app')
- await user.click(saveButton)
-
- expect(
- await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback'),
- ).toBeInTheDocument()
- expect(save).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- secret: 'correctable-app-secret',
- values: { appId: 'corrected-organization-app' },
- }),
- )
- })
-
- it('tests and retries a saved Feishu token update without requesting its unchanged App Secret', async () => {
- const user = userEvent.setup()
- const { repository, feishu } = await createSavedFeishuRepository()
- const testConnection = vi.spyOn(repository, 'testConnection').mockResolvedValue(feishu)
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValueOnce(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed),
- )
- .mockResolvedValue(feishu)
- renderSurface({ repository })
- await openConfigured(user, 'Feishu')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret')
- const token = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.verificationToken')
- expect(secret).toHaveValue('')
- expect(secret).not.toBeRequired()
- expect(screen.getAllByText('contacts.imPlatform.bindingDialog.secretConfigured')).toHaveLength(
- 3,
- )
- await user.type(token, 'rotated-verification-token')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
-
- expect(await screen.findByText('contacts.imPlatform.email.testSucceeded')).toBeInTheDocument()
- const expectedUpdate = expect.objectContaining({
- provider: ContactImProvider.Feishu,
- channelId: 'feishu-channel',
- expectedConfigVersion: 'version-at-open',
- values: { appId: 'saved-feishu-app', verificationToken: 'rotated-verification-token' },
- })
- expect(testConnection).toHaveBeenCalledExactlyOnceWith(expectedUpdate)
- expect(testConnection.mock.calls[0]?.[0]?.secret).toBeUndefined()
- expect(testConnection.mock.calls[0]?.[0]).not.toHaveProperty('retainSecret')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.saveFailed',
- )
- expect(token).toHaveValue('rotated-verification-token')
- expect(secret).toHaveValue('')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback')).toHaveValue(
- feishu.callbackUrl,
- )
- expect(save).toHaveBeenNthCalledWith(2, expectedUpdate)
- expect(save.mock.calls[1]?.[0]?.secret).toBeUndefined()
- expect(save.mock.calls[1]?.[0]).not.toHaveProperty('retainSecret')
- })
-
- it('marks an optional saved credential for clearing and sends an explicit clear only on save', async () => {
- const user = userEvent.setup()
- const { repository, feishu } = await createSavedFeishuRepository()
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValueOnce(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed),
- )
- .mockResolvedValue(feishu)
- renderSurface({ repository })
- await openConfigured(user, 'Feishu')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- const token = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.verificationToken')
- await user.click(
- screen.getByRole('button', { name: /field\.verificationToken.*clearSavedCredential/ }),
- )
-
- expect(token).toBeDisabled()
- expect(
- screen.getByText('contacts.imPlatform.bindingDialog.credentialWillBeCleared'),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: /field\.verificationToken.*undoClearCredential/ }),
- ).toBeEnabled()
- expect(
- screen.queryByRole('button', { name: /field\.secret.*clearSavedCredential/ }),
- ).not.toBeInTheDocument()
- expect(save).not.toHaveBeenCalled()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.saveFailed',
- )
- expect(token).toBeDisabled()
- expect(
- screen.getByRole('button', { name: /field\.verificationToken.*undoClearCredential/ }),
- ).toBeEnabled()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(
- await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback'),
- ).toBeInTheDocument()
- expect(save).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- channelId: 'feishu-channel',
- expectedConfigVersion: 'version-at-open',
- clearedFields: [ContactImProviderField.VerificationToken],
- values: expect.objectContaining({ appId: 'saved-feishu-app' }),
- }),
- )
- expect(save.mock.calls[0]?.[0]?.secret).toBeUndefined()
- })
-
- it('undoes a pending clear and allows replacing that optional saved credential', async () => {
- const user = userEvent.setup()
- const { repository, feishu } = await createSavedFeishuRepository()
- const save = vi.spyOn(repository, 'saveCredentials').mockResolvedValue(feishu)
- renderSurface({ repository })
- await openConfigured(user, 'Feishu')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- const token = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.verificationToken')
- await user.click(
- screen.getByRole('button', { name: /field\.verificationToken.*clearSavedCredential/ }),
- )
- await user.click(
- screen.getByRole('button', { name: /field\.verificationToken.*undoClearCredential/ }),
- )
-
- expect(token).toBeEnabled()
- expect(token).toHaveValue('')
- expect(
- screen.queryByText('contacts.imPlatform.bindingDialog.credentialWillBeCleared'),
- ).not.toBeInTheDocument()
- expect(save).not.toHaveBeenCalled()
- await user.type(token, 'replacement-after-undo')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(
- await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback'),
- ).toBeInTheDocument()
- expect(save).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({
- clearedFields: [],
- values: { appId: 'saved-feishu-app', verificationToken: 'replacement-after-undo' },
- }),
- )
- })
-
- it('still requires every mandatory credential when creating a Slack channel', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- vi.mocked(repository.getIntegrations).mockResolvedValue([])
- const save = vi.spyOn(repository, 'saveCredentials')
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- for (const field of ['clientId', 'clientSecret', 'signingSecret', 'botToken'])
- expect(
- screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`),
- ).toBeRequired()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(save).not.toHaveBeenCalled()
- expect(screen.getAllByText('contacts.imPlatform.bindingDialog.required')).toHaveLength(4)
- })
-
- it('uses legacy secretConfigured only for the primary secret when field metadata is absent', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const integrations = await repository.getIntegrations(organization.organizationId)
- vi.mocked(repository.getIntegrations).mockResolvedValue(
- integrations.map((integration) => ({ ...integration, configuredFields: undefined })),
- )
- renderSurface({ repository })
- await openConfigured(user, 'Slack')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
-
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- ).not.toBeRequired()
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.signingSecret'),
- ).toBeRequired()
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.botToken')).toBeRequired()
- expect(
- screen.getByText('contacts.imPlatform.bindingDialog.secretConfigured'),
- ).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /clearSavedCredential/ })).not.toBeInTheDocument()
- })
-
- it('still requires a new App Secret when replacing Slack with Feishu', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const save = vi.spyOn(repository, 'saveCredentials')
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /Feishu.*replace/i }))
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret')).toBeRequired()
- expect(
- screen.queryByText('contacts.imPlatform.bindingDialog.secretConfigured'),
- ).not.toBeInTheDocument()
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'replacement-feishu-app',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(save).not.toHaveBeenCalled()
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
- ).toHaveAccessibleDescription('contacts.imPlatform.bindingDialog.required')
- })
-
- it('updates Email sender details with a blank API key and captures its saved channel version', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const email = (await repository.getIntegrations(organization.organizationId)).find(
- (integration) => integration.provider === ContactImProvider.Email,
- )
- if (!email) throw new Error('Configured Email fixture is required')
- const save = vi.spyOn(repository, 'saveCredentials').mockResolvedValue(email)
- renderSurface({ repository })
- await openConfigured(user, 'Email')
- const senderEmail = screen.getByLabelText('contacts.imPlatform.email.senderEmail')
- const senderName = screen.getByLabelText('contacts.imPlatform.email.senderName')
- expect(senderEmail).not.toBeRequired()
- expect(screen.getByLabelText('contacts.imPlatform.email.apiKey')).not.toBeRequired()
- await user.clear(senderEmail)
- await user.clear(senderName)
- await user.type(senderName, 'Renamed sender')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.save' }))
+ }),
+ )
+ expect(
+ await within(dialog).findByLabelText('contacts.imPlatform.bindingDialog.callback'),
+ ).toHaveValue(channel.webhook_url)
+ expect(calls('/channels/im/channel-1', 'PUT')).toHaveLength(0)
+})
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(save).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({
- provider: ContactImProvider.Email,
- channelId: 'email-channel',
- expectedConfigVersion: 'version-at-open',
- clearedFields: [],
- values: { senderEmail: '', senderName: 'Renamed sender' },
- }),
- )
- expect(save.mock.calls[0]?.[0]?.secret).toBeUndefined()
- expect(save.mock.calls[0]?.[0]).not.toHaveProperty('retainSecret')
- })
+it('does not retain failed-save secrets in Query mutation variables', async () => {
+ network.handle.mockImplementation((request) =>
+ request.method === 'PUT'
+ ? json({ code: 'bad_request', message: 'Invalid credentials' }, 400)
+ : defaultResponse(request),
+ )
+ const user = userEvent.setup()
+ const client = renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ await user.type(
+ await within(dialog).findByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
+ 'private-retry-secret',
+ )
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
+ }),
+ )
+ await within(dialog).findByRole('alert')
+ expect(
+ JSON.stringify(
+ client
+ .getMutationCache()
+ .getAll()
+ .map((mutation) => mutation.state.variables),
+ ),
+ ).not.toContain('private-retry-secret')
+})
- it('uses the saved channel callback and reopens it without re-entering credentials', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const saved = {
- ...slack,
- channelId: 'new-slack-channel',
- configVersion: 'new-slack-version',
- callbackUrl: 'https://backend.example/callbacks/human-input/v2/im/new-slack-hook',
+it('tests a new IM channel before creating it with the entered credentials', async () => {
+ let saved = false
+ network.handle.mockImplementation((request) => {
+ if (request.url.endsWith('/channels')) return json({ channels: saved ? [channel] : [] })
+ if (request.method === 'POST' && request.url.endsWith('/channels/im/test'))
+ return json({ status: 'connected', status_description: 'Credentials verified' })
+ if (request.method === 'POST' && request.url.endsWith('/channels/im')) {
+ saved = true
+ return json({ summary: channel })
}
- const getIntegrations = vi.mocked(repository.getIntegrations).mockResolvedValue([])
- const save = vi.spyOn(repository, 'saveCredentials').mockImplementation(async () => {
- getIntegrations.mockResolvedValue([saved])
- return saved
- })
- const testConnection = vi.spyOn(repository, 'testConnection').mockResolvedValue(saved)
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /Slack.*connect/i }))
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- ).not.toBeInTheDocument()
- await fillSlackCredentials(user)
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- await user.click(
- await screen.findByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- )
- expect(copy).toHaveBeenLastCalledWith(saved.callbackUrl)
- const callback = screen.getByLabelText('contacts.imPlatform.bindingDialog.callback')
- expect(callback).toHaveValue(saved.callbackUrl)
- expect(callback).toHaveAttribute('readonly')
- expect(
- screen.queryByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- ).not.toBeInTheDocument()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
- )
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
-
- await openConfigured(user, 'Slack')
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
- ).toBeInTheDocument()
- expect(
- screen.queryByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- ).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- ).toHaveValue('')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
- expect(testConnection).toHaveBeenCalledWith(
- expect.objectContaining({
- channelId: saved.channelId,
- expectedConfigVersion: saved.configVersion,
- provider: ContactImProvider.Slack,
- }),
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
- ).toBeInTheDocument()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- )
- expect(copy).toHaveBeenLastCalledWith(saved.callbackUrl)
- expect(save).toHaveBeenCalledTimes(1)
- expect(testConnection).toHaveBeenCalledTimes(1)
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: 'Feishu — contacts.imPlatform.action.connect' }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.type(
+ within(dialog).getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
+ 'new-app',
+ )
+ await user.type(
+ within(dialog).getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
+ 'new-secret',
+ )
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
+ )
+ await waitFor(() =>
+ expect(within(dialog).getByRole('status')).toHaveTextContent(
+ 'contacts.imPlatform.email.testSucceeded',
+ ),
+ )
+ expect(calls('/channels/im', 'POST')).toHaveLength(0)
+ const test = calls('/channels/im/test', 'POST')[0]
+ if (!test) throw new Error('Expected a generated channel test request')
+ const payload = {
+ credentials: {
+ provider: 'feishu',
+ app_id: 'new-app',
+ app_secret: 'new-secret',
+ verification_token: null,
+ encrypt_key: null,
+ },
+ }
+ expect(await test.json()).toEqual(payload)
- it('updates the newly replaced channel when returning from callbacks to edit credentials', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const saved = {
- ...slack,
- provider: ContactImProvider.Feishu,
- channelId: 'replacement-feishu-channel',
- configVersion: 'feishu-version-1',
- displayIdentifier: 'cli_replacement',
- configuredValues: { appId: 'cli_replacement' },
- configuredFields: [ContactImProviderField.AppId, ContactImProviderField.Secret],
- callbackUrl: 'https://backend.example/callbacks/human-input/v2/im/feishu-only-hook',
- }
- const getIntegrations = vi.mocked(repository.getIntegrations)
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockImplementationOnce(async () => {
- getIntegrations.mockResolvedValue([saved])
- return saved
- })
- .mockResolvedValue({ ...saved, configVersion: 'feishu-version-2' })
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /Feishu.*replace/i }))
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'cli_replacement',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
- 'first-app-secret',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- await user.click(
- await screen.findByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- )
- expect(copy).toHaveBeenLastCalledWith(saved.callbackUrl)
- expect(save).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- channelId: 'slack-channel',
- expectedConfigVersion: 'version-at-open',
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: true,
- }),
- )
-
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')).toHaveValue(
- 'cli_replacement',
- )
- const secret = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret')
- expect(secret).toHaveValue('')
- expect(secret).not.toBeRequired()
- const appId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')
- await user.clear(appId)
- await user.type(appId, 'cli_replacement_updated')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(
- await screen.findByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
- ).toBeInTheDocument()
- expect(save).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- channelId: saved.channelId,
- expectedConfigVersion: saved.configVersion,
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: false,
- values: { appId: 'cli_replacement_updated' },
- }),
- )
- expect(save.mock.calls[1]?.[0]?.secret).toBeUndefined()
- expect(save.mock.calls[1]?.[0]).not.toHaveProperty('retainSecret')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- )
- expect(copy).toHaveBeenLastCalledWith(saved.callbackUrl)
- })
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
+ }),
+ )
+ await waitFor(() => expect(calls('/channels/im', 'POST')).toHaveLength(1))
+ expect(await calls('/channels/im', 'POST')[0]!.json()).toEqual(payload)
+ await waitFor(() => expect(calls('/channels/im/channel-1')).toHaveLength(1))
+ expect(
+ await within(dialog).findByLabelText('contacts.imPlatform.bindingDialog.callback'),
+ ).toHaveValue(channel.webhook_url)
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
+ )
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(await screen.findByRole('group', { name: 'Feishu' })).toHaveTextContent('saved-tenant')
+})
- it('keeps a channel with no returned callback on the single-step save flow', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const saved = {
- ...slack,
- provider: ContactImProvider.DingTalk,
- channelId: 'dingtalk-channel',
- callbackUrl: null,
+it('keeps credentials editable after a failed connection test and retries without saving', async () => {
+ let verified = false
+ network.handle.mockImplementation((request) => {
+ if (request.method === 'POST' && request.url.endsWith('/channels/im/channel-1/test')) {
+ if (!verified)
+ return json({
+ status: 'invalid_credentials',
+ status_description: 'The app secret was rejected',
+ })
+ return json({ status: 'connected', status_description: 'Connected' })
}
- const save = vi.spyOn(repository, 'saveCredentials').mockResolvedValue(saved)
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /DingTalk.*replace/i }))
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- ).not.toBeInTheDocument()
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientId'),
- 'dingtalk-client',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientSecret'),
- 'dingtalk-secret',
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.connect' }))
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(save).toHaveBeenCalledTimes(1)
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
- ).not.toBeInTheDocument()
+ return defaultResponse(request)
})
-
- it('edits a saved Slack channel without a webhook using the single-step credential form', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const savedWithoutWebhook = { ...slack, callbackUrl: null }
- const integrations = await repository.getIntegrations(organization.organizationId)
- vi.mocked(repository.getIntegrations).mockResolvedValue(
- integrations.map((integration) =>
- integration.provider === ContactImProvider.Slack ? savedWithoutWebhook : integration,
- ),
- )
- const save = vi.spyOn(repository, 'saveCredentials').mockResolvedValue(savedWithoutWebhook)
- renderSurface({ repository })
- await openConfigured(user, 'Slack')
-
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByText('contacts.imPlatform.bindingDialog.callbackStep'),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByText('contacts.imPlatform.bindingDialog.credentialsStep'),
- ).not.toBeInTheDocument()
- await fillSlackCredentials(user)
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.save' }))
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(save).toHaveBeenCalledWith(
- expect.objectContaining({
- channelId: slack.channelId,
- expectedConfigVersion: slack.configVersion,
- replaceActiveProvider: false,
- }),
- )
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ const secret = await within(dialog).findByLabelText(
+ 'contacts.imPlatform.bindingDialog.field.secret',
+ )
+ await user.type(secret, 'rejected-secret')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
+ )
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent('The app secret was rejected')
+ expect(secret).toHaveValue('rejected-secret')
+ expect(secret).toBeEnabled()
+ verified = true
+ await user.clear(secret)
+ await user.type(secret, 'corrected-secret')
+ expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument()
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
+ )
+ await waitFor(() =>
+ expect(within(dialog).getByRole('status')).toHaveTextContent(
+ 'contacts.imPlatform.email.testSucceeded',
+ ),
+ )
+ const requests = calls('/channels/im/channel-1/test', 'POST')
+ expect(requests).toHaveLength(2)
+ expect(await requests[1]!.json()).toMatchObject({
+ expected_config_version: channel.config_version,
+ credentials: { provider: 'feishu', app_secret: 'corrected-secret' },
})
+ expect(calls('/channels/im/channel-1', 'PUT')).toHaveLength(0)
+})
- it('updates one saved Slack secret while retaining the other masked credentials', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const save = vi.spyOn(repository, 'saveCredentials').mockResolvedValue(slack)
- renderSurface({ repository })
- await openConfigured(user, 'Slack')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- expect(
- screen.queryByText('contacts.imPlatform.bindingDialog.freshCredentials'),
- ).not.toBeInTheDocument()
- expect(screen.getAllByText('contacts.imPlatform.bindingDialog.secretConfigured')).toHaveLength(
- 4,
- )
- for (const field of ['clientSecret', 'signingSecret', 'botToken', 'appToken']) {
- const input = screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`)
- expect(input).toHaveAttribute('type', 'password')
- expect(input).toHaveValue('')
- expect(input).not.toBeRequired()
+it('clears secrets and prevents duplicate writes when a successful save cannot reload its redacted details', async () => {
+ let saved = false
+ network.handle.mockImplementation((request) => {
+ if (request.method === 'PUT') {
+ saved = true
+ return json({ summary: channel })
}
- expect(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appToken'),
- ).not.toBeRequired()
- expect(
- screen.getByRole('button', { name: /field\.appToken.*clearSavedCredential/ }),
- ).toBeEnabled()
- expect(screen.getAllByRole('button', { name: /clearSavedCredential/ })).toHaveLength(1)
- const clientId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.clientId')
- expect(clientId).not.toBeRequired()
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.signingSecret'),
- 'rotated-signing-secret',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(
- await screen.findByRole('button', { name: 'contacts.imPlatform.bindingDialog.finish' }),
- ).toBeInTheDocument()
- expect(screen.queryByDisplayValue('rotated-signing-secret')).not.toBeInTheDocument()
- expect(save).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- channelId: 'slack-channel',
- expectedConfigVersion: 'version-at-open',
- replaceActiveProvider: false,
- values: { signingSecret: 'rotated-signing-secret' },
- }),
- )
- expect(save.mock.calls[0]?.[0]?.secret).toBeUndefined()
- expect(save.mock.calls[0]?.[0]).not.toHaveProperty('retainSecret')
- })
-
- it('uses the server webhook and never reports a failed connection test as success', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const testConnection = vi
- .spyOn(repository, 'testConnection')
- .mockRejectedValueOnce(
- new ContactImRepositoryError(
- ContactImRepositoryErrorCode.MutationFailed,
- 'Provider error code: missing_scope. Missing permissions: users:read.email.',
- ),
- )
- .mockResolvedValue(slack)
- const save = vi.spyOn(repository, 'saveCredentials')
- renderSurface({ repository })
- await openConfigured(user, 'Slack')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.copyCallback' }),
- )
- expect(copy).toHaveBeenCalledWith('https://example.dify.test/actual-webhook')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- await fillSlackCredentials(user)
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'Provider error code: missing_scope. Missing permissions: users:read.email.',
- )
- expect(screen.queryByText('contacts.imPlatform.email.testSucceeded')).not.toBeInTheDocument()
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- expect(save).not.toHaveBeenCalled()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
- expect(await screen.findByText('contacts.imPlatform.email.testSucceeded')).toBeInTheDocument()
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appToken'),
- 'xapp-test-only',
- )
- expect(screen.queryByText('contacts.imPlatform.email.testSucceeded')).not.toBeInTheDocument()
- expect(testConnection).toHaveBeenCalledTimes(2)
+ if (saved && request.url.endsWith('/channels/im/channel-1'))
+ return json({ code: 'internal_server_error', message: 'Details unavailable' }, 500)
+ return defaultResponse(request)
+ })
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ const secret = await within(dialog).findByLabelText(
+ 'contacts.imPlatform.bindingDialog.field.secret',
+ )
+ await user.type(secret, 'saved-secret')
+ const save = within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
})
+ await user.click(save)
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.bindingDialog.savedDetailsUnavailable',
+ )
+ expect(secret).toHaveValue('')
+ expect(secret).toBeDisabled()
+ expect(save).toBeDisabled()
+ expect(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
+ ).toBeDisabled()
+ await user.click(save)
+ expect(calls('/channels/im/channel-1', 'PUT')).toHaveLength(1)
+})
- it('keeps replacement inputs when the captured configuration conflicts', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValue(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated),
- )
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /Feishu.*replace/i }))
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'),
- 'replacement-app',
- )
- await user.type(
- screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret'),
- 'replacement-secret',
- )
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
- expect(await screen.findByText('contacts.imPlatform.configurationUpdated')).toBeInTheDocument()
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- expect(save).toHaveBeenCalledWith(
- expect.objectContaining({
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: true,
- channelId: 'slack-channel',
- expectedConfigVersion: 'version-at-open',
- }),
- )
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')).toHaveValue(
- 'replacement-app',
- )
- expect(screen.getByLabelText('contacts.imPlatform.bindingDialog.field.secret')).toHaveValue(
- 'replacement-secret',
- )
- })
+it('keeps an IM draft after management permission is revoked without displaying server diagnostics', async () => {
+ network.handle.mockImplementation((request) =>
+ request.method === 'PUT'
+ ? json({ code: 'forbidden', message: 'Internal workspace permission diagnostics' }, 403)
+ : defaultResponse(request),
+ )
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ }),
+ )
+ const dialog = await screen.findByRole('dialog')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }),
+ )
+ const secret = await within(dialog).findByLabelText(
+ 'contacts.imPlatform.bindingDialog.field.secret',
+ )
+ await user.type(secret, 'unsaved-secret')
+ await user.click(
+ within(dialog).getByRole('button', {
+ name: 'contacts.imPlatform.bindingDialog.saveAndContinue',
+ }),
+ )
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.bindingDialog.saveFailed',
+ )
+ expect(
+ within(dialog).queryByText('Internal workspace permission diagnostics'),
+ ).not.toBeInTheDocument()
+ expect(secret).toHaveValue('unsaved-secret')
+ expect(secret).toBeEnabled()
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+})
- it('retries Feishu credentials after a failed save without re-entering secret fields', async () => {
- const user = userEvent.setup()
- const { repository, slack } = await createApiShapeRepository()
- const callbackUrl = 'https://backend.example/callbacks/human-input/v2/im/retried-feishu'
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValueOnce(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed),
- )
- .mockResolvedValue({
- ...slack,
- provider: ContactImProvider.Feishu,
- channelId: 'retried-feishu-channel',
- configVersion: 'retried-feishu-version',
- callbackUrl,
- })
- renderSurface({ repository })
- await user.click(await screen.findByRole('button', { name: /Feishu.*replace/i }))
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.replacement.confirm' }),
- )
- const appId = screen.getByLabelText('contacts.imPlatform.bindingDialog.field.appId')
- await user.type(appId, 'incorrect-app')
- const secretInputs = [
- ['secret', 'retained-app-secret'],
- ['verificationToken', 'retained-verification-token'],
- ['encryptKey', 'retained-encrypt-key'],
- ] as const
- for (const [field, value] of secretInputs) {
- const input = screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`)
- await user.type(input, value)
- expect(input).toHaveAttribute('type', 'password')
+it('retains a channel after a conflicted deletion and retries with the automatically refreshed version', async () => {
+ let version = channel.config_version
+ let removed = false
+ let attempts = 0
+ network.handle.mockImplementation((request) => {
+ const url = new URL(request.url)
+ if (url.pathname.endsWith('/channels'))
+ return json({ channels: removed ? [] : [{ ...channel, config_version: version }] })
+ if (request.method === 'DELETE' && url.pathname.endsWith('/channels/im/channel-1')) {
+ attempts++
+ if (attempts === 1) {
+ version = 'updated-config-version'
+ return json({ code: 'provider_configuration_updated', message: 'Channel changed' }, 409)
+ }
+ removed = true
+ return json({ channel_id: channel.id })
}
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.saveFailed',
- )
- for (const [field, value] of secretInputs)
- expect(screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`)).toHaveValue(
- value,
- )
-
- await user.clear(appId)
- await user.type(appId, 'corrected-app')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.saveAndContinue' }),
- )
-
- expect(await screen.findByLabelText('contacts.imPlatform.bindingDialog.callback')).toHaveValue(
- callbackUrl,
- )
- expect(save).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- provider: ContactImProvider.Feishu,
- secret: 'retained-app-secret',
- values: {
- appId: 'corrected-app',
- verificationToken: 'retained-verification-token',
- encryptKey: 'retained-encrypt-key',
- },
- }),
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }))
- for (const [field] of secretInputs)
- expect(screen.getByLabelText(`contacts.imPlatform.bindingDialog.field.${field}`)).toHaveValue(
- '',
- )
- })
-
- it('retries a failed Email save with the entered API key and clears it after saving', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValueOnce(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed),
- )
- renderSurface({ repository })
- await openConfigured(user, 'Email')
- const apiKey = screen.getByLabelText('contacts.imPlatform.email.apiKey')
- const senderName = screen.getByLabelText('contacts.imPlatform.email.senderName')
- await user.type(apiKey, 'retained-resend-key')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.save' }))
-
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'contacts.imPlatform.bindingDialog.saveFailed',
- )
- expect(apiKey).toHaveValue('retained-resend-key')
- expect(apiKey).toHaveAttribute('type', 'password')
- await user.clear(senderName)
- await user.type(senderName, 'Corrected sender')
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.save' }))
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(save).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- provider: ContactImProvider.Email,
- secret: 'retained-resend-key',
- values: { senderEmail: '[email protected]', senderName: 'Corrected sender' },
- }),
- )
- await openConfigured(user, 'Email')
- expect(screen.getByLabelText('contacts.imPlatform.email.apiKey')).toHaveValue('')
- })
-
- it('passes the delete version and keeps confirmation open when the channel changed', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const disconnect = vi
- .spyOn(repository, 'disconnect')
- .mockRejectedValue(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated),
- )
- renderSurface({ repository })
- await user.click(
- within(await screen.findByRole('group', { name: 'Slack' })).getByRole('button', {
- name: /contacts\.imPlatform\.action\.deleteChannel/,
- }),
- )
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.delete.confirm' }))
- expect(await screen.findByText('contacts.imPlatform.configurationUpdated')).toBeInTheDocument()
- expect(screen.getByRole('alertdialog')).toBeInTheDocument()
- expect(disconnect).toHaveBeenCalledWith({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- channelId: 'slack-channel',
- expectedConfigVersion: 'version-at-open',
- })
- })
-
- it('tests saved Email credentials in channel context and keeps drafts after a failed test', async () => {
- const user = userEvent.setup()
- const { repository } = await createApiShapeRepository()
- const testConnection = vi
- .spyOn(repository, 'testConnection')
- .mockRejectedValue(new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed))
- renderSurface({ repository })
- await openConfigured(user, 'Email')
- const apiKey = screen.getByLabelText('contacts.imPlatform.email.apiKey')
- expect(apiKey).not.toBeRequired()
- expect(apiKey).toHaveValue('')
- expect(screen.getByLabelText('contacts.imPlatform.email.senderName')).not.toBeRequired()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
- expect(
- await screen.findByText('contacts.imPlatform.bindingDialog.testFailed'),
- ).toBeInTheDocument()
- expect(testConnection).toHaveBeenCalledWith(
- expect.objectContaining({
- provider: ContactImProvider.Email,
- channelId: 'email-channel',
- expectedConfigVersion: 'version-at-open',
- values: { senderEmail: '[email protected]', senderName: 'Acme' },
- }),
- )
- expect(testConnection.mock.calls[0]?.[0]?.secret).toBeUndefined()
- expect(testConnection.mock.calls[0]?.[0]).not.toHaveProperty('retainSecret')
- await user.type(apiKey, 'resend-test-only')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.action.testConnection' }),
- )
- expect(
- await screen.findByText('contacts.imPlatform.bindingDialog.testFailed'),
- ).toBeInTheDocument()
- expect(screen.queryByText('contacts.imPlatform.email.testSucceeded')).not.toBeInTheDocument()
- expect(apiKey).toHaveValue('resend-test-only')
- expect(screen.getByLabelText('contacts.imPlatform.email.senderEmail')).toHaveValue(
- )
- expect(testConnection).toHaveBeenCalledWith(
- expect.objectContaining({
- channelId: 'email-channel',
- expectedConfigVersion: 'version-at-open',
- secret: 'resend-test-only',
- values: { senderEmail: '[email protected]', senderName: 'Acme' },
- }),
- )
-
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- await openConfigured(user, 'Email')
- expect(screen.getByLabelText('contacts.imPlatform.email.apiKey')).toHaveValue('')
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderSurface()
+ await user.click(
+ await screen.findByRole('button', { name: /contacts\.imPlatform\.action\.deleteChannel/ }),
+ )
+ const first = await screen.findByRole('alertdialog')
+ await user.click(
+ within(first).getByRole('button', { name: 'contacts.imPlatform.delete.confirm' }),
+ )
+ expect(await within(first).findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.configurationUpdated',
+ )
+ await user.click(within(first).getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(screen.getByRole('group', { name: 'Feishu' })).toHaveTextContent('saved-tenant')
+ await user.click(
+ screen.getByRole('button', { name: /contacts\.imPlatform\.action\.deleteChannel/ }),
+ )
+ const retry = await screen.findByRole('alertdialog')
+ await user.click(
+ within(retry).getByRole('button', { name: 'contacts.imPlatform.delete.confirm' }),
+ )
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(
+ await screen.findByRole('button', { name: 'Feishu — contacts.imPlatform.action.connect' }),
+ ).toBeInTheDocument()
+ expect(screen.getByRole('group', { name: 'Feishu' })).not.toHaveTextContent('saved-tenant')
+ const deletions = calls('/channels/im/channel-1', 'DELETE')
+ expect(deletions).toHaveLength(2)
+ expect(new URL(deletions[0]!.url).searchParams.get('expected_config_version')).toBe(
+ channel.config_version,
+ )
+ expect(new URL(deletions[1]!.url).searchParams.get('expected_config_version')).toBe(
+ 'updated-config-version',
+ )
})
diff --git a/web/features/contacts/im-platform/__tests__/mock-repository.spec.ts b/web/features/contacts/im-platform/__tests__/mock-repository.spec.ts
deleted file mode 100644
index 64b4931bf88..00000000000
--- a/web/features/contacts/im-platform/__tests__/mock-repository.spec.ts
+++ /dev/null
@@ -1,1190 +0,0 @@
-import type {
- EmailProviderCredentialsWritable,
- ImProviderCredentialsInputWritable,
-} from '@dify/contracts/api/console/workspaces/types.gen'
-import type { TestContactImConnectionCommand } from '../types'
-import { httpErrorFromResponse } from '@/service/http-error'
-import { createContactImApiRepository } from '../repository'
-import {
- ContactImConnectionStatus,
- ContactImProvider,
- ContactImRepositoryError,
- ContactImSyncResult,
- ContactImSyncStatus,
-} from '../types'
-import {
- channelSummary,
- createChannelClient,
- emailDetail,
- imDetail,
-} from './fixtures/channel-client'
-import {
- createContactImMockRepository,
- createContactImMockRepositoryFromSeed,
-} from './fixtures/repository'
-import { ContactImMockScenario, getContactImMockScenarioSeed } from './fixtures/scenarios'
-
-const organization = {
- canManage: true,
- organizationId: 'org-test',
- workspaceId: 'workspace-test',
-}
-
-describe('Contact IM mock repository', () => {
- it('keeps every named scenario internally consistent', () => {
- for (const scenario of Object.values(ContactImMockScenario)) {
- expect(() => getContactImMockScenarioSeed(scenario, organization)).not.toThrow()
- }
- })
-
- it('allows Email beside one active IM binding and requires explicit IM replacement', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
-
- await repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Email,
- replaceActiveProvider: false,
- retainSecret: false,
- secret: 'resend-secret',
- values: { senderEmail: '[email protected]' },
- })
-
- await expect(
- repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: false,
- retainSecret: false,
- secret: 'feishu-test-secret',
- values: { appId: 'feishu-test-app' },
- }),
- ).rejects.toMatchObject({ code: 'active_provider_exists' })
-
- await repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: true,
- retainSecret: false,
- secret: 'feishu-test-secret',
- values: { appId: 'feishu-test-app' },
- })
-
- const integrations = await repository.getIntegrations(organization.organizationId)
- expect(integrations.map(({ provider }) => provider)).toEqual([
- ContactImProvider.Email,
- ContactImProvider.Feishu,
- ])
- expect(integrations).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ provider: ContactImProvider.Email }),
- expect.objectContaining({
- provider: ContactImProvider.Feishu,
- status: ContactImConnectionStatus.Configured,
- }),
- ]),
- )
- })
-
- it('uses explicit advancement for deterministic sync transitions', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
-
- const queuedRun = await repository.startSync({
- organizationId: organization.organizationId,
- })
-
- expect(queuedRun).toMatchObject({
- id: 'mock-sync-1',
- status: ContactImSyncStatus.Queued,
- })
- await expect(
- repository.startSync({ organizationId: organization.organizationId }),
- ).rejects.toMatchObject({ code: 'sync_already_running' })
-
- const runningRun = await repository.advanceSync(queuedRun.id)
- expect(runningRun.status).toBe(ContactImSyncStatus.Running)
-
- const completedRun = await repository.advanceSync(queuedRun.id)
- expect(completedRun.status).toBe(ContactImSyncStatus.PartialSuccess)
- await expect(repository.getActiveSync(organization.organizationId)).resolves.toBeNull()
- })
-
- it('rejects a scenario whose summary counts disagree with detail items', () => {
- const seed = getContactImMockScenarioSeed(ContactImMockScenario.SyncSuccess, organization)
- const runId = Object.keys(seed.runs)[0]
-
- if (!runId) throw new Error('Sync success scenario must contain a run')
- const run = seed.runs[runId]
- if (!run) throw new Error('Sync success scenario run must be readable')
-
- run.counts[ContactImSyncResult.Failed] = (run.counts[ContactImSyncResult.Failed] ?? 0) + 1
-
- expect(() => createContactImMockRepositoryFromSeed(seed)).toThrow(
- 'Sync summary counts do not match detail items',
- )
- })
-
- it('records only secret configuration state and discards submitted secret text', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.NotConfigured,
- })
- const submittedSecret = 'do-not-retain-this-secret'
-
- await repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- replaceActiveProvider: false,
- retainSecret: false,
- secret: submittedSecret,
- values: { appId: 'app-safe-id' },
- })
-
- const integration = (await repository.getIntegrations(organization.organizationId)).find(
- ({ provider }) => provider === ContactImProvider.Slack,
- )
- expect(integration).toMatchObject({ secretConfigured: true })
- expect(JSON.stringify(repository.getDebugSnapshot())).not.toContain(submittedSecret)
- })
-
- it('returns typed safe errors without leaking mutation inputs', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.SaveFailure,
- })
- const submittedSecret = 'unsafe-secret-for-failure'
-
- const error = await repository
- .saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- replaceActiveProvider: false,
- retainSecret: false,
- secret: submittedSecret,
- values: { appId: 'app-safe-id' },
- })
- .catch((caughtError: unknown) => caughtError)
-
- expect(error).toBeInstanceOf(ContactImRepositoryError)
- expect(JSON.stringify(error)).not.toContain(submittedSecret)
- })
-
- it('tracks optional secret configuration without retaining values or persisting connection tests', async () => {
- const seed = getContactImMockScenarioSeed(ContactImMockScenario.NotConfigured, organization)
- const provider = seed.providers.find((item) => item.provider === ContactImProvider.Feishu)
- if (!provider) throw new Error('The seed must offer Feishu')
- provider.requiredFields.push({ field: 'verificationToken', required: false, secret: true })
- const repository = createContactImMockRepositoryFromSeed(seed)
- const saved = await repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: false,
- secret: 'private-app-secret',
- values: { appId: 'app-1', verificationToken: 'private-verification-token' },
- })
-
- expect(saved.configuredFields).toContain('verificationToken')
- expect(saved.configuredValues).toEqual({ appId: 'app-1' })
- const before = await repository.getIntegrations(organization.organizationId)
- const tested = await repository.testConnection({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- values: { appId: 'unsaved-app' },
- clearedFields: ['verificationToken'],
- })
-
- expect(tested.configuredFields).not.toContain('verificationToken')
- expect(await repository.getIntegrations(organization.organizationId)).toEqual(before)
- const cleared = await repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- replaceActiveProvider: false,
- values: {},
- clearedFields: ['verificationToken'],
- })
- expect(cleared.configuredFields).not.toContain('verificationToken')
- expect(JSON.stringify(repository.getDebugSnapshot())).not.toContain('private-')
- })
-})
-
-const slackCommand: TestContactImConnectionCommand = {
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- retainSecret: false,
- secret: 'test-client-secret',
- values: {
- clientId: 'client-1',
- signingSecret: 'test-signing-secret',
- botToken: 'test-bot-token',
- },
-}
-
-const credentialCases: {
- provider: ContactImProvider
- values: TestContactImConnectionCommand['values']
- expected: EmailProviderCredentialsWritable | ImProviderCredentialsInputWritable
-}[] = [
- {
- provider: ContactImProvider.Email,
- values: { senderEmail: ' [email protected] ', senderName: ' Sender ' },
- expected: {
- provider: 'resend',
- api_key: 'test-secret',
- },
- },
- {
- provider: ContactImProvider.Feishu,
- values: { appId: ' app-1 ', verificationToken: ' verification-1 ', encryptKey: ' ' },
- expected: {
- provider: 'feishu',
- app_id: 'app-1',
- app_secret: 'test-secret',
- verification_token: 'verification-1',
- encrypt_key: null,
- },
- },
- {
- provider: ContactImProvider.Lark,
- values: { appId: ' app-2 ' },
- expected: {
- provider: 'lark',
- app_id: 'app-2',
- app_secret: 'test-secret',
- verification_token: null,
- encrypt_key: null,
- },
- },
- {
- provider: ContactImProvider.Slack,
- values: {
- clientId: ' client-1 ',
- signingSecret: ' signing-1 ',
- botToken: ' bot-1 ',
- appToken: ' app-token-1 ',
- },
- expected: {
- provider: 'slack',
- client_id: 'client-1',
- client_secret: 'test-secret',
- signing_secret: 'signing-1',
- bot_token: 'bot-1',
- app_token: 'app-token-1',
- },
- },
- {
- provider: ContactImProvider.DingTalk,
- values: { corpId: ' corp-1 ', clientId: ' client-2 ' },
- expected: {
- provider: 'ding_talk',
- corp_id: 'corp-1',
- client_id: 'client-2',
- client_secret: 'test-secret',
- },
- },
- {
- provider: ContactImProvider.MSTeams,
- values: { tenantId: ' tenant-1 ', clientId: ' client-3 ' },
- expected: {
- provider: 'ms_teams',
- tenant_id: 'tenant-1',
- client_id: 'client-3',
- client_secret: 'test-secret',
- },
- },
- {
- provider: ContactImProvider.WeCom,
- values: { corpId: ' corp-2 ', agentId: ' agent-1 ' },
- expected: { provider: 'we_com', corp_id: 'corp-2', agent_id: 'agent-1', secret: 'test-secret' },
- },
-]
-
-describe('Contact IM channel API repository', () => {
- it('offers only server-listed providers and permits retaining saved credentials', async () => {
- const client = createChannelClient()
- client.channelProviders.get.mockResolvedValue({
- email_providers: [{ provider: 'resend', connection_mode: 'custom_app' }],
- im_providers: [
- { provider: 'slack', connection_mode: 'custom_app' },
- { provider: 'ding_talk', connection_mode: 'custom_app' },
- ],
- })
- const repository = createContactImApiRepository(organization, client)
- const definitions = await repository.getProviderDefinitions(organization.organizationId)
- expect(definitions.map((definition) => definition.provider)).toEqual([
- 'email',
- 'slack',
- 'dingtalk',
- ])
- expect(
- definitions.every(
- (definition) =>
- definition.availability === 'available' && !definition.requiresFreshCredentials,
- ),
- ).toBe(true)
- expect(
- definitions.find((definition) => definition.provider === 'slack')?.requiredFields,
- ).toEqual(
- expect.arrayContaining([
- { field: 'signingSecret', required: true, secret: true },
- { field: 'botToken', required: true, secret: true },
- ]),
- )
- expect(
- definitions.find((definition) => definition.provider === 'dingtalk')?.requiredFields,
- ).toContainEqual({ field: 'corpId', required: true })
- client.channelProviders.get.mockResolvedValue({ email_providers: [], im_providers: [] })
- await expect(repository.getProviderDefinitions(organization.organizationId)).resolves.toEqual(
- [],
- )
- })
-
- it('preserves configured Email status and prefills only safe channel metadata', async () => {
- const client = createChannelClient()
- const emailSummary = channelSummary({
- id: 'email-channel',
- status: 'configured',
- kind: 'email',
- provider: 'resend',
- webhook_url: null,
- })
- client.channels.get.mockResolvedValue({ channels: [emailSummary, channelSummary()] })
- client.channels.email.byChannelId.get.mockResolvedValue({
- ...emailDetail(emailSummary),
- })
- const integrations = await createContactImApiRepository(organization, client).getIntegrations(
- organization.organizationId,
- )
- expect(client.channels.email.byChannelId.get).toHaveBeenCalledWith(
- {
- params: { channel_id: 'email-channel' },
- },
- { context: { silent: true } },
- )
- expect(integrations[0]).toMatchObject({
- provider: 'email',
- status: 'configured',
- secretConfigured: true,
- configuredValues: { senderEmail: '[email protected]', senderName: 'Approvals' },
- channelId: 'email-channel',
- configVersion: 'snapshot-version',
- })
- expect(integrations[1]).toMatchObject({
- configuredValues: { clientId: 'client-1' },
- configuredFields: ['clientId', 'secret', 'signingSecret', 'botToken'],
- channelId: 'channel-1',
- callbackUrl: 'https://example.test/callback',
- })
- for (const integration of integrations) {
- expect(integration).not.toHaveProperty('secret')
- expect(integration.configuredValues).not.toHaveProperty('api_key')
- expect(integration.configuredValues).not.toHaveProperty('client_secret')
- }
- })
-
- it.each(credentialCases)(
- 'passes the complete $provider credential contract and never returns submitted secrets',
- async ({ provider, values, expected }) => {
- const client = createChannelClient()
- client.channels.email.test.post.mockResolvedValue({
- status: 'connected',
- status_description: 'Verified',
- })
- client.channels.im.test.post.mockResolvedValue({
- status: 'connected',
- status_description: 'Verified',
- })
- const result = await createContactImApiRepository(organization, client).testConnection({
- organizationId: organization.organizationId,
- provider,
- values,
- retainSecret: false,
- secret: ' test-secret ',
- })
- const endpoint =
- provider === 'email' ? client.channels.email.test.post : client.channels.im.test.post
- const body =
- provider === 'email'
- ? { sender_email: '[email protected]', sender_name: 'Sender', credentials: expected }
- : { credentials: expected }
- expect(endpoint).toHaveBeenCalledWith({ body }, { context: { silent: true } })
- expect(result).toMatchObject({ provider, status: 'connected', configuredValues: {} })
- expect(JSON.stringify(result)).not.toContain('test-secret')
- },
- )
-
- it.each(['feishu', 'lark', 'slack', 'ding_talk', 'ms_teams', 'we_com'] as const)(
- 'reads safe %s identities and converts redacted credentials into per-field state',
- async (provider) => {
- const client = createChannelClient()
- const summary = channelSummary({ provider })
- client.channels.get.mockResolvedValue({ channels: [summary] })
- client.channels.im.byChannelId.get.mockResolvedValue(imDetail(summary))
-
- const [integration] = await createContactImApiRepository(
- organization,
- client,
- ).getIntegrations(organization.organizationId)
-
- expect(integration?.configuredFields).toContain('secret')
- expect(integration?.secretConfigured).toBe(true)
- expect(JSON.stringify(integration)).not.toContain('redacted')
- expect(integration?.configuredValues).not.toHaveProperty('secret')
- expect(integration?.configuredValues).not.toHaveProperty('signingSecret')
- expect(integration?.configuredValues).not.toHaveProperty('verificationToken')
- if (provider === 'feishu' || provider === 'lark') {
- expect(integration?.configuredValues).toEqual({ appId: 'app-1' })
- expect(integration?.configuredFields).toEqual(['appId', 'secret', 'verificationToken'])
- }
- if (provider === 'slack') expect(integration?.configuredFields).not.toContain('appToken')
- },
- )
-
- it.each([
- {
- values: { verificationToken: ' new-verification ' },
- secret: undefined,
- changed: { verification_token: 'new-verification' },
- },
- {
- values: { encryptKey: ' new-encryption ' },
- secret: undefined,
- changed: { encrypt_key: 'new-encryption' },
- },
- { values: {}, secret: ' new-app-secret ', changed: { app_secret: 'new-app-secret' } },
- { values: { appId: ' new-app-id ' }, secret: undefined, changed: { app_id: 'new-app-id' } },
- ])(
- 'updates one Feishu field while retaining all other server values: $changed',
- async ({ values, secret, changed }) => {
- const client = createChannelClient()
- const summary = channelSummary({ provider: 'feishu', config_version: 'new-version' })
- client.channels.im.byChannelId.put.mockResolvedValue({ summary })
- client.channels.im.byChannelId.get.mockResolvedValue(imDetail(summary))
-
- const saved = await createContactImApiRepository(organization, client).saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- values,
- secret,
- })
-
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledWith(
- {
- params: { channel_id: 'channel-1' },
- body: {
- expected_config_version: 'snapshot-version',
- credentials: {
- provider: 'feishu',
- app_id: { type: 'unchanged' },
- app_secret: { type: 'unchanged' },
- verification_token: { type: 'unchanged' },
- encrypt_key: { type: 'unchanged' },
- ...changed,
- },
- },
- },
- { context: { silent: true } },
- )
- expect(saved).toMatchObject({
- configVersion: 'new-version',
- configuredValues: { appId: 'app-1' },
- configuredFields: ['appId', 'secret', 'verificationToken'],
- })
- expect(JSON.stringify(saved)).not.toContain('new-app-secret')
- },
- )
-
- it.each([
- {
- values: { signingSecret: ' signing-2 ' },
- secret: undefined,
- changed: { signing_secret: 'signing-2' },
- },
- { values: { botToken: ' bot-2 ' }, secret: undefined, changed: { bot_token: 'bot-2' } },
- { values: { appToken: ' app-2 ' }, secret: undefined, changed: { app_token: 'app-2' } },
- { values: {}, secret: ' client-secret-2 ', changed: { client_secret: 'client-secret-2' } },
- ])('updates each Slack secret independently: $changed', async ({ values, secret, changed }) => {
- const client = createChannelClient()
- client.channels.im.byChannelId.put.mockResolvedValue({ summary: channelSummary() })
-
- await createContactImApiRepository(organization, client).saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- values,
- secret,
- })
-
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledWith(
- {
- params: { channel_id: 'channel-1' },
- body: {
- expected_config_version: 'snapshot-version',
- credentials: {
- provider: 'slack',
- client_id: { type: 'unchanged' },
- client_secret: { type: 'unchanged' },
- signing_secret: { type: 'unchanged' },
- bot_token: { type: 'unchanged' },
- app_token: { type: 'unchanged' },
- ...changed,
- },
- },
- },
- { context: { silent: true } },
- )
- })
-
- it('sends null only for explicitly cleared optional fields', async () => {
- const client = createChannelClient()
- const summary = channelSummary({ provider: 'feishu' })
- client.channels.im.byChannelId.put.mockResolvedValue({ summary })
- client.channels.im.byChannelId.get.mockResolvedValue(imDetail(summary))
- const repository = createContactImApiRepository(organization, client)
- const command = {
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- values: { verificationToken: ' ', encryptKey: '' },
- }
-
- await repository.saveCredentials(command)
- expect(client.channels.im.byChannelId.put.mock.calls[0]?.[0]?.body.credentials).toMatchObject({
- verification_token: { type: 'unchanged' },
- encrypt_key: { type: 'unchanged' },
- })
- client.channels.im.byChannelId.get.mockResolvedValue({
- summary: channelSummary({ provider: 'feishu', config_version: 'cleared-version' }),
- credentials: {
- provider: 'feishu',
- app_id: 'app-1',
- app_secret: { type: 'redacted' },
- verification_token: null,
- encrypt_key: null,
- },
- })
- const cleared = await repository.saveCredentials({
- ...command,
- clearedFields: ['verificationToken'],
- })
- expect(client.channels.im.byChannelId.put.mock.calls[1]?.[0]?.body.credentials).toMatchObject({
- verification_token: null,
- encrypt_key: { type: 'unchanged' },
- app_secret: { type: 'unchanged' },
- })
- expect(cleared.configuredFields).toEqual(['appId', 'secret'])
- expect(cleared.configVersion).toBe('cleared-version')
- })
-
- it('clears the optional Slack App Token while retaining every required secret', async () => {
- const client = createChannelClient()
- client.channels.im.byChannelId.put.mockResolvedValue({ summary: channelSummary() })
-
- await createContactImApiRepository(organization, client).saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- values: {},
- clearedFields: ['appToken'],
- })
-
- expect(client.channels.im.byChannelId.put.mock.calls[0]?.[0]?.body.credentials).toEqual({
- provider: 'slack',
- client_id: { type: 'unchanged' },
- client_secret: { type: 'unchanged' },
- signing_secret: { type: 'unchanged' },
- bot_token: { type: 'unchanged' },
- app_token: null,
- })
- })
-
- it.each(['secret', 'appId', 'signingSecret'] as const)(
- 'rejects an invalid explicit clear of %s before writing',
- async (field) => {
- const client = createChannelClient()
- await expect(
- createContactImApiRepository(organization, client).saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- values: {},
- clearedFields: [field],
- }),
- ).rejects.toMatchObject({ code: 'invalid_command' })
- expect(client.channels.im.byChannelId.put).not.toHaveBeenCalled()
- },
- )
-
- it.each(['email', 'slack'] as const)(
- 'tests a saved %s channel using its version and the update draft without persisting it',
- async (provider) => {
- const client = createChannelClient()
- client.channels.email.byChannelId.test.post.mockResolvedValue({
- status: 'connected',
- status_description: 'Verified',
- })
- client.channels.im.byChannelId.test.post.mockResolvedValue({
- status: 'connected',
- status_description: 'Verified',
- })
- const repository = createContactImApiRepository(organization, client)
- await repository.testConnection({
- organizationId: organization.organizationId,
- provider,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- values:
- provider === 'email' ? { senderName: 'Updated sender' } : { botToken: 'Updated bot' },
- })
-
- const endpoint =
- provider === 'email'
- ? client.channels.email.byChannelId.test.post
- : client.channels.im.byChannelId.test.post
- expect(endpoint).toHaveBeenCalledWith(
- {
- params: { channel_id: 'channel-1' },
- body: {
- expected_config_version: 'snapshot-version',
- ...(provider === 'email'
- ? { sender_email: { type: 'unchanged' }, sender_name: 'Updated sender' }
- : {}),
- credentials:
- provider === 'email'
- ? {
- provider: 'resend',
- api_key: { type: 'unchanged' },
- }
- : {
- provider: 'slack',
- client_id: { type: 'unchanged' },
- client_secret: { type: 'unchanged' },
- bot_token: 'Updated bot',
- signing_secret: { type: 'unchanged' },
- app_token: { type: 'unchanged' },
- },
- },
- },
- { context: { silent: true } },
- )
- expect(client.channels.im.byChannelId.put).not.toHaveBeenCalled()
- expect(client.channels.email.byChannelId.put).not.toHaveBeenCalled()
- expect(client.channels.im.test.post).not.toHaveBeenCalled()
- expect(client.channels.email.test.post).not.toHaveBeenCalled()
- },
- )
-
- it('updates Email sender metadata without replacing its saved API Key', async () => {
- const client = createChannelClient()
- client.channels.email.byChannelId.put.mockResolvedValue({
- summary: channelSummary({ kind: 'email', provider: 'resend' }),
- })
- await createContactImApiRepository(organization, client).saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Email,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- values: { senderName: ' New sender ' },
- })
- expect(client.channels.email.byChannelId.put.mock.calls[0]?.[0]?.body).toEqual({
- expected_config_version: 'snapshot-version',
- credentials: { provider: 'resend', api_key: { type: 'unchanged' } },
- sender_email: { type: 'unchanged' },
- sender_name: 'New sender',
- })
- })
-
- it('requires a snapshot version before testing a saved channel', async () => {
- const client = createChannelClient()
- await expect(
- createContactImApiRepository(organization, client).testConnection({
- ...slackCommand,
- channelId: 'channel-1',
- }),
- ).rejects.toMatchObject({ code: 'configuration_updated' })
- expect(client.channels.im.byChannelId.test.post).not.toHaveBeenCalled()
- expect(client.channels.im.test.post).not.toHaveBeenCalled()
- })
-
- it.each(['email', 'slack'] as const)(
- 'reports a saved %s test version conflict without leaking its draft',
- async (provider) => {
- const client = createChannelClient()
- const endpoint =
- provider === 'email'
- ? client.channels.email.byChannelId.test.post
- : client.channels.im.byChannelId.test.post
- endpoint.mockRejectedValue(
- Response.json({ message: 'unsafe-new-secret-payload' }, { status: 409 }),
- )
-
- const error = await createContactImApiRepository(organization, client)
- .testConnection({
- organizationId: organization.organizationId,
- provider,
- channelId: 'channel-1',
- expectedConfigVersion: 'stale-version',
- secret: 'unsafe-new-secret-payload',
- values: {},
- })
- .catch((caught: unknown) => caught)
-
- expect(error).toMatchObject({ code: 'configuration_updated' })
- expect(JSON.stringify(error)).not.toContain('unsafe-new-secret-payload')
- },
- )
-
- it('creates without a version and updates or replaces using the edited snapshot version', async () => {
- const client = createChannelClient()
- client.channels.im.post.mockResolvedValue({
- summary: channelSummary({ config_version: 'created-version' }),
- })
- client.channels.im.byChannelId.put.mockResolvedValue({
- summary: channelSummary({ config_version: 'updated-version' }),
- })
- client.channels.im.byChannelId.replacement.post.mockResolvedValue({
- summary: channelSummary({ provider: 'feishu', config_version: 'replaced-version' }),
- })
- client.channels.im.byChannelId.get
- .mockResolvedValueOnce(imDetail(channelSummary({ config_version: 'created-version' })))
- .mockResolvedValueOnce(imDetail(channelSummary({ config_version: 'updated-version' })))
- .mockResolvedValueOnce(
- imDetail(channelSummary({ provider: 'feishu', config_version: 'replaced-version' })),
- )
- const repository = createContactImApiRepository(organization, client)
- expect(
- await repository.saveCredentials({ ...slackCommand, replaceActiveProvider: false }),
- ).toMatchObject({ configVersion: 'created-version' })
- expect(client.channels.im.post.mock.calls[0]?.[0]).toEqual({
- body: {
- credentials: {
- provider: 'slack',
- client_id: 'client-1',
- client_secret: 'test-client-secret',
- signing_secret: 'test-signing-secret',
- bot_token: 'test-bot-token',
- app_token: null,
- },
- },
- })
- expect(
- await repository.saveCredentials({
- ...slackCommand,
- replaceActiveProvider: false,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- }),
- ).toMatchObject({ configVersion: 'updated-version' })
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledWith(
- expect.objectContaining({
- params: { channel_id: 'channel-1' },
- body: expect.objectContaining({ expected_config_version: 'snapshot-version' }),
- }),
- { context: { silent: true } },
- )
- expect(
- await repository.saveCredentials({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Feishu,
- values: { appId: 'replacement-app' },
- secret: 'replacement-secret',
- retainSecret: false,
- replaceActiveProvider: true,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- }),
- ).toMatchObject({ provider: 'feishu', configVersion: 'replaced-version' })
- expect(client.channels.im.byChannelId.replacement.post).toHaveBeenCalledWith(
- {
- params: { channel_id: 'channel-1' },
- body: {
- expected_config_version: 'snapshot-version',
- credentials: {
- provider: 'feishu',
- app_id: 'replacement-app',
- app_secret: 'replacement-secret',
- encrypt_key: null,
- verification_token: null,
- },
- },
- },
- { context: { silent: true } },
- )
- expect(client.channels.get).not.toHaveBeenCalled()
- })
-
- it('routes Email create/update and both delete kinds with the caller snapshot version', async () => {
- const client = createChannelClient()
- const summary = channelSummary({ kind: 'email', provider: 'resend' })
- client.channels.email.post.mockResolvedValue({ summary })
- client.channels.email.byChannelId.put.mockResolvedValue({ summary })
- client.channels.email.byChannelId.delete.mockResolvedValue({ channel_id: 'email-id' })
- client.channels.im.byChannelId.delete.mockResolvedValue({ channel_id: 'im-id' })
- const repository = createContactImApiRepository(organization, client)
- const command = {
- organizationId: organization.organizationId,
- provider: ContactImProvider.Email,
- values: { senderEmail: '[email protected]', senderName: 'Sender' },
- secret: 'email-secret',
- retainSecret: false,
- replaceActiveProvider: false,
- }
- await repository.saveCredentials(command)
- await repository.saveCredentials({
- ...command,
- channelId: 'email-id',
- expectedConfigVersion: 'email-snapshot',
- })
- expect(client.channels.email.post).toHaveBeenCalledWith(
- {
- body: {
- sender_email: '[email protected]',
- sender_name: 'Sender',
- credentials: { provider: 'resend', api_key: 'email-secret' },
- },
- },
- { context: { silent: true } },
- )
- expect(client.channels.email.byChannelId.put).toHaveBeenCalledWith(
- expect.objectContaining({
- params: { channel_id: 'email-id' },
- body: expect.objectContaining({ expected_config_version: 'email-snapshot' }),
- }),
- { context: { silent: true } },
- )
- await repository.disconnect({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Email,
- channelId: 'email-id',
- expectedConfigVersion: 'email-snapshot',
- })
- await repository.disconnect({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- channelId: 'im-id',
- expectedConfigVersion: 'im-snapshot',
- })
- expect(client.channels.email.byChannelId.delete).toHaveBeenCalledWith(
- {
- params: { channel_id: 'email-id' },
- query: { expected_config_version: 'email-snapshot' },
- },
- { context: { silent: true } },
- )
- expect(client.channels.im.byChannelId.delete).toHaveBeenCalledWith(
- {
- params: { channel_id: 'im-id' },
- query: { expected_config_version: 'im-snapshot' },
- },
- { context: { silent: true } },
- )
- })
-
- it.each(['invalid_credentials', 'connection_failure'] as const)(
- 'rejects HTTP-success connection tests whose provider status is %s',
- async (status) => {
- const client = createChannelClient()
- client.channels.im.test.post.mockResolvedValue({
- status,
- status_description: 'Provider verification failed',
- })
- await expect(
- createContactImApiRepository(organization, client).testConnection(slackCommand),
- ).rejects.toMatchObject({
- code: 'mutation_failed',
- statusDescription: 'Provider verification failed',
- })
- },
- )
-
- it.each([
- [403, 'no_permission'],
- [409, 'configuration_updated'],
- ] as const)(
- 'returns a safe error for HTTP %s without retaining server or credential contents',
- async (status, code) => {
- const client = createChannelClient()
- client.channels.im.post.mockRejectedValue(
- new Response(JSON.stringify({ message: 'unsafe-provider-payload-test-client-secret' }), {
- status,
- }),
- )
- const error = await createContactImApiRepository(organization, client)
- .saveCredentials({ ...slackCommand, replaceActiveProvider: false })
- .catch((caught: unknown) => caught)
- expect(error).toBeInstanceOf(ContactImRepositoryError)
- expect(error).toMatchObject({ code })
- expect(String(error)).not.toContain('test-client-secret')
- expect(JSON.stringify(error)).not.toContain('unsafe-provider-payload')
- },
- )
-
- it.each([
- { kind: 'im', operation: 'create' },
- { kind: 'im', operation: 'update' },
- { kind: 'im', operation: 'replacement' },
- { kind: 'email', operation: 'create' },
- { kind: 'email', operation: 'update' },
- ] as const)(
- 'reports a persisted $kind $operation separately when only the details reload fails',
- async ({ kind, operation }) => {
- const client = createChannelClient()
- const summary = channelSummary({
- provider: kind === 'email' ? 'resend' : 'slack',
- kind,
- })
- const endpoint =
- operation === 'create'
- ? client.channels[kind].post
- : operation === 'replacement'
- ? client.channels.im.byChannelId.replacement.post
- : client.channels[kind].byChannelId.put
- endpoint.mockResolvedValue({ summary })
- client.channels[kind].byChannelId.get.mockRejectedValueOnce(
- Response.json({ message: 'unsafe-details-response' }, { status: 503 }),
- )
- client.channels.get.mockResolvedValue({ channels: [summary] })
- const repository = createContactImApiRepository(organization, client)
- const error = await repository
- .saveCredentials({
- ...slackCommand,
- provider: kind === 'email' ? ContactImProvider.Email : ContactImProvider.Slack,
- replaceActiveProvider: operation === 'replacement',
- channelId: operation === 'create' ? undefined : 'channel-1',
- expectedConfigVersion: operation === 'create' ? undefined : 'snapshot-version',
- values:
- kind === 'email'
- ? { senderEmail: '[email protected]', senderName: 'Sender' }
- : slackCommand.values,
- })
- .catch((caught: unknown) => caught)
-
- expect(error).toMatchObject({ code: 'saved_details_unavailable' })
- expect(JSON.stringify(error)).not.toContain('unsafe-details-response')
- expect(JSON.stringify(error)).not.toContain('test-client-secret')
- expect(endpoint).toHaveBeenCalledTimes(1)
- await expect(repository.getIntegrations(organization.organizationId)).resolves.toEqual([
- expect.objectContaining({ channelId: 'channel-1' }),
- ])
- expect(endpoint).toHaveBeenCalledTimes(1)
- },
- )
-
- it('keeps an ordinary details-read failure distinct from a completed save', async () => {
- const client = createChannelClient()
- client.channels.get.mockResolvedValue({ channels: [channelSummary()] })
- client.channels.im.byChannelId.get.mockRejectedValue(new Response(null, { status: 503 }))
-
- await expect(
- createContactImApiRepository(organization, client).getIntegrations(
- organization.organizationId,
- ),
- ).rejects.toMatchObject({ code: 'mutation_failed' })
- expect(client.channels.im.post).not.toHaveBeenCalled()
- expect(client.channels.im.byChannelId.put).not.toHaveBeenCalled()
- })
-
- it.each([
- {
- body: { code: 'replacement_required', message: 'unsafe-secret-provider-message' },
- expected: 'replacement_required',
- },
- {
- body: { code: 'provider_configuration_updated', message: 'unsafe-secret-provider-message' },
- expected: 'configuration_updated',
- },
- {
- body: { code: 'unknown_conflict', message: 'unsafe-secret-provider-message' },
- expected: 'configuration_updated',
- },
- { body: { message: 'unsafe-secret-provider-message' }, expected: 'configuration_updated' },
- ])(
- 'distinguishes the validated 409 reason $body.code without retaining the raw response',
- async ({ body, expected }) => {
- const client = createChannelClient()
- client.channels.im.byChannelId.put.mockRejectedValue(Response.json(body, { status: 409 }))
-
- const error = await createContactImApiRepository(organization, client)
- .saveCredentials({
- ...slackCommand,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- })
- .catch((caught: unknown) => caught)
-
- expect(error).toMatchObject({ code: expected })
- expect(JSON.stringify(error)).not.toContain('unsafe-secret-provider-message')
- expect(client.channels.im.byChannelId.get).not.toHaveBeenCalled()
- expect(client.channels.im.byChannelId.replacement.post).not.toHaveBeenCalled()
- },
- )
-
- it.each([
- { code: 'replacement_required', expected: 'replacement_required' },
- { code: 'provider_configuration_updated', expected: 'configuration_updated' },
- { code: 'unknown_conflict', expected: 'configuration_updated' },
- ])(
- 'maps the browser transport 409 reason $code without replacing the channel or retaining the response',
- async ({ code, expected }) => {
- const client = createChannelClient()
- const transportError = await httpErrorFromResponse(
- Response.json(
- { code, message: 'unsafe-secret-provider-message', status: 409 },
- { status: 409 },
- ),
- )
- client.channels.im.byChannelId.put.mockRejectedValue(transportError)
-
- const error = await createContactImApiRepository(organization, client)
- .saveCredentials({
- ...slackCommand,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- })
- .catch((caught: unknown) => caught)
-
- expect(error).toBeInstanceOf(ContactImRepositoryError)
- expect(error).toMatchObject({ code: expected })
- expect(String(error)).not.toContain('unsafe-secret-provider-message')
- expect(JSON.stringify(error)).not.toContain('unsafe-secret-provider-message')
- expect(client.channels.im.byChannelId.put).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({ params: { channel_id: 'channel-1' } }),
- { context: { silent: true } },
- )
- expect(client.channels.im.byChannelId.get).not.toHaveBeenCalled()
- expect(client.channels.im.byChannelId.replacement.post).not.toHaveBeenCalled()
- },
- )
-
- it('treats a malformed 409 response as a configuration conflict', async () => {
- const client = createChannelClient()
- client.channels.im.byChannelId.put.mockRejectedValue(new Response('not-json', { status: 409 }))
-
- await expect(
- createContactImApiRepository(organization, client).saveCredentials({
- ...slackCommand,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- replaceActiveProvider: false,
- }),
- ).rejects.toMatchObject({ code: 'configuration_updated' })
- })
-
- it.each(['im', 'email'] as const)(
- 'preserves safe provider diagnostics when creating a %s channel',
- async (kind) => {
- const client = createChannelClient()
- const message =
- 'The provider connection could not be established. Provider error code: 99991672. Missing permissions: contact:contact.base:readonly.'
- client.channels[kind].post.mockRejectedValue(
- Response.json({ code: 'bad_request', message }, { status: 400 }),
- )
- const command =
- kind === 'im'
- ? slackCommand
- : {
- ...slackCommand,
- provider: ContactImProvider.Email,
- values: { senderEmail: '[email protected]', senderName: 'Sender' },
- }
-
- await expect(
- createContactImApiRepository(organization, client).saveCredentials({
- ...command,
- replaceActiveProvider: false,
- }),
- ).rejects.toMatchObject({ code: 'mutation_failed', statusDescription: message })
- },
- )
-
- it('never bypasses complete create or replacement credentials through retainSecret', async () => {
- const client = createChannelClient()
- const repository = createContactImApiRepository(organization, client)
- await expect(
- repository.saveCredentials({
- ...slackCommand,
- secret: undefined,
- retainSecret: true,
- replaceActiveProvider: false,
- }),
- ).rejects.toMatchObject({ code: 'required_fields_missing' })
- await expect(
- repository.saveCredentials({
- ...slackCommand,
- secret: undefined,
- retainSecret: true,
- replaceActiveProvider: true,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot-version',
- }),
- ).rejects.toMatchObject({ code: 'required_fields_missing' })
- await expect(
- repository.testConnection({
- ...slackCommand,
- values: { clientId: 'client-1', signingSecret: 'signing-1' },
- retainSecret: true,
- }),
- ).rejects.toMatchObject({ code: 'required_fields_missing' })
- await expect(
- repository.testConnection({
- organizationId: organization.organizationId,
- provider: ContactImProvider.DingTalk,
- secret: 'corp-secret',
- retainSecret: true,
- values: { clientId: 'client-1' },
- }),
- ).rejects.toMatchObject({ code: 'required_fields_missing' })
- expect(client.channels.im.byChannelId.put).not.toHaveBeenCalled()
- expect(client.channels.im.test.post).not.toHaveBeenCalled()
- })
-
- it('rejects missing version, impossible replacement, and foreign organization before issuing writes', async () => {
- const client = createChannelClient()
- const repository = createContactImApiRepository(organization, client)
- await expect(
- repository.saveCredentials({
- ...slackCommand,
- replaceActiveProvider: false,
- channelId: 'channel-1',
- }),
- ).rejects.toMatchObject({ code: 'configuration_updated' })
- await expect(
- repository.saveCredentials({ ...slackCommand, replaceActiveProvider: true }),
- ).rejects.toMatchObject({ code: 'invalid_command' })
- await expect(
- repository.disconnect({
- organizationId: organization.organizationId,
- provider: ContactImProvider.Slack,
- channelId: 'channel-1',
- }),
- ).rejects.toMatchObject({ code: 'configuration_updated' })
- await expect(
- repository.saveCredentials({
- ...slackCommand,
- organizationId: 'foreign-org',
- replaceActiveProvider: false,
- }),
- ).rejects.toMatchObject({ code: 'no_permission' })
- expect(client.channels.im.post).not.toHaveBeenCalled()
- expect(client.channels.im.byChannelId.put).not.toHaveBeenCalled()
- expect(client.channels.im.byChannelId.delete).not.toHaveBeenCalled()
- })
-})
diff --git a/web/features/contacts/im-platform/__tests__/nested-dialog-backdrops.browser.spec.tsx b/web/features/contacts/im-platform/__tests__/nested-dialog-backdrops.browser.spec.tsx
new file mode 100644
index 00000000000..726126df70f
--- /dev/null
+++ b/web/features/contacts/im-platform/__tests__/nested-dialog-backdrops.browser.spec.tsx
@@ -0,0 +1,145 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import MenuDialog from '@/app/components/header/account-setting/menu-dialog'
+import { ContactsImPlatformRuntimeProvider } from '../composition'
+import { ContactsImPlatformManagementSurface } from '../management-surface'
+import { channelSummary } from './fixtures/channel-client'
+import { channel, defaultResponse, json } from './fixtures/http'
+
+const network = vi.hoisted(() => ({
+ handle: vi.fn<(request: Request) => Promise<Response> | Response>(),
+}))
+vi.mock('@/service/base', async () => {
+ const { httpErrorFromResponse } = await import('@/service/http-error')
+ return {
+ request: async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const response = await network.handle(options.request)
+ if (!response.ok) throw await httpErrorFromResponse(response)
+ return response
+ },
+ }
+})
+vi.mock('@/utils/client', () => ({ isClient: true, isServer: false }))
+vi.mock('@/context/i18n', () => ({
+ useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,
+}))
+
+// These surfaces previously lost their scrims when moved under Settings' transparent modal.
+// Independent component tests miss that nested-dialog condition. Real rendering must prove
+// the modal overlay covers the viewport; no particular radius, spacing or literal color is frozen.
+function visibleViewportScrims() {
+ const probe = document.createElement('div')
+ probe.style.backgroundColor = 'var(--color-background-overlay)'
+ document.body.append(probe)
+ const overlayColor = getComputedStyle(probe).backgroundColor
+ probe.remove()
+ return [...document.querySelectorAll<HTMLElement>('body *')].filter((element) => {
+ const style = getComputedStyle(element)
+ const bounds = element.getBoundingClientRect()
+ return (
+ overlayColor !== 'rgba(0, 0, 0, 0)' &&
+ style.backgroundColor === overlayColor &&
+ style.display !== 'none' &&
+ style.visibility === 'visible' &&
+ Number(style.opacity) > 0 &&
+ bounds.left <= 0 &&
+ bounds.top <= 0 &&
+ bounds.right >= window.innerWidth &&
+ bounds.bottom >= window.innerHeight
+ )
+ }).length
+}
+
+async function setup() {
+ network.handle.mockImplementation((request) => {
+ if (new URL(request.url).pathname.endsWith('/channels'))
+ return json({
+ channels: [
+ channel,
+ channelSummary({ id: 'channel-email', kind: 'email', provider: 'resend' }),
+ ],
+ })
+ return defaultResponse(request)
+ })
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ })
+ await render(
+ <QueryClientProvider client={queryClient}>
+ <NuqsTestingAdapter hasMemory>
+ <ContactsImPlatformRuntimeProvider
+ organization={{
+ canManage: true,
+ organizationId: 'workspace-1',
+ workspaceId: 'workspace-1',
+ }}
+ >
+ <MenuDialog title="Workspace settings" onClose={vi.fn()}>
+ <ContactsImPlatformManagementSurface />
+ </MenuDialog>
+ </ContactsImPlatformRuntimeProvider>
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
+ )
+ await expect.element(page.getByRole('group', { name: 'Feishu', exact: true })).toBeVisible()
+ expect(visibleViewportScrims()).toBe(0)
+ return queryClient
+}
+
+it.each(['IM configuration', 'Email configuration', 'replacement', 'deletion', 'sync details'])(
+ 'dims Settings behind the nested %s and removes the scrim when it closes',
+ async (surface) => {
+ await page.viewport(1280, 900)
+ const client = await setup()
+ try {
+ let role: 'dialog' | 'alertdialog' = 'dialog'
+ let title = /contacts\.imPlatform\.bindingDialog\.configureTitle/
+ if (surface === 'IM configuration' || surface === 'Email configuration') {
+ const provider = surface === 'IM configuration' ? 'Feishu' : 'Email'
+ await page
+ .getByRole('group', { name: provider, exact: true })
+ .getByRole('button', { name: /contacts\.imPlatform\.action\.configureChannel/ })
+ .click()
+ if (surface === 'Email configuration') title = /contacts\.imPlatform\.email\.title/
+ } else if (surface === 'replacement') {
+ await page
+ .getByRole('group', { name: 'Slack', exact: true })
+ .getByRole('button', { name: /contacts\.imPlatform\.action\.replace/ })
+ .click()
+ role = 'alertdialog'
+ title = /contacts\.imPlatform\.replacement\.title/
+ } else if (surface === 'deletion') {
+ await page
+ .getByRole('group', { name: 'Feishu', exact: true })
+ .getByRole('button', { name: /contacts\.imPlatform\.action\.deleteChannel/ })
+ .click()
+ role = 'alertdialog'
+ title = /contacts\.imPlatform\.delete\.title/
+ } else {
+ await page.getByRole('button', { name: 'contacts.imPlatform.action.viewDetails' }).click()
+ title = /contacts\.imPlatform\.details\.title/
+ }
+ const popup = page.getByRole(role, { name: title })
+ await expect.element(popup).toBeVisible()
+ await expect.poll(visibleViewportScrims).toBe(1)
+ if (surface === 'IM configuration') {
+ await popup.getByRole('button', { name: 'contacts.imPlatform.bindingDialog.back' }).click()
+ await expect
+ .element(popup.getByLabelText('contacts.imPlatform.bindingDialog.field.appId'))
+ .toBeVisible()
+ expect(visibleViewportScrims()).toBe(1)
+ }
+ await userEvent.keyboard('{Escape}')
+ await expect.element(popup).not.toBeInTheDocument()
+ await expect.poll(visibleViewportScrims).toBe(0)
+ await expect
+ .element(page.getByRole('dialog', { name: 'Workspace settings', exact: true }))
+ .toBeVisible()
+ expect(network.handle.mock.calls.every(([request]) => request.method === 'GET')).toBe(true)
+ } finally {
+ client.clear()
+ }
+ },
+)
diff --git a/web/features/contacts/im-platform/__tests__/repository-hooks.spec.tsx b/web/features/contacts/im-platform/__tests__/repository-hooks.spec.tsx
deleted file mode 100644
index 1d2a375d57b..00000000000
--- a/web/features/contacts/im-platform/__tests__/repository-hooks.spec.tsx
+++ /dev/null
@@ -1,569 +0,0 @@
-import type { ImSyncRun } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ReactNode } from 'react'
-import type { ContactImPlatformRepository } from '../repository'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { act, renderHook, waitFor } from '@testing-library/react'
-import { consoleQuery } from '@/service/console'
-import { ContactsImPlatformProvider } from '../composition'
-import {
- CONTACT_IM_SYNC_POLL_INTERVAL_MS,
- useContactImActiveSync,
- useContactImIntegrations,
- useContactImProviderDefinitions,
- useContactImSyncItems,
- useContactImSyncRun,
- useSaveContactImCredentials,
- useStartContactImSync,
-} from '../hooks'
-import { contactImPlatformQueryKeys } from '../query-keys'
-import { createContactImSyncApi } from '../repository'
-import {
- ContactImProvider,
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
- ContactImSyncStatus,
-} from '../types'
-import { createContactImMockRepository } from './fixtures/repository'
-import { ContactImMockScenario } from './fixtures/scenarios'
-
-const organization = {
- canManage: true,
- organizationId: 'org-hooks',
- workspaceId: 'workspace-hooks',
-}
-
-const createHarness = (
- repository: ContactImPlatformRepository,
- queryClient = new QueryClient({
- defaultOptions: {
- mutations: { retry: false },
- queries: { retry: false },
- },
- }),
-) => ({
- queryClient,
- wrapper: ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <ContactsImPlatformProvider organization={organization} repository={repository}>
- {children}
- </ContactsImPlatformProvider>
- </QueryClientProvider>
- ),
-})
-
-describe('Contact IM repository hooks', () => {
- it('reads through the injected repository without making a network request', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const getIntegrations = vi.spyOn(repository, 'getIntegrations')
- const fetchSpy = vi.spyOn(globalThis, 'fetch')
- const { queryClient, wrapper } = createHarness(repository)
- const { result } = renderHook(() => useContactImIntegrations(), { wrapper })
-
- await waitFor(() => expect(result.current.isSuccess).toBe(true))
-
- expect(getIntegrations).toHaveBeenCalledWith(organization.organizationId)
- expect(fetchSpy).not.toHaveBeenCalled()
- expect(
- queryClient.getQueryData([
- ...contactImPlatformQueryKeys.integrations(
- organization.organizationId,
- repository.queryKey,
- ),
- repository,
- ]),
- ).toEqual([expect.objectContaining({ provider: ContactImProvider.Slack })])
-
- fetchSpy.mockRestore()
- queryClient.clear()
- })
-
- it('refreshes channel state and dependent contact choices after saving', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.NotConfigured,
- })
- const { queryClient, wrapper } = createHarness(repository)
- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
- const { result } = renderHook(() => useSaveContactImCredentials(), { wrapper })
- const secret = 'discard-after-save'
-
- await act(async () => {
- await result.current.saveCredentials({
- provider: ContactImProvider.Slack,
- replaceActiveProvider: false,
- retainSecret: false,
- secret,
- values: { appId: 'app-hooks' },
- })
- })
-
- for (const queryKey of [
- ['contacts-management', organization.workspaceId],
- consoleQuery.workspaces.current.humanInput.v2.channels.key(),
- consoleQuery.workspaces.current.humanInput.v2.contactOptions.key(),
- consoleQuery.workspaces.current.humanInput.v2.imIdentities.key(),
- ])
- expect(invalidateQueries).toHaveBeenCalledWith({ queryKey })
- expect(invalidateQueries).toHaveBeenCalledWith({
- queryKey: contactImPlatformQueryKeys.integrations(
- organization.organizationId,
- repository.queryKey,
- ),
- })
- expect(invalidateQueries).toHaveBeenCalledWith({
- queryKey: contactImPlatformQueryKeys.activeSync(
- organization.organizationId,
- repository.queryKey,
- ),
- })
- expect(JSON.stringify(queryClient.getMutationCache().getAll())).not.toContain(secret)
- queryClient.clear()
- })
-
- it('does not retain or log a secret after a rejected mutation', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.SaveFailure,
- })
- const { queryClient, wrapper } = createHarness(repository)
- const { result } = renderHook(() => useSaveContactImCredentials(), { wrapper })
- const secret = 'never-log-or-cache-this-secret'
- const consoleSpies = [
- vi.spyOn(console, 'error').mockImplementation(() => undefined),
- vi.spyOn(console, 'log').mockImplementation(() => undefined),
- vi.spyOn(console, 'warn').mockImplementation(() => undefined),
- ]
- let caughtError: unknown
-
- await act(async () => {
- caughtError = await result.current
- .saveCredentials({
- provider: ContactImProvider.Slack,
- replaceActiveProvider: false,
- retainSecret: false,
- secret,
- values: { appId: 'safe-app-id' },
- })
- .catch((error: unknown) => error)
- })
-
- expect(JSON.stringify(caughtError)).not.toContain(secret)
- expect(JSON.stringify(queryClient.getMutationCache().getAll())).not.toContain(secret)
- expect(JSON.stringify(consoleSpies.flatMap((spy) => spy.mock.calls))).not.toContain(secret)
-
- for (const spy of consoleSpies) spy.mockRestore()
- queryClient.clear()
- })
-
- it('refreshes persisted channel state when saving succeeds but reloading its details fails', async () => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValue(
- new ContactImRepositoryError(ContactImRepositoryErrorCode.SavedDetailsUnavailable),
- )
- const { queryClient, wrapper } = createHarness(
- repository,
- new QueryClient({
- defaultOptions: {
- mutations: { retry: 2, retryDelay: 0 },
- queries: { retry: false },
- },
- }),
- )
- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
- const { result } = renderHook(() => useSaveContactImCredentials(), { wrapper })
- const secret = 'discard-after-persisted-save'
- let error: unknown
-
- await act(async () => {
- error = await result.current
- .saveCredentials({
- provider: ContactImProvider.Slack,
- channelId: 'channel-1',
- expectedConfigVersion: 'snapshot',
- replaceActiveProvider: false,
- secret,
- values: {},
- })
- .catch((caught: unknown) => caught)
- })
-
- expect(error).toMatchObject({ code: 'saved_details_unavailable' })
- expect(save).toHaveBeenCalledTimes(1)
- for (const queryKey of [
- consoleQuery.workspaces.current.humanInput.v2.channels.key(),
- consoleQuery.workspaces.current.humanInput.v2.contactOptions.key(),
- contactImPlatformQueryKeys.integrations(organization.organizationId, repository.queryKey),
- contactImPlatformQueryKeys.activeSync(organization.organizationId, repository.queryKey),
- ])
- expect(invalidateQueries).toHaveBeenCalledWith({ queryKey })
- expect(JSON.stringify(queryClient.getMutationCache().getAll())).not.toContain(secret)
- queryClient.clear()
- })
-
- it.each([
- ContactImRepositoryErrorCode.MutationFailed,
- ContactImRepositoryErrorCode.ConfigurationUpdated,
- ContactImRepositoryErrorCode.ReplacementRequired,
- ])('does not refresh or repeat a save rejected with %s', async (code) => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const save = vi
- .spyOn(repository, 'saveCredentials')
- .mockRejectedValue(new ContactImRepositoryError(code))
- const { queryClient, wrapper } = createHarness(repository)
- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
- const { result } = renderHook(() => useSaveContactImCredentials(), { wrapper })
-
- await act(async () => {
- await result.current
- .saveCredentials({
- provider: ContactImProvider.Slack,
- replaceActiveProvider: false,
- values: {},
- })
- .catch(() => undefined)
- })
-
- expect(save).toHaveBeenCalledTimes(1)
- expect(invalidateQueries).not.toHaveBeenCalled()
- queryClient.clear()
- })
-
- it('polls an active run under timer control and stops at its terminal state', async () => {
- vi.useFakeTimers()
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.ActiveSync,
- })
- const getSyncRun = vi.spyOn(repository, 'getSyncRun')
- const { queryClient, wrapper } = createHarness(repository)
- const { result, unmount } = renderHook(() => useContactImSyncRun('mock-active-sync'), {
- wrapper,
- })
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(result.current.data?.status).toBe(ContactImSyncStatus.Queued)
-
- await repository.advanceSync('mock-active-sync')
- await act(async () => {
- await vi.advanceTimersByTimeAsync(CONTACT_IM_SYNC_POLL_INTERVAL_MS + 1)
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(result.current.data?.status).toBe(ContactImSyncStatus.Running)
-
- await repository.advanceSync('mock-active-sync')
- await act(async () => {
- await vi.advanceTimersByTimeAsync(CONTACT_IM_SYNC_POLL_INTERVAL_MS + 1)
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(result.current.data?.status).toBe(ContactImSyncStatus.PartialSuccess)
- const terminalCallCount = getSyncRun.mock.calls.length
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(CONTACT_IM_SYNC_POLL_INTERVAL_MS * 3)
- })
- expect(getSyncRun).toHaveBeenCalledTimes(terminalCallCount)
-
- unmount()
- queryClient.clear()
- vi.useRealTimers()
- })
-
- it.each([
- [ContactImMockScenario.SyncSuccess, 'mock-sync-success', ContactImSyncStatus.Success],
- [
- ContactImMockScenario.SyncPartialSuccess,
- 'mock-sync-partial',
- ContactImSyncStatus.PartialSuccess,
- ],
- [ContactImMockScenario.SyncFailure, 'mock-sync-failure', ContactImSyncStatus.Failure],
- ])('does not poll the %s terminal scenario', async (scenario, runId, status) => {
- vi.useFakeTimers()
- const repository = createContactImMockRepository({ organization, scenario })
- const getSyncRun = vi.spyOn(repository, 'getSyncRun')
- const { queryClient, wrapper } = createHarness(repository)
- const { result, unmount } = renderHook(() => useContactImSyncRun(runId), { wrapper })
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(0)
- })
- expect(result.current.data?.status).toBe(status)
- await act(async () => {
- await vi.advanceTimersByTimeAsync(CONTACT_IM_SYNC_POLL_INTERVAL_MS * 3)
- })
- expect(getSyncRun).toHaveBeenCalledTimes(1)
-
- unmount()
- queryClient.clear()
- vi.useRealTimers()
- })
-})
-
-type SyncClient = NonNullable<Parameters<typeof createContactImSyncApi>[1]>
-const createApiRun = (status: ImSyncRun['status'] = 'queued'): ImSyncRun => ({
- id: 'server-run',
- status,
- provider: 'slack',
- channel_id: 'server-channel',
- channel_config_version: 1,
- started_at: status === 'queued' ? null : 1_700_000_000,
- finished_at: status === 'succeeded' ? 1_700_000_030 : null,
- result_counts: { added: 2, failed: 0, not_matched: 0, removed: 1, skipped: 0 },
-})
-const createSyncClient = (run = createApiRun()) => ({
- imSyncRuns: {
- post: vi.fn<SyncClient['imSyncRuns']['post']>().mockResolvedValue({ run }),
- latest: {
- get: vi.fn<SyncClient['imSyncRuns']['latest']['get']>().mockResolvedValue({ run }),
- results: {
- get: vi
- .fn<SyncClient['imSyncRuns']['latest']['results']['get']>()
- .mockResolvedValue({ data: [], page: 1, limit: 20, total: 0 }),
- },
- },
- },
-})
-
-describe('Contact IM server synchronization', () => {
- it('preserves the sync provider and contact avatar needed by the results dialog', async () => {
- const client = createSyncClient({ ...createApiRun('succeeded'), provider: 'ding_talk' })
- client.imSyncRuns.latest.results.get.mockResolvedValue({
- data: [
- {
- id: 'added-contact',
- result: {
- type: 'added',
- contact: {
- id: 'contact-1',
- name: 'Contact 1',
- created_at: 1_700_000_000,
- avatar_url: 'https://example.com/avatar.png',
- },
- entry: { provider_user_id: 'member-1', display_name: 'Member 1' },
- },
- },
- ],
- page: 1,
- limit: 20,
- total: 1,
- })
- const repository = createContactImSyncApi(organization.workspaceId, client)
-
- await expect(repository.getSyncRun('server-run')).resolves.toMatchObject({
- provider: 'dingtalk',
- })
- await expect(repository.getSyncItems({ runId: 'server-run' })).resolves.toMatchObject({
- items: [{ matchedContact: { avatarUrl: 'https://example.com/avatar.png' } }],
- })
- })
-
- it('posts to the generated sync endpoint and preserves a queued run with no invented start time', async () => {
- const client = createSyncClient()
- const repository = createContactImSyncApi(organization.workspaceId, client)
- await expect(
- repository.startSync({ organizationId: organization.organizationId }),
- ).resolves.toMatchObject({
- id: 'server-run',
- status: ContactImSyncStatus.Queued,
- startedAt: null,
- startedBy: null,
- durationMs: null,
- })
- expect(client.imSyncRuns.post).toHaveBeenCalledWith(undefined, { context: { silent: true } })
- })
-
- it('treats a missing latest run as empty but preserves network and server failures for retry', async () => {
- const client = createSyncClient()
- const repository = createContactImSyncApi(organization.workspaceId, client)
- client.imSyncRuns.latest.get.mockRejectedValueOnce(new Response(null, { status: 404 }))
- await expect(repository.getActiveSync(organization.organizationId)).resolves.toBeNull()
- client.imSyncRuns.latest.get.mockRejectedValueOnce(new Response(null, { status: 500 }))
- await expect(repository.getActiveSync(organization.organizationId)).rejects.toMatchObject({
- status: 500,
- })
- await expect(repository.getActiveSync(organization.organizationId)).resolves.toMatchObject({
- id: 'server-run',
- })
- })
-
- it('does not request results for an old run when the server latest run has changed', async () => {
- const client = createSyncClient(createApiRun('succeeded'))
- const repository = createContactImSyncApi(organization.workspaceId, client)
- await expect(repository.getSyncItems({ runId: 'an-old-run' })).rejects.toMatchObject({
- code: 'sync_run_not_found',
- })
- expect(client.imSyncRuns.latest.results.get).not.toHaveBeenCalled()
- })
-
- it('rejects results if the latest run changes while the result page is loading', async () => {
- const client = createSyncClient(createApiRun('succeeded'))
- client.imSyncRuns.latest.get
- .mockResolvedValueOnce({ run: createApiRun('succeeded') })
- .mockResolvedValue({ run: { ...createApiRun(), id: 'new-server-run' } })
- const repository = createContactImSyncApi(organization.workspaceId, client)
-
- await expect(repository.getSyncItems({ runId: 'server-run' })).rejects.toMatchObject({
- code: 'sync_run_not_found',
- })
- expect(client.imSyncRuns.latest.results.get).toHaveBeenCalledTimes(1)
- })
-
- it('polls through a recoverable request failure until the server finishes, then refreshes Contacts and stops', async () => {
- vi.useFakeTimers()
- const client = createSyncClient()
- const repository = Object.assign(
- createContactImMockRepository({ organization }),
- createContactImSyncApi(organization.workspaceId, client),
- )
- const { queryClient, wrapper } = createHarness(repository)
- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
- const { result, unmount } = renderHook(
- () => {
- const { data, isError } = useContactImActiveSync()
- return { data, isError }
- },
- { wrapper },
- )
- const advancePoll = async () => {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(CONTACT_IM_SYNC_POLL_INTERVAL_MS + 1)
- await vi.advanceTimersByTimeAsync(0)
- })
- }
- try {
- await advancePoll()
- expect(result.current.data?.status).toBe(ContactImSyncStatus.Queued)
- expect(client.imSyncRuns.latest.get.mock.calls.length).toBeGreaterThan(1)
- client.imSyncRuns.latest.get.mockResolvedValue({ run: createApiRun('running') })
- await advancePoll()
- expect(result.current.data?.status).toBe(ContactImSyncStatus.Running)
- client.imSyncRuns.latest.get.mockRejectedValue(new TypeError('Network unavailable'))
- await advancePoll()
- expect(result.current.isError).toBe(true)
- expect(result.current.data?.status).toBe(ContactImSyncStatus.Running)
- client.imSyncRuns.latest.get.mockResolvedValue({ run: createApiRun('succeeded') })
- await advancePoll()
- expect(result.current.data?.status).toBe(ContactImSyncStatus.Success)
- expect(invalidateQueries).toHaveBeenCalledWith({
- queryKey: ['contacts-management', organization.workspaceId],
- })
- const terminalCalls = client.imSyncRuns.latest.get.mock.calls.length
- await advancePoll()
- expect(client.imSyncRuns.latest.get).toHaveBeenCalledTimes(terminalCalls)
- } finally {
- unmount()
- queryClient.clear()
- vi.useRealTimers()
- }
- })
-
- it('does not reuse another workspace latest-run cache even with the same repository key and organization', async () => {
- const client = createSyncClient(createApiRun('succeeded'))
- const repository = Object.assign(
- createContactImMockRepository({ organization }),
- createContactImSyncApi(organization.workspaceId, client),
- )
- const { queryClient, wrapper } = createHarness(repository)
- const first = renderHook(() => useContactImActiveSync(), { wrapper })
- await waitFor(() => expect(first.result.current.data?.id).toBe('server-run'))
- first.unmount()
-
- let resolveLatest: ((value: { run: ImSyncRun }) => void) | undefined
- client.imSyncRuns.latest.get.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveLatest = resolve
- }),
- )
- const nextOrganization = { ...organization, workspaceId: 'workspace-other' }
- const nextWrapper = ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <ContactsImPlatformProvider organization={nextOrganization} repository={repository}>
- {children}
- </ContactsImPlatformProvider>
- </QueryClientProvider>
- )
- const second = renderHook(() => useContactImActiveSync(), { wrapper: nextWrapper })
- expect(second.result.current.data).toBeUndefined()
- await act(async () =>
- resolveLatest?.({ run: { ...createApiRun('succeeded'), id: 'workspace-other-run' } }),
- )
- await waitFor(() => expect(second.result.current.data?.id).toBe('workspace-other-run'))
- second.unmount()
- queryClient.clear()
- })
-})
-
-describe('Contacts channel request admission', () => {
- it.each([
- {
- canManage: false,
- workspaceId: organization.workspaceId,
- organizationId: organization.organizationId,
- },
- { canManage: true, workspaceId: '', organizationId: organization.organizationId },
- { canManage: true, workspaceId: organization.workspaceId, organizationId: '' },
- ])('keeps config and sync requests idle for an unavailable context: %j', async (scope) => {
- const repository = createContactImMockRepository({
- organization,
- scenario: ContactImMockScenario.Connected,
- })
- const reads = [
- vi.spyOn(repository, 'getIntegrations'),
- vi.spyOn(repository, 'getProviderDefinitions'),
- vi.spyOn(repository, 'getActiveSync'),
- vi.spyOn(repository, 'getSyncRun'),
- vi.spyOn(repository, 'getSyncItems'),
- ]
- const startSync = vi.spyOn(repository, 'startSync')
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
- })
- const wrapper = ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <ContactsImPlatformProvider organization={scope} repository={repository}>
- {children}
- </ContactsImPlatformProvider>
- </QueryClientProvider>
- )
- const { result } = renderHook(
- () => ({
- integrations: useContactImIntegrations(),
- providers: useContactImProviderDefinitions(),
- active: useContactImActiveSync(),
- run: useContactImSyncRun('existing-run'),
- items: useContactImSyncItems({ runId: 'existing-run' }),
- start: useStartContactImSync(),
- }),
- { wrapper },
- )
- await act(async () => {
- await expect(result.current.start.mutateAsync()).rejects.toMatchObject({
- code: 'no_permission',
- })
- })
- for (const query of [
- result.current.integrations,
- result.current.providers,
- result.current.active,
- result.current.run,
- result.current.items,
- ])
- expect(query.fetchStatus).toBe('idle')
- for (const read of reads) expect(read).not.toHaveBeenCalled()
- expect(startSync).not.toHaveBeenCalled()
- queryClient.clear()
- })
-})
diff --git a/web/features/contacts/im-platform/__tests__/sync-details-dialog.spec.tsx b/web/features/contacts/im-platform/__tests__/sync-details-dialog.spec.tsx
index 1ee518ce045..8c73f58a0fa 100644
--- a/web/features/contacts/im-platform/__tests__/sync-details-dialog.spec.tsx
+++ b/web/features/contacts/im-platform/__tests__/sync-details-dialog.spec.tsx
@@ -1,359 +1,571 @@
-import type { ImSyncRun } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ReactNode } from 'react'
+import type { ImSyncResultItem } from '@dify/contracts/api/console/workspaces/types.gen'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
-import { ContactsImPlatformProvider } from '../composition'
-import { createContactImSyncApi } from '../repository'
import { ContactImSyncDetailsDialog } from '../sync-details-dialog'
-import { createContactImMockRepository } from './fixtures/repository'
+import { loadContactImSyncReport } from '../sync-report'
+import { useContactImSyncResultUrlState, useContactImSyncRunUrlState } from '../sync-run-url-state'
+import { defaultResponse, json, syncRun } from './fixtures/http'
+const network = vi.hoisted(() => ({
+ handle: vi.fn<(request: Request) => Promise<Response> | Response>(),
+}))
+vi.mock('@/service/base', async () => {
+ const { httpErrorFromResponse } = await import('@/service/http-error')
+ return {
+ request: async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const response = await network.handle(options.request)
+ if (!response.ok) throw await httpErrorFromResponse(response)
+ return response
+ },
+ }
+})
+vi.mock('@/utils/client', () => ({ isClient: true, isServer: false }))
vi.mock('@/utils/download', () => ({ downloadBlob: vi.fn() }))
-
-type SyncClient = NonNullable<Parameters<typeof createContactImSyncApi>[1]>
-type ImSyncResultItem = Awaited<
- ReturnType<SyncClient['imSyncRuns']['latest']['results']['get']>
->['data'][number]
-const organization = {
- canManage: true,
- organizationId: 'org-details',
- workspaceId: 'workspace-details',
+const clients: QueryClient[] = []
+const newClient = () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ clients.push(client)
+ return client
}
-const createRun = (overrides: Partial<ImSyncRun> = {}): ImSyncRun => ({
- id: 'sync-latest',
- status: 'succeeded',
- provider: 'slack',
- channel_id: 'channel-slack',
- channel_config_version: 1,
- started_at: 1_700_000_000,
- finished_at: 1_700_000_030,
- error_message: null,
- result_counts: { added: 21, not_matched: 1, failed: 1, removed: 1, skipped: 1 },
- ...overrides,
-})
-const addedItem = (index: number): ImSyncResultItem => ({
- id: `added-${index}`,
+const contact = { id: 'contact-1', name: 'Alice', avatar_url: '', created_at: 1 }
+const added = (index: number): ImSyncResultItem => ({
+ id: `item-${index}`,
result: {
type: 'added',
- contact: {
- id: `contact-${index}`,
- name: `Contact ${index}`,
- created_at: 1_700_000_000,
- avatar_url: '',
- },
- entry: {
- provider_user_id: `member-${index}`,
- display_name: `Member ${index}`,
- email: `member${index}@example.com`,
- },
+ contact: { ...contact, id: `contact-${index}`, name: `Contact ${index}` },
+ entry: { provider_user_id: `user-${index}`, display_name: `User ${index}` },
},
})
-const renderDetails = ({
- run = createRun(),
- pageFailure = false,
- initialFailure = false,
-}: { run?: ImSyncRun; pageFailure?: boolean; initialFailure?: boolean } = {}) => {
- const latest = vi.fn<SyncClient['imSyncRuns']['latest']['get']>().mockResolvedValue({ run })
- if (initialFailure) latest.mockRejectedValueOnce(new TypeError('Network unavailable'))
- let shouldFailPage = pageFailure
- const results = vi
- .fn<SyncClient['imSyncRuns']['latest']['results']['get']>()
- .mockImplementation(async ({ query }) => {
- const page = query.page ?? 1
- const limit = query.limit ?? 20
- if (page > 1 && shouldFailPage) {
- shouldFailPage = false
- throw new TypeError('Network unavailable')
- }
- const data: ImSyncResultItem[] =
- query.result === 'added'
- ? Array.from({ length: page === 1 ? 20 : 1 }, (_, index) =>
- addedItem((page - 1) * limit + index + 1),
- )
- : query.result === 'not_matched'
- ? [{ id: 'not-matched', result: { type: 'not_matched', entry: null } }]
- : query.result === 'failed'
- ? [
- {
- id: 'failed',
- result: {
- type: 'failed',
- entry: { provider_user_id: 'failed-member', display_name: 'Failed member' },
- reason: 'Directory access denied',
- },
- },
- ]
- : query.result === 'removed'
- ? [
- {
- id: 'removed',
- result: {
- type: 'removed',
- contact: {
- id: 'removed-contact',
- name: 'Removed contact',
- created_at: 1_700_000_000,
- avatar_url: '',
- },
- last_known_identity: {
- identity_id: 'removed-identity',
- provider_user_id: 'removed-member',
- display_name: 'Removed member',
- },
- reason: 'not_present_in_directory',
- },
- },
- ]
- : [
- {
- id: 'skipped',
- result: {
- type: 'skipped',
- contact: {
- id: 'skipped-contact',
- name: 'Skipped contact',
- created_at: 1_700_000_000,
- avatar_url: '',
- },
- entry: null,
- },
- },
- ]
- return { data, page, limit, total: query.result === 'added' ? 21 : 1 }
- })
- const client: SyncClient = {
- imSyncRuns: {
- latest: { get: latest, results: { get: results } },
- post: vi.fn<SyncClient['imSyncRuns']['post']>().mockResolvedValue({ run }),
- },
- }
- const repository = Object.assign(
- createContactImMockRepository({ organization }),
- createContactImSyncApi(organization.workspaceId, client),
+const renderDetails = (runId = 'run-1', searchParams = '') =>
+ render(
+ <QueryClientProvider client={newClient()}>
+ <NuqsTestingAdapter hasMemory searchParams={searchParams}>
+ <ContactImSyncDetailsDialog open runId={runId} onOpenChange={() => {}} />
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
)
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const wrapper = ({ children }: { children: ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- <ContactsImPlatformProvider organization={organization} repository={repository}>
- {children}
- </ContactsImPlatformProvider>
- </QueryClientProvider>
+beforeEach(() => {
+ network.handle.mockImplementation(defaultResponse)
+})
+afterEach(() => clients.splice(0).forEach((client) => client.clear()))
+
+it('renders localized removal reasons with decorative avatars and the generated result type', async () => {
+ network.handle.mockImplementation((request) =>
+ request.url.includes('/latest/results')
+ ? json({
+ data: [
+ {
+ id: 'removed-1',
+ result: {
+ type: 'removed',
+ contact,
+ last_known_identity: {
+ identity_id: 'identity-1',
+ provider_user_id: 'alice',
+ display_name: 'Alice IM',
+ },
+ reason: 'binding_replaced',
+ },
+ },
+ ],
+ total: 1,
+ page: 1,
+ limit: 20,
+ })
+ : defaultResponse(request),
)
- return {
- latest,
- results,
- queryClient,
- ...render(<ContactImSyncDetailsDialog open runId="latest" onOpenChange={() => undefined} />, {
- wrapper,
- }),
- }
-}
+ render(
+ <QueryClientProvider client={newClient()}>
+ <NuqsTestingAdapter searchParams="?sync_result=removed">
+ <ContactImSyncDetailsDialog open runId="run-1" onOpenChange={() => {}} />
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
+ )
+ const table = await screen.findByRole('table', { name: 'contacts.imPlatform.details.title' })
+ expect(
+ await within(table).findByText('contacts.imPlatform.details.removalReason.binding_replaced'),
+ ).toBeVisible()
+ expect(within(table).queryByText('binding_replaced')).not.toBeInTheDocument()
+ expect(within(table).queryByRole('img', { name: 'Alice' })).not.toBeInTheDocument()
+ expect(
+ screen.queryByText('contacts.imPlatform.details.filter.created_binding'),
+ ).not.toBeInTheDocument()
+})
-describe('Contact IM sync details dialog', () => {
- beforeEach(() => vi.mocked(downloadBlob).mockClear())
+it('retains a focused load-more action after the final page', async () => {
+ network.handle.mockImplementation((request) => {
+ if (request.url.includes('/latest/results')) {
+ const page = Number(new URL(request.url).searchParams.get('page'))
+ return json({ data: [added(page)], total: 21, page, limit: 20 })
+ }
+ return defaultResponse(request)
+ })
+ const user = userEvent.setup()
+ render(
+ <QueryClientProvider client={newClient()}>
+ <NuqsTestingAdapter>
+ <ContactImSyncDetailsDialog open runId="run-1" onOpenChange={() => {}} />
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
+ )
+ const button = await screen.findByRole('button', { name: 'contacts.imPlatform.action.loadMore' })
+ await user.click(button)
+ expect(await screen.findByText('Contact 2')).toBeVisible()
+ expect(button).toHaveFocus()
+ expect(button).toHaveAttribute('aria-disabled', 'true')
+})
- it('exports every page and result category, escaping spreadsheet formulas and CSV values', async () => {
- const user = userEvent.setup()
- const { results } = renderDetails()
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- const getResults = results.getMockImplementation()
- if (!getResults) throw new Error('Expected the real-contract result fixture')
- results.mockImplementation(async (...args) => {
- const response = await getResults(...args)
- const first = response.data[0]?.result
- if (first?.type === 'added') {
- first.contact.name = ' =HYPERLINK("https://example.com")'
- if (first.entry) first.entry.display_name = 'Name, "quoted"'
+it.each(['run', 'results'] as const)(
+ 'recovers an initial %s failure while preserving the selected result filter',
+ async (failedRequest) => {
+ let failed = false
+ network.handle.mockImplementation((request) => {
+ const url = new URL(request.url)
+ const matchesRequest =
+ failedRequest === 'run'
+ ? url.pathname.endsWith('/latest')
+ : url.pathname.endsWith('/latest/results')
+ if (matchesRequest && !failed) {
+ failed = true
+ return json({ message: 'Temporarily unavailable' }, 503)
}
- return response
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderDetails('run-1', '?sync_result=failed')
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
- )
-
- await waitFor(() => expect(downloadBlob).toHaveBeenCalledTimes(1))
- const download = vi.mocked(downloadBlob).mock.calls[0]?.[0]
- if (!download) throw new Error('Expected a complete CSV download')
- const content = await download.data.text()
- expect(download.fileName).toBe('im-sync-sync-latest.csv')
- expect(content.split('\r\n')).toHaveLength(26)
- expect(content).toContain("' =HYPERLINK")
- expect(content).toContain('"Name, ""quoted"""')
- expect(content).toContain('member-21')
- expect(content).toContain('removed-member')
- expect(content).toContain('Directory access denied')
- for (const result of ['added', 'not_matched', 'failed', 'removed', 'skipped'])
- expect(results).toHaveBeenCalledWith(
- { query: { result, page: 1, limit: 20 } },
- { context: { silent: true } },
- )
- expect(results).toHaveBeenCalledWith(
- { query: { result: 'added', page: 2, limit: 20 } },
- { context: { silent: true } },
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.details.loadError',
)
- })
+ await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.retry' }))
- it('does not download a partial report when a page fails and permits a complete retry', async () => {
- const user = userEvent.setup()
- renderDetails({ pageFailure: true })
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
- )
+ expect(await screen.findByText('contacts.imPlatform.details.empty')).toBeVisible()
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
expect(
- await screen.findByText('contacts.imPlatform.details.downloadFailed'),
- ).toBeInTheDocument()
- expect(downloadBlob).not.toHaveBeenCalled()
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
- )
- await waitFor(() => expect(downloadBlob).toHaveBeenCalledTimes(1))
- })
+ screen.getByRole('radio', { name: 'contacts.imPlatform.details.filter.failed 0' }),
+ ).toBeChecked()
+ const resultRequests = network.handle.mock.calls
+ .map(([request]) => new URL(request.url))
+ .filter((url) => url.pathname.endsWith('/latest/results'))
+ expect(resultRequests.length).toBeGreaterThan(0)
+ expect(resultRequests.every((url) => url.searchParams.get('result') === 'failed')).toBe(true)
+ expect(
+ screen.getByRole('button', { name: 'contacts.imPlatform.action.loadMore' }),
+ ).toHaveAttribute('aria-disabled', 'true')
+ },
+)
- it('refuses the report if another sync becomes latest while a result page loads', async () => {
- const user = userEvent.setup()
- const { latest, results } = renderDetails()
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- const getResults = results.getMockImplementation()
- if (!getResults) throw new Error('Expected the real-contract result fixture')
- results.mockImplementationOnce(async (...args) => {
- latest.mockResolvedValue({ run: createRun({ id: 'new-run' }) })
- return getResults(...args)
- })
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
- )
- expect(await screen.findByText('contacts.imPlatform.details.reportChanged')).toBeInTheDocument()
- expect(downloadBlob).not.toHaveBeenCalled()
+it('keeps loaded contacts when the next page fails and retries that page without duplicates', async () => {
+ let failedPage = false
+ network.handle.mockImplementation((request) => {
+ const url = new URL(request.url)
+ if (url.pathname.endsWith('/latest/results')) {
+ const page = Number(url.searchParams.get('page'))
+ if (page === 2 && !failedPage) {
+ failedPage = true
+ return json({ message: 'Temporarily unavailable' }, 503)
+ }
+ return json({
+ data: page === 1 ? Array.from({ length: 20 }, (_, index) => added(index + 1)) : [added(21)],
+ total: 21,
+ page,
+ limit: 20,
+ })
+ }
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderDetails()
+ const table = await screen.findByRole('table', { name: 'contacts.imPlatform.details.title' })
+ expect(within(table).getByText('Contact 20')).toBeVisible()
+ await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.loadMore' }))
- it('refuses incomplete result totals instead of exporting a truncated report', async () => {
- const user = userEvent.setup()
- const { results } = renderDetails()
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- results.mockResolvedValueOnce({ data: [addedItem(1)], page: 1, limit: 20, total: 1 })
- await user.click(
- screen.getByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
- )
- expect(
- await screen.findByText('contacts.imPlatform.details.downloadFailed'),
- ).toBeInTheDocument()
- expect(downloadBlob).not.toHaveBeenCalled()
- })
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.details.pageError',
+ )
+ expect(within(table).getByText('Contact 1')).toBeVisible()
+ expect(within(table).getAllByRole('row')).toHaveLength(21)
+ await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.retry' }))
- it('disables report download until the synchronization reaches a terminal state', async () => {
- renderDetails({ run: createRun({ status: 'running', finished_at: null }) })
- expect(
- await screen.findByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
- ).toBeDisabled()
- expect(downloadBlob).not.toHaveBeenCalled()
- })
+ expect(await within(table).findByText('Contact 21')).toBeVisible()
+ expect(within(table).getAllByRole('row')).toHaveLength(22)
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'contacts.imPlatform.action.loadMore' }),
+ ).toHaveAttribute('aria-disabled', 'true')
+ const pages = network.handle.mock.calls
+ .map(([request]) => new URL(request.url))
+ .filter((url) => url.pathname.endsWith('/latest/results'))
+ expect(pages.map((url) => url.searchParams.get('page'))).toEqual(['1', '2', '2'])
+ expect(pages.every((url) => url.searchParams.get('limit') === '20')).toBe(true)
+})
- it('uses the five server result categories and never requests an all-results filter', async () => {
- const { results } = renderDetails()
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- for (const [result, count] of [
- ['added', 21],
- ['not_matched', 1],
- ['failed', 1],
- ['removed', 1],
- ['skipped', 1],
- ]) {
- expect(
- screen.getByRole('radio', {
- name: `contacts.imPlatform.details.filter.${result} ${count}`,
+it('keeps contact matches separate from directory identities when switching result filters', async () => {
+ const results: Record<string, ImSyncResultItem[]> = {
+ added: [added(1)],
+ not_matched: [
+ {
+ id: 'unmatched-email',
+ result: {
+ type: 'not_matched',
+ entry: { provider_user_id: 'unmatched-user', email: '[email protected]' },
+ },
+ },
+ { id: 'unmatched-no-identity', result: { type: 'not_matched', entry: null } },
+ ],
+ failed: [
+ {
+ id: 'failed-user',
+ result: {
+ type: 'failed',
+ entry: { provider_user_id: 'suspended-user' },
+ reason: 'Directory account suspended',
+ },
+ },
+ ],
+ skipped: [{ id: 'skipped-contact', result: { type: 'skipped', contact, entry: null } }],
+ }
+ network.handle.mockImplementation((request) => {
+ const url = new URL(request.url)
+ if (url.pathname.endsWith('/latest'))
+ return json({
+ run: syncRun({
+ status: 'failed',
+ error_message: 'Some directory entries could not be synchronized',
+ result_counts: { added: 1, not_matched: 2, failed: 1, removed: 0, skipped: 1 },
}),
- ).toBeInTheDocument()
+ })
+ if (url.pathname.endsWith('/latest/results')) {
+ const rows = results[url.searchParams.get('result') ?? 'added'] ?? []
+ return json({ data: rows, total: rows.length, page: 1, limit: 20 })
}
- expect(screen.queryByRole('radio', { name: /filter.all/ })).not.toBeInTheDocument()
- expect(results).toHaveBeenCalledWith(
- { query: { result: 'added', page: 1, limit: 20 } },
- { context: { silent: true } },
- )
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderDetails()
+ const table = await screen.findByRole('table', { name: 'contacts.imPlatform.details.title' })
+ expect(within(table).getByText('Contact 1')).toBeVisible()
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'Some directory entries could not be synchronized',
+ )
- it('filters unmatched results with nullable entries and isolates results when switching categories', async () => {
- const user = userEvent.setup()
- const { results } = renderDetails()
- await user.click(
- await screen.findByRole('radio', {
- name: 'contacts.imPlatform.details.filter.not_matched 1',
- }),
- )
- await waitFor(() => expect(screen.queryByText('Member 1')).not.toBeInTheDocument())
- expect(screen.getAllByText('contacts.imPlatform.details.missing').length).toBeGreaterThan(0)
- expect(results).toHaveBeenCalledWith(
- { query: { result: 'not_matched', page: 1, limit: 20 } },
- { context: { silent: true } },
- )
- await user.click(
- screen.getByRole('radio', { name: 'contacts.imPlatform.details.filter.failed 1' }),
- )
- expect(await screen.findByText('Failed member')).toBeInTheDocument()
- expect(screen.getByText('Directory access denied')).toBeInTheDocument()
+ await user.click(
+ screen.getByRole('radio', { name: 'contacts.imPlatform.details.filter.not_matched 2' }),
+ )
+ const email = await screen.findByText('[email protected]')
+ const unmatchedRow = email.closest('tr')!
+ const unmatchedTable = screen.getByRole('table', { name: 'contacts.imPlatform.details.title' })
+ expect(within(unmatchedRow).getAllByRole('cell')[0]).toHaveTextContent(
+ 'contacts.imPlatform.details.missing',
+ )
+ expect(within(unmatchedTable).queryByText('Contact 1')).not.toBeInTheDocument()
+ expect(within(unmatchedTable).queryByText('unmatched-user')).not.toBeInTheDocument()
+ expect(within(unmatchedTable).getAllByRole('row')).toHaveLength(3)
+ expect(within(unmatchedTable).getAllByText('contacts.imPlatform.details.missing')).toHaveLength(3)
+
+ await user.click(
+ screen.getByRole('radio', { name: 'contacts.imPlatform.details.filter.failed 1' }),
+ )
+ expect(await screen.findByText('suspended-user')).toBeVisible()
+ const failedTable = screen.getByRole('table', { name: 'contacts.imPlatform.details.title' })
+ expect(within(failedTable).getByText('Directory account suspended')).toBeVisible()
+ expect(within(failedTable).queryByText('[email protected]')).not.toBeInTheDocument()
+
+ await user.click(
+ screen.getByRole('radio', { name: 'contacts.imPlatform.details.filter.skipped 1' }),
+ )
+ const skippedRow = (await screen.findByText('Alice')).closest('tr')!
+ expect(within(skippedRow).getAllByRole('cell')[1]).toHaveTextContent(
+ 'contacts.imPlatform.details.missing',
+ )
+ expect(screen.queryByText('suspended-user')).not.toBeInTheDocument()
+})
+
+it('does not show another run’s results under the requested run identity', async () => {
+ network.handle.mockImplementation((request) =>
+ request.url.endsWith('/latest')
+ ? json({ run: syncRun({ id: 'run-2' }) })
+ : defaultResponse(request),
+ )
+ renderDetails('run-1')
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.details.reportChanged',
+ )
+ expect(screen.queryByRole('table')).not.toBeInTheDocument()
+ expect(
+ network.handle.mock.calls.some(([request]) => request.url.includes('/latest/results')),
+ ).toBe(false)
+})
+
+it('exports pages of 100 without reloading latest before and after every page', async () => {
+ network.handle.mockImplementation((request) => {
+ if (request.url.endsWith('/latest'))
+ return json({
+ run: syncRun({
+ result_counts: { added: 101, not_matched: 0, failed: 0, removed: 0, skipped: 0 },
+ }),
+ })
+ if (request.url.includes('/latest/results')) {
+ const params = new URL(request.url).searchParams
+ const page = Number(params.get('page'))
+ const result = params.get('result')
+ expect(params.get('limit')).toBe('100')
+ return json({
+ data:
+ result === 'added'
+ ? page === 1
+ ? Array.from({ length: 100 }, (_, index) => added(index))
+ : [added(100)]
+ : [],
+ page,
+ limit: 100,
+ total: result === 'added' ? 101 : 0,
+ })
+ }
+ return defaultResponse(request)
})
+ const result = await loadContactImSyncReport(newClient(), 'run-1')
+ expect(result.items).toHaveLength(101)
+ const requests = network.handle.mock.calls.map(([request]) => request)
+ expect(requests.filter((request) => request.url.endsWith('/latest'))).toHaveLength(2)
+ expect(requests.filter((request) => request.url.includes('/latest/results'))).toHaveLength(6)
+})
- it('renders a removed binding from its last-known identity', async () => {
- const user = userEvent.setup()
- renderDetails()
- await user.click(
- await screen.findByRole('radio', { name: 'contacts.imPlatform.details.filter.removed 1' }),
- )
- expect(await screen.findByText('Removed contact')).toBeInTheDocument()
- expect(screen.getByText('Removed member')).toBeInTheDocument()
+it('downloads the selected latest report with contact and platform columns kept distinct and formulae escaped', async () => {
+ const rows: Record<string, ImSyncResultItem[]> = {
+ added: [
+ {
+ id: 'added-formula',
+ result: {
+ type: 'added',
+ contact: { ...contact, name: '=Alice' },
+ entry: {
+ provider_user_id: 'alice-im',
+ display_name: '+Directory Alice',
+ email: '[email protected]',
+ },
+ },
+ },
+ ],
+ not_matched: [{ id: 'unmatched', result: { type: 'not_matched', entry: null } }],
+ failed: [{ id: 'failed', result: { type: 'failed', reason: 'Directory unavailable' } }],
+ removed: [
+ {
+ id: 'removed',
+ result: {
+ type: 'removed',
+ contact,
+ last_known_identity: { identity_id: 'old-id', provider_user_id: 'old-alice' },
+ reason: 'binding_invalidated',
+ },
+ },
+ ],
+ skipped: [{ id: 'skipped', result: { type: 'skipped', contact, entry: null } }],
+ }
+ network.handle.mockImplementation((request) => {
+ const url = new URL(request.url)
+ if (url.pathname.endsWith('/latest'))
+ return json({
+ run: syncRun({
+ result_counts: { added: 1, not_matched: 1, failed: 1, removed: 1, skipped: 1 },
+ }),
+ })
+ if (url.pathname.endsWith('/latest/results')) {
+ const result = url.searchParams.get('result') ?? 'added'
+ return json({
+ data: rows[result],
+ total: 1,
+ page: Number(url.searchParams.get('page')),
+ limit: Number(url.searchParams.get('limit')),
+ })
+ }
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderDetails('latest')
+ await user.click(
+ await screen.findByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
+ )
- it('loads server page two without duplicating the first page', async () => {
- const user = userEvent.setup()
- const { results } = renderDetails()
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.loadMore' }))
- expect(await screen.findByText('Member 21')).toBeInTheDocument()
- expect(screen.getAllByText('Member 1')).toHaveLength(1)
- expect(results).toHaveBeenLastCalledWith(
- { query: { result: 'added', page: 2, limit: 20 } },
- { context: { silent: true } },
- )
- expect(
- screen.queryByRole('button', { name: 'contacts.imPlatform.action.loadMore' }),
- ).not.toBeInTheDocument()
+ await waitFor(() => expect(downloadBlob).toHaveBeenCalledOnce())
+ const { data, fileName } = vi.mocked(downloadBlob).mock.calls[0]![0]
+ expect(fileName).toBe('im-sync-run-1.csv')
+ expect(data.type).toBe('text/csv;charset=utf-8;')
+ const csv = await data.text()
+ expect(csv).toContain(
+ '\uFEFFrun_id,result,contact_id,contact_name,provider,platform_user_id,platform_display_name,platform_email,reason',
+ )
+ expect(csv).toContain("'=Alice")
+ expect(csv).toContain("'+Directory Alice")
+ expect(csv).toContain('feishu,alice-im,')
+ expect(csv).toContain('[email protected]')
+ expect(csv).toContain('run-1,contacts.imPlatform.details.filter.not_matched,,,feishu,,,,')
+ expect(csv).toContain(
+ 'run-1,contacts.imPlatform.details.filter.failed,,,feishu,,,,Directory unavailable',
+ )
+ expect(csv).toContain('old-alice,,,contacts.imPlatform.details.removalReason.binding_invalidated')
+ expect(csv).toContain(
+ 'run-1,contacts.imPlatform.details.filter.skipped,contact-1,Alice,feishu,,,,',
+ )
+})
+
+it('keeps an empty report available after a failed download and allows retrying', async () => {
+ let failed = false
+ network.handle.mockImplementation((request) => {
+ const url = new URL(request.url)
+ if (
+ url.pathname.endsWith('/latest/results') &&
+ url.searchParams.get('limit') === '100' &&
+ !failed
+ ) {
+ failed = true
+ return json({ message: 'Report temporarily unavailable' }, 503)
+ }
+ return defaultResponse(request)
+ })
+ const user = userEvent.setup()
+ renderDetails()
+ const download = await screen.findByRole('button', {
+ name: 'contacts.imPlatform.details.downloadReport',
})
+ expect(screen.getByText('contacts.imPlatform.details.empty')).toBeVisible()
+ await user.click(download)
- it('retains loaded results after a failed page and retries that page successfully', async () => {
- const user = userEvent.setup()
- renderDetails({ pageFailure: true })
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.loadMore' }))
- expect(await screen.findByText('contacts.imPlatform.details.pageError')).toBeInTheDocument()
- expect(screen.getByText('Member 1')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.retry' }))
- expect(await screen.findByText('Member 21')).toBeInTheDocument()
- expect(screen.queryByText('contacts.imPlatform.details.pageError')).not.toBeInTheDocument()
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.details.downloadFailed',
+ )
+ expect(downloadBlob).not.toHaveBeenCalled()
+ expect(screen.getByText('contacts.imPlatform.details.empty')).toBeVisible()
+ await user.click(download)
+
+ await waitFor(() => expect(downloadBlob).toHaveBeenCalledOnce())
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+})
+
+it('refuses to download when latest is replaced after the dialog opened', async () => {
+ let latestRequests = 0
+ network.handle.mockImplementation((request) => {
+ if (request.url.endsWith('/latest')) {
+ latestRequests += 1
+ return json({ run: syncRun({ id: latestRequests === 1 ? 'run-1' : 'run-2' }) })
+ }
+ return defaultResponse(request)
})
+ const user = userEvent.setup()
+ renderDetails('latest')
+ await user.click(
+ await screen.findByRole('button', { name: 'contacts.imPlatform.details.downloadReport' }),
+ )
- it('recovers from an initial offline failure without requesting results before the run loads', async () => {
- const user = userEvent.setup()
- const { results } = renderDetails({ initialFailure: true })
- expect(await screen.findByText('contacts.imPlatform.details.loadError')).toBeInTheDocument()
- expect(results).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'contacts.imPlatform.action.retry' }))
- expect(await screen.findByText('Member 1')).toBeInTheDocument()
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'contacts.imPlatform.details.reportChanged',
+ )
+ expect(downloadBlob).not.toHaveBeenCalled()
+})
+
+it('refuses a report when a newer run replaced the requested one', async () => {
+ network.handle.mockImplementation((request) =>
+ request.url.endsWith('/latest')
+ ? json({ run: syncRun({ id: 'run-2' }) })
+ : defaultResponse(request),
+ )
+ await expect(loadContactImSyncReport(newClient(), 'run-1')).rejects.toMatchObject({
+ code: 'sync_run_not_found',
})
+ expect(network.handle).toHaveBeenCalledTimes(1)
+})
- it('shows the real server failure and handles runs that never started', async () => {
- renderDetails({
- run: createRun({
- status: 'failed',
- started_at: null,
- finished_at: null,
- error_message: 'Directory synchronization could not start',
- }),
- })
- expect(await screen.findByText('Directory synchronization could not start')).toBeInTheDocument()
- expect(screen.queryByText(/by null|Invalid Date/)).not.toBeInTheDocument()
+it('stores the actual run ID and result filter in URL state without adding history entries', async () => {
+ const update = vi.fn()
+ function Probe() {
+ const [run, setRun] = useContactImSyncRunUrlState()
+ const [result, setResult] = useContactImSyncResultUrlState()
+ return (
+ <>
+ <output>
+ {run}:{result}
+ </output>
+ <button onClick={() => setRun('run-42')}>Open run</button>
+ <button onClick={() => setResult('removed')}>Removed</button>
+ </>
+ )
+ }
+ const user = userEvent.setup()
+ render(
+ <NuqsTestingAdapter hasMemory onUrlUpdate={update}>
+ <Probe />
+ </NuqsTestingAdapter>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Open run' }))
+ await user.click(screen.getByRole('button', { name: 'Removed' }))
+ await waitFor(() =>
+ expect(update.mock.lastCall?.[0].searchParams.get('sync_run_id')).toBe('run-42'),
+ )
+ expect(update.mock.calls.map(([event]) => event.options.history)).not.toContain('push')
+ await waitFor(() =>
+ expect(update.mock.lastCall?.[0].searchParams.get('sync_result')).toBe('removed'),
+ )
+ expect(screen.getByText('run-42:removed')).toBeVisible()
+})
+
+it('refuses a report when pagination repeats a result instead of silently exporting duplicates', async () => {
+ network.handle.mockImplementation((request) => {
+ if (request.url.endsWith('/latest'))
+ return json({
+ run: syncRun({
+ result_counts: { added: 2, not_matched: 0, failed: 0, removed: 0, skipped: 0 },
+ }),
+ })
+ return json({ data: [added(1), added(1)], total: 2, page: 1, limit: 100 })
+ })
+ await expect(loadContactImSyncReport(newClient(), 'run-1')).rejects.toMatchObject({
+ code: 'page_load_failed',
})
})
+
+it.each(['queued', 'running'] as const)(
+ 'waits for a %s run to finish before fetching final results',
+ async (status) => {
+ let finished = false
+ network.handle.mockImplementation((request) => {
+ if (request.url.endsWith('/latest')) return json({ run: syncRun({ status }) })
+ if (request.url.includes('/latest/results'))
+ return json({
+ data: finished ? [added(1)] : [],
+ total: finished ? 1 : 0,
+ page: 1,
+ limit: 20,
+ })
+ return defaultResponse(request)
+ })
+ const client = newClient()
+ render(
+ <QueryClientProvider client={client}>
+ <NuqsTestingAdapter>
+ <ContactImSyncDetailsDialog open runId="run-1" onOpenChange={() => {}} />
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
+ )
+ const latest = consoleQuery.workspaces.current.humanInput.v2.imSyncRuns.latest.get
+ await waitFor(() =>
+ expect(client.getQueryData(latest.queryKey())).toEqual({ run: syncRun({ status }) }),
+ )
+ expect(
+ network.handle.mock.calls.filter(([request]) => request.url.includes('/latest/results')),
+ ).toHaveLength(0)
+
+ finished = true
+ act(() => {
+ client.setQueryData(latest.queryKey(), { run: syncRun({ status: 'succeeded' }) })
+ })
+ expect(await screen.findByText('Contact 1')).toBeVisible()
+ expect(
+ network.handle.mock.calls.filter(([request]) => request.url.includes('/latest/results')),
+ ).toHaveLength(1)
+ },
+)
diff --git a/web/features/contacts/im-platform/account-setting-page.tsx b/web/features/contacts/im-platform/account-setting-page.tsx
index 5b0bce1bae9..afdc2227fbd 100644
--- a/web/features/contacts/im-platform/account-setting-page.tsx
+++ b/web/features/contacts/im-platform/account-setting-page.tsx
@@ -22,7 +22,9 @@ export function ContactsImPlatformAccountSettingPage({
return (
<ContactsImPlatformRuntimeProvider organization={organization}>
- <ContactsImPlatformManagementSurface />
+ <div className="-mt-2">
+ <ContactsImPlatformManagementSurface />
+ </div>
</ContactsImPlatformRuntimeProvider>
)
}
diff --git a/web/features/contacts/im-platform/binding-dialog.tsx b/web/features/contacts/im-platform/binding-dialog.tsx
index 52efc4c43fc..a6b7d63f661 100644
--- a/web/features/contacts/im-platform/binding-dialog.tsx
+++ b/web/features/contacts/im-platform/binding-dialog.tsx
@@ -1,5 +1,6 @@
'use client'
+import type { ChannelSummary } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ContactImIntegrationView, ContactImProviderDefinition } from './types'
import {
AlertDialog,
@@ -14,15 +15,15 @@ import {
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
- Dialog,
- DialogClose,
- DialogContent,
+ DialogBody,
DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -44,16 +45,14 @@ type CredentialValues = Partial<Record<Exclude<ContactImProviderField, 'secret'>
export type ContactImBindingDialogProps = {
integration: ContactImIntegrationView | null
- open: boolean
provider: ContactImProviderDefinition
replaceActiveProvider: boolean
- replacedIntegration?: ContactImIntegrationView
+ replacedIntegration?: ChannelSummary
onOpenChange: (open: boolean) => void
}
-export function ContactImBindingDialog({
+export function ContactImBindingContent({
integration,
- open,
provider,
replaceActiveProvider,
replacedIntegration,
@@ -72,7 +71,7 @@ export function ContactImBindingDialog({
replaceActiveProvider ? null : integration,
)
const [step, setStep] = useState<'credentials' | 'callbacks'>(() =>
- !replaceActiveProvider && integration?.callbackUrl ? 'callbacks' : 'credentials',
+ !replaceActiveProvider && integration?.webhook_url ? 'callbacks' : 'credentials',
)
const [values, setValues] = useState<CredentialValues>(() =>
replaceActiveProvider ? {} : { ...integration?.configuredValues },
@@ -89,7 +88,7 @@ export function ContactImBindingDialog({
saveCredentials.error instanceof ContactImRepositoryError &&
saveCredentials.error.code === ContactImRepositoryErrorCode.SavedDetailsUnavailable
const credentialsDisabled = isPending || savedDetailsUnavailable
- const callbackUrl = savedIntegration?.callbackUrl
+ const callbackUrl = savedIntegration?.webhook_url
const callbackSetup =
provider.provider === ContactImProvider.Email
? null
@@ -98,15 +97,14 @@ export function ContactImBindingDialog({
const canContinueWithoutSaving = Boolean(callbackUrl) && !credentialsEdited
const targetIntegration = savedIntegration ?? replacedIntegration
const canRetainField = (field: ContactImProviderField) =>
- !replaceTenant &&
- canRetainCredential(savedIntegration, field, provider.requiresFreshCredentials)
+ !replaceTenant && canRetainCredential(savedIntegration, field)
useEffect(() => {
if (step === 'credentials') firstCredentialRef.current?.focus()
}, [step])
const credentialCommand = () => ({
- channelId: replaceTenant ? undefined : savedIntegration?.channelId,
- expectedConfigVersion: replaceTenant ? undefined : savedIntegration?.configVersion,
+ channelId: replaceTenant ? undefined : savedIntegration?.id,
+ expectedConfigVersion: replaceTenant ? undefined : savedIntegration?.config_version,
provider: provider.provider,
clearedFields,
secret: secret.trim() || undefined,
@@ -146,14 +144,9 @@ export function ContactImBindingDialog({
const closeDialog = () => {
if (isPending) return
- clearSecrets()
onOpenChange(false)
}
- const handleOpenChange = (nextOpen: boolean) => {
- if (!nextOpen) closeDialog()
- }
-
const handleTestConnection = async () => {
if (credentialsDisabled || !formRef.current?.reportValidity()) return
setTestSucceeded(false)
@@ -171,8 +164,8 @@ export function ContactImBindingDialog({
try {
const saved = await saveCredentials.saveCredentials({
...credentialCommand(),
- channelId: targetIntegration?.channelId,
- expectedConfigVersion: targetIntegration?.configVersion,
+ channelId: targetIntegration?.id,
+ expectedConfigVersion: targetIntegration?.config_version,
replaceActiveProvider: replaceCurrentTenant || (replaceActiveProvider && !savedIntegration),
})
setSavedIntegration(saved)
@@ -180,7 +173,7 @@ export function ContactImBindingDialog({
setValues(saved.configuredValues)
setCredentialsEdited(false)
clearSecrets()
- if (saved.callbackUrl) setStep('callbacks')
+ if (saved.webhook_url) setStep('callbacks')
else onOpenChange(false)
} catch (error) {
if (
@@ -202,8 +195,7 @@ export function ContactImBindingDialog({
}
const handleSave = () => {
- if (replaceTenant) setReplacementConfirmationOpen(true)
- else return save()
+ return save(replaceTenant)
}
const confirmReplacement = () => {
@@ -263,202 +255,186 @@ export function ContactImBindingDialog({
}
return (
- <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal={isPending}>
- <DialogContent
- backdropProps={{ forceRender: true }}
- className={cn(
- 'max-h-[calc(100dvh-2rem)] max-w-[calc(100vw-2rem)] overflow-hidden!',
- hasCallbackSetup ? 'w-120' : 'w-104',
- )}
- >
- <DialogClose
- render={
- <IconButton
- aria-label={tCommon(($) => $['operation.close'])}
- className="absolute inset-e-5 top-5"
- disabled={isPending}
- size="lg"
- >
- <span aria-hidden className="i-ri-close-line size-4.5" />
- </IconButton>
- }
+ <>
+ <DialogHeader>
+ <DialogHeaderCloseButton
+ aria-label={tCommon(($) => $['operation.close'])}
+ disabled={isPending}
/>
- <div className="shrink-0 space-y-1 ps-6 pe-14 pt-6 pb-3">
- <DialogTitle>{title}</DialogTitle>
- <DialogDescription className={hasCallbackSetup ? undefined : 'sr-only'}>
- {hasCallbackSetup
- ? step === 'callbacks'
- ? t(($) => $['imPlatform.bindingDialog.callbackDescription'], {
- provider: provider.displayName,
- })
- : t(($) => $['imPlatform.bindingDialog.credentialsDescription'], {
- provider: provider.displayName,
- })
- : t(($) => $['imPlatform.bindingDialog.description'])}
- </DialogDescription>
- </div>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription className={hasCallbackSetup ? undefined : 'sr-only'}>
+ {hasCallbackSetup
+ ? step === 'callbacks'
+ ? t(($) => $['imPlatform.bindingDialog.callbackDescription'], {
+ provider: provider.displayName,
+ })
+ : t(($) => $['imPlatform.bindingDialog.credentialsDescription'], {
+ provider: provider.displayName,
+ })
+ : t(($) => $['imPlatform.bindingDialog.description'])}
+ </DialogDescription>
+ </DialogHeader>
- {hasCallbackSetup && (
- <ol className="flex shrink-0 items-center gap-3 px-6 pt-2 pb-5">
- {(['credentials', 'callbacks'] as const).map((item, index) => (
- <li
- key={item}
- aria-current={step === item ? 'step' : undefined}
+ {hasCallbackSetup && (
+ <ol className="flex shrink-0 items-center gap-3 px-6 pt-2 pb-5">
+ {(['credentials', 'callbacks'] as const).map((item, index) => (
+ <li
+ key={item}
+ aria-current={step === item ? 'step' : undefined}
+ className={cn(
+ 'flex min-w-0 items-center gap-2 system-xs-medium-uppercase',
+ step === item ? 'text-text-accent' : 'text-text-quaternary',
+ )}
+ >
+ {index > 0 && <span aria-hidden className="me-1 h-px w-4 bg-divider-subtle" />}
+ <span
className={cn(
- 'flex min-w-0 items-center gap-2 system-xs-medium-uppercase',
- step === item ? 'text-text-accent' : 'text-text-quaternary',
+ 'shrink-0 rounded-full px-1.5 py-0.5',
+ step === item
+ ? 'bg-components-button-primary-bg text-components-button-primary-text'
+ : 'ring-1 ring-divider-subtle',
)}
>
- {index > 0 && <span aria-hidden className="me-1 h-px w-4 bg-divider-subtle" />}
- <span
- className={cn(
- 'shrink-0 rounded-full px-1.5 py-0.5',
- step === item
- ? 'bg-components-button-primary-bg text-components-button-primary-text'
- : 'ring-1 ring-divider-subtle',
- )}
- >
- {step === item
- ? t(($) => $['imPlatform.bindingDialog.step'], { step: index + 1 })
- : index + 1}
- </span>
- {item === 'credentials'
- ? t(($) => $['imPlatform.bindingDialog.credentialsStep'])
- : t(($) => $['imPlatform.bindingDialog.callbackStep'])}
- </li>
- ))}
- </ol>
- )}
+ {step === item
+ ? t(($) => $['imPlatform.bindingDialog.step'], { step: index + 1 })
+ : index + 1}
+ </span>
+ {item === 'credentials'
+ ? t(($) => $['imPlatform.bindingDialog.credentialsStep'])
+ : t(($) => $['imPlatform.bindingDialog.callbackStep'])}
+ </li>
+ ))}
+ </ol>
+ )}
- {step === 'callbacks' && callbackUrl ? (
- <ContactImCallbackSetup
- callbackUrl={callbackUrl}
- providerName={provider.displayName}
- setup={callbackSetup}
- setupGuideUrl={adapter.setupGuideUrl}
- onBack={() => setStep('credentials')}
- onFinish={closeDialog}
- />
- ) : (
- <Form<CredentialValues>
- ref={formRef}
- className="flex min-h-0 flex-1 flex-col"
- onFormSubmit={handleSave}
- >
- <div className="space-y-4 overflow-y-auto px-6 py-3">
- {isCurrentProvider && (provider.requiresFreshCredentials || replaceTenant) && (
- <p className="system-sm-regular text-text-tertiary">
- {t(($) => $['imPlatform.bindingDialog.freshCredentials'])}
- </p>
- )}
- {adapter.fields.map(({ field, required, secret: isSecret }, index) => (
- <Field key={field} name={field}>
- <div className="flex items-center justify-between gap-2">
- <FieldLabel>{fieldLabels[field]}</FieldLabel>
- {isSecret && !required && canRetainField(field) && (
- <Button
- size="small"
- variant="ghost"
- disabled={credentialsDisabled}
- aria-label={`${fieldLabels[field]}: ${
- clearedFields.includes(field)
- ? t(($) => $['imPlatform.bindingDialog.undoClearCredential'])
- : t(($) => $['imPlatform.bindingDialog.clearSavedCredential'])
- }`}
- onClick={() => {
- setClearedFields((current) =>
- current.includes(field)
- ? current.filter((item) => item !== field)
- : [...current, field],
- )
- setValues((current) => ({ ...current, [field]: '' }))
- setCredentialsEdited(true)
- setTestSucceeded(false)
- testConnection.reset()
- saveCredentials.reset()
- }}
- >
- {clearedFields.includes(field)
+ {step === 'callbacks' && callbackUrl ? (
+ <ContactImCallbackSetup
+ callbackUrl={callbackUrl}
+ providerName={provider.displayName}
+ setup={callbackSetup}
+ setupGuideUrl={adapter.setupGuideUrl}
+ onBack={() => setStep('credentials')}
+ onFinish={closeDialog}
+ />
+ ) : (
+ <Form<CredentialValues>
+ ref={formRef}
+ className="flex min-h-0 flex-1 flex-col"
+ onFormSubmit={handleSave}
+ >
+ <DialogBody className="space-y-4">
+ {isCurrentProvider && replaceTenant && (
+ <p className="system-sm-regular text-text-tertiary">
+ {t(($) => $['imPlatform.bindingDialog.freshCredentials'])}
+ </p>
+ )}
+ {adapter.fields.map(({ field, required, secret: isSecret }, index) => (
+ <Field key={field} name={field}>
+ <div className="flex items-center justify-between gap-2">
+ <FieldLabel>{fieldLabels[field]}</FieldLabel>
+ {isSecret && !required && canRetainField(field) && (
+ <Button
+ size="small"
+ variant="ghost"
+ disabled={credentialsDisabled}
+ aria-label={`${fieldLabels[field]}: ${
+ clearedFields.includes(field)
? t(($) => $['imPlatform.bindingDialog.undoClearCredential'])
- : t(($) => $['imPlatform.bindingDialog.clearSavedCredential'])}
- </Button>
- )}
- </div>
- <Input
- ref={index === 0 ? firstCredentialRef : undefined}
- autoComplete={isSecret ? 'new-password' : 'off'}
- disabled={credentialsDisabled || clearedFields.includes(field)}
- placeholder={
- isSecret && canRetainField(field) && !clearedFields.includes(field)
- ? '••••••••'
- : fieldPlaceholders[field]
- }
- required={required && !canRetainField(field)}
- type={isSecret ? 'password' : 'text'}
- value={field === ContactImProviderField.Secret ? secret : (values[field] ?? '')}
- onChange={(event) => {
- const value = event.currentTarget.value
- setCredentialsEdited(true)
- setTestSucceeded(false)
- testConnection.reset()
- saveCredentials.reset()
- if (field === ContactImProviderField.Secret) setSecret(value)
- else setValues((current) => ({ ...current, [field]: value }))
- }}
- />
- {clearedFields.includes(field) ? (
- <FieldDescription>
- {t(($) => $['imPlatform.bindingDialog.credentialWillBeCleared'])}
- </FieldDescription>
- ) : (
- isSecret &&
- canRetainField(field) && (
- <FieldDescription>
- {t(($) => $['imPlatform.bindingDialog.secretConfigured'])}
- </FieldDescription>
- )
+ : t(($) => $['imPlatform.bindingDialog.clearSavedCredential'])
+ }`}
+ onClick={() => {
+ setClearedFields((current) =>
+ current.includes(field)
+ ? current.filter((item) => item !== field)
+ : [...current, field],
+ )
+ setValues((current) => ({ ...current, [field]: '' }))
+ setCredentialsEdited(true)
+ setTestSucceeded(false)
+ testConnection.reset()
+ saveCredentials.reset()
+ }}
+ >
+ {clearedFields.includes(field)
+ ? t(($) => $['imPlatform.bindingDialog.undoClearCredential'])
+ : t(($) => $['imPlatform.bindingDialog.clearSavedCredential'])}
+ </Button>
)}
- <FieldError match="valueMissing">
- {t(($) => $['imPlatform.bindingDialog.required'])}
- </FieldError>
- </Field>
- ))}
- <Button
- aria-labelledby={testLabelId}
- disabled={saveCredentials.isPending || savedDetailsUnavailable}
- loading={testConnection.isPending}
- onClick={handleTestConnection}
- >
- <span aria-hidden className="i-ri-send-plane-2-line size-4" />
- <span id={testLabelId}>
- {testConnection.isPending
- ? t(($) => $['imPlatform.action.testing'])
- : t(($) => $['imPlatform.action.testConnection'])}
- </span>
- </Button>
- {testSucceeded && (
- <div role="status" className="system-xs-regular text-text-success">
- {t(($) => $['imPlatform.email.testSucceeded'])}
</div>
- )}
- {testConnection.isError && (
- <div role="alert" className="system-sm-regular text-text-destructive">
- {safeErrorMessage(
- testConnection.error,
- t(($) => $['imPlatform.bindingDialog.testFailed']),
- )}
- </div>
- )}
- {saveCredentials.isError && (
- <div role="alert" className="system-sm-regular text-text-destructive">
- {safeErrorMessage(
- saveCredentials.error,
- t(($) => $['imPlatform.bindingDialog.saveFailed']),
- )}
- </div>
- )}
+ <Input
+ ref={index === 0 ? firstCredentialRef : undefined}
+ autoComplete={isSecret ? 'new-password' : 'off'}
+ disabled={credentialsDisabled || clearedFields.includes(field)}
+ placeholder={
+ isSecret && canRetainField(field) && !clearedFields.includes(field)
+ ? '••••••••'
+ : fieldPlaceholders[field]
+ }
+ required={required && !canRetainField(field)}
+ type={isSecret ? 'password' : 'text'}
+ value={field === ContactImProviderField.Secret ? secret : (values[field] ?? '')}
+ onChange={(event) => {
+ const value = event.currentTarget.value
+ setCredentialsEdited(true)
+ setTestSucceeded(false)
+ testConnection.reset()
+ saveCredentials.reset()
+ if (field === ContactImProviderField.Secret) setSecret(value)
+ else setValues((current) => ({ ...current, [field]: value }))
+ }}
+ />
+ {clearedFields.includes(field) ? (
+ <FieldDescription>
+ {t(($) => $['imPlatform.bindingDialog.credentialWillBeCleared'])}
+ </FieldDescription>
+ ) : (
+ isSecret &&
+ canRetainField(field) && (
+ <FieldDescription>
+ {t(($) => $['imPlatform.bindingDialog.secretConfigured'])}
+ </FieldDescription>
+ )
+ )}
+ <FieldError match="valueMissing">
+ {t(($) => $['imPlatform.bindingDialog.required'])}
+ </FieldError>
+ </Field>
+ ))}
+ <Button
+ aria-labelledby={testLabelId}
+ disabled={saveCredentials.isPending || savedDetailsUnavailable}
+ loading={testConnection.isPending}
+ onClick={handleTestConnection}
+ >
+ <span aria-hidden className="i-ri-send-plane-2-line size-4" />
+ <span id={testLabelId}>
+ {testConnection.isPending
+ ? t(($) => $['imPlatform.action.testing'])
+ : t(($) => $['imPlatform.action.testConnection'])}
+ </span>
+ </Button>
+ <div role="status" aria-atomic="true" className="system-xs-regular text-text-success">
+ {testSucceeded ? t(($) => $['imPlatform.email.testSucceeded']) : ''}
</div>
- <div className="mt-auto flex shrink-0 flex-wrap items-center justify-between gap-3 px-6 pt-5 pb-6">
+ {testConnection.isError && (
+ <div role="alert" className="system-sm-regular text-text-destructive">
+ {safeErrorMessage(
+ testConnection.error,
+ t(($) => $['imPlatform.bindingDialog.testFailed']),
+ )}
+ </div>
+ )}
+ {saveCredentials.isError && (
+ <div role="alert" className="system-sm-regular text-text-destructive">
+ {safeErrorMessage(
+ saveCredentials.error,
+ t(($) => $['imPlatform.bindingDialog.saveFailed']),
+ )}
+ </div>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <div className="flex w-full flex-wrap items-center justify-between gap-3">
<a
className="inline-flex items-center gap-1 rounded-sm system-xs-regular text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
href={adapter.setupGuideUrl}
@@ -495,16 +471,15 @@ export function ContactImBindingDialog({
</Button>
</div>
</div>
- </Form>
- )}
- </DialogContent>
+ </DialogFooter>
+ </Form>
+ )}
<AlertDialog open={replacementConfirmationOpen} onOpenChange={setReplacementConfirmationOpen}>
<AlertDialogContent backdropProps={{ forceRender: true }}>
<AlertDialogHeader>
<AlertDialogTitle>
- {t(($) => $['imPlatform.replacement.title'], {
- current: provider.displayName,
- next: provider.displayName,
+ {t(($) => $['imPlatform.bindingDialog.replaceTenantTitle'], {
+ identity: savedIntegration?.display_identifier ?? provider.displayName,
})}
</AlertDialogTitle>
<AlertDialogDescription>
@@ -521,6 +496,6 @@ export function ContactImBindingDialog({
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
- </Dialog>
+ </>
)
}
diff --git a/web/features/contacts/im-platform/callback-setup.tsx b/web/features/contacts/im-platform/callback-setup.tsx
index 0c850100a3c..116cc380ce7 100644
--- a/web/features/contacts/im-platform/callback-setup.tsx
+++ b/web/features/contacts/im-platform/callback-setup.tsx
@@ -1,11 +1,10 @@
import type { resolveContactImCallbackSetup } from './provider-form-adapters'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
-import copy from 'copy-to-clipboard'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useRef } from 'react'
import { Trans, useTranslation } from 'react-i18next'
+import { CopyFeedback } from '@/app/components/base/copy-feedback'
type ContactImCallbackSetupProps = {
callbackUrl: string
@@ -26,7 +25,6 @@ export function ContactImCallbackSetup({
}: ContactImCallbackSetupProps) {
const { t } = useTranslation(['contacts'])
const inputRef = useRef<HTMLInputElement>(null)
- const [copied, setCopied] = useState(false)
useEffect(() => {
inputRef.current?.focus()
@@ -40,26 +38,13 @@ export function ContactImCallbackSetup({
<InputGroup>
<InputGroupInput ref={inputRef} readOnly value={callbackUrl} />
<InputGroupAddon align="inline-end">
- <IconButton
- aria-label={t(($) => $['imPlatform.action.copyCallback'])}
- onClick={async () => {
- try {
- setCopied(await copy(callbackUrl))
- } catch {
- setCopied(false)
- }
- }}
- >
- <span
- aria-hidden
- className={copied ? 'i-ri-check-line size-4' : 'i-ri-file-copy-line size-4'}
- />
- </IconButton>
+ <CopyFeedback
+ content={callbackUrl}
+ copyLabel={t(($) => $['imPlatform.action.copyCallback'])}
+ copiedLabel={t(($) => $['imPlatform.action.copied'])}
+ />
</InputGroupAddon>
</InputGroup>
- <span role="status" className="sr-only">
- {copied ? t(($) => $['imPlatform.action.copied']) : ''}
- </span>
</Field>
{setup && (
diff --git a/web/features/contacts/im-platform/composition-context.ts b/web/features/contacts/im-platform/composition-context.ts
index 974e3b6a55d..69d8dce0038 100644
--- a/web/features/contacts/im-platform/composition-context.ts
+++ b/web/features/contacts/im-platform/composition-context.ts
@@ -1,27 +1,10 @@
'use client'
-
import type { ContactsImPlatformOrganizationContext } from './context'
-import type { ContactImPlatformRepository } from './repository'
import { createContext, use } from 'react'
-
-export const ContactImPlatformRepositoryContext = createContext<ContactImPlatformRepository | null>(
- null,
-)
export const ContactImPlatformOrganizationContext =
createContext<ContactsImPlatformOrganizationContext | null>(null)
-
-export const useContactsImPlatformRepository = () => {
- const repository = use(ContactImPlatformRepositoryContext)
-
- if (!repository) throw new Error('ContactsImPlatformProvider is required')
-
- return repository
-}
-
export const useContactsImPlatformOrganization = () => {
const organization = use(ContactImPlatformOrganizationContext)
-
if (!organization) throw new Error('ContactsImPlatformProvider is required')
-
return organization
}
diff --git a/web/features/contacts/im-platform/composition.tsx b/web/features/contacts/im-platform/composition.tsx
index f34c2a06aa5..89348403036 100644
--- a/web/features/contacts/im-platform/composition.tsx
+++ b/web/features/contacts/im-platform/composition.tsx
@@ -1,35 +1,7 @@
'use client'
-
import type { ReactNode } from 'react'
import type { ContactsImPlatformOrganizationContext } from './context'
-import type { ContactImPlatformRepository } from './repository'
-import { useMemo } from 'react'
-import {
- ContactImPlatformOrganizationContext,
- ContactImPlatformRepositoryContext,
-} from './composition-context'
-import { createContactImApiRepository } from './repository'
-
-export type ContactsImPlatformProviderProps = {
- children: ReactNode
- organization: ContactsImPlatformOrganizationContext
- repository: ContactImPlatformRepository
-}
-
-export function ContactsImPlatformProvider({
- children,
- organization,
- repository,
-}: ContactsImPlatformProviderProps) {
- return (
- <ContactImPlatformOrganizationContext value={organization}>
- <ContactImPlatformRepositoryContext value={repository}>
- {children}
- </ContactImPlatformRepositoryContext>
- </ContactImPlatformOrganizationContext>
- )
-}
-
+import { ContactImPlatformOrganizationContext } from './composition-context'
export function ContactsImPlatformRuntimeProvider({
children,
organization,
@@ -37,14 +9,9 @@ export function ContactsImPlatformRuntimeProvider({
children: ReactNode
organization: ContactsImPlatformOrganizationContext
}) {
- const repository = useMemo(() => createContactImApiRepository(organization), [organization])
return (
- <ContactsImPlatformProvider
- key={repository.queryKey}
- organization={organization}
- repository={repository}
- >
+ <ContactImPlatformOrganizationContext value={organization}>
{children}
- </ContactsImPlatformProvider>
+ </ContactImPlatformOrganizationContext>
)
}
diff --git a/web/features/contacts/im-platform/credential-draft.ts b/web/features/contacts/im-platform/credential-draft.ts
index fd3fe91ce13..143f79f6fd0 100644
--- a/web/features/contacts/im-platform/credential-draft.ts
+++ b/web/features/contacts/im-platform/credential-draft.ts
@@ -4,9 +4,7 @@ import type { ContactImIntegrationView, ContactImProviderField } from './types'
export const canRetainCredential = (
integration: ContactImIntegrationView | null,
field: ContactImProviderField,
- requiresFreshCredentials = false,
) =>
- !requiresFreshCredentials &&
Boolean(integration) &&
(integration?.configuredFields?.includes(field) ??
(field === 'secret'
diff --git a/web/features/contacts/im-platform/credentials.ts b/web/features/contacts/im-platform/credentials.ts
new file mode 100644
index 00000000000..2fa01091625
--- /dev/null
+++ b/web/features/contacts/im-platform/credentials.ts
@@ -0,0 +1,284 @@
+import type {
+ EmailChannelDetailResponse,
+ EmailProviderCredentialsUpdateInputWritable,
+ EmailProviderCredentialsWritable,
+ ImChannelDetailResponse,
+ ImProviderCredentialsInputWritable,
+ ImProviderCredentialsUpdateInputWritable,
+ UnchangedInput,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import type {
+ ContactImIntegrationView,
+ ContactImProvider,
+ ContactImProviderField,
+ ContactImProviderFieldDefinition,
+ TestContactImConnectionCommand,
+} from './types'
+import { ContactImRepositoryError, ContactImRepositoryErrorCode } from './types'
+
+export const providerMetadata: Record<
+ ContactImProvider,
+ { name: string; fields: ContactImProviderFieldDefinition[] }
+> = {
+ resend: {
+ name: 'Email',
+ fields: [
+ { field: 'senderEmail', required: true },
+ { field: 'senderName', required: true },
+ { field: 'secret', required: true, secret: true },
+ ],
+ },
+ feishu: {
+ name: 'Feishu',
+ fields: [
+ { field: 'appId', required: true },
+ { field: 'secret', required: true, secret: true },
+ { field: 'verificationToken', required: false, secret: true },
+ { field: 'encryptKey', required: false, secret: true },
+ ],
+ },
+ lark: {
+ name: 'Lark',
+ fields: [
+ { field: 'appId', required: true },
+ { field: 'secret', required: true, secret: true },
+ { field: 'verificationToken', required: false, secret: true },
+ { field: 'encryptKey', required: false, secret: true },
+ ],
+ },
+ slack: {
+ name: 'Slack',
+ fields: [
+ { field: 'clientId', required: true },
+ { field: 'secret', required: true, secret: true },
+ { field: 'signingSecret', required: true, secret: true },
+ { field: 'botToken', required: true, secret: true },
+ { field: 'appToken', required: false, secret: true },
+ ],
+ },
+ ding_talk: {
+ name: 'DingTalk',
+ fields: [
+ { field: 'corpId', required: true },
+ { field: 'clientId', required: true },
+ { field: 'secret', required: true, secret: true },
+ ],
+ },
+ ms_teams: {
+ name: 'Microsoft Teams',
+ fields: [
+ { field: 'tenantId', required: true },
+ { field: 'clientId', required: true },
+ { field: 'secret', required: true, secret: true },
+ ],
+ },
+ we_com: {
+ name: 'WeCom',
+ fields: [
+ { field: 'corpId', required: true },
+ { field: 'agentId', required: true },
+ { field: 'secret', required: true, secret: true },
+ ],
+ },
+}
+
+export function emailSettingsFor(command: TestContactImConnectionCommand) {
+ const sender_email = command.values.senderEmail?.trim()
+ const sender_name = command.values.senderName?.trim()
+ if (!sender_email || !sender_name)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.RequiredFieldsMissing)
+ return { sender_email, sender_name }
+}
+
+export function updateEmailSettingsFor(command: TestContactImConnectionCommand) {
+ const unchanged: UnchangedInput = { type: 'unchanged' }
+ return {
+ sender_email: command.values.senderEmail?.trim() || unchanged,
+ sender_name: command.values.senderName?.trim() || unchanged,
+ }
+}
+
+function validateClearedFields(command: TestContactImConnectionCommand) {
+ for (const field of command.clearedFields ?? []) {
+ const definition = providerMetadata[command.provider].fields.find(
+ (item) => item.field === field,
+ )
+ if (!definition || definition.required)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
+ }
+}
+
+export function createCredentialsFor(command: TestContactImConnectionCommand) {
+ validateClearedFields(command)
+ const required = (field: ContactImProviderField) => {
+ const value = (field === 'secret' ? command.secret : command.values[field])?.trim()
+ if (!value)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.RequiredFieldsMissing)
+ return value
+ }
+ const optional = (field: Exclude<ContactImProviderField, 'secret'>) =>
+ command.clearedFields?.includes(field) ? null : command.values[field]?.trim() || null
+ switch (command.provider) {
+ case 'resend':
+ return {
+ provider: 'resend',
+ api_key: required('secret'),
+ } satisfies EmailProviderCredentialsWritable
+ case 'feishu':
+ case 'lark':
+ return {
+ provider: command.provider,
+ app_id: required('appId'),
+ app_secret: required('secret'),
+ encrypt_key: optional('encryptKey'),
+ verification_token: optional('verificationToken'),
+ } satisfies ImProviderCredentialsInputWritable
+ case 'slack':
+ return {
+ provider: 'slack',
+ client_id: required('clientId'),
+ client_secret: required('secret'),
+ signing_secret: required('signingSecret'),
+ bot_token: required('botToken'),
+ app_token: optional('appToken'),
+ } satisfies ImProviderCredentialsInputWritable
+ case 'ding_talk':
+ return {
+ provider: 'ding_talk',
+ corp_id: required('corpId'),
+ client_id: required('clientId'),
+ client_secret: required('secret'),
+ } satisfies ImProviderCredentialsInputWritable
+ case 'ms_teams':
+ return {
+ provider: 'ms_teams',
+ tenant_id: required('tenantId'),
+ client_id: required('clientId'),
+ client_secret: required('secret'),
+ } satisfies ImProviderCredentialsInputWritable
+ case 'we_com':
+ return {
+ provider: 'we_com',
+ corp_id: required('corpId'),
+ agent_id: required('agentId'),
+ secret: required('secret'),
+ } satisfies ImProviderCredentialsInputWritable
+ }
+}
+
+export function updateCredentialsFor(
+ command: TestContactImConnectionCommand,
+): EmailProviderCredentialsUpdateInputWritable | ImProviderCredentialsUpdateInputWritable {
+ validateClearedFields(command)
+ const unchanged: UnchangedInput = { type: 'unchanged' }
+ const value = (field: ContactImProviderField) =>
+ (field === 'secret' ? command.secret : command.values[field])?.trim() || unchanged
+ const optional = (field: Exclude<ContactImProviderField, 'secret'>) =>
+ command.clearedFields?.includes(field) ? null : value(field)
+
+ switch (command.provider) {
+ case 'resend':
+ return {
+ provider: 'resend',
+ api_key: value('secret'),
+ }
+ case 'feishu':
+ case 'lark':
+ return {
+ provider: command.provider,
+ app_id: value('appId'),
+ app_secret: value('secret'),
+ encrypt_key: optional('encryptKey'),
+ verification_token: optional('verificationToken'),
+ }
+ case 'slack':
+ return {
+ provider: 'slack',
+ client_id: value('clientId'),
+ client_secret: value('secret'),
+ signing_secret: value('signingSecret'),
+ bot_token: value('botToken'),
+ app_token: optional('appToken'),
+ }
+ case 'ding_talk':
+ return {
+ provider: 'ding_talk',
+ corp_id: value('corpId'),
+ client_id: value('clientId'),
+ client_secret: value('secret'),
+ }
+ case 'ms_teams':
+ return {
+ provider: 'ms_teams',
+ tenant_id: value('tenantId'),
+ client_id: value('clientId'),
+ client_secret: value('secret'),
+ }
+ case 'we_com':
+ return {
+ provider: 'we_com',
+ corp_id: value('corpId'),
+ agent_id: value('agentId'),
+ secret: value('secret'),
+ }
+ }
+}
+
+export const toDetailView = (
+ detail: EmailChannelDetailResponse | ImChannelDetailResponse,
+): ContactImIntegrationView => {
+ const integration = detail.summary
+ const configuredFields: ContactImProviderField[] = []
+ const configuredValues: ContactImIntegrationView['configuredValues'] = {}
+ const configured = (field: ContactImProviderField, present = true) => {
+ if (present) configuredFields.push(field)
+ }
+ const plain = (field: Exclude<ContactImProviderField, 'secret'>, value: string) => {
+ configuredValues[field] = value
+ configured(field, Boolean(value))
+ }
+ if ('sender_email' in detail) {
+ plain('senderEmail', detail.sender_email)
+ plain('senderName', detail.sender_name)
+ configured('secret', Boolean(detail.credentials.api_key))
+ } else {
+ const credentials = detail.credentials
+ switch (credentials.provider) {
+ case 'feishu':
+ case 'lark':
+ plain('appId', credentials.app_id)
+ configured('secret', Boolean(credentials.app_secret))
+ configured('verificationToken', credentials.verification_token !== null)
+ configured('encryptKey', credentials.encrypt_key !== null)
+ break
+ case 'slack':
+ plain('clientId', credentials.client_id)
+ configured('secret', Boolean(credentials.client_secret))
+ configured('signingSecret', Boolean(credentials.signing_secret))
+ configured('botToken', Boolean(credentials.bot_token))
+ configured('appToken', credentials.app_token !== null)
+ break
+ case 'ding_talk':
+ plain('corpId', credentials.corp_id)
+ plain('clientId', credentials.client_id)
+ configured('secret', Boolean(credentials.client_secret))
+ break
+ case 'ms_teams':
+ plain('tenantId', credentials.tenant_id)
+ plain('clientId', credentials.client_id)
+ configured('secret', Boolean(credentials.client_secret))
+ break
+ case 'we_com':
+ plain('corpId', credentials.corp_id)
+ plain('agentId', credentials.agent_id)
+ configured('secret', Boolean(credentials.secret))
+ break
+ }
+ }
+ return {
+ ...integration,
+ configuredFields,
+ configuredValues,
+ secretConfigured: configuredFields.includes('secret'),
+ }
+}
diff --git a/web/features/contacts/im-platform/email-config-dialog.tsx b/web/features/contacts/im-platform/email-config-dialog.tsx
index 1b780955b1e..062b243c532 100644
--- a/web/features/contacts/im-platform/email-config-dialog.tsx
+++ b/web/features/contacts/im-platform/email-config-dialog.tsx
@@ -3,18 +3,17 @@
import type { ContactImIntegrationView, ContactImProviderDefinition } from './types'
import { Button } from '@langgenius/dify-ui/button'
import {
- Dialog,
- DialogClose,
- DialogContent,
+ DialogBody,
DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
-import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
-import { useRef, useState } from 'react'
+import { useId, useRef, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import { canRetainCredential } from './credential-draft'
@@ -33,14 +32,12 @@ type EmailConfigValues = {
export type ContactEmailConfigDialogProps = {
integration: ContactImIntegrationView | null
- open: boolean
provider: ContactImProviderDefinition
onOpenChange: (open: boolean) => void
}
-export function ContactEmailConfigDialog({
+export function ContactEmailConfigContent({
integration,
- open,
provider,
onOpenChange,
}: ContactEmailConfigDialogProps) {
@@ -55,14 +52,15 @@ export function ContactEmailConfigDialog({
senderName: integration?.configuredValues.senderName ?? '',
}))
const [apiKey, setApiKey] = useState('')
+ const testLabelId = useId()
+ const saveLabelId = useId()
const [testSucceeded, setTestSucceeded] = useState(false)
const isPending = saveCredentials.isPending || testConnection.isPending
const savedDetailsUnavailable =
saveCredentials.error instanceof ContactImRepositoryError &&
saveCredentials.error.code === ContactImRepositoryErrorCode.SavedDetailsUnavailable
const credentialsDisabled = isPending || savedDetailsUnavailable
- const canRetainField = (field: ContactImProviderField) =>
- canRetainCredential(integration, field, provider.requiresFreshCredentials)
+ const canRetainField = (field: ContactImProviderField) => canRetainCredential(integration, field)
const canRetainSecret = canRetainField(ContactImProviderField.Secret)
const safeErrorMessage = (error: unknown, fallback: string) => {
if (!(error instanceof ContactImRepositoryError)) return fallback
@@ -79,8 +77,8 @@ export function ContactEmailConfigDialog({
throw new Error('ContactEmailConfigDialog requires the Email provider definition')
const command = () => ({
- channelId: integration?.channelId,
- expectedConfigVersion: integration?.configVersion,
+ channelId: integration?.id,
+ expectedConfigVersion: integration?.config_version,
provider: provider.provider,
clearedFields: [],
secret: apiKey.trim() || undefined,
@@ -94,7 +92,6 @@ export function ContactEmailConfigDialog({
const closeDialog = () => {
if (isPending) return
- setApiKey('')
onOpenChange(false)
}
@@ -117,8 +114,8 @@ export function ContactEmailConfigDialog({
await saveCredentials.saveCredentials({
...command(),
replaceActiveProvider: false,
- channelId: integration?.channelId,
- expectedConfigVersion: integration?.configVersion,
+ channelId: integration?.id,
+ expectedConfigVersion: integration?.config_version,
})
setApiKey('')
onOpenChange(false)
@@ -135,262 +132,248 @@ export function ContactEmailConfigDialog({
}
return (
- <Dialog
- open={open}
- disablePointerDismissal={isPending}
- onOpenChange={(nextOpen) => {
- if (!nextOpen) closeDialog()
- }}
- >
- <DialogContent
- backdropProps={{ forceRender: true }}
- className="max-h-[calc(100dvh-2rem)] w-[520px] overflow-hidden!"
- >
- <DialogClose
- render={
- <IconButton
- aria-label={tCommon(($) => $['operation.close'])}
- className="absolute inset-e-5 top-5"
- disabled={isPending}
- size="lg"
- >
- <span aria-hidden className="i-ri-close-line size-4.5" />
- </IconButton>
- }
+ <>
+ <DialogHeader>
+ <DialogHeaderCloseButton
+ aria-label={tCommon(($) => $['operation.close'])}
+ disabled={isPending}
/>
- <div className="shrink-0 space-y-1 ps-6 pe-14 pt-6 pb-3">
- <DialogTitle>{t(($) => $['imPlatform.email.title'])}</DialogTitle>
- <DialogDescription>
- <Trans
- ns="contacts"
- i18nKey={($) => $['imPlatform.email.description']}
- components={{ emphasis: <span className="text-text-secondary" /> }}
- />{' '}
- <a
- className="text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- href={docLink('/use-dify/nodes/human-input')}
- rel="noreferrer"
- target="_blank"
- >
- {t(($) => $['imPlatform.learnMore'])}
- </a>
- </DialogDescription>
- </div>
+ <DialogTitle>{t(($) => $['imPlatform.email.title'])}</DialogTitle>
+ <DialogDescription>
+ <Trans
+ ns="contacts"
+ i18nKey={($) => $['imPlatform.email.description']}
+ components={{ emphasis: <span className="text-text-secondary" /> }}
+ />{' '}
+ <a
+ className="text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ href={docLink('/use-dify/nodes/human-input')}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {t(($) => $['imPlatform.learnMore'])}
+ </a>
+ </DialogDescription>
+ </DialogHeader>
- <Form<EmailConfigValues>
- ref={formRef}
- className="flex min-h-0 flex-1 flex-col"
- onFormSubmit={handleSave}
- >
- <div className="space-y-6 overflow-y-auto px-6 py-3">
- <Field name="emailProvider">
- <FieldLabel>{t(($) => $['imPlatform.email.provider'])}</FieldLabel>
- <InputGroup>
- <InputGroupInput disabled value="Resend" />
- <InputGroupAddon align="inline-end">
- <span aria-hidden className="i-ri-arrow-down-s-line size-4" />
- </InputGroupAddon>
- </InputGroup>
- </Field>
+ <Form<EmailConfigValues>
+ ref={formRef}
+ className="flex min-h-0 flex-1 flex-col"
+ onFormSubmit={handleSave}
+ >
+ <DialogBody className="space-y-6">
+ <div className="space-y-2">
+ <p className="system-sm-medium text-text-primary">
+ {t(($) => $['imPlatform.email.provider'])}
+ </p>
+ <p className="system-sm-regular text-text-primary">Resend</p>
+ </div>
- <div className="space-y-4">
- <div className="flex items-center gap-2">
- <span className="system-xs-medium-uppercase text-text-tertiary">
- {t(($) => $['imPlatform.email.resendSettings'])}
- </span>
- <span className="h-px flex-1 bg-divider-subtle" />
- </div>
+ <div className="space-y-4">
+ <div className="flex items-center gap-2">
+ <span className="system-xs-medium-uppercase text-text-tertiary">
+ {t(($) => $['imPlatform.email.resendSettings'])}
+ </span>
+ <span className="h-px flex-1 bg-divider-subtle" />
+ </div>
- <p className="pb-0.5 body-xs-regular text-text-tertiary">
- <Trans
- ns="contacts"
- i18nKey={($) => $['imPlatform.email.resendDescription']}
- components={{
- apiKey: (
- <a
- className="rounded-sm underline decoration-text-tertiary/30 underline-offset-2 focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- href="https://resend.com/docs/dashboard/api-keys/introduction"
- rel="noreferrer"
- target="_blank"
- >
- Resend {t(($) => $['imPlatform.email.apiKey'])}
- </a>
- ),
- resend: (
- <a
- className="rounded-sm underline decoration-text-tertiary/30 underline-offset-2 focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- href="https://www.resend.com/"
- rel="noreferrer"
- target="_blank"
- >
- Resend
- </a>
- ),
- }}
- />
- </p>
+ <p className="pb-0.5 body-xs-regular text-text-tertiary">
+ <Trans
+ ns="contacts"
+ i18nKey={($) => $['imPlatform.email.resendDescription']}
+ components={{
+ apiKey: (
+ <a
+ className="rounded-sm underline decoration-text-tertiary/30 underline-offset-2 focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ href="https://resend.com/docs/dashboard/api-keys/introduction"
+ rel="noreferrer"
+ target="_blank"
+ >
+ Resend {t(($) => $['imPlatform.email.apiKey'])}
+ </a>
+ ),
+ resend: (
+ <a
+ className="rounded-sm underline decoration-text-tertiary/30 underline-offset-2 focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ href="https://www.resend.com/"
+ rel="noreferrer"
+ target="_blank"
+ >
+ Resend
+ </a>
+ ),
+ }}
+ />
+ </p>
- <Field name="senderEmail">
- <div>
- <div className="flex items-center gap-1">
- <FieldLabel>{t(($) => $['imPlatform.email.senderEmail'])}</FieldLabel>
+ <Field name="senderEmail">
+ <div>
+ <div className="flex items-center gap-1">
+ <FieldLabel>{t(($) => $['imPlatform.email.senderEmail'])}</FieldLabel>
+ {!canRetainField(ContactImProviderField.SenderEmail) && (
<span aria-hidden className="system-xs-regular text-text-destructive-secondary">
*
</span>
- </div>
- <FieldDescription className="pt-0">
- {t(($) => $['imPlatform.email.senderEmailDescription'])}
- </FieldDescription>
- </div>
- <Input
- required={!canRetainField(ContactImProviderField.SenderEmail)}
- disabled={credentialsDisabled}
- autoComplete="email"
- placeholder="[email protected]"
- type="email"
- value={values.senderEmail}
- onChange={(event) => {
- const senderEmail = event.currentTarget.value
- setTestSucceeded(false)
- testConnection.reset()
- saveCredentials.reset()
- setValues((current) => ({ ...current, senderEmail }))
- }}
- />
- <FieldError match="valueMissing">
- {t(($) => $['imPlatform.bindingDialog.required'])}
- </FieldError>
- <FieldError match="typeMismatch">
- {t(($) => $['imPlatform.email.invalidEmail'])}
- </FieldError>
- </Field>
-
- <Field name="senderName">
- <div>
- <FieldLabel className="block">
- {t(($) => $['imPlatform.email.senderName'])}
- </FieldLabel>
- <FieldDescription className="pt-0">
- {t(($) => $['imPlatform.email.senderNameDescription'])}
- </FieldDescription>
+ )}
</div>
- <Input
- required={!canRetainField(ContactImProviderField.SenderName)}
- disabled={credentialsDisabled}
- maxLength={255}
- autoComplete="organization"
- placeholder="joe"
- value={values.senderName}
- onChange={(event) => {
- const senderName = event.currentTarget.value
- setTestSucceeded(false)
- testConnection.reset()
- saveCredentials.reset()
- setValues((current) => ({ ...current, senderName }))
- }}
- />
- <FieldError match="valueMissing">
- {t(($) => $['imPlatform.bindingDialog.required'])}
- </FieldError>
- </Field>
-
- <Field name="apiKey">
- <div>
- <div className="flex items-center gap-1">
- <FieldLabel>{t(($) => $['imPlatform.email.apiKey'])}</FieldLabel>
- {!canRetainSecret && (
- <span
- aria-hidden
- className="system-xs-regular text-text-destructive-secondary"
- >
- *
- </span>
- )}
- </div>
- <FieldDescription className="pt-0">
- {integration && provider.requiresFreshCredentials
- ? t(($) => $['imPlatform.bindingDialog.freshCredentials'])
- : canRetainSecret
- ? t(($) => $['imPlatform.email.apiKeyConfigured'])
- : t(($) => $['imPlatform.email.apiKeyDescription'])}
- </FieldDescription>
- </div>
- <Input
- disabled={credentialsDisabled}
- autoComplete="new-password"
- placeholder={
- canRetainSecret ? '••••••••' : t(($) => $['imPlatform.email.apiKeyPlaceholder'])
- }
- required={!canRetainSecret}
- type="password"
- value={apiKey}
- onChange={(event) => {
- const value = event.currentTarget.value
- setTestSucceeded(false)
- testConnection.reset()
- saveCredentials.reset()
- setApiKey(value)
- }}
- />
- <FieldError match="valueMissing">
- {t(($) => $['imPlatform.bindingDialog.required'])}
- </FieldError>
- </Field>
- </div>
-
- {testSucceeded && (
- <div role="status" className="system-xs-regular text-text-success">
- {t(($) => $['imPlatform.email.testSucceeded'])}
+ <FieldDescription className="pt-0">
+ {t(($) => $['imPlatform.email.senderEmailDescription'])}
+ </FieldDescription>
</div>
- )}
- {testConnection.isError && (
- <div role="alert" className="system-xs-regular text-text-destructive">
- {safeErrorMessage(
- testConnection.error,
- t(($) => $['imPlatform.bindingDialog.testFailed']),
+ <Input
+ required={!canRetainField(ContactImProviderField.SenderEmail)}
+ disabled={credentialsDisabled}
+ autoComplete="email"
+ placeholder="[email protected]"
+ type="email"
+ value={values.senderEmail}
+ onChange={(event) => {
+ const senderEmail = event.currentTarget.value
+ setTestSucceeded(false)
+ testConnection.reset()
+ saveCredentials.reset()
+ setValues((current) => ({ ...current, senderEmail }))
+ }}
+ />
+ <FieldError match="valueMissing">
+ {t(($) => $['imPlatform.bindingDialog.required'])}
+ </FieldError>
+ <FieldError match="typeMismatch">
+ {t(($) => $['imPlatform.email.invalidEmail'])}
+ </FieldError>
+ </Field>
+
+ <Field name="senderName">
+ <div>
+ <FieldLabel className="block">
+ {t(($) => $['imPlatform.email.senderName'])}
+ </FieldLabel>
+ {!canRetainField(ContactImProviderField.SenderName) && (
+ <span aria-hidden className="text-text-destructive-secondary">
+ *
+ </span>
)}
+ <FieldDescription className="pt-0">
+ {t(($) => $['imPlatform.email.senderNameDescription'])}
+ </FieldDescription>
</div>
- )}
- {saveCredentials.isError && (
- <div role="alert" className="system-xs-regular text-text-destructive">
- {safeErrorMessage(
- saveCredentials.error,
- t(($) => $['imPlatform.bindingDialog.saveFailed']),
- )}
+ <Input
+ required={!canRetainField(ContactImProviderField.SenderName)}
+ disabled={credentialsDisabled}
+ maxLength={255}
+ autoComplete="organization"
+ placeholder="joe"
+ value={values.senderName}
+ onChange={(event) => {
+ const senderName = event.currentTarget.value
+ setTestSucceeded(false)
+ testConnection.reset()
+ saveCredentials.reset()
+ setValues((current) => ({ ...current, senderName }))
+ }}
+ />
+ <FieldError match="valueMissing">
+ {t(($) => $['imPlatform.bindingDialog.required'])}
+ </FieldError>
+ </Field>
+
+ <Field name="apiKey">
+ <div>
+ <div className="flex items-center gap-1">
+ <FieldLabel>{t(($) => $['imPlatform.email.apiKey'])}</FieldLabel>
+ {!canRetainSecret && (
+ <span aria-hidden className="system-xs-regular text-text-destructive-secondary">
+ *
+ </span>
+ )}
+ </div>
+ <FieldDescription className="pt-0">
+ {canRetainSecret
+ ? t(($) => $['imPlatform.email.apiKeyConfigured'])
+ : t(($) => $['imPlatform.email.apiKeyDescription'])}
+ </FieldDescription>
</div>
- )}
+ <Input
+ disabled={credentialsDisabled}
+ autoComplete="new-password"
+ placeholder={
+ canRetainSecret ? '••••••••' : t(($) => $['imPlatform.email.apiKeyPlaceholder'])
+ }
+ required={!canRetainSecret}
+ type="password"
+ value={apiKey}
+ onChange={(event) => {
+ const value = event.currentTarget.value
+ setTestSucceeded(false)
+ testConnection.reset()
+ saveCredentials.reset()
+ setApiKey(value)
+ }}
+ />
+ <FieldError match="valueMissing">
+ {t(($) => $['imPlatform.bindingDialog.required'])}
+ </FieldError>
+ </Field>
</div>
- <div className="mt-auto flex shrink-0 items-center justify-between gap-3 px-6 pt-5 pb-6">
+ <div role="status" aria-atomic="true" className="system-xs-regular text-text-success">
+ {testSucceeded ? t(($) => $['imPlatform.email.testSucceeded']) : ''}
+ </div>
+ {testConnection.isError && (
+ <div role="alert" className="system-xs-regular text-text-destructive">
+ {safeErrorMessage(
+ testConnection.error,
+ t(($) => $['imPlatform.bindingDialog.testFailed']),
+ )}
+ </div>
+ )}
+ {saveCredentials.isError && (
+ <div role="alert" className="system-xs-regular text-text-destructive">
+ {safeErrorMessage(
+ saveCredentials.error,
+ t(($) => $['imPlatform.bindingDialog.saveFailed']),
+ )}
+ </div>
+ )}
+ </DialogBody>
+
+ <DialogFooter>
+ <div className="flex w-full items-center justify-between gap-3">
<Button
+ aria-labelledby={testLabelId}
disabled={saveCredentials.isPending || savedDetailsUnavailable}
loading={testConnection.isPending}
onClick={handleTestConnection}
>
<span aria-hidden="true" className="i-ri-send-plane-2-line size-4" />
- {testConnection.isPending
- ? t(($) => $['imPlatform.action.testing'])
- : t(($) => $['imPlatform.action.testConnection'])}
+ <span id={testLabelId}>
+ {testConnection.isPending
+ ? t(($) => $['imPlatform.action.testing'])
+ : t(($) => $['imPlatform.action.testConnection'])}
+ </span>
</Button>
<div className="flex gap-2">
<Button className="min-w-18" disabled={isPending} onClick={closeDialog}>
{tCommon(($) => $['operation.cancel'])}
</Button>
<Button
+ aria-labelledby={saveLabelId}
type="submit"
className="min-w-18"
variant="primary"
disabled={testConnection.isPending || savedDetailsUnavailable}
loading={saveCredentials.isPending}
>
- {saveCredentials.isPending
- ? t(($) => $['imPlatform.action.saving'])
- : t(($) => $['imPlatform.action.save'])}
+ <span id={saveLabelId}>
+ {saveCredentials.isPending
+ ? t(($) => $['imPlatform.action.saving'])
+ : t(($) => $['imPlatform.action.save'])}
+ </span>
</Button>
</div>
</div>
- </Form>
- </DialogContent>
- </Dialog>
+ </DialogFooter>
+ </Form>
+ </>
)
}
diff --git a/web/features/contacts/im-platform/hooks.ts b/web/features/contacts/im-platform/hooks.ts
index 04f938f1499..81193b8deef 100644
--- a/web/features/contacts/im-platform/hooks.ts
+++ b/web/features/contacts/im-platform/hooks.ts
@@ -1,419 +1,219 @@
'use client'
-import type { ContactImPlatformRepository } from './repository'
-import type {
- ContactImProviderCommand,
- ContactImSyncResult,
- ContactImSyncRunView,
- SaveContactImCredentialsCommand,
- TestContactImConnectionCommand,
-} from './types'
+import type { ChannelSummary } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { SaveContactImCredentialsCommand, TestContactImConnectionCommand } from './types'
+import { ORPCError } from '@orpc/client'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useRef } from 'react'
+import { consoleQuery } from '@/service/console'
import {
- queryOptions,
- skipToken,
- useInfiniteQuery,
- useMutation,
- useQuery,
- useQueryClient,
-} from '@tanstack/react-query'
-import { useEffect, useRef } from 'react'
-import {
- invalidateHumanInputChannelQueries,
- invalidateHumanInputContactQueries,
-} from '@/service/console'
-import {
- useContactsImPlatformOrganization,
- useContactsImPlatformRepository,
-} from './composition-context'
-import { contactImPlatformQueryKeys } from './query-keys'
-import {
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
- ContactImSyncStatus,
-} from './types'
-
-type SaveCredentialsInput = Omit<SaveContactImCredentialsCommand, 'organizationId'>
-type ProviderInput = Omit<ContactImProviderCommand, 'organizationId'>
-type TestConnectionInput = Omit<TestContactImConnectionCommand, 'organizationId'>
+ createCredentialsFor,
+ emailSettingsFor,
+ toDetailView,
+ updateCredentialsFor,
+ updateEmailSettingsFor,
+} from './credentials'
+import { ContactImRepositoryError, ContactImRepositoryErrorCode } from './types'
export const CONTACT_IM_SYNC_POLL_INTERVAL_MS = 2_000
-const isActiveSyncStatus = (status: ContactImSyncStatus | undefined) =>
- status === ContactImSyncStatus.Queued || status === ContactImSyncStatus.Running
-
-const getIntegrationsQueryOptions = (
- repository: ContactImPlatformRepository,
- organizationId: string,
-) => ({
- queryFn: () => repository.getIntegrations(organizationId),
- queryKey: [
- ...contactImPlatformQueryKeys.integrations(organizationId, repository.queryKey),
- repository,
- ] as const,
-})
-
-const getProviderDefinitionsQueryOptions = (
- repository: ContactImPlatformRepository,
- organizationId: string,
-) => ({
- queryFn: () => repository.getProviderDefinitions(organizationId),
- queryKey: [
- ...contactImPlatformQueryKeys.providers(organizationId, repository.queryKey),
- repository,
- ] as const,
-})
-
-const getActiveSyncQueryOptions = (
- repository: ContactImPlatformRepository,
- organizationId: string,
- workspaceId: string,
-) => ({
- enabled: Boolean(workspaceId),
- queryFn: () => repository.getActiveSync(organizationId),
- queryKey: [
- ...contactImPlatformQueryKeys.activeSync(organizationId, repository.queryKey),
- { workspaceId },
- repository,
- ] as const,
-})
-
-const getSyncRunQueryOptions = (
- repository: ContactImPlatformRepository,
- workspaceId: string,
- runId: string | null,
-) =>
- queryOptions({
- enabled: Boolean(workspaceId && runId),
- queryFn: runId ? () => repository.getSyncRun(runId) : skipToken,
- queryKey: [
- ...contactImPlatformQueryKeys.syncRun(runId ?? 'none', repository.queryKey),
- { workspaceId },
- repository,
- ] as const,
- })
-
-const getSyncItemsQueryOptions = (
- repository: ContactImPlatformRepository,
- {
- enabled,
- workspaceId,
- pageSize,
- result,
- runId,
- }: {
- enabled: boolean
- workspaceId: string
- pageSize: number
- result?: ContactImSyncResult
- runId: string
- },
-) => ({
- enabled: enabled && Boolean(workspaceId),
- getNextPageParam: (lastPage: Awaited<ReturnType<ContactImPlatformRepository['getSyncItems']>>) =>
- lastPage.nextCursor ?? undefined,
- initialPageParam: undefined as string | undefined,
- queryFn: ({ pageParam }: { pageParam: string | undefined }) =>
- repository.getSyncItems({
- cursor: pageParam,
- pageSize,
- result,
- runId,
- }),
- queryKey: [
- ...contactImPlatformQueryKeys.syncItems(runId, repository.queryKey, result, pageSize),
- { workspaceId },
- repository,
- ] as const,
-})
-
-export const useContactImIntegrations = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
-
- return useQuery({
- ...getIntegrationsQueryOptions(repository, organization.organizationId),
- enabled: Boolean(
- organization.organizationId && organization.workspaceId && organization.canManage,
- ),
- })
-}
-
-export const useContactImProviderDefinitions = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
-
- return useQuery({
- ...getProviderDefinitionsQueryOptions(repository, organization.organizationId),
- enabled: Boolean(
- organization.organizationId && organization.workspaceId && organization.canManage,
- ),
- })
+export function channelError(error: unknown) {
+ if (error instanceof ContactImRepositoryError) return error
+ if (error instanceof ORPCError) {
+ if (error.status === 403)
+ return new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
+ if (error.status === 409) {
+ const data = error.data
+ return new ContactImRepositoryError(
+ typeof data === 'object' &&
+ data !== null &&
+ 'code' in data &&
+ data.code === 'replacement_required'
+ ? ContactImRepositoryErrorCode.ReplacementRequired
+ : ContactImRepositoryErrorCode.ConfigurationUpdated,
+ )
+ }
+ return new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed, error.message)
+ }
+ return new ContactImRepositoryError(ContactImRepositoryErrorCode.MutationFailed)
}
-const useRefreshCompletedContactImSync = (run: ContactImSyncRunView | null | undefined) => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
+export function useSaveContactImCredentials() {
const queryClient = useQueryClient()
- const refreshedRunRef = useRef<string | null>(null)
-
- useEffect(() => {
- if (
- !organization.canManage ||
- !organization.workspaceId ||
- !organization.organizationId ||
- !run ||
- isActiveSyncStatus(run.status)
- )
- return
- const completedRunKey = `${organization.workspaceId}:${run.id}:${run.status}`
- if (refreshedRunRef.current === completedRunKey) return
- refreshedRunRef.current = completedRunKey
-
- void Promise.all([
- invalidateHumanInputContactQueries(queryClient, organization.workspaceId),
- queryClient.invalidateQueries({
- queryKey: contactImPlatformQueryKeys.integrations(
- organization.organizationId,
- repository.queryKey,
- ),
- }),
- queryClient.invalidateQueries({
- queryKey: contactImPlatformQueryKeys.syncItemsPrefix(run.id, repository.queryKey),
- }),
- ])
- }, [
- organization.canManage,
- organization.organizationId,
- organization.workspaceId,
- run,
- queryClient,
- repository.queryKey,
- ])
-}
-
-export const useContactImActiveSync = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const query = useQuery({
- ...getActiveSyncQueryOptions(repository, organization.organizationId, organization.workspaceId),
- enabled: Boolean(
- organization.canManage && organization.workspaceId && organization.organizationId,
- ),
- refetchInterval: ({ state }) =>
- isActiveSyncStatus(state.data?.status) ? CONTACT_IM_SYNC_POLL_INTERVAL_MS : false,
- })
- useRefreshCompletedContactImSync(query.data)
- return query
-}
-
-export const useContactImSyncRun = (runId: string | null) => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const query = useQuery({
- ...getSyncRunQueryOptions(repository, organization.workspaceId, runId),
- enabled: Boolean(
- organization.canManage && organization.workspaceId && organization.organizationId && runId,
- ),
- refetchInterval: ({ state }) =>
- isActiveSyncStatus(state.data?.status) ? CONTACT_IM_SYNC_POLL_INTERVAL_MS : false,
- })
- useRefreshCompletedContactImSync(query.data)
- return query
-}
-
-export const useContactImSyncItems = ({
- enabled = true,
- pageSize = 20,
- result,
- runId,
-}: {
- enabled?: boolean
- pageSize?: number
- result?: ContactImSyncResult
- runId: string
-}) => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
-
- return useInfiniteQuery(
- getSyncItemsQueryOptions(repository, {
- enabled: enabled && organization.canManage && Boolean(organization.organizationId),
- workspaceId: organization.workspaceId,
- pageSize,
- result,
- runId,
+ const channels = consoleQuery.workspaces.current.humanInput.v2.channels
+ const createEmail = useMutation(
+ channels.email.post.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const updateEmail = useMutation(
+ channels.email.byChannelId.put.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const createIM = useMutation(
+ channels.im.post.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const updateIM = useMutation(
+ channels.im.byChannelId.put.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const replaceIM = useMutation(
+ channels.im.byChannelId.replacement.post.mutationOptions({
+ context: { silent: true },
+ gcTime: 0,
}),
)
-}
-
-const useInvalidateOrganizationQueries = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const queryClient = useQueryClient()
-
- return async () => {
- await Promise.all([
- invalidateHumanInputChannelQueries(queryClient, organization.workspaceId),
- queryClient.invalidateQueries({
- queryKey: contactImPlatformQueryKeys.integrations(
- organization.organizationId,
- repository.queryKey,
- ),
- }),
- queryClient.invalidateQueries({
- queryKey: contactImPlatformQueryKeys.activeSync(
- organization.organizationId,
- repository.queryKey,
- ),
- }),
- ])
- }
-}
-
-export const useSaveContactImCredentials = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const invalidateOrganizationQueries = useInvalidateOrganizationQueries()
- const commandRef = useRef<SaveCredentialsInput | null>(null)
- const inFlightRef = useRef(false)
-
- const mutation = useMutation({
+ const mutations = [createEmail, updateEmail, createIM, updateIM, replaceIM]
+ const commandRef = useRef<Omit<SaveContactImCredentialsCommand, 'organizationId'> | null>(null)
+ const operation = useMutation({
+ mutationKey: channels.key(),
+ gcTime: 0,
retry: false,
- mutationFn: () => {
- const input = commandRef.current
+ mutationFn: async () => {
+ const command = commandRef.current
commandRef.current = null
-
- if (!input) throw new Error('Contact IM credential command is required')
-
- return repository.saveCredentials({
- ...input,
- organizationId: organization.organizationId,
- })
- },
- onSuccess: invalidateOrganizationQueries,
- onError: async (error) => {
- if (
- error instanceof ContactImRepositoryError &&
- error.code === ContactImRepositoryErrorCode.SavedDetailsUnavailable
- )
- await invalidateOrganizationQueries()
+ if (!command) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
+
+ const params = command.channelId ? { channel_id: command.channelId } : null
+ const version = command.expectedConfigVersion
+ if (params && !version)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated)
+ let summary: ChannelSummary
+ try {
+ if (params && version && !command.replaceActiveProvider) {
+ const credentials = updateCredentialsFor(command)
+ const body = { credentials, expected_config_version: version }
+ summary =
+ credentials.provider === 'resend'
+ ? (
+ await updateEmail.mutateAsync({
+ params,
+ body: { ...body, ...updateEmailSettingsFor(command), credentials },
+ })
+ ).summary
+ : (await updateIM.mutateAsync({ params, body: { ...body, credentials } })).summary
+ } else {
+ const credentials = createCredentialsFor(command)
+ summary =
+ credentials.provider === 'resend'
+ ? (
+ await createEmail.mutateAsync({
+ body: { ...emailSettingsFor(command), credentials },
+ })
+ ).summary
+ : params && version
+ ? (
+ await replaceIM.mutateAsync({
+ params,
+ body: { credentials, expected_config_version: version },
+ })
+ ).summary
+ : (await createIM.mutateAsync({ body: { credentials } })).summary
+ }
+ try {
+ const input = { params: { channel_id: summary.id } }
+ const detail =
+ summary.kind === 'email'
+ ? await queryClient.query(
+ channels.email.byChannelId.get.queryOptions({
+ input,
+ context: { silent: true },
+ staleTime: 0,
+ }),
+ )
+ : await queryClient.query(
+ channels.im.byChannelId.get.queryOptions({
+ input,
+ context: { silent: true },
+ staleTime: 0,
+ }),
+ )
+ return toDetailView(detail)
+ } catch {
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SavedDetailsUnavailable)
+ }
+ } catch (error) {
+ const safeError = channelError(error)
+ throw safeError
+ } finally {
+ mutations.forEach((mutation) => mutation.reset())
+ }
},
})
-
- const saveCredentials = async (input: SaveCredentialsInput) => {
- if (inFlightRef.current) throw new Error('Contact IM credential save is already running')
-
- inFlightRef.current = true
- commandRef.current = input
-
- try {
- return await mutation.mutateAsync()
- } finally {
- commandRef.current = null
- inFlightRef.current = false
- }
- }
-
return {
- ...mutation,
- saveCredentials,
+ ...operation,
+ saveCredentials: (input: Omit<SaveContactImCredentialsCommand, 'organizationId'>) => {
+ commandRef.current = input
+ return operation.mutateAsync()
+ },
}
}
-export const useTestContactImConnection = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const commandRef = useRef<TestConnectionInput | null>(null)
- const inFlightRef = useRef(false)
-
- const mutation = useMutation({
- mutationFn: () => {
- const input = commandRef.current
+export function useTestContactImConnection() {
+ const channels = consoleQuery.workspaces.current.humanInput.v2.channels
+ const createEmail = useMutation(
+ channels.email.test.post.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const updateEmail = useMutation(
+ channels.email.byChannelId.test.post.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const createIM = useMutation(
+ channels.im.test.post.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const updateIM = useMutation(
+ channels.im.byChannelId.test.post.mutationOptions({ context: { silent: true }, gcTime: 0 }),
+ )
+ const mutations = [createEmail, updateEmail, createIM, updateIM]
+ const commandRef = useRef<Omit<TestContactImConnectionCommand, 'organizationId'> | null>(null)
+ const operation = useMutation({
+ mutationKey: channels.key(),
+ gcTime: 0,
+ retry: false,
+ mutationFn: async () => {
+ const command = commandRef.current
commandRef.current = null
-
- if (!input) throw new Error('Contact channel connection-test command is required')
-
- return repository.testConnection({
- ...input,
- organizationId: organization.organizationId,
- })
+ if (!command) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
+
+ const params = command.channelId ? { channel_id: command.channelId } : null
+ const version = command.expectedConfigVersion
+ if (params && !version)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated)
+ try {
+ let response
+ if (params && version) {
+ const credentials = updateCredentialsFor(command)
+ const body = { credentials, expected_config_version: version }
+ response =
+ credentials.provider === 'resend'
+ ? await updateEmail.mutateAsync({
+ params,
+ body: { ...body, ...updateEmailSettingsFor(command), credentials },
+ })
+ : await updateIM.mutateAsync({ params, body: { ...body, credentials } })
+ } else {
+ const credentials = createCredentialsFor(command)
+ response =
+ credentials.provider === 'resend'
+ ? await createEmail.mutateAsync({
+ body: { ...emailSettingsFor(command), credentials },
+ })
+ : await createIM.mutateAsync({ body: { credentials } })
+ }
+ if (response.status !== 'connected')
+ throw new ContactImRepositoryError(
+ ContactImRepositoryErrorCode.MutationFailed,
+ response.status_description,
+ )
+ return response
+ } catch (error) {
+ const safeError = channelError(error)
+ throw safeError
+ } finally {
+ mutations.forEach((mutation) => mutation.reset())
+ }
},
})
-
- const testConnection = async (input: TestConnectionInput) => {
- if (inFlightRef.current) throw new Error('Contact channel connection test is already running')
-
- inFlightRef.current = true
- commandRef.current = input
-
- try {
- return await mutation.mutateAsync()
- } finally {
- commandRef.current = null
- inFlightRef.current = false
- }
- }
-
return {
- ...mutation,
- testConnection,
- }
-}
-
-export const useDisconnectContactImProvider = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const invalidateOrganizationQueries = useInvalidateOrganizationQueries()
-
- return useMutation({
- mutationFn: (input: ProviderInput) =>
- repository.disconnect({ ...input, organizationId: organization.organizationId }),
- onSuccess: invalidateOrganizationQueries,
- })
-}
-
-export const useStartContactImSync = () => {
- const organization = useContactsImPlatformOrganization()
- const repository = useContactsImPlatformRepository()
- const queryClient = useQueryClient()
-
- return useMutation({
- mutationFn: () => {
- if (!organization.canManage || !organization.workspaceId || !organization.organizationId)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
- return repository.startSync({ organizationId: organization.organizationId })
+ ...operation,
+ testConnection: (input: Omit<TestContactImConnectionCommand, 'organizationId'>) => {
+ commandRef.current = input
+ return operation.mutateAsync()
},
- onMutate: () => ({ organization, repository }),
- onSuccess: async (run, _variables, context) => {
- if (!context) return
- const { organization: currentOrganization, repository: currentRepository } = context
- queryClient.setQueryData(
- getActiveSyncQueryOptions(
- currentRepository,
- currentOrganization.organizationId,
- currentOrganization.workspaceId,
- ).queryKey,
- run,
- )
- queryClient.setQueryData(
- getSyncRunQueryOptions(currentRepository, currentOrganization.workspaceId, 'latest')
- .queryKey,
- run,
- )
- await Promise.all([
- queryClient.invalidateQueries({
- queryKey: contactImPlatformQueryKeys.activeSync(
- currentOrganization.organizationId,
- currentRepository.queryKey,
- ),
- }),
- queryClient.invalidateQueries({
- queryKey: contactImPlatformQueryKeys.integrations(
- currentOrganization.organizationId,
- currentRepository.queryKey,
- ),
- }),
- ])
- },
- })
+ }
}
diff --git a/web/features/contacts/im-platform/management-surface.tsx b/web/features/contacts/im-platform/management-surface.tsx
index 99bd5bc7cd7..236ed778d19 100644
--- a/web/features/contacts/im-platform/management-surface.tsx
+++ b/web/features/contacts/im-platform/management-surface.tsx
@@ -1,6 +1,7 @@
'use client'
-import type { ContactImIntegrationView, ContactImProviderDefinition } from './types'
+import type { ChannelSummary } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ContactImProviderDefinition } from './types'
import {
AlertDialog,
AlertDialogBody,
@@ -14,99 +15,210 @@ import {
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogHeaderCloseButton,
+ DialogTitle,
+} from '@langgenius/dify-ui/dialog'
+import { skipToken, useIsMutating, useMutation, useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { ContactImBindingDialog } from './binding-dialog'
+import { consoleQuery } from '@/service/console'
+import { ContactImBindingContent } from './binding-dialog'
import { useContactsImPlatformOrganization } from './composition-context'
-import { ContactEmailConfigDialog } from './email-config-dialog'
-import {
- useContactImIntegrations,
- useContactImProviderDefinitions,
- useDisconnectContactImProvider,
-} from './hooks'
+import { providerMetadata, toDetailView } from './credentials'
+import { ContactEmailConfigContent } from './email-config-dialog'
+import { channelError } from './hooks'
import { ContactImProviderCard } from './provider-card'
import { ContactImSyncDetailsDialog } from './sync-details-dialog'
-import { useContactImSyncRunUrlState } from './sync-run-url-state'
+import { useContactImSyncResultUrlState, useContactImSyncRunUrlState } from './sync-run-url-state'
import { ContactImDirectorySyncSection } from './sync-section'
-import {
- ContactImConnectionStatus,
- ContactImProvider,
- ContactImProviderAvailability,
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
- ContactImStatusReason,
- ContactImUnavailableReason,
-} from './types'
+import { ContactImRepositoryErrorCode } from './types'
type BindingTarget = {
- integration: ContactImIntegrationView | null
+ integration: ChannelSummary | null
provider: ContactImProviderDefinition
replaceActiveProvider: boolean
- replacedIntegration?: ContactImIntegrationView
+ replacedIntegration?: ChannelSummary
+}
+
+function ConfigurationSession({
+ target,
+ onOpenChange,
+}: {
+ target: BindingTarget
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation(['contacts'])
+ const channels = consoleQuery.workspaces.current.humanInput.v2.channels
+ const email = useQuery(
+ channels.email.byChannelId.get.queryOptions({
+ input:
+ target.integration?.kind === 'email'
+ ? { params: { channel_id: target.integration.id } }
+ : skipToken,
+ context: { silent: true },
+ }),
+ )
+ const im = useQuery(
+ channels.im.byChannelId.get.queryOptions({
+ input:
+ target.integration?.kind === 'im'
+ ? { params: { channel_id: target.integration.id } }
+ : skipToken,
+ context: { silent: true },
+ }),
+ )
+ const detail = target.integration?.kind === 'email' ? email : im
+ if (target.integration && !detail.data)
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{target.provider.displayName}</DialogTitle>
+ <DialogHeaderCloseButton aria-label={t(($) => $['action.close'])} />
+ </DialogHeader>
+ {detail.isError ? (
+ <div role="alert" className="p-6">
+ <p>{t(($) => $['imPlatform.loadError.description'])}</p>
+ <Button onClick={() => detail.refetch()}>
+ {t(($) => $['imPlatform.action.retry'])}
+ </Button>
+ </div>
+ ) : (
+ <div
+ aria-busy="true"
+ className="m-6 h-40 animate-pulse rounded-xl bg-state-base-active"
+ />
+ )}
+ </>
+ )
+ const integration = detail.data ? toDetailView(detail.data) : null
+ return target.provider.provider === 'resend' ? (
+ <ContactEmailConfigContent
+ integration={integration}
+ provider={target.provider}
+ onOpenChange={onOpenChange}
+ />
+ ) : (
+ <ContactImBindingContent
+ integration={integration}
+ provider={target.provider}
+ replaceActiveProvider={target.replaceActiveProvider}
+ replacedIntegration={target.replacedIntegration}
+ onOpenChange={onOpenChange}
+ />
+ )
}
export function ContactsImPlatformManagementSurface() {
const { t } = useTranslation(['contacts'])
const { t: tCommon } = useTranslation(['common'])
const organization = useContactsImPlatformOrganization()
- const integrationsQuery = useContactImIntegrations()
- const providersQuery = useContactImProviderDefinitions()
- const disconnectProvider = useDisconnectContactImProvider()
+ const api = consoleQuery.workspaces.current.humanInput.v2
+ const integrationsQuery = useQuery(
+ api.channels.get.queryOptions({ enabled: organization.canManage, context: { silent: true } }),
+ )
+ const providersQuery = useQuery(
+ api.channelProviders.get.queryOptions({
+ enabled: organization.canManage,
+ context: { silent: true },
+ }),
+ )
+ const deleteEmail = useMutation(
+ api.channels.email.byChannelId.delete.mutationOptions({ context: { silent: true } }),
+ )
+ const deleteIM = useMutation(
+ api.channels.im.byChannelId.delete.mutationOptions({ context: { silent: true } }),
+ )
+ const pendingCredentials = useIsMutating({ mutationKey: api.channels.key() }) > 0
const [bindingTarget, setBindingTarget] = useState<BindingTarget | null>(null)
+ const [bindingOpen, setBindingOpen] = useState(false)
const [replacementProvider, setReplacementProvider] =
useState<ContactImProviderDefinition | null>(null)
- const [deleteTarget, setDeleteTarget] = useState<
- | (ContactImProviderDefinition & Pick<ContactImIntegrationView, 'channelId' | 'configVersion'>)
- | null
- >(null)
+ const [replacementOpen, setReplacementOpen] = useState(false)
+ const [deleteTarget, setDeleteTarget] = useState<ChannelSummary | null>(null)
+ const [deleteOpen, setDeleteOpen] = useState(false)
const [syncRunId, setSyncRunId] = useContactImSyncRunUrlState()
-
- if (organization.organizationId && organization.workspaceId && !organization.canManage) {
- return (
- <div className="mb-4 rounded-xl border border-divider-subtle bg-background-default-subtle p-4">
- <div className="system-sm-semibold text-text-primary">
- {t(($) => $['imPlatform.permission.title'])}
- </div>
- <div className="mt-1 system-sm-regular text-text-tertiary">
- {t(($) => $['imPlatform.permission.description'])}
- </div>
- </div>
- )
+ const [, setSyncResult] = useContactImSyncResultUrlState()
+ const integrations = integrationsQuery.data?.channels ?? []
+ const providers = [
+ ...(providersQuery.data?.email_providers ?? []),
+ ...(providersQuery.data?.im_providers ?? []),
+ ].map(({ provider }) => ({
+ provider,
+ displayName: providerMetadata[provider].name,
+ requiredFields: providerMetadata[provider].fields,
+ }))
+ const byProvider = new Map(integrations.map((integration) => [integration.provider, integration]))
+ const configured = providers.filter((provider) => byProvider.has(provider.provider))
+ const available = providers.filter((provider) => !byProvider.has(provider.provider))
+ const activeIM = integrations.find((integration) => integration.kind === 'im')
+ const deleteMutation = deleteTarget?.kind === 'email' ? deleteEmail : deleteIM
+ const openBinding = (target: BindingTarget) => {
+ setBindingTarget(target)
+ setBindingOpen(true)
}
-
- if (
- !organization.organizationId ||
- !organization.workspaceId ||
- integrationsQuery.isPending ||
- providersQuery.isPending
- ) {
+ const openProvider = (provider: ContactImProviderDefinition) => {
+ const integration = byProvider.get(provider.provider) ?? null
+ if (provider.provider !== 'resend' && !integration && activeIM) {
+ setReplacementProvider(provider)
+ setReplacementOpen(true)
+ return
+ }
+ openBinding({ integration, provider, replaceActiveProvider: false })
+ }
+ const descriptions = {
+ ding_talk: t(($) => $['imPlatform.provider.dingtalkDescription']),
+ resend: t(($) => $['imPlatform.provider.emailDescription']),
+ feishu: t(($) => $['imPlatform.provider.feishuDescription']),
+ slack: t(($) => $['imPlatform.provider.slackDescription']),
+ lark: t(($) => $['imPlatform.provider.larkDescription']),
+ ms_teams: t(($) => $['imPlatform.provider.msTeamsDescription']),
+ we_com: t(($) => $['imPlatform.provider.weComDescription']),
+ }
+ const statuses = {
+ connected: t(($) => $['imPlatform.status.connected']),
+ configured: t(($) => $['imPlatform.status.configured']),
+ connection_failure: t(($) => $['imPlatform.status.connection_error']),
+ invalid_credentials: t(($) => $['imPlatform.status.permission_issue']),
+ }
+ const cards = available.map((provider) => (
+ <ContactImProviderCard
+ key={provider.provider}
+ actionAriaLabel={`${provider.displayName} — ${provider.provider !== 'resend' && activeIM ? t(($) => $['imPlatform.action.replace']) : t(($) => $['imPlatform.action.connect'])}`}
+ actionDisabled={!organization.canManage}
+ actionLabel={
+ provider.provider !== 'resend' && activeIM
+ ? t(($) => $['imPlatform.action.replace'])
+ : t(($) => $['imPlatform.action.connect'])
+ }
+ description={descriptions[provider.provider]}
+ mode="available"
+ provider={provider}
+ showAddIcon={provider.provider === 'resend' || !activeIM}
+ onAction={() => openProvider(provider)}
+ />
+ ))
+ if (!organization.canManage) return null
+ if (integrationsQuery.isPending || providersQuery.isPending)
return (
- <div
- role="status"
- aria-label={t(($) => $['imPlatform.loading'])}
- className="max-w-[760px] space-y-3"
- >
- <div className="h-4 w-52 animate-pulse rounded-md bg-state-base-active motion-reduce:animate-none" />
- <div className="h-16 w-full animate-pulse rounded-xl bg-state-base-active motion-reduce:animate-none" />
- <div className="h-16 w-full animate-pulse rounded-xl bg-state-base-active motion-reduce:animate-none" />
+ <div aria-busy="true" className="max-w-190 space-y-3 pt-4">
+ <div className="h-4 w-52 animate-pulse rounded-md bg-state-base-active" />
+ <div className="h-16 animate-pulse rounded-xl bg-state-base-active" />
+ <div className="h-16 animate-pulse rounded-xl bg-state-base-active" />
</div>
)
- }
-
- if (integrationsQuery.isError || providersQuery.isError) {
+ if (integrationsQuery.isError || providersQuery.isError)
return (
<div
role="alert"
- className="max-w-[760px] rounded-xl border border-divider-subtle bg-background-default-subtle p-5"
+ className="max-w-190 rounded-xl border border-divider-subtle bg-background-default-subtle p-5"
>
- <div className="system-md-semibold text-text-primary">
- {t(($) => $['imPlatform.loadError.title'])}
- </div>
- <div className="mt-1 system-sm-regular text-text-tertiary">
- {t(($) => $['imPlatform.loadError.description'])}
- </div>
+ <div className="system-md-semibold">{t(($) => $['imPlatform.loadError.title'])}</div>
+ <p>{t(($) => $['imPlatform.loadError.description'])}</p>
<Button
- className="mt-4"
onClick={() => {
void integrationsQuery.refetch()
void providersQuery.refetch()
@@ -116,261 +228,95 @@ export function ContactsImPlatformManagementSurface() {
</Button>
</div>
)
- }
-
- const integrations = integrationsQuery.data
- const providers = providersQuery.data
- const integrationsByProvider = new Map(
- integrations.map((integration) => [integration.provider, integration]),
- )
- const configuredProviders = providers.filter((provider) =>
- integrationsByProvider.has(provider.provider),
- )
- const availableProviders = providers.filter(
- (provider) => !integrationsByProvider.has(provider.provider),
- )
- const activeImIntegration = integrations.find(
- (integration) => integration.provider !== ContactImProvider.Email,
- )
- const activeImProvider = providers.find(
- (provider) => provider.provider === activeImIntegration?.provider,
- )
- const syncIntegration =
- integrations.find(
- (integration) =>
- integration.status === ContactImConnectionStatus.Connected &&
- integration.capabilities.directorySync,
- ) ??
- integrations.find((integration) => integration.capabilities.directorySync) ??
- integrations.find((integration) => integration.provider !== ContactImProvider.Email)
- const providerDescriptions = {
- [ContactImProvider.DingTalk]: t(($) => $['imPlatform.provider.dingtalkDescription']),
- [ContactImProvider.Email]: t(($) => $['imPlatform.provider.emailDescription']),
- [ContactImProvider.Feishu]: t(($) => $['imPlatform.provider.feishuDescription']),
- [ContactImProvider.Slack]: t(($) => $['imPlatform.provider.slackDescription']),
- [ContactImProvider.Lark]: t(($) => $['imPlatform.provider.larkDescription']),
- [ContactImProvider.MSTeams]: t(($) => $['imPlatform.provider.msTeamsDescription']),
- [ContactImProvider.WeCom]: t(($) => $['imPlatform.provider.weComDescription']),
- }
- const statusLabels = {
- [ContactImConnectionStatus.CallbackError]: t(($) => $['imPlatform.status.callback_error']),
- [ContactImConnectionStatus.Configured]: t(($) => $['imPlatform.status.configured']),
- [ContactImConnectionStatus.Connected]: t(($) => $['imPlatform.status.connected']),
- [ContactImConnectionStatus.ConnectionError]: t(($) => $['imPlatform.status.connection_error']),
- [ContactImConnectionStatus.NotConfigured]: t(($) => $['imPlatform.status.not_configured']),
- [ContactImConnectionStatus.PermissionIssue]: t(($) => $['imPlatform.status.permission_issue']),
- }
- const statusReasonLabels = {
- [ContactImStatusReason.CallbackMismatch]: t(
- ($) => $['imPlatform.statusReason.callback_mismatch'],
- ),
- [ContactImStatusReason.MissingDirectoryPermission]: t(
- ($) => $['imPlatform.statusReason.missing_directory_permission'],
- ),
- [ContactImStatusReason.ProviderRequestFailed]: t(
- ($) => $['imPlatform.statusReason.provider_request_failed'],
- ),
- }
- const unavailableReasonLabels = {
- [ContactImUnavailableReason.DeploymentUnsupported]: t(
- ($) => $['imPlatform.provider.unavailableReason.deployment_unsupported'],
- ),
- [ContactImUnavailableReason.NotReleased]: t(
- ($) => $['imPlatform.provider.unavailableReason.not_released'],
- ),
- }
- const openProvider = (provider: ContactImProviderDefinition) => {
- if (
- provider.availability !== ContactImProviderAvailability.Available ||
- !organization.canManage
- ) {
- return
- }
-
- const integration = integrationsByProvider.get(provider.provider) ?? null
- if (provider.provider !== ContactImProvider.Email && !integration && activeImIntegration) {
- setReplacementProvider(provider)
- return
- }
-
- setBindingTarget({
- integration,
- provider,
- replaceActiveProvider: false,
- })
- }
-
- const openDeleteDialog = (provider: ContactImProviderDefinition) => {
- if (!organization.canManage) return
-
- disconnectProvider.reset()
- const integration = integrationsByProvider.get(provider.provider)
- setDeleteTarget({
- ...provider,
- channelId: integration?.channelId,
- configVersion: integration?.configVersion,
- })
- }
-
- const handleDeleteDialogOpenChange = (open: boolean) => {
- if (open || disconnectProvider.isPending) return
-
- setDeleteTarget(null)
- }
-
- const deleteChannel = () => {
- if (!deleteTarget || disconnectProvider.isPending) return
-
- disconnectProvider.mutate(
- {
- provider: deleteTarget.provider,
- channelId: deleteTarget.channelId,
- expectedConfigVersion: deleteTarget.configVersion,
- },
- { onSuccess: () => setDeleteTarget(null) },
- )
- }
-
- const getConfiguredDescription = (
- provider: ContactImProviderDefinition,
- integration: ContactImIntegrationView,
- ) => {
- if (integration.statusDescription) return integration.statusDescription
- if (integration.statusReason) return statusReasonLabels[integration.statusReason]
- if (provider.provider === ContactImProvider.Email) {
- const senderEmail = integration.configuredValues.senderEmail
- return senderEmail
- ? t(($) => $['imPlatform.email.summary'], { email: senderEmail })
- : statusLabels[integration.status]
- }
- if (provider.provider === ContactImProvider.Slack) return statusLabels[integration.status]
- return integration.displayIdentifier ?? statusLabels[integration.status]
- }
-
- const availableProviderCards = availableProviders.map((provider) => {
- const unavailable = provider.availability === ContactImProviderAvailability.Unavailable
- const isReplacement =
- provider.provider !== ContactImProvider.Email && Boolean(activeImIntegration)
- const actionLabel = isReplacement
- ? t(($) => $['imPlatform.action.replace'])
- : t(($) => $['imPlatform.action.connect'])
-
- return (
- <ContactImProviderCard
- key={provider.provider}
- actionAriaLabel={`${provider.displayName} — ${
- unavailable ? t(($) => $['imPlatform.provider.unavailable']) : actionLabel
- }`}
- actionDisabled={unavailable || !organization.canManage}
- actionLabel={unavailable ? t(($) => $['imPlatform.provider.unavailable']) : actionLabel}
- description={providerDescriptions[provider.provider]}
- mode="available"
- provider={provider}
- showAddIcon={!unavailable && !isReplacement}
- unavailableReason={
- provider.unavailableReason
- ? unavailableReasonLabels[provider.unavailableReason]
- : undefined
- }
- onAction={() => openProvider(provider)}
- />
- )
- })
-
return (
- <section className="max-w-[760px] pb-8" aria-labelledby="contacts-channels-title">
- <h2 id="contacts-channels-title" className="sr-only">
- {t(($) => $['imPlatform.title'])}
- </h2>
-
- {configuredProviders.length > 0 && (
- <div className="space-y-2">
- {configuredProviders.map((provider) => {
- const integration = integrationsByProvider.get(provider.provider)
- if (!integration) return null
-
- return (
- <div key={provider.provider}>
- <span className="sr-only" aria-live="polite">
- {statusLabels[integration.status]}
- </span>
- <ContactImProviderCard
- actionDisabled={!organization.canManage}
- configureAriaLabel={t(($) => $['imPlatform.action.configureChannel'], {
- provider: provider.displayName,
- })}
- deleteAriaLabel={t(($) => $['imPlatform.action.deleteChannel'], {
- provider: provider.displayName,
- })}
- description={getConfiguredDescription(provider, integration)}
- mode="configured"
- provider={provider}
- onConfigure={() => openProvider(provider)}
- onDelete={() => openDeleteDialog(provider)}
- />
- </div>
- )
- })}
- </div>
- )}
-
- {syncIntegration && (
- <ContactImDirectorySyncSection integration={syncIntegration} onViewDetails={setSyncRunId} />
+ <div className="max-w-190 pb-8">
+ <div className="space-y-2">
+ {configured.map((provider) => {
+ const integration = byProvider.get(provider.provider)
+ if (!integration) return null
+ return (
+ <ContactImProviderCard
+ key={provider.provider}
+ actionDisabled={!organization.canManage}
+ configureAriaLabel={t(($) => $['imPlatform.action.configureChannel'], {
+ provider: provider.displayName,
+ })}
+ deleteAriaLabel={t(($) => $['imPlatform.action.deleteChannel'], {
+ provider: provider.displayName,
+ })}
+ description={[
+ integration.display_identifier,
+ statuses[integration.status],
+ integration.status === 'connection_failure' ||
+ integration.status === 'invalid_credentials'
+ ? integration.status_description
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ mode="configured"
+ provider={provider}
+ onConfigure={() => openProvider(provider)}
+ onDelete={() => {
+ deleteEmail.reset()
+ deleteIM.reset()
+ setDeleteTarget(integration)
+ setDeleteOpen(true)
+ }}
+ />
+ )
+ })}
+ </div>
+ {activeIM && (
+ <ContactImDirectorySyncSection integration={activeIM} onViewDetails={setSyncRunId} />
)}
-
- {availableProviders.length > 0 && configuredProviders.length > 0 && (
- <Collapsible
- defaultOpen
- className="mt-4 pt-4 shadow-[inset_0_1px_0_0_var(--color-divider-subtle)]"
+ {available.length > 0 &&
+ (configured.length > 0 ? (
+ <Collapsible defaultOpen className="mt-4 border-t border-divider-subtle pt-4">
+ <CollapsibleTrigger className="group/collapsible mb-2 flex min-h-4 items-center gap-1 rounded-sm text-start system-sm-medium-uppercase text-text-tertiary">
+ <span
+ aria-hidden
+ className="i-ri-arrow-down-s-line size-4 shrink-0 -rotate-90 group-data-panel-open/collapsible:rotate-0"
+ />
+ {t(($) => $['imPlatform.connectMore'])}
+ </CollapsibleTrigger>
+ <CollapsiblePanel className="space-y-2">{cards}</CollapsiblePanel>
+ </Collapsible>
+ ) : (
+ <div className="space-y-2 pt-2">
+ <h4 className="system-sm-medium-uppercase text-text-tertiary">
+ {t(($) => $['imPlatform.chooseProvider'])}
+ </h4>
+ {cards}
+ </div>
+ ))}
+ <Dialog
+ open={bindingOpen}
+ disablePointerDismissal={pendingCredentials}
+ onOpenChange={(open) => {
+ if (!pendingCredentials) setBindingOpen(open)
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) setBindingTarget(null)
+ }}
+ >
+ <DialogContent
+ backdropProps={{ forceRender: true }}
+ className={bindingTarget?.provider.provider === 'resend' ? 'w-130' : 'w-120'}
>
- <CollapsibleTrigger className="group/collapsible mb-2 flex min-h-4 items-center gap-1 rounded-sm text-start system-sm-medium-uppercase text-text-tertiary outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid">
- <span
- aria-hidden
- className="i-ri-arrow-down-s-line size-4 shrink-0 -rotate-90 group-data-panel-open/collapsible:rotate-0"
+ {bindingTarget && (
+ <ConfigurationSession
+ key={`${bindingTarget.provider.provider}:${bindingTarget.integration?.id ?? 'new'}`}
+ target={bindingTarget}
+ onOpenChange={setBindingOpen}
/>
- {t(($) => $['imPlatform.connectMore'])}
- </CollapsibleTrigger>
- <CollapsiblePanel className="space-y-2">{availableProviderCards}</CollapsiblePanel>
- </Collapsible>
- )}
-
- {availableProviders.length > 0 && configuredProviders.length === 0 && (
- <div className="space-y-2 pt-2">
- <h3 className="system-sm-medium-uppercase text-text-tertiary">
- {t(($) => $['imPlatform.chooseProvider'])}
- </h3>
- {availableProviderCards}
- </div>
- )}
-
- {bindingTarget?.provider.provider === ContactImProvider.Email && (
- <ContactEmailConfigDialog
- integration={bindingTarget.integration}
- open
- provider={bindingTarget.provider}
- onOpenChange={(open) => {
- if (!open) setBindingTarget(null)
- }}
- />
- )}
-
- {bindingTarget && bindingTarget.provider.provider !== ContactImProvider.Email && (
- <ContactImBindingDialog
- key={`${bindingTarget.provider.provider}-${bindingTarget.replaceActiveProvider}`}
- integration={bindingTarget.integration}
- open
- provider={bindingTarget.provider}
- replaceActiveProvider={bindingTarget.replaceActiveProvider}
- replacedIntegration={bindingTarget.replacedIntegration}
- onOpenChange={(open) => {
- if (!open) setBindingTarget(null)
- }}
- />
- )}
-
+ )}
+ </DialogContent>
+ </Dialog>
<AlertDialog
- open={Boolean(replacementProvider)}
- onOpenChange={(open) => {
+ open={replacementOpen}
+ onOpenChange={setReplacementOpen}
+ onOpenChangeComplete={(open) => {
if (!open) setReplacementProvider(null)
}}
>
@@ -378,7 +324,7 @@ export function ContactsImPlatformManagementSurface() {
<AlertDialogHeader>
<AlertDialogTitle>
{t(($) => $['imPlatform.replacement.title'], {
- current: activeImProvider?.displayName ?? '',
+ current: activeIM ? providerMetadata[activeIM.provider].name : '',
next: replacementProvider?.displayName ?? '',
})}
</AlertDialogTitle>
@@ -394,13 +340,13 @@ export function ContactsImPlatformManagementSurface() {
tone="default"
onClick={() => {
if (!replacementProvider) return
- setBindingTarget({
+ openBinding({
integration: null,
provider: replacementProvider,
replaceActiveProvider: true,
- replacedIntegration: activeImIntegration,
+ replacedIntegration: activeIM,
})
- setReplacementProvider(null)
+ setReplacementOpen(false)
}}
>
{t(($) => $['imPlatform.replacement.confirm'])}
@@ -408,52 +354,67 @@ export function ContactsImPlatformManagementSurface() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
-
- <AlertDialog open={Boolean(deleteTarget)} onOpenChange={handleDeleteDialogOpenChange}>
+ <AlertDialog
+ open={deleteOpen}
+ onOpenChange={(open) => {
+ if (!deleteMutation.isPending) setDeleteOpen(open)
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) setDeleteTarget(null)
+ }}
+ >
<AlertDialogContent backdropProps={{ forceRender: true }}>
<AlertDialogHeader>
<AlertDialogTitle>
{t(($) => $['imPlatform.delete.title'], {
- provider: deleteTarget?.displayName ?? '',
+ provider: deleteTarget ? providerMetadata[deleteTarget.provider].name : '',
})}
</AlertDialogTitle>
<AlertDialogDescription>
{t(($) => $['imPlatform.delete.description'])}
</AlertDialogDescription>
</AlertDialogHeader>
- {disconnectProvider.isError && (
+ {deleteMutation.isError && (
<AlertDialogBody>
- <div role="alert" className="system-sm-regular text-text-destructive">
- {disconnectProvider.error instanceof ContactImRepositoryError &&
- disconnectProvider.error.code === ContactImRepositoryErrorCode.ConfigurationUpdated
+ <div role="alert" className="text-text-destructive">
+ {channelError(deleteMutation.error).code ===
+ ContactImRepositoryErrorCode.ConfigurationUpdated
? t(($) => $['imPlatform.configurationUpdated'])
: t(($) => $['imPlatform.delete.failed'])}
</div>
</AlertDialogBody>
)}
<AlertDialogFooter>
- <AlertDialogCancelButton disabled={disconnectProvider.isPending}>
+ <AlertDialogCancelButton disabled={deleteMutation.isPending}>
{tCommon(($) => $['operation.cancel'])}
</AlertDialogCancelButton>
<AlertDialogConfirmButton
- loading={disconnectProvider.isPending}
- onClick={deleteChannel}
+ loading={deleteMutation.isPending}
+ onClick={() => {
+ if (!deleteTarget) return
+ deleteMutation.mutate(
+ {
+ params: { channel_id: deleteTarget.id },
+ query: { expected_config_version: deleteTarget.config_version },
+ },
+ { onSuccess: () => setDeleteOpen(false) },
+ )
+ }}
>
{t(($) => $['imPlatform.delete.confirm'])}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
-
- {syncRunId && (
- <ContactImSyncDetailsDialog
- open
- runId={syncRunId}
- onOpenChange={(open) => {
- if (!open) setSyncRunId(null)
- }}
- />
- )}
- </section>
+ <ContactImSyncDetailsDialog
+ open={Boolean(syncRunId)}
+ runId={syncRunId}
+ onOpenChange={(open) => {
+ if (open) return
+ void setSyncRunId(null)
+ void setSyncResult(null)
+ }}
+ />
+ </div>
)
}
diff --git a/web/features/contacts/im-platform/provider-card.tsx b/web/features/contacts/im-platform/provider-card.tsx
index 068f1e9ecc6..b867cb3db4b 100644
--- a/web/features/contacts/im-platform/provider-card.tsx
+++ b/web/features/contacts/im-platform/provider-card.tsx
@@ -9,7 +9,6 @@ import { ContactImProvider } from './types'
type ContactImProviderCardBaseProps = {
description: string
provider: ContactImProviderDefinition
- unavailableReason?: string
}
type ContactImAvailableProviderCardProps = ContactImProviderCardBaseProps & {
@@ -35,26 +34,27 @@ export type ContactImProviderCardProps =
| ContactImConfiguredProviderCardProps
export function ContactImProviderCard(props: ContactImProviderCardProps) {
- const { description, provider, unavailableReason } = props
+ const { description, provider } = props
return (
<div
role="group"
aria-label={provider.displayName}
- className="flex min-h-16 w-full items-center gap-3 rounded-[15px] bg-third-party-model-bg-default py-3 ps-3 pe-4 inset-ring-[0.5px] inset-ring-components-panel-border"
+ className="rounded-3.75 flex min-h-16 w-full items-center gap-3 bg-third-party-model-bg-default py-3 ps-3 pe-4 inset-ring-[0.5px] inset-ring-components-panel-border"
>
- <div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-[10px] border border-divider-regular bg-components-panel-on-panel-item-bg backdrop-blur-[4px]">
+ <div className="rounded-2.5 flex size-10 shrink-0 items-center justify-center overflow-hidden border border-divider-regular bg-components-panel-on-panel-item-bg backdrop-blur-xs">
{provider.provider === ContactImProvider.Email ? (
<span aria-hidden className="i-ri-mail-send-fill size-6 text-text-accent" />
) : (
- <ContactChannelIcon provider={provider.provider} className="size-8" />
+ <ContactChannelIcon
+ provider={provider.provider === 'ding_talk' ? 'dingtalk' : provider.provider}
+ className="size-8"
+ />
)}
</div>
<div className="min-w-0 flex-1">
<div className="system-md-semibold text-text-primary">{provider.displayName}</div>
- <div className="system-xs-regular text-text-tertiary">
- {unavailableReason ?? description}
- </div>
+ <div className="system-xs-regular text-text-tertiary">{description}</div>
</div>
{props.mode === 'configured' ? (
<div className="flex shrink-0 items-center gap-2">
diff --git a/web/features/contacts/im-platform/provider-form-adapters.ts b/web/features/contacts/im-platform/provider-form-adapters.ts
index 00a12eec2f6..08767f31898 100644
--- a/web/features/contacts/im-platform/provider-form-adapters.ts
+++ b/web/features/contacts/im-platform/provider-form-adapters.ts
@@ -1,12 +1,12 @@
import type { ContactImProviderDefinition } from './types'
-import { ContactImAuthMode, ContactImProvider, ContactImProviderField } from './types'
+import { ContactImProvider, ContactImProviderField } from './types'
-const setupGuideUrls: Record<Exclude<ContactImProvider, 'email'>, string> = {
+const setupGuideUrls: Record<Exclude<ContactImProvider, 'resend'>, string> = {
slack: 'https://docs.slack.dev/interactivity/handling-user-interaction/',
feishu:
'https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/event-subscription-guide/callback-subscription/callback-overview',
lark: 'https://open.larksuite.com/document/uAjLw4CM/ukTMukTMukTM/event-subscription-guide/callback-subscription/callback-overview',
- dingtalk: 'https://open.dingtalk.com/document/',
+ ding_talk: 'https://open.dingtalk.com/document/',
ms_teams:
'https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/bot-sso-register-aad',
we_com: 'https://developer.work.weixin.qq.com/document/path/90665',
@@ -18,7 +18,7 @@ type ContactImCallbackSetup = {
}
export const resolveContactImCallbackSetup = (
- provider: Exclude<ContactImProvider, 'email'>,
+ provider: Exclude<ContactImProvider, 'resend'>,
): ContactImCallbackSetup | null => {
switch (provider) {
case ContactImProvider.Feishu:
@@ -51,8 +51,6 @@ export const resolveContactImCallbackSetup = (
export const resolveContactImProviderFormAdapter = (definition: ContactImProviderDefinition) => {
if (definition.provider === ContactImProvider.Email)
throw new Error('Email uses its dedicated configuration form')
- if (definition.authMode !== ContactImAuthMode.Credentials)
- throw new Error(`Provider requires application credentials: ${definition.provider}`)
return {
setupGuideUrl: setupGuideUrls[definition.provider],
diff --git a/web/features/contacts/im-platform/query-keys.ts b/web/features/contacts/im-platform/query-keys.ts
deleted file mode 100644
index f751a66312d..00000000000
--- a/web/features/contacts/im-platform/query-keys.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import type { ContactImSyncResult } from './types'
-
-export const contactImPlatformQueryKeys = {
- activeSync: (organizationId: string, repositoryKey: string) =>
- [
- ...contactImPlatformQueryKeys.organization(organizationId, repositoryKey),
- 'active-sync',
- ] as const,
- all: ['contacts', 'im-platform'] as const,
- integrations: (organizationId: string, repositoryKey: string) =>
- [
- ...contactImPlatformQueryKeys.organization(organizationId, repositoryKey),
- 'integrations',
- ] as const,
- organization: (organizationId: string, repositoryKey: string) =>
- [...contactImPlatformQueryKeys.all, repositoryKey, organizationId] as const,
- providers: (organizationId: string, repositoryKey: string) =>
- [
- ...contactImPlatformQueryKeys.organization(organizationId, repositoryKey),
- 'providers',
- ] as const,
- syncItems: (
- runId: string,
- repositoryKey: string,
- result?: ContactImSyncResult,
- pageSize?: number,
- ) =>
- [
- ...contactImPlatformQueryKeys.syncItemsPrefix(runId, repositoryKey),
- result ?? 'all',
- pageSize ?? 'default',
- ] as const,
- syncItemsPrefix: (runId: string, repositoryKey: string) =>
- [...contactImPlatformQueryKeys.syncRun(runId, repositoryKey), 'items'] as const,
- syncRun: (runId: string, repositoryKey: string) =>
- [...contactImPlatformQueryKeys.all, repositoryKey, 'sync-run', runId] as const,
-}
diff --git a/web/features/contacts/im-platform/repository.ts b/web/features/contacts/im-platform/repository.ts
deleted file mode 100644
index 9e872717ef2..00000000000
--- a/web/features/contacts/im-platform/repository.ts
+++ /dev/null
@@ -1,756 +0,0 @@
-import type {
- ChannelSummary,
- EmailChannelDetailResponse,
- EmailProviderCredentialsUpdateInputWritable,
- EmailProviderCredentialsWritable,
- ImChannelDetailResponse,
- ImProviderCredentialsInputWritable,
- ImProviderCredentialsUpdateInputWritable,
- ImSyncResultItem,
- ImSyncRun,
- UnchangedInput,
-} from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ContactsImPlatformOrganizationContext } from './context'
-import type {
- AuthorizeContactImProviderCommand,
- ContactImIntegrationView,
- ContactImOrganizationCommand,
- ContactImPage,
- ContactImProvider,
- ContactImProviderCommand,
- ContactImProviderDefinition,
- ContactImProviderField,
- ContactImProviderFieldDefinition,
- ContactImSyncItemView,
- ContactImSyncRunView,
- ListContactImSyncItemsInput,
- SaveContactImCredentialsCommand,
- TestContactImConnectionCommand,
-} from './types'
-import { zChannelConflictResponse } from '@dify/contracts/api/console/workspaces/zod.gen'
-import { ORPCError } from '@orpc/client'
-import { z } from 'zod'
-import { consoleClient } from '@/service/console'
-import {
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
- ContactImSyncResult,
- ContactImSyncStatus,
-} from './types'
-
-export type ContactImPlatformRepository = {
- authorizeProvider: (
- command: AuthorizeContactImProviderCommand,
- ) => Promise<ContactImIntegrationView>
- disconnect: (command: ContactImProviderCommand) => Promise<ContactImIntegrationView[]>
- getActiveSync: (organizationId: string) => Promise<ContactImSyncRunView | null>
- getIntegrations: (organizationId: string) => Promise<ContactImIntegrationView[]>
- getProviderDefinitions: (organizationId: string) => Promise<ContactImProviderDefinition[]>
- getSyncItems: (
- input: ListContactImSyncItemsInput,
- ) => Promise<ContactImPage<ContactImSyncItemView>>
- getSyncRun: (runId: string) => Promise<ContactImSyncRunView>
- queryKey: string
- saveCredentials: (command: SaveContactImCredentialsCommand) => Promise<ContactImIntegrationView>
- startSync: (command: ContactImOrganizationCommand) => Promise<ContactImSyncRunView>
- testConnection: (command: TestContactImConnectionCommand) => Promise<ContactImIntegrationView>
-}
-
-const syncReportResults = [
- ContactImSyncResult.Added,
- ContactImSyncResult.NotMatched,
- ContactImSyncResult.Failed,
- ContactImSyncResult.Removed,
- ContactImSyncResult.Skipped,
-]
-
-/** Export a completed run in full, refusing stale runs or incomplete result pages. */
-export async function loadContactImSyncReport(
- repository: Pick<ContactImPlatformRepository, 'getSyncRun' | 'getSyncItems'>,
- runId: string,
-) {
- const run = await repository.getSyncRun(runId)
- if (run.status === ContactImSyncStatus.Queued || run.status === ContactImSyncStatus.Running)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncNotAllowed)
-
- const items: ContactImSyncItemView[] = []
- const itemIds = new Set<string>()
- for (const result of syncReportResults) {
- let cursor: string | undefined
- const cursors = new Set<string>()
- let count = 0
- do {
- const page = await repository.getSyncItems({ runId: run.id, result, cursor, pageSize: 20 })
- for (const item of page.items) {
- if (item.result !== result || itemIds.has(item.id))
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
- itemIds.add(item.id)
- items.push(item)
- count += 1
- }
- if (page.nextCursor && (cursors.has(page.nextCursor) || page.items.length === 0))
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
- if (page.nextCursor) cursors.add(page.nextCursor)
- cursor = page.nextCursor ?? undefined
- } while (cursor)
- if (count !== (run.counts[result] ?? 0))
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
- }
-
- const current = await repository.getSyncRun(run.id)
- if (
- current.id !== run.id ||
- current.status !== run.status ||
- current.completedAt !== run.completedAt ||
- syncReportResults.some((result) => current.counts[result] !== run.counts[result])
- )
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
-
- return { run, items }
-}
-
-const apiProviderNames = {
- ding_talk: 'dingtalk',
- resend: 'email',
- feishu: 'feishu',
- lark: 'lark',
- ms_teams: 'ms_teams',
- slack: 'slack',
- we_com: 'we_com',
-} as const
-
-const toContactImSyncRunView = (run: ImSyncRun): ContactImSyncRunView => ({
- completedAt: run.finished_at == null ? null : new Date(run.finished_at * 1000).toISOString(),
- counts: run.result_counts,
- durationMs:
- run.started_at == null || run.finished_at == null
- ? null
- : (run.finished_at - run.started_at) * 1000,
- errorMessage: run.error_message ?? null,
- id: run.id,
- provider: apiProviderNames[run.provider],
- safeError: null,
- startedAt: run.started_at == null ? null : new Date(run.started_at * 1000).toISOString(),
- startedBy: null,
- status:
- run.status === 'succeeded'
- ? ContactImSyncStatus.Success
- : run.status === 'failed'
- ? ContactImSyncStatus.Failure
- : run.status,
-})
-
-const toContactImSyncItemView = ({ id, result }: ImSyncResultItem): ContactImSyncItemView => {
- const contact = 'contact' in result ? result.contact : null
- const entry = result.type === 'removed' ? result.last_known_identity : result.entry
-
- return {
- id,
- matchedContact: contact
- ? { id: contact.id, name: contact.name, email: null, avatarUrl: contact.avatar_url }
- : null,
- platformIdentity: {
- displayName: entry?.display_name ?? null,
- email: entry?.email ?? null,
- platformUserId: entry?.provider_user_id ?? null,
- },
- reason: 'reason' in result ? result.reason : null,
- result: result.type,
- safeReason: null,
- }
-}
-
-/** The server exposes the latest run only; run IDs guard against showing another run's results. */
-export function createContactImSyncApi(
- workspaceId: string,
- client: Pick<typeof consoleClient.workspaces.current.humanInput.v2, 'imSyncRuns'> = consoleClient
- .workspaces.current.humanInput.v2,
-): Pick<
- ContactImPlatformRepository,
- 'getActiveSync' | 'getSyncRun' | 'getSyncItems' | 'startSync'
-> {
- const getLatest = async () => {
- if (!workspaceId) throw new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
-
- try {
- const response = await client.imSyncRuns.latest.get(undefined, { context: { silent: true } })
- return toContactImSyncRunView(response.run)
- } catch (error) {
- if (typeof error === 'object' && error !== null && 'status' in error && error.status === 404)
- return null
- throw error
- }
- }
- const getSyncRun = async (runId: string) => {
- const run = await getLatest()
- if (!run || (runId !== 'latest' && run.id !== runId))
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
- return run
- }
-
- return {
- getActiveSync: getLatest,
- getSyncRun,
- async getSyncItems({ cursor, pageSize = 20, result = ContactImSyncResult.Added, runId }) {
- if (
- result !== ContactImSyncResult.Added &&
- result !== ContactImSyncResult.NotMatched &&
- result !== ContactImSyncResult.Removed &&
- result !== ContactImSyncResult.Failed &&
- result !== ContactImSyncResult.Skipped
- )
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- const page = cursor ? Number(cursor) : 1
- if (!Number.isInteger(page) || page < 1)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
-
- const run = await getSyncRun(runId)
- const response = await client.imSyncRuns.latest.results.get(
- {
- query: { result, page, limit: pageSize },
- },
- { context: { silent: true } },
- )
- await getSyncRun(run.id)
- return {
- items: response.data.map(toContactImSyncItemView),
- nextCursor:
- response.page * response.limit < response.total ? String(response.page + 1) : null,
- }
- },
- async startSync() {
- if (!workspaceId)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
- const response = await client.imSyncRuns.post(undefined, { context: { silent: true } })
- return toContactImSyncRunView(response.run)
- },
- }
-}
-
-const providerMetadata: Record<
- ContactImProvider,
- { name: string; fields: ContactImProviderFieldDefinition[] }
-> = {
- email: {
- name: 'Email',
- fields: [
- { field: 'senderEmail', required: true },
- { field: 'senderName', required: true },
- { field: 'secret', required: true, secret: true },
- ],
- },
- feishu: {
- name: 'Feishu',
- fields: [
- { field: 'appId', required: true },
- { field: 'secret', required: true, secret: true },
- { field: 'verificationToken', required: false, secret: true },
- { field: 'encryptKey', required: false, secret: true },
- ],
- },
- lark: {
- name: 'Lark',
- fields: [
- { field: 'appId', required: true },
- { field: 'secret', required: true, secret: true },
- { field: 'verificationToken', required: false, secret: true },
- { field: 'encryptKey', required: false, secret: true },
- ],
- },
- slack: {
- name: 'Slack',
- fields: [
- { field: 'clientId', required: true },
- { field: 'secret', required: true, secret: true },
- { field: 'signingSecret', required: true, secret: true },
- { field: 'botToken', required: true, secret: true },
- { field: 'appToken', required: false, secret: true },
- ],
- },
- dingtalk: {
- name: 'DingTalk',
- fields: [
- { field: 'corpId', required: true },
- { field: 'clientId', required: true },
- { field: 'secret', required: true, secret: true },
- ],
- },
- ms_teams: {
- name: 'Microsoft Teams',
- fields: [
- { field: 'tenantId', required: true },
- { field: 'clientId', required: true },
- { field: 'secret', required: true, secret: true },
- ],
- },
- we_com: {
- name: 'WeCom',
- fields: [
- { field: 'corpId', required: true },
- { field: 'agentId', required: true },
- { field: 'secret', required: true, secret: true },
- ],
- },
-}
-
-function emailSettingsFor(command: TestContactImConnectionCommand) {
- const sender_email = command.values.senderEmail?.trim()
- const sender_name = command.values.senderName?.trim()
- if (!sender_email || !sender_name)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.RequiredFieldsMissing)
- return { sender_email, sender_name }
-}
-
-function updateEmailSettingsFor(command: TestContactImConnectionCommand) {
- const unchanged: UnchangedInput = { type: 'unchanged' }
- return {
- sender_email: command.values.senderEmail?.trim() || unchanged,
- sender_name: command.values.senderName?.trim() || unchanged,
- }
-}
-
-function validateClearedFields(command: TestContactImConnectionCommand) {
- for (const field of command.clearedFields ?? []) {
- const definition = providerMetadata[command.provider].fields.find(
- (item) => item.field === field,
- )
- if (!definition || definition.required)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
- }
-}
-
-function createCredentialsFor(command: TestContactImConnectionCommand) {
- validateClearedFields(command)
- const required = (field: ContactImProviderField) => {
- const value = (field === 'secret' ? command.secret : command.values[field])?.trim()
- if (!value)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.RequiredFieldsMissing)
- return value
- }
- const optional = (field: Exclude<ContactImProviderField, 'secret'>) =>
- command.clearedFields?.includes(field) ? null : command.values[field]?.trim() || null
- switch (command.provider) {
- case 'email':
- return {
- provider: 'resend',
- api_key: required('secret'),
- } satisfies EmailProviderCredentialsWritable
- case 'feishu':
- case 'lark':
- return {
- provider: command.provider,
- app_id: required('appId'),
- app_secret: required('secret'),
- encrypt_key: optional('encryptKey'),
- verification_token: optional('verificationToken'),
- } satisfies ImProviderCredentialsInputWritable
- case 'slack':
- return {
- provider: 'slack',
- client_id: required('clientId'),
- client_secret: required('secret'),
- signing_secret: required('signingSecret'),
- bot_token: required('botToken'),
- app_token: optional('appToken'),
- } satisfies ImProviderCredentialsInputWritable
- case 'dingtalk':
- return {
- provider: 'ding_talk',
- corp_id: required('corpId'),
- client_id: required('clientId'),
- client_secret: required('secret'),
- } satisfies ImProviderCredentialsInputWritable
- case 'ms_teams':
- return {
- provider: 'ms_teams',
- tenant_id: required('tenantId'),
- client_id: required('clientId'),
- client_secret: required('secret'),
- } satisfies ImProviderCredentialsInputWritable
- case 'we_com':
- return {
- provider: 'we_com',
- corp_id: required('corpId'),
- agent_id: required('agentId'),
- secret: required('secret'),
- } satisfies ImProviderCredentialsInputWritable
- }
-}
-
-function updateCredentialsFor(
- command: TestContactImConnectionCommand,
-): EmailProviderCredentialsUpdateInputWritable | ImProviderCredentialsUpdateInputWritable {
- validateClearedFields(command)
- const unchanged: UnchangedInput = { type: 'unchanged' }
- const value = (field: ContactImProviderField) =>
- (field === 'secret' ? command.secret : command.values[field])?.trim() || unchanged
- const optional = (field: Exclude<ContactImProviderField, 'secret'>) =>
- command.clearedFields?.includes(field) ? null : value(field)
-
- switch (command.provider) {
- case 'email':
- return {
- provider: 'resend',
- api_key: value('secret'),
- }
- case 'feishu':
- case 'lark':
- return {
- provider: command.provider,
- app_id: value('appId'),
- app_secret: value('secret'),
- encrypt_key: optional('encryptKey'),
- verification_token: optional('verificationToken'),
- }
- case 'slack':
- return {
- provider: 'slack',
- client_id: value('clientId'),
- client_secret: value('secret'),
- signing_secret: value('signingSecret'),
- bot_token: value('botToken'),
- app_token: optional('appToken'),
- }
- case 'dingtalk':
- return {
- provider: 'ding_talk',
- corp_id: value('corpId'),
- client_id: value('clientId'),
- client_secret: value('secret'),
- }
- case 'ms_teams':
- return {
- provider: 'ms_teams',
- tenant_id: value('tenantId'),
- client_id: value('clientId'),
- client_secret: value('secret'),
- }
- case 'we_com':
- return {
- provider: 'we_com',
- corp_id: value('corpId'),
- agent_id: value('agentId'),
- secret: value('secret'),
- }
- }
-}
-
-const channelProviderErrorSchema = z.object({
- code: z.literal('bad_request'),
- message: z.string().min(1),
-})
-
-async function channelProviderErrorMessage(error: unknown): Promise<string | undefined> {
- if (!(error instanceof Response) || error.status !== 400) return undefined
- try {
- const parsed = channelProviderErrorSchema.safeParse(await error.clone().json())
- return parsed.success ? parsed.data.message : undefined
- } catch {
- return undefined
- }
-}
-
-async function channelRequest<T>(request: () => Promise<T>): Promise<T> {
- try {
- return await request()
- } catch (error) {
- if (error instanceof ContactImRepositoryError) throw error
- const status =
- typeof error === 'object' && error !== null && 'status' in error ? error.status : undefined
- if (status === 403)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
- if (status === 409) {
- let conflictBody: unknown
- if (error instanceof ORPCError) {
- conflictBody = error.data
- } else if (error instanceof Response) {
- try {
- conflictBody = await error.clone().json()
- } catch {
- // Missing or malformed conflict details still require refreshing the saved configuration.
- }
- }
- const conflict = zChannelConflictResponse.safeParse(conflictBody)
- throw new ContactImRepositoryError(
- conflict.success && conflict.data.code === 'replacement_required'
- ? ContactImRepositoryErrorCode.ReplacementRequired
- : ContactImRepositoryErrorCode.ConfigurationUpdated,
- )
- }
- throw new ContactImRepositoryError(
- ContactImRepositoryErrorCode.MutationFailed,
- await channelProviderErrorMessage(error),
- )
- }
-}
-
-/** Adapts the generated channel contract to the existing settings views. Secrets stay in commands only. */
-export function createContactImApiRepository(
- organization: ContactsImPlatformOrganizationContext,
- client: Pick<
- typeof consoleClient.workspaces.current.humanInput.v2,
- 'channelProviders' | 'channels'
- > = consoleClient.workspaces.current.humanInput.v2,
-): ContactImPlatformRepository {
- const requestOptions = { context: { silent: true } }
- const guard = (organizationId: string) => {
- if (
- !organization.canManage ||
- !organization.workspaceId ||
- organizationId !== organization.organizationId
- )
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.NoPermission)
- }
- const baseView = (provider: ContactImProvider): ContactImIntegrationView => ({
- canManage: organization.canManage,
- capabilities: { directorySync: provider !== 'email' },
- channelKind: provider === 'email' ? 'email' : 'im',
- configuredValues: {},
- configuredFields: [],
- displayIdentifier: null,
- lastCheckedAt: null,
- lastSync: null,
- organizationId: organization.organizationId,
- provider,
- secretConfigured: false,
- status: 'not_configured',
- statusReason: null,
- })
- const toView = (summary: ChannelSummary): ContactImIntegrationView => ({
- ...baseView(apiProviderNames[summary.provider]),
- channelId: summary.id,
- configVersion: summary.config_version,
- callbackUrl: summary.webhook_url,
- displayIdentifier: summary.display_identifier,
- status:
- summary.status === 'connected' || summary.status === 'configured'
- ? summary.status
- : summary.status === 'invalid_credentials'
- ? 'permission_issue'
- : 'connection_error',
- statusDescription: summary.status_description,
- })
- const toDetailView = (
- detail: EmailChannelDetailResponse | ImChannelDetailResponse,
- ): ContactImIntegrationView => {
- const integration = toView(detail.summary)
- const configuredFields: ContactImProviderField[] = []
- const configuredValues: ContactImIntegrationView['configuredValues'] = {}
- const configured = (field: ContactImProviderField, present = true) => {
- if (present) configuredFields.push(field)
- }
- const plain = (field: Exclude<ContactImProviderField, 'secret'>, value: string) => {
- configuredValues[field] = value
- configured(field, Boolean(value))
- }
- if ('sender_email' in detail) {
- plain('senderEmail', detail.sender_email)
- plain('senderName', detail.sender_name)
- configured('secret', Boolean(detail.credentials.api_key))
- } else {
- const credentials = detail.credentials
- switch (credentials.provider) {
- case 'feishu':
- case 'lark':
- plain('appId', credentials.app_id)
- configured('secret', Boolean(credentials.app_secret))
- configured('verificationToken', credentials.verification_token !== null)
- configured('encryptKey', credentials.encrypt_key !== null)
- break
- case 'slack':
- plain('clientId', credentials.client_id)
- configured('secret', Boolean(credentials.client_secret))
- configured('signingSecret', Boolean(credentials.signing_secret))
- configured('botToken', Boolean(credentials.bot_token))
- configured('appToken', credentials.app_token !== null)
- break
- case 'ding_talk':
- plain('corpId', credentials.corp_id)
- plain('clientId', credentials.client_id)
- configured('secret', Boolean(credentials.client_secret))
- break
- case 'ms_teams':
- plain('tenantId', credentials.tenant_id)
- plain('clientId', credentials.client_id)
- configured('secret', Boolean(credentials.client_secret))
- break
- case 'we_com':
- plain('corpId', credentials.corp_id)
- plain('agentId', credentials.agent_id)
- configured('secret', Boolean(credentials.secret))
- break
- }
- }
- return {
- ...integration,
- configuredFields,
- configuredValues,
- secretConfigured: configuredFields.includes('secret'),
- }
- }
- const getDetail = async (summary: ChannelSummary) => {
- const input = { params: { channel_id: summary.id } }
- const detail =
- summary.kind === 'email'
- ? await client.channels.email.byChannelId.get(input, requestOptions)
- : await client.channels.im.byChannelId.get(input, requestOptions)
- return toDetailView(detail)
- }
- const getIntegrations = async (organizationId: string) => {
- guard(organizationId)
- return channelRequest(async () => {
- const { channels } = await client.channels.get(undefined, requestOptions)
- return Promise.all(channels.map(getDetail))
- })
- }
- return {
- ...createContactImSyncApi(organization.workspaceId),
- queryKey: `api:${organization.workspaceId}`,
- getIntegrations,
- async getProviderDefinitions(organizationId) {
- guard(organizationId)
- return channelRequest(async () => {
- const providers = await client.channelProviders.get(undefined, requestOptions)
- return [...providers.email_providers, ...providers.im_providers].map(
- ({ provider: apiProvider }) => {
- const provider = apiProviderNames[apiProvider]
- const metadata = providerMetadata[provider]
- return {
- authMode: 'credentials' as const,
- availability: 'available' as const,
- callbackUrl: null,
- capabilities: { directorySync: provider !== 'email' },
- channelKind: provider === 'email' ? ('email' as const) : ('im' as const),
- displayName: metadata.name,
- provider,
- requiredFields: metadata.fields,
- requiresFreshCredentials: false,
- unavailableReason: null,
- }
- },
- )
- })
- },
- async authorizeProvider() {
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ProviderUnavailable)
- },
- async saveCredentials(command) {
- guard(command.organizationId)
- if (command.channelId && !command.expectedConfigVersion)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated)
- if (command.replaceActiveProvider && !command.channelId)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
- return channelRequest(async () => {
- const params = command.channelId ? { channel_id: command.channelId } : null
- const version = command.expectedConfigVersion
- let response
- if (params && version && !command.replaceActiveProvider) {
- const credentials = updateCredentialsFor(command)
- if (credentials.provider === 'resend') {
- response = await client.channels.email.byChannelId.put(
- {
- params,
- body: {
- ...updateEmailSettingsFor(command),
- credentials,
- expected_config_version: version,
- },
- },
- requestOptions,
- )
- } else {
- response = await client.channels.im.byChannelId.put(
- { params, body: { credentials, expected_config_version: version } },
- requestOptions,
- )
- }
- } else {
- const credentials = createCredentialsFor(command)
- if (credentials.provider === 'resend') {
- if (command.replaceActiveProvider)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.InvalidCommand)
- response = await client.channels.email.post(
- { body: { ...emailSettingsFor(command), credentials } },
- requestOptions,
- )
- } else if (params && version) {
- response = await client.channels.im.byChannelId.replacement.post(
- { params, body: { credentials, expected_config_version: version } },
- requestOptions,
- )
- } else {
- response = await client.channels.im.post({ body: { credentials } }, requestOptions)
- }
- }
- try {
- return await getDetail(response.summary)
- } catch {
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SavedDetailsUnavailable)
- }
- })
- },
- async testConnection(command) {
- guard(command.organizationId)
- if (command.channelId && !command.expectedConfigVersion)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated)
- return channelRequest(async () => {
- let response
- if (command.channelId && command.expectedConfigVersion) {
- const credentials = updateCredentialsFor(command)
- const input = {
- params: { channel_id: command.channelId },
- body: { credentials, expected_config_version: command.expectedConfigVersion },
- }
- response =
- credentials.provider === 'resend'
- ? await client.channels.email.byChannelId.test.post(
- {
- ...input,
- body: { ...input.body, ...updateEmailSettingsFor(command), credentials },
- },
- requestOptions,
- )
- : await client.channels.im.byChannelId.test.post(
- { ...input, body: { ...input.body, credentials } },
- requestOptions,
- )
- } else {
- const credentials = createCredentialsFor(command)
- response =
- credentials.provider === 'resend'
- ? await client.channels.email.test.post(
- { body: { ...emailSettingsFor(command), credentials } },
- requestOptions,
- )
- : await client.channels.im.test.post({ body: { credentials } }, requestOptions)
- }
- if (response.status !== 'connected')
- throw new ContactImRepositoryError(
- ContactImRepositoryErrorCode.MutationFailed,
- response.status_description,
- )
- return {
- ...baseView(command.provider),
- status: 'connected',
- statusDescription: response.status_description,
- }
- })
- },
- async disconnect(command) {
- guard(command.organizationId)
- if (!command.channelId || !command.expectedConfigVersion)
- throw new ContactImRepositoryError(ContactImRepositoryErrorCode.ConfigurationUpdated)
- const input = {
- params: { channel_id: command.channelId },
- query: { expected_config_version: command.expectedConfigVersion },
- }
- await channelRequest(() =>
- command.provider === 'email'
- ? client.channels.email.byChannelId.delete(input, requestOptions)
- : client.channels.im.byChannelId.delete(input, requestOptions),
- )
- return []
- },
- }
-}
diff --git a/web/features/contacts/im-platform/sync-details-dialog.tsx b/web/features/contacts/im-platform/sync-details-dialog.tsx
index eedeffbde39..9caace4c583 100644
--- a/web/features/contacts/im-platform/sync-details-dialog.tsx
+++ b/web/features/contacts/im-platform/sync-details-dialog.tsx
@@ -1,58 +1,33 @@
'use client'
-import type { ContactImSafeReason, ContactImSyncResult } from './types'
+import type { ImSyncResultItem } from '@dify/contracts/api/console/workspaces/types.gen'
import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
import {
Dialog,
- DialogClose,
+ DialogBody,
DialogContent,
DialogDescription,
+ DialogHeader,
+ DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import {
- SegmentedControl,
- SegmentedControlDivider,
- SegmentedControlItem,
-} from '@langgenius/dify-ui/segmented-control'
-import { useMutation } from '@tanstack/react-query'
-import { Fragment, useState } from 'react'
+ skipToken,
+ useInfiniteQuery,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from '@tanstack/react-query'
+import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { jsonToCSV } from 'react-papaparse'
+import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
import { ContactChannelIcon } from '../management/channel-icon'
-import { useContactsImPlatformRepository } from './composition-context'
-import { useContactImSyncItems, useContactImSyncRun } from './hooks'
-import { loadContactImSyncReport } from './repository'
-import {
- ContactImRepositoryError,
- ContactImRepositoryErrorCode,
- ContactImSyncStatus,
- ContactImSafeReason as SafeReason,
- ContactImSyncResult as SyncResult,
-} from './types'
-
-const results = [
- SyncResult.Added,
- SyncResult.NotMatched,
- SyncResult.Failed,
- SyncResult.Removed,
- SyncResult.Skipped,
-]
-
-const resultToneClassNames = {
- [SyncResult.Added]: 'border-text-accent text-text-accent',
- [SyncResult.NotMatched]: 'border-divider-deep text-text-tertiary',
- [SyncResult.Removed]: 'border-text-warning text-text-warning',
- [SyncResult.CreatedBinding]: 'border-text-accent text-text-accent',
- [SyncResult.Failed]: 'border-text-destructive text-text-destructive',
- [SyncResult.Matched]: 'border-divider-deep text-text-tertiary',
- [SyncResult.Skipped]: 'border-divider-deep text-text-tertiary',
- [SyncResult.Unmatched]: 'border-divider-deep text-text-tertiary',
- [SyncResult.UpdatedBinding]: 'border-text-accent text-text-accent',
-} satisfies Record<ContactImSyncResult, string>
+import { loadContactImSyncReport, syncResults } from './sync-report'
+import { useContactImSyncResultUrlState } from './sync-run-url-state'
+import { ContactImRepositoryError, ContactImRepositoryErrorCode } from './types'
export function ContactImSyncDetailsDialog({
open,
@@ -60,335 +35,293 @@ export function ContactImSyncDetailsDialog({
onOpenChange,
}: {
open: boolean
- runId: string
+ runId: string | null
onOpenChange: (open: boolean) => void
}) {
+ const [displayedRunId, setDisplayedRunId] = useState(runId)
+ const subject = runId ?? displayedRunId
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen) setDisplayedRunId(runId)
+ onOpenChange(nextOpen)
+ }}
+ onOpenChangeComplete={(nextOpen) => {
+ setDisplayedRunId(nextOpen ? runId : null)
+ }}
+ >
+ <DialogContent backdropProps={{ forceRender: true }} className="h-180 w-173.25">
+ {subject && <SyncDetailsContent key={subject} runId={subject} />}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function SyncDetailsContent({ runId }: { runId: string }) {
const { t, i18n } = useTranslation(['contacts'])
const { t: tCommon } = useTranslation(['common'])
- const repository = useContactsImPlatformRepository()
- const reportDownload = useMutation({
- mutationFn: (id: string) => loadContactImSyncReport(repository, id),
- onSuccess: ({ run: reportRun, items: reportItems }) => {
- const content = jsonToCSV(
+ const queryClient = useQueryClient()
+ const [result, setResult] = useContactImSyncResultUrlState()
+ const titleId = useId()
+ const downloadLabelId = useId()
+ const api = consoleQuery.workspaces.current.humanInput.v2.imSyncRuns.latest
+ const runQuery = useQuery(
+ api.get.queryOptions({
+ context: { silent: true },
+ }),
+ )
+ const run = runQuery.data?.run
+ const matchesRun = Boolean(run && (runId === 'latest' || run.id === runId))
+ const canReadResults = matchesRun && run?.status !== 'queued' && run?.status !== 'running'
+ const itemsQuery = useInfiniteQuery(
+ api.results.get.infiniteOptions({
+ input: canReadResults
+ ? (page: number) => ({ query: { result, page, limit: 20 } })
+ : skipToken,
+ initialPageParam: 1,
+ getNextPageParam: (page) => (page.page * page.limit < page.total ? page.page + 1 : undefined),
+ context: { silent: true },
+ }),
+ )
+ const items = itemsQuery.data?.pages.flatMap((page) => page.data) ?? []
+ const labels = {
+ added: t(($) => $['imPlatform.details.filter.added']),
+ not_matched: t(($) => $['imPlatform.details.filter.not_matched']),
+ failed: t(($) => $['imPlatform.details.filter.failed']),
+ removed: t(($) => $['imPlatform.details.filter.removed']),
+ skipped: t(($) => $['imPlatform.details.filter.skipped']),
+ }
+ const statuses = {
+ failed: t(($) => $['imPlatform.sync.status.failure']),
+ queued: t(($) => $['imPlatform.sync.status.queued']),
+ running: t(($) => $['imPlatform.sync.status.running']),
+ succeeded: t(($) => $['imPlatform.sync.status.success']),
+ }
+ const removalReasons = {
+ not_present_in_directory: t(
+ ($) => $['imPlatform.details.removalReason.not_present_in_directory'],
+ ),
+ binding_replaced: t(($) => $['imPlatform.details.removalReason.binding_replaced']),
+ binding_invalidated: t(($) => $['imPlatform.details.removalReason.binding_invalidated']),
+ }
+ const reason = (item: ImSyncResultItem) =>
+ item.result.type === 'removed'
+ ? removalReasons[item.result.reason]
+ : item.result.type === 'failed'
+ ? item.result.reason
+ : ''
+ const report = useMutation({
+ mutationFn: async () => {
+ const { run: reportRun, items: reportItems } = await loadContactImSyncReport(
+ queryClient,
+ runId === 'latest' && run ? run.id : runId,
+ )
+ const { jsonToCSV } = await import('react-papaparse')
+ const csv = jsonToCSV(
{
fields: [
'run_id',
'result',
'contact_id',
'contact_name',
- 'contact_email',
'provider',
'platform_user_id',
'platform_display_name',
'platform_email',
'reason',
],
- data: reportItems.map((item) => [
- reportRun.id,
- item.result,
- item.matchedContact?.id ?? '',
- item.matchedContact?.name ?? '',
- item.matchedContact?.email ?? '',
- reportRun.provider ?? '',
- item.platformIdentity.platformUserId ?? '',
- item.platformIdentity.displayName ?? '',
- item.platformIdentity.email ?? '',
- item.reason ?? item.safeReason ?? '',
- ]),
+ data: reportItems.map((item) => {
+ const row = item.result
+ const contact = 'contact' in row ? row.contact : null
+ const entry = row.type === 'removed' ? row.last_known_identity : row.entry
+ return [
+ reportRun.id,
+ labels[row.type],
+ contact?.id ?? '',
+ contact?.name ?? '',
+ reportRun.provider,
+ entry?.provider_user_id ?? '',
+ entry?.display_name ?? '',
+ entry?.email ?? '',
+ reason(item),
+ ]
+ }),
},
{ escapeFormulae: /^[\t\r\n]|^\s*[=+\-@]/ },
)
downloadBlob({
- data: new Blob([`\uFEFF${content}`], { type: 'text/csv;charset=utf-8;' }),
+ data: new Blob([`\uFEFF${csv}`], { type: 'text/csv;charset=utf-8;' }),
fileName: `im-sync-${reportRun.id}.csv`,
})
},
})
- const [resultFilter, setResultFilter] = useState<ContactImSyncResult>(SyncResult.Added)
- const runQuery = useContactImSyncRun(open ? runId : null)
- const run = runQuery.data
- const itemsQuery = useContactImSyncItems({
- enabled: open && Boolean(run),
- pageSize: 20,
- result: resultFilter,
- runId: run?.id ?? runId,
- })
- const items = itemsQuery.data?.pages.flatMap((page) => page.items) ?? []
- const resultLabels = {
- [SyncResult.Added]: t(($) => $['imPlatform.details.filter.added']),
- [SyncResult.NotMatched]: t(($) => $['imPlatform.details.filter.not_matched']),
- [SyncResult.Removed]: t(($) => $['imPlatform.details.filter.removed']),
- [SyncResult.CreatedBinding]: t(($) => $['imPlatform.details.filter.created_binding']),
- [SyncResult.Failed]: t(($) => $['imPlatform.details.filter.failed']),
- [SyncResult.Matched]: t(($) => $['imPlatform.details.filter.matched']),
- [SyncResult.Skipped]: t(($) => $['imPlatform.details.filter.skipped']),
- [SyncResult.Unmatched]: t(($) => $['imPlatform.details.filter.unmatched']),
- [SyncResult.UpdatedBinding]: t(($) => $['imPlatform.details.filter.updated_binding']),
- }
- const statusLabels = {
- [ContactImSyncStatus.Failure]: t(($) => $['imPlatform.sync.status.failure']),
- [ContactImSyncStatus.PartialSuccess]: t(($) => $['imPlatform.sync.status.partial_success']),
- [ContactImSyncStatus.Queued]: t(($) => $['imPlatform.sync.status.queued']),
- [ContactImSyncStatus.Running]: t(($) => $['imPlatform.sync.status.running']),
- [ContactImSyncStatus.Success]: t(($) => $['imPlatform.sync.status.success']),
- }
- const safeReasonLabels = {
- [SafeReason.ContactUpdateFailed]: t(
- ($) => $['imPlatform.details.safeReason.contact_update_failed'],
- ),
- [SafeReason.DuplicateIdentity]: t(($) => $['imPlatform.details.safeReason.duplicate_identity']),
- [SafeReason.MissingEmail]: t(($) => $['imPlatform.details.safeReason.missing_email']),
- [SafeReason.NoMatchingContact]: t(
- ($) => $['imPlatform.details.safeReason.no_matching_contact'],
- ),
- [SafeReason.ProviderRequestFailed]: t(
- ($) => $['imPlatform.details.safeReason.provider_request_failed'],
- ),
- } satisfies Record<ContactImSafeReason, string>
const missing = t(($) => $['imPlatform.details.missing'])
- const formatDate = (value: string | null) =>
- value
- ? new Intl.DateTimeFormat(i18n.language, {
- dateStyle: 'medium',
- timeStyle: 'short',
- }).format(new Date(value))
- : missing
- const initialLoadFailed =
- runQuery.isError || (itemsQuery.isError && !itemsQuery.data && !itemsQuery.isFetchNextPageError)
-
+ const date = run?.finished_at ?? run?.started_at
+ const formattedDate = date
+ ? new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(
+ new Date(date * 1000),
+ )
+ : missing
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent
- backdropProps={{ forceRender: true }}
- className="h-180 max-h-[calc(100dvh-2rem)] w-[693px] overflow-hidden!"
- >
- <DialogClose
- render={
- <IconButton
- aria-label={tCommon(($) => $['operation.close'])}
- className="absolute inset-e-5 top-5"
- size="lg"
- >
- <span aria-hidden className="i-ri-close-line size-4.5" />
- </IconButton>
- }
- />
- <div className="shrink-0 ps-6 pe-14 pt-6 pb-3">
- <DialogTitle>{t(($) => $['imPlatform.details.title'])}</DialogTitle>
- <DialogDescription>
- {run
- ? run.status === ContactImSyncStatus.Success
- ? run.startedBy
- ? t(($) => $['imPlatform.sync.lastSynced'], {
- date: formatDate(run.completedAt ?? run.startedAt),
- user: run.startedBy,
- })
- : t(($) => $['imPlatform.sync.latestSynced'], {
- date: formatDate(run.completedAt ?? run.startedAt),
- })
- : t(($) => $['imPlatform.details.latestMetadata'], {
- date: formatDate(run.completedAt ?? run.startedAt),
- status: statusLabels[run.status],
- })
- : t(($) => $['imPlatform.details.description'])}
- </DialogDescription>
- {(run?.errorMessage || run?.safeError) && (
- <div role="alert" className="mt-3 system-xs-regular text-text-destructive">
- {run.errorMessage ?? (run.safeError ? safeReasonLabels[run.safeError] : null)}
- </div>
- )}
- </div>
-
- {initialLoadFailed ? (
- <div role="alert" className="m-6 mt-2 rounded-xl bg-background-default-subtle p-5">
- <div className="system-sm-medium text-text-primary">
- {t(($) => $['imPlatform.details.loadError'])}
- </div>
+ <>
+ <DialogHeader>
+ <DialogHeaderCloseButton aria-label={tCommon(($) => $['operation.close'])} />
+ <DialogTitle id={titleId}>{t(($) => $['imPlatform.details.title'])}</DialogTitle>
+ <DialogDescription>
+ {run
+ ? t(($) => $['imPlatform.details.latestMetadata'], {
+ date: formattedDate,
+ status: statuses[run.status],
+ })
+ : t(($) => $['imPlatform.details.description'])}
+ </DialogDescription>
+ </DialogHeader>
+ <div role="status" aria-atomic="true" className="sr-only">
+ {run ? `${statuses[run.status]} · ${labels[result]}: ${items.length}` : ''}
+ </div>
+ <DialogBody>
+ {runQuery.isError || (itemsQuery.isError && !itemsQuery.data) ? (
+ <div role="alert">
+ <p>{t(($) => $['imPlatform.details.loadError'])}</p>
<Button
- className="mt-3"
onClick={() => {
void runQuery.refetch()
- if (run) void itemsQuery.refetch()
+ if (canReadResults) void itemsQuery.refetch()
}}
>
{t(($) => $['imPlatform.action.retry'])}
</Button>
</div>
- ) : runQuery.isPending || itemsQuery.isPending || !run ? (
- <div
- role="status"
- aria-label={t(($) => $['imPlatform.details.loading'])}
- className="m-6 mt-2 h-32 animate-pulse rounded-xl bg-state-base-active motion-reduce:animate-none"
- />
+ ) : run && !matchesRun ? (
+ <div role="alert">{t(($) => $['imPlatform.details.reportChanged'])}</div>
+ ) : !run || itemsQuery.isPending ? (
+ <div aria-busy="true" className="h-32 animate-pulse rounded-xl bg-state-base-active" />
) : (
<>
- <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 px-6 py-1">
- <div className="min-w-0 overflow-x-auto">
- <SegmentedControl
- aria-label={t(($) => $['imPlatform.details.filters'])}
- value={resultFilter}
- onValueChange={(value) => {
- const result = results.find((result) => result === value)
- if (result) setResultFilter(result)
- }}
- >
- {results.map((result, index) => (
- <Fragment key={result}>
- {index > 0 && (
- <SegmentedControlDivider
- className={cn(
- '-mx-px',
- (resultFilter === result || resultFilter === results[index - 1]) &&
- 'invisible',
- )}
- />
- )}
- <SegmentedControlItem
- className="gap-1 px-2.5 data-checked:text-text-primary"
- value={result}
- >
- {resultLabels[result]}{' '}
- <span
- className={cn(
- 'min-w-4 rounded-[5px] border px-0.75 text-center text-[10px] leading-3 font-medium',
- resultToneClassNames[result],
- )}
- >
- {run.counts[result] ?? 0}
- </span>
- </SegmentedControlItem>
- </Fragment>
- ))}
- </SegmentedControl>
+ {run.error_message && (
+ <div role="alert" className="mb-3 text-text-destructive">
+ {run.error_message}
</div>
+ )}
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <SegmentedControl
+ aria-label={t(($) => $['imPlatform.details.filters'])}
+ value={result}
+ onValueChange={(value) => {
+ const next = syncResults.find((result) => result === value)
+ if (next) void setResult(next)
+ }}
+ >
+ {syncResults.map((result) => (
+ <SegmentedControlItem key={result} value={result}>
+ {labels[result]} <span>{run.result_counts[result]}</span>
+ </SegmentedControlItem>
+ ))}
+ </SegmentedControl>
<Button
- className="shrink-0"
- disabled={
- run.status === ContactImSyncStatus.Queued ||
- run.status === ContactImSyncStatus.Running
- }
- loading={reportDownload.isPending}
- onClick={() => reportDownload.mutate(run.id)}
+ aria-labelledby={downloadLabelId}
+ disabled={run.status === 'queued' || run.status === 'running'}
+ loading={report.isPending}
+ onClick={() => report.mutate()}
>
<span aria-hidden className="i-ri-download-line size-4" />
- {reportDownload.isPending
- ? t(($) => $['imPlatform.details.downloadingReport'])
- : t(($) => $['imPlatform.details.downloadReport'])}
+ <span id={downloadLabelId}>
+ {report.isPending
+ ? t(($) => $['imPlatform.details.downloadingReport'])
+ : t(($) => $['imPlatform.details.downloadReport'])}
+ </span>
</Button>
</div>
-
- {reportDownload.isError && (
- <div role="alert" className="px-6 pt-2 system-xs-regular text-text-destructive">
- {reportDownload.error instanceof ContactImRepositoryError &&
- reportDownload.error.code === ContactImRepositoryErrorCode.SyncRunNotFound
+ {report.isError && (
+ <div role="alert" className="pt-2 text-text-destructive">
+ {report.error instanceof ContactImRepositoryError &&
+ report.error.code === ContactImRepositoryErrorCode.SyncRunNotFound
? t(($) => $['imPlatform.details.reportChanged'])
: t(($) => $['imPlatform.details.downloadFailed'])}
</div>
)}
-
- <div className="min-h-0 flex-1 overflow-auto px-6 pt-2 pb-6">
- <table className="w-full table-fixed border-collapse text-start">
- <thead className="sticky top-0 z-10 bg-background-section-burn">
- <tr>
- <th className="w-1/2 rounded-s-lg px-3 py-1.5 system-xs-medium-uppercase text-text-tertiary">
- {t(($) => $['imPlatform.details.column.contact'])}
- </th>
- <th className="w-1/2 rounded-e-lg px-3 py-1.5 system-xs-medium-uppercase text-text-tertiary">
- {t(($) => $['imPlatform.details.column.platform'])}
- </th>
- </tr>
- </thead>
- <tbody>
- {items.map((item) => (
+ <table
+ aria-labelledby={titleId}
+ className="mt-3 w-full table-fixed border-collapse text-start"
+ >
+ <thead>
+ <tr>
+ <th className="w-1/2 p-3 text-start system-xs-medium-uppercase text-text-tertiary">
+ {t(($) => $['imPlatform.details.column.contact'])}
+ </th>
+ <th className="w-1/2 p-3 text-start system-xs-medium-uppercase text-text-tertiary">
+ {t(($) => $['imPlatform.details.column.platform'])}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {items.map((item) => {
+ const row = item.result
+ const contact = 'contact' in row ? row.contact : null
+ const entry = row.type === 'removed' ? row.last_known_identity : row.entry
+ return (
<tr key={item.id} className="h-12 border-b border-divider-subtle">
- <td className="px-3 py-1.5">
+ <td className="p-3">
<div className="flex items-center gap-2.5">
- {item.matchedContact && (
- <Avatar size="md">
- <AvatarImage
- src={item.matchedContact.avatarUrl ?? null ?? undefined}
- alt={item.matchedContact.name}
- />
+ {contact && (
+ <Avatar size="md" aria-hidden="true">
+ <AvatarImage src={contact.avatar_url ?? undefined} alt="" />
<AvatarFallback>
- {item.matchedContact.name?.[0]?.toLocaleUpperCase()}
+ {contact.name[0]?.toLocaleUpperCase()}
</AvatarFallback>
</Avatar>
)}
- <div className="min-w-0">
- <div className="truncate system-md-medium text-text-secondary">
- {item.matchedContact?.name ?? missing}
- </div>
- {item.matchedContact?.email && (
- <div className="truncate system-xs-regular text-text-tertiary">
- {item.matchedContact.email}
- </div>
- )}
- </div>
+ <span className="truncate">{contact?.name ?? missing}</span>
</div>
</td>
- <td className="px-3 py-1.5">
- <div className="flex flex-wrap items-center gap-2">
- <span
- className={cn(
- 'inline-flex max-w-full items-center gap-1 rounded-md border py-0.75 ps-1 pe-2 system-sm-regular',
- resultToneClassNames[item.result],
- item.result === SyncResult.Added && 'text-text-secondary',
- )}
- >
- {run.provider && (
- <ContactChannelIcon className="size-4" provider={run.provider} />
- )}
- <span className="truncate">
- {item.platformIdentity.displayName ??
- item.platformIdentity.email ??
- item.platformIdentity.platformUserId ??
- missing}
- </span>
+ <td className="p-3">
+ <div className="flex items-center gap-1">
+ <ContactChannelIcon
+ className="size-4"
+ provider={run.provider === 'ding_talk' ? 'dingtalk' : run.provider}
+ />
+ <span className="truncate">
+ {entry?.display_name ??
+ entry?.email ??
+ entry?.provider_user_id ??
+ missing}
</span>
</div>
- {(item.reason || item.safeReason) && (
- <div className="mt-2 system-xs-regular text-text-tertiary">
- {item.reason ??
- (item.safeReason ? safeReasonLabels[item.safeReason] : null)}
- </div>
+ {reason(item) && (
+ <p className="mt-1 system-xs-regular text-text-tertiary">
+ {reason(item)}
+ </p>
)}
</td>
</tr>
- ))}
- </tbody>
- </table>
-
- {items.length === 0 && (
- <div className="py-12 text-center system-sm-regular text-text-tertiary">
- {t(($) => $['imPlatform.details.empty'])}
- </div>
- )}
-
- {itemsQuery.isFetchNextPageError && (
- <div role="alert" className="mt-3 flex items-center justify-between gap-3">
- <span className="system-xs-regular text-text-destructive">
- {t(($) => $['imPlatform.details.pageError'])}
- </span>
- <Button onClick={() => itemsQuery.fetchNextPage()}>
- {t(($) => $['imPlatform.action.retry'])}
- </Button>
- </div>
- )}
-
- {itemsQuery.hasNextPage && !itemsQuery.isFetchNextPageError && (
- <div className="mt-4 flex justify-center">
- <Button
- loading={itemsQuery.isFetchingNextPage}
- onClick={() => itemsQuery.fetchNextPage()}
- >
- {t(($) => $['imPlatform.action.loadMore'])}
- </Button>
- </div>
- )}
+ )
+ })}
+ </tbody>
+ </table>
+ {items.length === 0 && (
+ <p className="py-12 text-center">{t(($) => $['imPlatform.details.empty'])}</p>
+ )}
+ {itemsQuery.isFetchNextPageError && (
+ <p role="alert" className="mt-3 text-text-destructive">
+ {t(($) => $['imPlatform.details.pageError'])}
+ </p>
+ )}
+ <div className="mt-4 flex justify-center">
+ <Button
+ disabled={!itemsQuery.hasNextPage}
+ focusableWhenDisabled
+ loading={itemsQuery.isFetchingNextPage}
+ onClick={() => itemsQuery.fetchNextPage()}
+ >
+ {itemsQuery.isFetchNextPageError
+ ? t(($) => $['imPlatform.action.retry'])
+ : t(($) => $['imPlatform.action.loadMore'])}
+ </Button>
</div>
</>
)}
- </DialogContent>
- </Dialog>
+ </DialogBody>
+ </>
)
}
diff --git a/web/features/contacts/im-platform/sync-report.ts b/web/features/contacts/im-platform/sync-report.ts
new file mode 100644
index 00000000000..558328c7092
--- /dev/null
+++ b/web/features/contacts/im-platform/sync-report.ts
@@ -0,0 +1,56 @@
+import type { ImSyncResultItem } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { QueryClient } from '@tanstack/react-query'
+import { consoleQuery } from '@/service/console'
+import { ContactImRepositoryError, ContactImRepositoryErrorCode } from './types'
+
+export const syncResults = ['added', 'not_matched', 'failed', 'removed', 'skipped'] as const
+
+export async function loadContactImSyncReport(queryClient: QueryClient, runId: string) {
+ const api = consoleQuery.workspaces.current.humanInput.v2.imSyncRuns.latest
+ const { run } = await queryClient.query(
+ api.get.queryOptions({ context: { silent: true }, staleTime: 0 }),
+ )
+ if (run.id !== runId || run.status === 'queued' || run.status === 'running')
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
+ const items: ImSyncResultItem[] = []
+ const itemIds = new Set<string>()
+ for (const result of syncResults) {
+ let page = 1
+ let count = 0
+ while (true) {
+ const response = await queryClient.query(
+ api.results.get.queryOptions({
+ input: { query: { result, page, limit: 100 } },
+ context: { silent: true },
+ staleTime: 0,
+ }),
+ )
+ if (response.page !== page)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
+ for (const item of response.data) {
+ if (item.result.type !== result || itemIds.has(item.id))
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
+ itemIds.add(item.id)
+ items.push(item)
+ }
+ count += response.data.length
+ if (response.page * response.limit >= response.total) break
+ if (response.data.length === 0)
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
+ page += 1
+ }
+ if (count !== run.result_counts[result])
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.PageLoadFailed)
+ }
+ const { run: current } = await queryClient.query(
+ api.get.queryOptions({ context: { silent: true }, staleTime: 0 }),
+ )
+ if (
+ current.id !== run.id ||
+ current.status !== run.status ||
+ current.finished_at !== run.finished_at ||
+ syncResults.some((result) => current.result_counts[result] !== run.result_counts[result])
+ )
+ throw new ContactImRepositoryError(ContactImRepositoryErrorCode.SyncRunNotFound)
+ return { run, items }
+}
diff --git a/web/features/contacts/im-platform/sync-run-url-state.ts b/web/features/contacts/im-platform/sync-run-url-state.ts
index 7b2c696d252..61e0faa7060 100644
--- a/web/features/contacts/im-platform/sync-run-url-state.ts
+++ b/web/features/contacts/im-platform/sync-run-url-state.ts
@@ -1,32 +1,19 @@
'use client'
-import { useCallback, useState } from 'react'
-import { usePathname, useRouter, useSearchParams } from '@/next/navigation'
+import type { ImSyncResultItem } from '@dify/contracts/api/console/workspaces/types.gen'
+import { parseAsString, parseAsStringEnum, useQueryState } from 'nuqs'
-const CONTACT_IM_SYNC_RUN_QUERY_PARAM = 'sync_run_id'
+type SyncResult = ImSyncResultItem['result']['type']
+export const useContactImSyncRunUrlState = () => useQueryState('sync_run_id', parseAsString)
-export const useContactImSyncRunUrlState = () => {
- const pathname = usePathname()
- const router = useRouter()
- const searchParams = useSearchParams()
- const serializedSearchParams = searchParams.toString()
- const [runId, setRunId] = useState<string | null>(() =>
- searchParams.has(CONTACT_IM_SYNC_RUN_QUERY_PARAM) ? 'latest' : null,
+export const useContactImSyncResultUrlState = () =>
+ useQueryState(
+ 'sync_result',
+ parseAsStringEnum<SyncResult>([
+ 'added',
+ 'not_matched',
+ 'failed',
+ 'removed',
+ 'skipped',
+ ]).withDefault('added'),
)
-
- const updateRunId = useCallback(
- (nextRunId: string | null) => {
- const nextSearchParams = new URLSearchParams(serializedSearchParams)
-
- if (nextRunId) nextSearchParams.set(CONTACT_IM_SYNC_RUN_QUERY_PARAM, 'latest')
- else nextSearchParams.delete(CONTACT_IM_SYNC_RUN_QUERY_PARAM)
-
- setRunId(nextRunId ? 'latest' : null)
- const query = nextSearchParams.toString()
- router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false })
- },
- [pathname, router, serializedSearchParams],
- )
-
- return [runId, updateRunId] as const
-}
diff --git a/web/features/contacts/im-platform/sync-section.tsx b/web/features/contacts/im-platform/sync-section.tsx
index b53bb0df56f..52ee3a80f1b 100644
--- a/web/features/contacts/im-platform/sync-section.tsx
+++ b/web/features/contacts/im-platform/sync-section.tsx
@@ -1,91 +1,110 @@
'use client'
-import type { ContactImIntegrationView, ContactImSyncRunView } from './types'
+import type { ChannelSummary } from '@dify/contracts/api/console/workspaces/types.gen'
import { Button } from '@langgenius/dify-ui/button'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useEffect, useId, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
-import { useContactImActiveSync, useStartContactImSync } from './hooks'
-import { ContactImConnectionStatus, ContactImSafeReason, ContactImSyncStatus } from './types'
-
-const isActiveRun = (run: ContactImSyncRunView | null | undefined) =>
- run?.status === ContactImSyncStatus.Queued || run?.status === ContactImSyncStatus.Running
+import { consoleQuery } from '@/service/console'
+import { getHttpErrorStatus } from '@/service/http-error'
+import { useContactsImPlatformOrganization } from './composition-context'
+import { CONTACT_IM_SYNC_POLL_INTERVAL_MS } from './hooks'
export function ContactImDirectorySyncSection({
integration,
onViewDetails,
}: {
- integration: ContactImIntegrationView
+ integration: ChannelSummary
onViewDetails: (runId: string) => void
}) {
const { t } = useTranslation(['contacts'])
+ const { canManage } = useContactsImPlatformOrganization()
const { formatTimeFromNow } = useFormatTimeFromNow()
- const activeSyncQuery = useContactImActiveSync()
- const startSync = useStartContactImSync()
- const currentRun = activeSyncQuery.data
- const displayedRun = currentRun ?? integration.lastSync
- const displayedRunDate = displayedRun?.completedAt ?? displayedRun?.startedAt
- const displayedRunIsActive = isActiveRun(displayedRun)
- const syncIsActive = isActiveRun(currentRun)
- const canStart =
- integration.canManage &&
- integration.status === ContactImConnectionStatus.Connected &&
- integration.capabilities.directorySync
- const isSyncing = startSync.isPending || syncIsActive
- const buttonDisabled =
- activeSyncQuery.isPending || activeSyncQuery.isError || !canStart || syncIsActive
- const disabledReason = !integration.canManage
- ? t(($) => $['imPlatform.sync.noPermission'])
- : integration.status !== ContactImConnectionStatus.Connected
- ? t(($) => $['imPlatform.sync.notConnected'])
- : !integration.capabilities.directorySync
- ? t(($) => $['imPlatform.sync.unsupported'])
- : null
+ const api = consoleQuery.workspaces.current.humanInput.v2.imSyncRuns
+ const runQuery = useQuery(
+ api.latest.get.queryOptions({
+ context: { silent: true },
+ retry: (count, error) => getHttpErrorStatus(error) !== 404 && count < 2,
+ refetchInterval: ({ state }) =>
+ state.data?.run.status === 'queued' || state.data?.run.status === 'running'
+ ? CONTACT_IM_SYNC_POLL_INTERVAL_MS
+ : false,
+ }),
+ )
+ const startSync = useMutation(api.post.mutationOptions({ context: { silent: true } }))
+ const queryClient = useQueryClient()
+ const previousRunRef = useRef<{ id: string; active: boolean } | null>(null)
+ const run = runQuery.data?.run
+ const active = run?.status === 'queued' || run?.status === 'running'
+ useEffect(() => {
+ if (!run) return
+ const previous = previousRunRef.current
+ previousRunRef.current = { id: run.id, active }
+ if (previous && previous.id !== run.id) {
+ void queryClient.resetQueries({ queryKey: api.latest.results.key() })
+ }
+ if (previous?.id === run.id && previous.active && !active) {
+ void Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.humanInput.v2.contacts.key(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.humanInput.v2.contactOptions.key(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.humanInput.v2.imIdentities.key(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.humanInput.v2.channels.key(),
+ }),
+ queryClient.invalidateQueries({ queryKey: api.latest.results.key() }),
+ ])
+ }
+ }, [active, api.latest.results, queryClient, run])
+ const requestError = runQuery.isError && getHttpErrorStatus(runQuery.error) !== 404
+ const date = run?.finished_at ?? run?.started_at
const statusLabels = {
- [ContactImSyncStatus.Failure]: t(($) => $['imPlatform.sync.status.failure']),
- [ContactImSyncStatus.PartialSuccess]: t(($) => $['imPlatform.sync.status.partial_success']),
- [ContactImSyncStatus.Queued]: t(($) => $['imPlatform.sync.status.queued']),
- [ContactImSyncStatus.Running]: t(($) => $['imPlatform.sync.status.running']),
- [ContactImSyncStatus.Success]: t(($) => $['imPlatform.sync.status.success']),
- }
- const safeErrorLabels = {
- [ContactImSafeReason.ContactUpdateFailed]: t(
- ($) => $['imPlatform.details.safeReason.contact_update_failed'],
- ),
- [ContactImSafeReason.DuplicateIdentity]: t(
- ($) => $['imPlatform.details.safeReason.duplicate_identity'],
- ),
- [ContactImSafeReason.MissingEmail]: t(($) => $['imPlatform.details.safeReason.missing_email']),
- [ContactImSafeReason.NoMatchingContact]: t(
- ($) => $['imPlatform.details.safeReason.no_matching_contact'],
- ),
- [ContactImSafeReason.ProviderRequestFailed]: t(
- ($) => $['imPlatform.details.safeReason.provider_request_failed'],
- ),
+ failed: t(($) => $['imPlatform.sync.status.failure']),
+ queued: t(($) => $['imPlatform.sync.status.queued']),
+ running: t(($) => $['imPlatform.sync.status.running']),
+ succeeded: t(($) => $['imPlatform.sync.status.success']),
}
-
+ const labelId = useId()
+ const reasonId = useId()
+ const reason = !canManage
+ ? t(($) => $['imPlatform.sync.noPermission'])
+ : integration.status !== 'connected'
+ ? t(($) => $['imPlatform.sync.notConnected'])
+ : runQuery.isPending
+ ? t(($) => $['imPlatform.sync.loading'])
+ : requestError
+ ? t(($) => $['imPlatform.sync.startFailed'])
+ : undefined
return (
<div className="mt-2 rounded-xl bg-background-section-burn px-4 py-3">
+ <div role="status" aria-atomic="true" className="sr-only">
+ {run ? `${integration.display_identifier}: ${statusLabels[run.status]}` : ''}
+ </div>
<div className="flex items-center gap-2">
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5 system-xs-regular text-text-tertiary">
<span aria-hidden className="i-ri-loop-left-line size-3 shrink-0" />
- {displayedRun ? (
- displayedRunIsActive ? (
- <span aria-live="polite">{statusLabels[displayedRun.status]}</span>
+ {run ? (
+ active ? (
+ <span>{statusLabels[run.status]}</span>
) : (
<>
<span>
{t(($) => $['imPlatform.sync.latestSynced'], {
- date: displayedRunDate
- ? formatTimeFromNow(new Date(displayedRunDate).getTime())
+ date: date
+ ? formatTimeFromNow(date * 1000)
: t(($) => $['imPlatform.details.missing']),
})}
</span>
- <span aria-hidden className="flex shrink-0 px-1">
- <span className="h-3 w-px bg-divider-regular" />
- </span>
+ <span aria-hidden className="mx-1 h-3 w-px bg-divider-regular" />
<Button
className="h-auto shrink-0 rounded-none px-0 font-normal hover:bg-transparent hover:underline"
- onClick={() => onViewDetails(displayedRun.id)}
+ onClick={() => onViewDetails(run.id)}
size="small"
variant="ghost-accent"
>
@@ -95,66 +114,47 @@ export function ContactImDirectorySyncSection({
)
) : (
<span>
- {activeSyncQuery.isPending
+ {runQuery.isPending
? t(($) => $['imPlatform.sync.loading'])
: t(($) => $['imPlatform.sync.noRuns'])}
</span>
)}
</div>
<Button
- aria-label={
- isSyncing
- ? t(($) => $['imPlatform.action.syncing'])
- : t(($) => $['imPlatform.action.syncNow'])
- }
- disabled={buttonDisabled}
- loading={startSync.isPending}
- onClick={() => {
- if (buttonDisabled || startSync.isPending) return
- startSync.mutate()
- }}
+ aria-labelledby={labelId}
+ aria-describedby={reason ? reasonId : undefined}
+ disabled={Boolean(reason)}
+ focusableWhenDisabled
+ loading={startSync.isPending || active}
+ onClick={() => startSync.mutate(undefined)}
size="small"
>
- {isSyncing
- ? t(($) => $['imPlatform.action.syncing'])
- : t(($) => $['imPlatform.action.syncNow'])}
+ <span id={labelId}>
+ {startSync.isPending || active
+ ? t(($) => $['imPlatform.action.syncing'])
+ : t(($) => $['imPlatform.action.syncNow'])}
+ </span>
</Button>
</div>
-
- {disabledReason && (
- <div className="mt-2 system-xs-regular text-text-tertiary">{disabledReason}</div>
+ {reason && (
+ <div id={reasonId} className="mt-2 system-xs-regular text-text-tertiary">
+ {reason}
+ </div>
)}
-
- {(activeSyncQuery.isError || startSync.isError) && (
+ {(requestError || startSync.isError) && (
<div role="alert" className="mt-2 system-xs-regular text-text-destructive">
{t(($) => $['imPlatform.sync.startFailed'])}
- {activeSyncQuery.isError && (
- <Button className="ms-3" onClick={() => activeSyncQuery.refetch()} size="small">
+ {requestError && (
+ <Button className="ms-3" onClick={() => runQuery.refetch()} size="small">
{t(($) => $['imPlatform.action.retry'])}
</Button>
)}
</div>
)}
-
- {displayedRun && !displayedRunIsActive && (
- <>
- <div
- aria-live="polite"
- className={
- displayedRun.status === ContactImSyncStatus.Success
- ? 'sr-only'
- : 'mt-2 system-xs-medium text-text-destructive'
- }
- >
- {statusLabels[displayedRun.status]}
- </div>
- {(displayedRun.errorMessage || displayedRun.safeError) && (
- <div className="mt-2 system-xs-regular text-text-destructive">
- {displayedRun.errorMessage ??
- (displayedRun.safeError ? safeErrorLabels[displayedRun.safeError] : null)}
- </div>
- )}
- </>
+ {run?.status === 'failed' && (
+ <div className="mt-2 system-xs-regular text-text-destructive">
+ {run.error_message ?? statusLabels.failed}
+ </div>
)}
</div>
)
diff --git a/web/features/contacts/im-platform/types.ts b/web/features/contacts/im-platform/types.ts
index 21a13196e54..132082b79c4 100644
--- a/web/features/contacts/im-platform/types.ts
+++ b/web/features/contacts/im-platform/types.ts
@@ -1,73 +1,15 @@
+import type { ChannelSummary } from '@dify/contracts/api/console/workspaces/types.gen'
type ValueOf<T> = T[keyof T]
-
export const ContactImProvider = {
- DingTalk: 'dingtalk',
- Email: 'email',
+ DingTalk: 'ding_talk',
+ Email: 'resend',
Feishu: 'feishu',
Lark: 'lark',
MSTeams: 'ms_teams',
WeCom: 'we_com',
Slack: 'slack',
} as const
-
-export type ContactImProvider = ValueOf<typeof ContactImProvider>
-
-export const ContactChannelKind = {
- Email: 'email',
- Im: 'im',
-} as const
-
-export type ContactChannelKind = ValueOf<typeof ContactChannelKind>
-
-export const ContactImAuthMode = {
- Credentials: 'credentials',
- OAuth: 'oauth',
-} as const
-
-export type ContactImAuthMode = ValueOf<typeof ContactImAuthMode>
-
-export const ContactImProviderAvailability = {
- Available: 'available',
- Unavailable: 'unavailable',
-} as const
-
-export type ContactImProviderAvailability = ValueOf<typeof ContactImProviderAvailability>
-
-export const ContactImConnectionStatus = {
- CallbackError: 'callback_error',
- Configured: 'configured',
- Connected: 'connected',
- ConnectionError: 'connection_error',
- NotConfigured: 'not_configured',
- PermissionIssue: 'permission_issue',
-} as const
-
-export type ContactImConnectionStatus = ValueOf<typeof ContactImConnectionStatus>
-
-export const ContactImSyncStatus = {
- Failure: 'failure',
- PartialSuccess: 'partial_success',
- Queued: 'queued',
- Running: 'running',
- Success: 'success',
-} as const
-
-export type ContactImSyncStatus = ValueOf<typeof ContactImSyncStatus>
-
-export const ContactImSyncResult = {
- Added: 'added',
- NotMatched: 'not_matched',
- Removed: 'removed',
- CreatedBinding: 'created_binding',
- Failed: 'failed',
- Matched: 'matched',
- Skipped: 'skipped',
- Unmatched: 'unmatched',
- UpdatedBinding: 'updated_binding',
-} as const
-
-export type ContactImSyncResult = ValueOf<typeof ContactImSyncResult>
-
+export type ContactImProvider = ChannelSummary['provider']
export const ContactImProviderField = {
AppId: 'appId',
CorpId: 'corpId',
@@ -86,48 +28,15 @@ export const ContactImProviderField = {
export type ContactImProviderField = ValueOf<typeof ContactImProviderField>
-export const ContactImStatusReason = {
- CallbackMismatch: 'callback_mismatch',
- MissingDirectoryPermission: 'missing_directory_permission',
- ProviderRequestFailed: 'provider_request_failed',
-} as const
-
-export type ContactImStatusReason = ValueOf<typeof ContactImStatusReason>
-
-export const ContactImUnavailableReason = {
- DeploymentUnsupported: 'deployment_unsupported',
- NotReleased: 'not_released',
-} as const
-
-export type ContactImUnavailableReason = ValueOf<typeof ContactImUnavailableReason>
-
-export const ContactImSafeReason = {
- ContactUpdateFailed: 'contact_update_failed',
- DuplicateIdentity: 'duplicate_identity',
- MissingEmail: 'missing_email',
- NoMatchingContact: 'no_matching_contact',
- ProviderRequestFailed: 'provider_request_failed',
-} as const
-
-export type ContactImSafeReason = ValueOf<typeof ContactImSafeReason>
-
export const ContactImRepositoryErrorCode = {
- ActiveProviderExists: 'active_provider_exists',
ConfigurationUpdated: 'configuration_updated',
- DetailLoadFailed: 'detail_load_failed',
- IntegrationLoadFailed: 'integration_load_failed',
InvalidCommand: 'invalid_command',
MutationFailed: 'mutation_failed',
NoPermission: 'no_permission',
PageLoadFailed: 'page_load_failed',
- PermissionLoadFailed: 'permission_load_failed',
- ProviderLoadFailed: 'provider_load_failed',
- ProviderUnavailable: 'provider_unavailable',
ReplacementRequired: 'replacement_required',
RequiredFieldsMissing: 'required_fields_missing',
SavedDetailsUnavailable: 'saved_details_unavailable',
- SyncAlreadyRunning: 'sync_already_running',
- SyncNotAllowed: 'sync_not_allowed',
SyncRunNotFound: 'sync_run_not_found',
} as const
@@ -152,129 +61,39 @@ export class ContactImRepositoryError extends Error {
}
}
-type ContactImProviderCapabilities = {
- directorySync: boolean
-}
-
export type ContactImProviderFieldDefinition = {
field: ContactImProviderField
required: boolean
secret?: boolean
}
-
export type ContactImProviderDefinition = {
- authMode: ContactImAuthMode
- availability: ContactImProviderAvailability
- callbackUrl: string | null
- capabilities: ContactImProviderCapabilities
- channelKind: ContactChannelKind
displayName: string
provider: ContactImProvider
requiredFields: ContactImProviderFieldDefinition[]
- requiresFreshCredentials?: boolean
- unavailableReason: ContactImUnavailableReason | null
-}
-
-export type ContactImSyncCounts = Partial<Record<ContactImSyncResult, number>>
-
-export type ContactImSyncRunView = {
- completedAt: string | null
- counts: ContactImSyncCounts
- durationMs: number | null
- id: string
- provider?: ContactImProvider
- safeError: ContactImSafeReason | null
- startedAt: string | null
- startedBy: string | null
- errorMessage?: string | null
- status: ContactImSyncStatus
}
-
-export type ContactImIntegrationView = {
- channelId?: string
- configVersion?: string
- callbackUrl?: string | null
- statusDescription?: string
- canManage: boolean
- capabilities: ContactImProviderCapabilities
- channelKind: ContactChannelKind
+export type ContactImIntegrationView = ChannelSummary & {
configuredValues: Partial<Record<Exclude<ContactImProviderField, 'secret'>, string>>
- configuredFields?: ContactImProviderField[]
- displayIdentifier: string | null
- lastCheckedAt: string | null
- lastSync: ContactImSyncRunView | null
- organizationId: string
- provider: ContactImProvider
+ configuredFields: ContactImProviderField[]
secretConfigured: boolean
- status: ContactImConnectionStatus
- statusReason: ContactImStatusReason | null
-}
-
-type ContactImPlatformIdentityView = {
- displayName: string | null
- email: string | null
- platformUserId: string | null
-}
-
-type ContactImMatchedContactView = {
- avatarUrl?: string | null
- email: string | null
- id: string
- name: string
-}
-
-export type ContactImSyncItemView = {
- reason?: string | null
- id: string
- matchedContact: ContactImMatchedContactView | null
- platformIdentity: ContactImPlatformIdentityView
- result: ContactImSyncResult
- safeReason: ContactImSafeReason | null
}
-
-export type ContactImPage<T> = {
- items: T[]
- nextCursor: string | null
-}
-
export type SaveContactImCredentialsCommand = {
channelId?: string
expectedConfigVersion?: string
- organizationId: string
provider: ContactImProvider
replaceActiveProvider: boolean
- retainSecret?: boolean
clearedFields?: ContactImProviderField[]
secret?: string
values: Partial<Record<Exclude<ContactImProviderField, 'secret'>, string>>
}
-export type AuthorizeContactImProviderCommand = {
- organizationId: string
- provider: ContactImProvider
- replaceActiveProvider: boolean
-}
-
-export type ContactImOrganizationCommand = {
- organizationId: string
-}
-
-export type ContactImProviderCommand = ContactImOrganizationCommand & {
+type ContactImProviderCommand = {
channelId?: string
expectedConfigVersion?: string
provider: ContactImProvider
}
export type TestContactImConnectionCommand = ContactImProviderCommand & {
- retainSecret?: boolean
clearedFields?: ContactImProviderField[]
secret?: string
values: Partial<Record<Exclude<ContactImProviderField, 'secret'>, string>>
}
-
-export type ListContactImSyncItemsInput = {
- cursor?: string
- pageSize?: number
- result?: ContactImSyncResult
- runId: string
-}
diff --git a/web/features/contacts/management/README.md b/web/features/contacts/management/README.md
index 83b0ae85ee7..ba5750c8eb0 100644
--- a/web/features/contacts/management/README.md
+++ b/web/features/contacts/management/README.md
@@ -1,32 +1,35 @@
# Contacts Management
-This frontend feature owns the `/contacts` directory, contact details,
-External contact creation, EE Add from Platform selection, removable-contact
-selection, the External-to-Workspace Contact confirmation composed into member
-invitations, and the narrow Contacts impact composed into active-member removal.
+This feature owns the `/contacts` directory, contact details, external-contact
+creation and editing, platform-directory imports, and removable-contact selection.
+Only workspace managers may access it. The runtime provider reads the current
+workspace permissions and the authoritative `im_centrally_managed` capability;
+it does not own a repository or synthetic API state.
-## Release Gate
+Components use generated `consoleQuery` query and mutation options directly.
+Shared mutation policies own cache invalidation. Contact and directory data keep
+the generated API shape, including nullable or omitted email and avatar fields.
+Tests stub the generated transport responses while preserving query keys,
+mutation policies, and production pagination behavior.
-`NEXT_PUBLIC_ENABLE_HITL_IM` defaults to `false`. Set it to `true` and restart
-Web to expose the Contacts navigation and route, workspace IM channel settings,
-and contact-aware member interactions. Reload the browser after restarting.
-This gate is independent of `NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW` and does not
-change `im_centrally_managed`, which determines where IM configuration is managed.
-When off, the editor creates legacy V1 Human Input nodes, hides migration UI,
-and blocks V2 insertion, contact selection, message templates and IM debug UI.
-Existing V2 nodes keep their original data and show an unavailable state; they
-are not converted to V1. V1 editing and forms remain available. New V2 approval
-routes and `/contacts` return not found while disabled.
+`NEXT_PUBLIC_ENABLE_HITL_IM` is the independent, default-off release gate. The
+`im_centrally_managed` capability determines whether platform imports and
+organization-managed bindings are available. In centrally managed mode contact
+details do not request workspace channel-management endpoints.
-Runtime data and mutations flow through `ContactsManagementRepository` and its
-Console API adapter, composed by `ContactsManagementRuntimeProvider`. The
-deterministic in-memory adapter in `__tests__/fixtures/` is used only by tests.
-Components use the repository rather than calling Contact APIs directly. Add
-from Platform selects available Platform contacts. The sibling
-`contacts/im-platform` feature keeps an independent repository and shares only
-workspace/deployment shell context.
+External-contact and platform-picker drafts, search, selection, and mutations
+live inside each dialog content session. They remain visible throughout closing
+transitions, reset after unmount, and survive failed submissions for correction.
+Server duplicate-email errors belong to the email field.
-When a member invitation or selected Platform contact exactly matches an
-External Contact email, the owning workflow pauses before mutation. Confirming
-the dialog upgrades the Contact type while preserving its Contact ID,
-workflow references, history, and remaining identity fields.
+Platform candidates are paginated by the backend and resolved against existing
+contacts through the generated batch operation. The available-candidates query
+orchestrates those generated operations and skips fully imported pages until a
+selectable contact, terminal page, or request error is reached. It keeps underlying
+pages in their generated caches, isolates workspace/search identities, and stops
+on cancellation or non-progressing pagination. Only search and contact-type
+filters are shareable URL state; loaded page count is local query state.
+
+Member invitations and member removal use their existing generated workspace
+member operations. Contact-upgrade and contact-retention workflows are not
+exposed because no backend contract supports them.
diff --git a/web/features/contacts/management/__tests__/composition.spec.tsx b/web/features/contacts/management/__tests__/composition.spec.tsx
index ca48c01e85f..263e6de8e0b 100644
--- a/web/features/contacts/management/__tests__/composition.spec.tsx
+++ b/web/features/contacts/management/__tests__/composition.spec.tsx
@@ -33,10 +33,6 @@ vi.mock('@/service/console', async () => {
}
})
-vi.mock('../repository', () => ({
- createContactsApiRepository: () => ({}),
-}))
-
function CapabilityProbe() {
const context = useContactsFeatureContext()
return (
diff --git a/web/features/contacts/management/__tests__/contact-im-channels.spec.tsx b/web/features/contacts/management/__tests__/contact-im-channels.spec.tsx
index be46439987d..f4355fb55c6 100644
--- a/web/features/contacts/management/__tests__/contact-im-channels.spec.tsx
+++ b/web/features/contacts/management/__tests__/contact-im-channels.spec.tsx
@@ -1,48 +1,86 @@
-import type { ContactView } from '../types'
+import type {
+ ChannelSummary,
+ ContactImBindingDetail,
+ ImIdentity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ContactsFeatureContextValue, ContactView } from '../types'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor, within } from '@testing-library/react'
-import { consoleClient } from '@/service/console'
+import userEvent from '@testing-library/user-event'
import { ContactsManagementProvider } from '../composition'
import { ContactDetailsPanel } from '../contact-details-panel'
-import { createContactsApiRepository } from '../repository'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
+import { alice, managerContext } from './fixtures/data'
-vi.mock('@/service/console', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/console')>()),
- consoleClient: {
- workspaces: {
- current: {
- humanInput: { v2: { channels: { get: vi.fn() } } },
- },
- },
- },
+const api = vi.hoisted(() => ({
+ channels: vi.fn(),
+ identities: vi.fn(),
+ bind: vi.fn(),
+ override: vi.fn(),
+ unbind: vi.fn(),
+ reset: vi.fn(),
}))
-
-function renderContact(imCentrallyManaged: boolean, bound: boolean) {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const contact: ContactView = {
- id: 'contact-member',
- type: 'workspace',
- name: 'Workspace Member',
- email: '[email protected]',
- avatar_url: '',
- created_at: 1,
- im_bindings: bound ? [{ id: 'binding-feishu', provider: 'feishu', scope: 'organization' }] : [],
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.humanInput.v2.channels.get': api.channels,
+ 'workspaces.current.humanInput.v2.imIdentities.get': api.identities,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imBindings.put': api.bind,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imOverride.put': api.override,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imBindings.delete': api.unbind,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imOverride.delete': api.reset,
+ }),
}
+})
+const identity: ImIdentity = {
+ id: 'identity-1',
+ display_name: 'Alice IM',
+ provider: 'feishu',
+ provider_user_id: 'ou_alice',
+ email: '[email protected]',
+ binding_status: 'unbound',
+}
+const detail: ContactImBindingDetail = {
+ id: 'binding-1',
+ provider: 'feishu',
+ scope: 'organization',
+ identity: {
+ id: identity.id,
+ display_name: identity.display_name ?? null,
+ email: identity.email ?? null,
+ provider_user_id: identity.provider_user_id,
+ },
+}
+const channel: ChannelSummary = {
+ id: 'channel-1',
+ config_version: 'version-1',
+ created_at: 1780000000,
+ updated_at: 1780000000,
+ display_identifier: 'Test Feishu',
+ kind: 'im',
+ provider: 'feishu',
+ status: 'connected',
+ status_description: '',
+ webhook_url: null,
+}
+const workspaceContact: ContactView = {
+ ...alice,
+ type: 'workspace',
+ im_bindings: [{ id: detail.id, provider: detail.provider, scope: detail.scope }],
+ im_binding_details: [detail],
+}
+function setup(
+ context: ContactsFeatureContextValue = managerContext,
+ contact: ContactView = workspaceContact,
+) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
render(
<QueryClientProvider client={queryClient}>
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }}
- repository={createContactsApiRepository()}
- >
+ <ContactsManagementProvider context={context}>
<ContactDetailsPanel
contact={contact}
onClose={vi.fn()}
@@ -52,68 +90,79 @@ function renderContact(imCentrallyManaged: boolean, bound: boolean) {
</ContactsManagementProvider>
</QueryClientProvider>,
)
- return screen.getByRole('complementary', { name: 'contacts.details.title' })
}
+beforeEach(() => {
+ api.channels.mockReset().mockResolvedValue({ channels: [channel] })
+ api.identities.mockReset().mockResolvedValue({ data: [identity], page: 1, limit: 20, total: 1 })
+ api.bind.mockReset().mockResolvedValue({ contact: workspaceContact })
+ api.override.mockReset().mockResolvedValue({ contact: workspaceContact })
+ api.unbind.mockReset().mockResolvedValue({})
+ api.reset.mockReset().mockResolvedValue({})
+})
+
+it.each([true, undefined])(
+ 'never calls workspace channel management while centralized capability=%s',
+ async (imCentrallyManaged) => {
+ setup({ ...managerContext, imCentrallyManaged })
+ expect(screen.getByRole('region', { name: 'Alice' })).toBeInTheDocument()
+ await Promise.resolve()
+ expect(api.channels).not.toHaveBeenCalled()
+ },
+)
-describe('Contact details IM channel availability', () => {
- const channels = consoleClient.workspaces.current.humanInput.v2.channels
+it('keeps external contacts email-only even when a channel is configured', () => {
+ setup(managerContext, alice)
+ expect(screen.queryByRole('button', { name: /imBinding.changeTitle/ })).not.toBeInTheDocument()
+ expect(api.channels).not.toHaveBeenCalled()
+})
- beforeEach(() => vi.resetAllMocks())
+it('offers an initially unbound workspace contact a provider-described bind action', async () => {
+ setup(managerContext, { ...workspaceContact, im_bindings: [], im_binding_details: [] })
+ const bind = await screen.findByRole('button', { name: 'contacts.imBinding.bind' })
+ expect(bind).toHaveAccessibleDescription('Feishu')
+})
- it.each([false, true])(
- 'does not call workspace channel management in centrally managed mode when bound is %s',
- async (bound) => {
- vi.mocked(channels.get).mockRejectedValue(
- Object.assign(new Error('Workspace channel management is unavailable'), { status: 501 }),
- )
+it('unbinds a default identity through the generated delete operation', async () => {
+ const user = userEvent.setup()
+ setup()
+ await user.click(screen.getByRole('button', { name: /imBinding.changeTitle.*Feishu/ }))
+ const dialog = await screen.findByRole('dialog')
+ await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.remove' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(api.unbind).toHaveBeenCalledWith({ params: { contact_id: alice.id } })
+ expect(api.reset).not.toHaveBeenCalled()
+})
- const details = renderContact(true, bound)
- await waitFor(() => {
- expect(
- within(details).getByText('contacts.imBinding.enterpriseReadOnly'),
- ).toBeInTheDocument()
- expect(within(details).queryByRole('alert')).not.toBeInTheDocument()
- })
+it('exposes centralized binding modes with an associated organization identity preview', async () => {
+ const user = userEvent.setup()
+ setup({ ...managerContext, imCentrallyManaged: true })
+ await user.click(screen.getByRole('button', { name: /imBinding.changeTitle.*Feishu/ }))
+ const group = await screen.findByRole('radiogroup', { name: 'contacts.imBinding.modeLabel' })
+ const organization = within(group).getByRole('radio', {
+ name: 'contacts.imBinding.organizationMode',
+ })
+ expect(organization).toBeChecked()
+ expect(organization).toHaveAccessibleDescription(/Alice IM/)
+ expect(api.channels).not.toHaveBeenCalled()
+})
- expect(channels.get).not.toHaveBeenCalled()
- expect(
- within(details).queryByRole('button', { name: 'contacts.imBinding.bind' }),
- ).not.toBeInTheDocument()
- if (bound) {
- expect(within(details).getByText('Feishu')).toBeInTheDocument()
- expect(
- within(details).getByRole('button', { name: /^contacts\.imBinding\.changeTitle/ }),
- ).toBeEnabled()
- } else {
- expect(within(details).queryByText('Feishu')).not.toBeInTheDocument()
- }
+it('restores an override with the override delete operation instead of unbinding the default', async () => {
+ const user = userEvent.setup()
+ const overridden = { ...detail, scope: 'workspace' as const }
+ setup(
+ { ...managerContext, imCentrallyManaged: true },
+ {
+ ...workspaceContact,
+ im_bindings: [{ id: detail.id, provider: 'feishu', scope: 'workspace' }],
+ im_binding_details: [overridden],
},
)
-
- it('still discovers configured IM channels and offers initial binding in workspace-managed mode', async () => {
- vi.mocked(channels.get).mockResolvedValue({
- channels: [
- {
- id: 'channel-feishu',
- kind: 'im',
- provider: 'feishu',
- config_version: 'version-1',
- created_at: 1,
- updated_at: 1,
- display_identifier: 'feishu-app',
- status: 'configured',
- status_description: '',
- webhook_url: null,
- },
- ],
- })
-
- const details = renderContact(false, false)
-
- expect(
- await within(details).findByRole('button', { name: 'contacts.imBinding.bind' }),
- ).toBeEnabled()
- expect(within(details).getByText('Feishu')).toBeInTheDocument()
- expect(channels.get).toHaveBeenCalledExactlyOnceWith(undefined, { context: { silent: true } })
- })
+ await user.click(screen.getByRole('button', { name: /imBinding.changeTitle.*Feishu/ }))
+ await user.click(
+ await screen.findByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
+ )
+ await user.click(screen.getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(api.reset).toHaveBeenCalledWith({ params: { contact_id: alice.id } })
+ expect(api.unbind).not.toHaveBeenCalled()
})
diff --git a/web/features/contacts/management/__tests__/directory-errors.spec.tsx b/web/features/contacts/management/__tests__/directory-errors.spec.tsx
new file mode 100644
index 00000000000..08a20b0f335
--- /dev/null
+++ b/web/features/contacts/management/__tests__/directory-errors.spec.tsx
@@ -0,0 +1,84 @@
+import { QueryClient } from '@tanstack/react-query'
+import { render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { ContactsManagementProvider } from '../composition'
+import { ContactsDirectoryPage } from '../directory-page'
+import { alice, managerContext } from './fixtures/data'
+
+const network = vi.hoisted(() => ({
+ details: vi.fn<() => Response>(),
+}))
+
+const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ })
+
+vi.mock('@/service/base', async () => {
+ const { httpErrorFromResponse } = await import('@/service/http-error')
+ return {
+ request: async (_url: string, _init: RequestInit, options: { request: Request }) => {
+ const url = new URL(options.request.url)
+ const response = url.pathname.endsWith(`/contacts/${alice.id}`)
+ ? network.details()
+ : url.pathname.endsWith('/channels')
+ ? json({ channels: [] })
+ : json({
+ data: url.searchParams.get('group') === 'workspace' ? [] : [alice],
+ page: 1,
+ limit: Number(url.searchParams.get('limit')) || 20,
+ total: url.searchParams.get('group') === 'workspace' ? 0 : 1,
+ })
+ if (!response.ok) throw await httpErrorFromResponse(response)
+ return response
+ },
+ }
+})
+vi.mock('@/utils/client', () => ({ isClient: true, isServer: false }))
+
+let client: QueryClient
+beforeEach(() => {
+ network.details.mockReset()
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+})
+afterEach(() => client.clear())
+
+const openDetails = async () => {
+ const user = userEvent.setup()
+ render(
+ <QueryClientTestProvider queryClient={client}>
+ <NuqsTestingAdapter hasMemory>
+ <ContactsManagementProvider context={managerContext}>
+ <ContactsDirectoryPage />
+ </ContactsManagementProvider>
+ </NuqsTestingAdapter>
+ </QueryClientTestProvider>,
+ )
+ await user.click(await screen.findByRole('button', { name: /Alice [email protected]/ }))
+ return { user, panel: screen.getByRole('region', { name: 'contacts.details.title' }) }
+}
+
+it('shows a removed contact as no longer in the directory after HTTP 404 without retry', async () => {
+ network.details.mockReturnValue(json({ code: 'not_found', message: 'Contact removed' }, 404))
+ const { panel } = await openDetails()
+ expect(await within(panel).findByText('contacts.details.notFound')).toBeVisible()
+ expect(within(panel).queryByText('contacts.details.error')).not.toBeInTheDocument()
+ expect(
+ within(panel).queryByRole('button', { name: 'contacts.action.retry' }),
+ ).not.toBeInTheDocument()
+ expect(network.details).toHaveBeenCalledOnce()
+})
+
+it('offers retry after HTTP 500 and opens the recovered contact details', async () => {
+ network.details
+ .mockReturnValueOnce(json({ code: 'internal_server_error', message: 'Unavailable' }, 500))
+ .mockImplementation(() => json({ contact: alice, im_binding_details: [] }))
+ const { user, panel } = await openDetails()
+ expect(await within(panel).findByRole('alert')).toHaveTextContent('contacts.details.error')
+ await user.click(within(panel).getByRole('button', { name: 'contacts.action.retry' }))
+ expect(await screen.findByRole('region', { name: 'Alice' })).toBeVisible()
+ await waitFor(() => expect(network.details).toHaveBeenCalledTimes(2))
+})
diff --git a/web/features/contacts/management/__tests__/directory-page.browser.spec.tsx b/web/features/contacts/management/__tests__/directory-page.browser.spec.tsx
index 3a56988b120..9f9f0aea575 100644
--- a/web/features/contacts/management/__tests__/directory-page.browser.spec.tsx
+++ b/web/features/contacts/management/__tests__/directory-page.browser.spec.tsx
@@ -1,52 +1,85 @@
+import type { HumanInputContact } from '@dify/contracts/api/console/workspaces/types.gen'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { page, userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
+import { ContactsManagementProvider } from '../composition'
import { ContactsDirectoryPage } from '../directory-page'
-import { ContactsManagementMockProvider } from './fixtures/composition'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
+import { alice, bob, managerContext } from './fixtures/data'
-it.each([ContactsMockScenario.CeMixed, ContactsMockScenario.ReadOnly])(
- 'opens contact details from the whole row in %s without consuming selection or keyboard access',
- async (scenarioName) => {
- // The regression is the native hit target across table cells, which DOM events cannot prove.
- await page.viewport(1280, 720)
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })
- const scenario = createContactsMockScenario(scenarioName)
- const screen = await render(
- <QueryClientProvider client={queryClient}>
- <NuqsTestingAdapter hasMemory>
- <ContactsManagementMockProvider scenario={scenario}>
- <div className="h-screen">
- <ContactsDirectoryPage />
- </div>
- </ContactsManagementMockProvider>
- </NuqsTestingAdapter>
- </QueryClientProvider>,
- )
+const api = vi.hoisted(() => ({
+ list: vi.fn(),
+ details: vi.fn(),
+ remove: vi.fn(),
+ channels: vi.fn(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.humanInput.v2.contacts.get': api.list,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.get': api.details,
+ 'workspaces.current.humanInput.v2.contacts.remove.post': api.remove,
+ 'workspaces.current.humanInput.v2.channels.get': api.channels,
+ }),
+ }
+})
+async function setup(contacts: HumanInputContact[] = [alice, bob], canManage = true) {
+ api.list.mockImplementation(
+ async ({ query }: { query?: { limit: number; group?: string } } = {}) => {
+ const data = contacts.filter((contact) => !query?.group || contact.type === query.group)
+ const limit = query?.limit ?? 20
+ return { data: data.slice(0, limit), limit, total: data.length, page: 1 }
+ },
+ )
+ api.details.mockImplementation(async ({ params }: { params: { contact_id: string } }) => ({
+ contact: contacts.find((contact) => contact.id === params.contact_id),
+ im_binding_details: [],
+ }))
+ api.channels.mockResolvedValue({ channels: [] })
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const screen = await render(
+ <QueryClientProvider client={queryClient}>
+ <NuqsTestingAdapter hasMemory>
+ <ContactsManagementProvider
+ context={{
+ ...managerContext,
+ permissions: { ...managerContext.permissions, canManageContacts: canManage },
+ }}
+ >
+ <div className="h-screen">
+ <ContactsDirectoryPage />
+ </div>
+ </ContactsManagementProvider>
+ </NuqsTestingAdapter>
+ </QueryClientProvider>,
+ )
+ return { screen, queryClient }
+}
+it.each([true, false])(
+ 'opens details from the full row without consuming selection, with management=%s',
+ async (canManage) => {
+ await page.viewport(1280, 720)
+ const { screen, queryClient } = await setup([alice, bob], canManage)
try {
- const row = screen.getByRole('row', { name: /Courtney Henry/ })
- const trigger = row.getByRole('button', { name: /Courtney Henry/ })
- const details = screen.getByRole('complementary', { name: 'contacts.details.title' })
+ const row = screen.getByRole('row', { name: /Alice/ })
+ const trigger = row.getByRole('button', { name: /Alice [email protected]/ })
+ const details = screen.getByRole('region', { name: 'Alice', exact: true })
await expect.element(trigger).toBeVisible()
-
- if (scenario.permissions.canManageContacts) {
- const checkbox = row.getByRole('checkbox', { name: /Courtney Henry/ })
+ if (canManage) {
+ const checkbox = row.getByRole('checkbox')
await checkbox.click()
await expect.element(checkbox).toBeChecked()
await expect.element(details).not.toBeInTheDocument()
await checkbox.click()
}
-
- const selectionColumnOffset = scenario.permissions.canManageContacts ? 1 : 0
- for (const columnIndex of [1, 2, 3]) {
- const cell = row.getByRole('cell').nth(columnIndex + selectionColumnOffset)
+ for (const index of [1, 2, 3]) {
+ const cell = row.getByRole('cell').nth(index + (canManage ? 1 : 0))
const rowBounds = row.element().getBoundingClientRect()
const cellBounds = cell.element().getBoundingClientRect()
- // Click the right padding too, so a text-only handler cannot satisfy the contract.
await row.click({
position: {
x: cellBounds.right - rowBounds.left - 4,
@@ -54,12 +87,13 @@ it.each([ContactsMockScenario.CeMixed, ContactsMockScenario.ReadOnly])(
},
})
await expect.element(details).toBeVisible()
- await expect.element(details.getByText('Courtney Henry', { exact: true })).toBeVisible()
+ await expect
+ .element(details.getByRole('heading', { name: 'Alice', exact: true }))
+ .toHaveFocus()
await details.getByRole('button', { name: 'contacts.action.close' }).click()
await expect.element(details).not.toBeInTheDocument()
await expect.element(trigger).toHaveFocus()
}
-
await userEvent.keyboard('{Enter}')
await expect.element(details).toBeVisible()
} finally {
@@ -67,3 +101,27 @@ it.each([ContactsMockScenario.CeMixed, ContactsMockScenario.ReadOnly])(
}
},
)
+
+it('keeps keyboard-focused final rows above the floating bulk bar', async () => {
+ await page.viewport(1280, 500)
+ const contacts = Array.from({ length: 20 }, (_, index) => ({
+ ...alice,
+ id: `contact-${index}`,
+ name: `Person ${index}`,
+ email: `person${index}@example.com`,
+ }))
+ const { screen, queryClient } = await setup(contacts)
+ try {
+ await screen.getByRole('checkbox', { name: /selectContact.*Person 0/ }).click()
+ const last = screen.getByRole('button', { name: 'Person 19 [email protected]' })
+ await expect.element(last).toBeVisible()
+ last.element().focus()
+ await expect.element(last).toHaveFocus()
+ const bar = screen.getByRole('button', { name: 'contacts.directory.removeSelected' })
+ expect(last.element().getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ bar.element().getBoundingClientRect().top,
+ )
+ } finally {
+ queryClient.clear()
+ }
+})
diff --git a/web/features/contacts/management/__tests__/directory-page.spec.tsx b/web/features/contacts/management/__tests__/directory-page.spec.tsx
index 8df1e0cd19d..a8aac215cd8 100644
--- a/web/features/contacts/management/__tests__/directory-page.spec.tsx
+++ b/web/features/contacts/management/__tests__/directory-page.spec.tsx
@@ -1,1874 +1,217 @@
-import type { GetContactResponse } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ReactNode } from 'react'
-import type { ContactsManagementRepository } from '../repository'
import type {
- ContactIMChannel,
- ContactIMIdentity,
- ContactsFeatureContextValue,
- ContactView,
-} from '../types'
-import type { ContactsMockScenarioDefinition } from './fixtures/scenarios'
-import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+ GetContactResponse,
+ HumanInputContact,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ReactNode } from 'react'
+import type { ContactsFeatureContextValue } from '../types'
+import { QueryClient } from '@tanstack/react-query'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { createDeferred } from '@/test/deferred'
import { ContactsManagementProvider } from '../composition'
-import { ContactAvatar, ContactDetailsPanel } from '../contact-details-panel'
import { ContactsDirectoryPage } from '../directory-page'
-import { ContactIMRequestError } from '../repository'
-import { ContactsManagementMockProvider } from './fixtures/composition'
-import { createContactsMockRepository } from './fixtures/repository'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
+import { alice, bob, managerContext } from './fixtures/data'
+
+const api = vi.hoisted(() => ({
+ list: vi.fn(),
+ details: vi.fn(),
+ remove: vi.fn(),
+ channels: vi.fn(),
+ identities: vi.fn(),
+ bind: vi.fn(),
+ override: vi.fn(),
+ unbind: vi.fn(),
+ reset: vi.fn(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.humanInput.v2.contacts.get': api.list,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.get': api.details,
+ 'workspaces.current.humanInput.v2.contacts.remove.post': api.remove,
+ 'workspaces.current.humanInput.v2.channels.get': api.channels,
+ 'workspaces.current.humanInput.v2.imIdentities.get': api.identities,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imBindings.put': api.bind,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imOverride.put': api.override,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imBindings.delete': api.unbind,
+ 'workspaces.current.humanInput.v2.contacts.byContactId.imOverride.delete': api.reset,
+ }),
+ }
+})
-function renderDirectory(
- scenario: ContactsMockScenarioDefinition,
- searchParams = '',
- repository?: ContactsManagementRepository,
- contextOverrides: Partial<ContactsFeatureContextValue> = {},
-) {
+let contacts: HumanInputContact[]
+function setup(context: ContactsFeatureContextValue = managerContext, searchParams = '') {
const queryClient = new QueryClient({
- defaultOptions: {
- mutations: { retry: false },
- queries: { retry: false },
- },
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
const onUrlUpdate = vi.fn()
- function Wrapper({ children }: { children: ReactNode }) {
- return (
- <QueryClientProvider client={queryClient}>
- <NuqsTestingAdapter hasMemory searchParams={searchParams} onUrlUpdate={onUrlUpdate}>
- {repository ? (
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- ...contextOverrides,
- }}
- repository={repository}
- >
- {children}
- </ContactsManagementProvider>
- ) : (
- <ContactsManagementMockProvider scenario={scenario}>
- {children}
- </ContactsManagementMockProvider>
- )}
- </NuqsTestingAdapter>
- </QueryClientProvider>
- )
- }
-
- return { onUrlUpdate, queryClient, ...render(<ContactsDirectoryPage />, { wrapper: Wrapper }) }
-}
-
-async function findLoadedDetails(content: string) {
- await waitFor(() => {
- expect(screen.getByRole('complementary', { name: 'contacts.details.title' })).toHaveTextContent(
- content,
- )
- })
- return screen.getByRole('complementary', { name: 'contacts.details.title' })
-}
-
-async function confirmContactRemoval(user: ReturnType<typeof userEvent.setup>) {
- const dialog = await screen.findByRole('alertdialog', {
- name: 'contacts.directory.removalTitle',
- })
- await user.click(
- within(dialog).getByRole('button', {
- name: 'contacts.directory.removeSelected',
- }),
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientTestProvider queryClient={queryClient}>
+ <NuqsTestingAdapter searchParams={searchParams} hasMemory onUrlUpdate={onUrlUpdate}>
+ <ContactsManagementProvider context={context}>{children}</ContactsManagementProvider>
+ </NuqsTestingAdapter>
+ </QueryClientTestProvider>
)
+ const view = render(<ContactsDirectoryPage />, { wrapper })
+ return { ...view, queryClient, onUrlUpdate }
}
-
-describe('ContactsDirectoryPage', () => {
- it('waits for capability data without querying contacts or clearing an EE Platform URL', () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const listContacts = vi.spyOn(repository, 'listContacts')
- const { onUrlUpdate } = renderDirectory(
- scenario,
- '?contact_kind=platform&contact_pages=2',
- repository,
- { imCentrallyManaged: undefined },
- )
-
- expect(screen.getByRole('status', { name: 'contacts.directory.loading' })).toBeInTheDocument()
- expect(listContacts.mock.calls.some(([query]) => query.limit === 20)).toBe(false)
- expect(listContacts.mock.calls.some(([query]) => query.kind === 'platform')).toBe(false)
- expect(onUrlUpdate).not.toHaveBeenCalled()
- expect(
- screen.queryByRole('button', { name: 'contacts.directory.addContact' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'contacts.directory.addExternal' }),
- ).not.toBeInTheDocument()
- })
-
- it('offers a capability retry after failure without treating the workspace as CE', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const retryIMCapability = vi.fn()
- const { onUrlUpdate } = renderDirectory(scenario, '?contact_kind=platform', repository, {
- imCentrallyManaged: undefined,
- imCapabilityError: new Error('offline'),
- retryIMCapability,
- })
- const user = userEvent.setup()
-
- expect(screen.getByText('contacts.directory.errorTitle')).toBeInTheDocument()
- expect(
- screen.queryByRole('status', { name: 'contacts.directory.loading' }),
- ).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.action.retry' }))
- expect(retryIMCapability).toHaveBeenCalledOnce()
- expect(onUrlUpdate).not.toHaveBeenCalled()
- })
-
- it.each(['ce', 'saas'] as const)(
- 'offers Platform contacts and imports them when centrally managed on %s',
- async (deployment) => {
- const scenario = {
- ...createContactsMockScenario(ContactsMockScenario.EeMixed),
- deployment,
- imCentrallyManaged: true,
- }
- renderDirectory(scenario)
- const user = userEvent.setup()
- await screen.findByText('Ralph Edwards')
-
- expect(screen.getByRole('radio', { name: 'contacts.filter.platform' })).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.directory.addContact' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.directory.addFromPlatform' }))
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- await user.click(await within(picker).findByRole('checkbox', { name: /Ada Lovelace/ }))
- await user.click(within(picker).getByRole('button', { name: 'contacts.platformPicker.add' }))
-
- expect(await screen.findByText('Ada Lovelace')).toBeInTheDocument()
- },
- )
-
- it('hides Platform controls on EE when centrally managed binding is disabled', async () => {
- renderDirectory({
- ...createContactsMockScenario(ContactsMockScenario.EeMixed),
- imCentrallyManaged: false,
- })
- await screen.findByText('Ralph Edwards')
-
- expect(
- screen.queryByRole('radio', { name: 'contacts.filter.platform' }),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'contacts.directory.addContact' }),
- ).not.toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'contacts.directory.addExternal' }),
- ).toBeInTheDocument()
- expect(screen.getByText('Leslie Alexander')).toBeInTheDocument()
- })
-
- it('normalizes a stale Platform URL to All before querying when the capability is disabled', async () => {
- const scenario = {
- ...createContactsMockScenario(ContactsMockScenario.EeMixed),
- imCentrallyManaged: false,
- }
- const repository = createContactsMockRepository({ scenario })
- const listContacts = vi.spyOn(repository, 'listContacts')
- const { onUrlUpdate } = renderDirectory(
- scenario,
- '?contact_kind=platform&contact_pages=2',
- repository,
- )
-
- expect(await screen.findByText('Ralph Edwards')).toBeInTheDocument()
- expect(screen.getByRole('radio', { name: 'contacts.filter.all' })).toHaveAttribute(
- 'aria-checked',
- 'true',
- )
- expect(listContacts).toHaveBeenCalledWith(expect.objectContaining({ kind: 'all', page: 1 }))
- expect(listContacts.mock.calls.some(([query]) => query.kind === 'platform')).toBe(false)
- await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())
- expect(onUrlUpdate.mock.lastCall?.[0].queryString).not.toContain('contact_kind=platform')
- expect(onUrlUpdate.mock.lastCall?.[0].queryString).not.toContain('contact_pages=2')
- })
-
- it('keeps loaded contact photos visible while refreshed signatures load after a name change', async () => {
- const complete = vi
- .spyOn(HTMLImageElement.prototype, 'complete', 'get')
- .mockImplementation(function (this: HTMLImageElement) {
- return !this.src.includes('nonce=new')
- })
- const naturalWidth = vi
- .spyOn(HTMLImageElement.prototype, 'naturalWidth', 'get')
- .mockReturnValue(128)
- const alice = 'https://example.com/files/alice/file-preview'
- const bob = 'https://example.com/files/bob/file-preview'
-
- try {
- const { rerender } = render(
- <>
- <ContactAvatar name="Alice" avatar={`${alice}?nonce=old`} />
- <ContactAvatar name="Bob" avatar={`${bob}?nonce=old`} />
- </>,
- )
- const alicePhoto = await screen.findByRole('img', { name: 'Alice' })
- const bobPhoto = await screen.findByRole('img', { name: 'Bob' })
-
- rerender(
- <>
- <ContactAvatar name="Alice renamed" avatar={`${alice}?nonce=new`} />
- <ContactAvatar name="Bob" avatar={`${bob}?nonce=new`} />
- </>,
- )
-
- expect(alicePhoto).toBeVisible()
- expect(bobPhoto).toBeVisible()
- expect(screen.queryByText('A')).not.toBeInTheDocument()
- expect(screen.queryByText('B')).not.toBeInTheDocument()
- fireEvent.load(alicePhoto)
- fireEvent.load(bobPhoto)
- expect(await screen.findByRole('img', { name: 'Alice renamed' })).toHaveAttribute(
- 'src',
- `${alice}?nonce=new`,
- )
- expect(screen.getByRole('img', { name: 'Bob' })).toHaveAttribute('src', `${bob}?nonce=new`)
- } finally {
- complete.mockRestore()
- naturalWidth.mockRestore()
- }
- })
-
- it('keeps contact initials hidden while loading without changing shared avatar fallback behavior', async () => {
- const complete = vi.spyOn(HTMLImageElement.prototype, 'complete', 'get').mockReturnValue(false)
- const OriginalImage = window.Image
- const images: HTMLImageElement[] = []
- window.Image = class extends OriginalImage {
- constructor() {
- super()
- Object.defineProperties(this, {
- complete: { value: false },
- src: { value: '', writable: true },
- })
- images.push(this)
- }
- }
-
- try {
- const { rerender } = render(
- <>
- <ContactAvatar name="Alice" avatar="https://example.com/contact-avatar.png" />
- <Avatar>
- <AvatarImage src={'https://example.com/shared-avatar.png'} alt={'Shared'} />
- <AvatarFallback>{'Shared'?.[0]?.toLocaleUpperCase()}</AvatarFallback>
- </Avatar>
- </>,
- )
- await waitFor(() => expect(images).toHaveLength(1))
- expect(screen.queryByText('A')).not.toBeInTheDocument()
- expect(screen.getByText('S')).toBeInTheDocument()
-
- fireEvent.error(screen.getByAltText('Alice'))
- expect(await screen.findByText('A')).toBeInTheDocument()
-
- rerender(<ContactAvatar name="Alice" avatar="https://example.com/new-avatar.png" />)
- expect(screen.queryByText('A')).not.toBeInTheDocument()
- fireEvent.load(screen.getByAltText('Alice'))
- const loadedPhoto = await screen.findByRole('img', { name: 'Alice' })
-
- rerender(<ContactAvatar name="Alice" avatar="https://example.com/replaced-avatar.png" />)
- expect(loadedPhoto).not.toBeInTheDocument()
- expect(screen.getByAltText('Alice')).toHaveAttribute(
- 'src',
- 'https://example.com/replaced-avatar.png',
- )
- expect(screen.queryByText('A')).not.toBeInTheDocument()
-
- rerender(<ContactAvatar name="Alice" avatar={null} />)
- expect(screen.getByText('A')).toBeInTheDocument()
- expect(screen.queryByRole('img')).not.toBeInTheDocument()
- } finally {
- window.Image = OriginalImage
- complete.mockRestore()
- }
- })
-
- it('renders API timestamps expressed in Unix seconds', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const firstContact = scenario.contacts[0]!
- firstContact.created_at = Math.floor(Date.now() / 1000) - 5 * 60 * 60
-
- renderDirectory(scenario)
-
- expect(await screen.findByText('5 hours ago')).toBeInTheDocument()
- })
-
- it('renders all three contact types and restores details from the loaded list', async () => {
- renderDirectory(
- createContactsMockScenario(ContactsMockScenario.EeMixed),
- '?contact_id=contact-platform',
- )
-
- expect(await screen.findByText('Ralph Edwards')).toBeInTheDocument()
- expect(screen.getAllByText('Leslie Alexander')).toHaveLength(2)
- expect(screen.getByText('Courtney Henry')).toBeInTheDocument()
- const details = await findLoadedDetails('Leslie Alexander')
- expect(details).toHaveTextContent('contacts.type.platform')
- expect(details).not.toHaveTextContent('org-user-platform')
- expect(details).not.toHaveTextContent('contacts.imPlatform.title')
- })
-
- it('renders common list fields and the contact type without type-specific identities', async () => {
- const workspaceView = renderDirectory(
- createContactsMockScenario(ContactsMockScenario.EeMixed),
- '?contact_id=contact-owner',
- )
- let details = await findLoadedDetails('[email protected]')
- expect(details).toHaveTextContent('[email protected]')
- expect(details).toHaveTextContent('contacts.type.workspace')
- expect(details).toHaveTextContent('Slack')
- expect(within(details).queryByRole('button', { name: /edit|remove/i })).not.toBeInTheDocument()
- workspaceView.unmount()
-
- renderDirectory(
- createContactsMockScenario(ContactsMockScenario.EeMixed),
- '?contact_id=contact-external',
- )
- details = await findLoadedDetails('[email protected]')
- expect(details).toHaveTextContent('[email protected]')
- expect(details).toHaveTextContent('contacts.type.external')
- expect(details).not.toHaveTextContent('contacts.details.emailOnly')
- })
-
- it('edits an External contact from the details action menu', async () => {
- const user = userEvent.setup()
- renderDirectory(
- createContactsMockScenario(ContactsMockScenario.EeMixed),
- '?contact_id=contact-external',
- )
- const details = await findLoadedDetails('Courtney Henry')
-
- await user.click(within(details).getByRole('button', { name: 'contacts.details.more' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.details.edit' }))
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.editTitle' })
- const name = within(dialog).getByRole('textbox', { name: 'contacts.external.name' })
- expect(name).toHaveValue('Courtney Henry')
- await user.clear(name)
- await user.type(name, 'Courtney Cooper')
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.save' }))
-
- await waitFor(() =>
- expect(
- screen.queryByRole('dialog', { name: 'contacts.external.editTitle' }),
- ).not.toBeInTheDocument(),
- )
- expect(await screen.findAllByText('Courtney Cooper')).toHaveLength(2)
- })
-
- it.each(['details menu', 'selection toolbar'])(
- 'requires confirmation and preserves contacts when canceling removal from the %s',
- async (entry) => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const removeContacts = vi.spyOn(repository, 'removeContacts')
- const user = userEvent.setup()
- renderDirectory(scenario, '', repository)
- await screen.findByText('Courtney Henry')
- const openConfirmation = async () => {
- if (entry === 'selection toolbar') {
- await user.click(
- screen.getByRole('button', { name: 'contacts.directory.removeSelected' }),
- )
- } else {
- const details = await findLoadedDetails('Courtney Henry')
- await user.click(within(details).getByRole('button', { name: 'contacts.details.more' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.details.remove' }))
+beforeEach(() => {
+ contacts = structuredClone([alice, bob])
+ api.list
+ .mockReset()
+ .mockImplementation(
+ async ({
+ query,
+ }: { query?: { group?: string; keyword?: string; page?: number; limit?: number } } = {}) => {
+ const data = contacts.filter(
+ (contact) =>
+ (!query?.group || contact.type === query.group) &&
+ (!query?.keyword || `${contact.name} ${contact.email}`.includes(query.keyword)),
+ )
+ const limit = query?.limit ?? 20
+ const page = query?.page ?? 1
+ return {
+ data: data.slice((page - 1) * limit, page * limit),
+ limit,
+ page,
+ total: data.length,
}
- }
- if (entry === 'selection toolbar')
- await user.click(screen.getByRole('checkbox', { name: /Courtney Henry/ }))
- else await user.click(screen.getByRole('button', { name: /Courtney Henry/ }))
-
- await openConfirmation()
- expect(await screen.findByRole('alertdialog')).toHaveTextContent(
- 'contacts.directory.removalDescription',
- )
- expect(removeContacts).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
-
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(removeContacts).not.toHaveBeenCalled()
- expect(screen.getAllByText('Courtney Henry').length).toBeGreaterThan(0)
- if (entry === 'selection toolbar')
- expect(screen.getByRole('checkbox', { name: /Courtney Henry/ })).toBeChecked()
- await openConfirmation()
- await confirmContactRemoval(user)
-
- await waitFor(() => expect(screen.queryByText('Courtney Henry')).not.toBeInTheDocument())
- expect(removeContacts).toHaveBeenCalledExactlyOnceWith({ contactIds: ['contact-external'] })
- },
- )
-
- it('keeps the confirmation open for retry after a thrown removal failure', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const remove = repository.removeContacts.bind(repository)
- const removeContacts = vi
- .spyOn(repository, 'removeContacts')
- .mockRejectedValueOnce(new Error('offline'))
- .mockImplementation(remove)
- const user = userEvent.setup()
- renderDirectory(scenario, '', repository)
- await screen.findByText('Courtney Henry')
- await user.click(screen.getByRole('checkbox', { name: /Courtney Henry/ }))
- await user.click(screen.getByRole('button', { name: 'contacts.directory.removeSelected' }))
- await confirmContactRemoval(user)
-
- const dialog = screen.getByRole('alertdialog')
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.directory.removalFailed',
- )
- expect(screen.getAllByText('Courtney Henry').length).toBeGreaterThan(0)
- await user.click(
- within(dialog).getByRole('button', { name: 'contacts.directory.removeSelected' }),
- )
-
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(screen.queryByText('Courtney Henry')).not.toBeInTheDocument()
- expect(removeContacts).toHaveBeenCalledTimes(2)
- })
-
- it('prevents duplicate removal and dismissal while the confirmation is submitting', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const remove = repository.removeContacts.bind(repository)
- let release = () => {}
- const pending = new Promise<void>((resolve) => {
- release = resolve
- })
- const removeContacts = vi
- .spyOn(repository, 'removeContacts')
- .mockImplementation(async (command) => {
- await pending
- return remove(command)
- })
- const user = userEvent.setup()
- renderDirectory(scenario, '', repository)
- await screen.findByText('Courtney Henry')
- await user.click(screen.getByRole('checkbox', { name: /Courtney Henry/ }))
- await user.click(screen.getByRole('button', { name: 'contacts.directory.removeSelected' }))
- const dialog = await screen.findByRole('alertdialog')
- const confirm = within(dialog).getByRole('button', {
- name: 'contacts.directory.removeSelected',
- })
- await user.click(confirm)
-
- expect(confirm).toHaveAttribute('aria-disabled', 'true')
- expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
- await user.click(confirm)
- await user.keyboard('{Escape}')
- expect(screen.getByRole('alertdialog')).toBeInTheDocument()
- expect(removeContacts).toHaveBeenCalledTimes(1)
- await act(async () => release())
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(screen.queryByText('Courtney Henry')).not.toBeInTheDocument()
- })
-
- it('removes a non-workspace contact from the details action menu', async () => {
- const user = userEvent.setup()
- renderDirectory(
- createContactsMockScenario(ContactsMockScenario.EeMixed),
- '?contact_id=contact-external',
- )
- const details = await findLoadedDetails('Courtney Henry')
-
- await user.click(within(details).getByRole('button', { name: 'contacts.details.more' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.details.remove' }))
- await confirmContactRemoval(user)
-
- await waitFor(() => expect(screen.queryByText('Courtney Henry')).not.toBeInTheDocument())
- expect(
- screen.queryByRole('complementary', { name: 'contacts.details.title' }),
- ).not.toBeInTheDocument()
- })
-
- it('preserves list context and restores row focus after closing details', async () => {
- const user = userEvent.setup()
- renderDirectory(
- createContactsMockScenario(ContactsMockScenario.CeMixed),
- '?contact_kind=external&contact_search=Courtney',
- )
- const search = screen.getByRole('searchbox', { name: 'contacts.directory.search' })
- const row = await screen.findByRole('button', { name: /Courtney Henry/ })
- await user.click(row)
- const details = await screen.findByRole('complementary', { name: 'contacts.details.title' })
- await user.click(within(details).getByRole('button', { name: 'contacts.action.close' }))
-
- await waitFor(() => expect(row).toHaveFocus())
- expect(search).toHaveValue('Courtney')
- expect(screen.getByRole('radio', { name: 'contacts.filter.external' })).toHaveAttribute(
- 'aria-checked',
- 'true',
- )
- })
-
- it('does not resend an ID removed from details in the next batch removal', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const removeContacts = vi.spyOn(repository, 'removeContacts')
- const user = userEvent.setup()
- renderDirectory(scenario, '', repository)
- await screen.findByText('Courtney Henry')
-
- await user.click(screen.getByRole('checkbox', { name: /Courtney Henry/ }))
- await user.click(screen.getByRole('button', { name: /Courtney Henry/ }))
- const details = await findLoadedDetails('Courtney Henry')
- await user.click(within(details).getByRole('button', { name: 'contacts.details.more' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.details.remove' }))
- await confirmContactRemoval(user)
- await waitFor(() => expect(screen.queryByText('Courtney Henry')).not.toBeInTheDocument())
- await user.click(screen.getByRole('checkbox', { name: /Leslie Alexander/ }))
- await user.click(screen.getByRole('button', { name: 'contacts.directory.removeSelected' }))
- await confirmContactRemoval(user)
-
- await waitFor(() => expect(removeContacts).toHaveBeenCalledTimes(2))
- expect(removeContacts).toHaveBeenNthCalledWith(1, { contactIds: ['contact-external'] })
- expect(removeContacts).toHaveBeenNthCalledWith(2, { contactIds: ['contact-platform'] })
- })
-
- it('shows not-found details for a deleted contact while retaining the directory', async () => {
- renderDirectory(
- createContactsMockScenario(ContactsMockScenario.EeMixed),
- '?contact_id=contact-missing',
- )
- expect(await screen.findByText('Ralph Edwards')).toBeInTheDocument()
- expect(await screen.findByText('contacts.details.notFound')).toBeInTheDocument()
- expect(screen.getByText('Courtney Henry')).toBeInTheDocument()
- })
-
- it('loads a URL-selected contact independently of filtered rows and shows its loading state', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- let finishDetails: ((contact: ContactView | null) => void) | undefined
- const getContact = vi.spyOn(repository, 'getContact').mockImplementation(
- () =>
- new Promise((resolve) => {
- finishDetails = resolve
- }),
- )
- const platform = scenario.contacts.find((contact) => contact.id === 'contact-platform')!
- renderDirectory(
- scenario,
- '?contact_id=contact-platform&contact_kind=external&contact_search=Courtney',
- repository,
- )
-
- await waitFor(() => expect(getContact).toHaveBeenCalledWith('contact-platform'))
- expect(await screen.findByText('Courtney Henry')).toBeInTheDocument()
- expect(screen.getByText('contacts.details.loading')).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /Leslie Alexander/ })).not.toBeInTheDocument()
-
- await act(async () => finishDetails?.(platform))
-
- const details = await findLoadedDetails('Leslie Alexander')
- expect(within(details).getByText('Leslie Alexander')).toBeInTheDocument()
- expect(screen.getByRole('searchbox', { name: 'contacts.directory.search' })).toHaveValue(
- 'Courtney',
- )
- expect(screen.getByRole('radio', { name: 'contacts.filter.external' })).toHaveAttribute(
- 'aria-checked',
- 'true',
- )
- })
-
- it('retries unavailable contact details without replacing the error with stale list data', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const repository = createContactsMockRepository({ scenario })
- const platform = scenario.contacts.find((contact) => contact.id === 'contact-platform')!
- const getContact = vi
- .spyOn(repository, 'getContact')
- .mockRejectedValueOnce(new Error('Details unavailable'))
- .mockResolvedValueOnce(platform)
- const user = userEvent.setup()
- renderDirectory(scenario, '?contact_id=contact-platform&contact_kind=external', repository)
-
- expect(await screen.findByText('contacts.details.error')).toBeInTheDocument()
- expect(screen.getByText('Courtney Henry')).toBeInTheDocument()
- expect(screen.queryByText('contacts.details.notFound')).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.action.retry' }))
-
- expect(await screen.findByText('Leslie Alexander')).toBeInTheDocument()
- expect(getContact).toHaveBeenCalledTimes(2)
- })
-
- it('filters the directory and exposes a recoverable no-result state', async () => {
- const user = userEvent.setup()
- const { onUrlUpdate } = renderDirectory(
- createContactsMockScenario(ContactsMockScenario.CeMixed),
- )
- await screen.findByText('Ralph Edwards')
-
- await user.click(screen.getByRole('radio', { name: 'contacts.filter.external' }))
- await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())
- await waitFor(() => expect(screen.queryByText('Ralph Edwards')).not.toBeInTheDocument())
- expect(screen.getByText('Courtney Henry')).toBeInTheDocument()
-
- await user.type(screen.getByRole('searchbox', { name: 'contacts.directory.search' }), 'missing')
- expect(await screen.findByText('contacts.directory.noResultsTitle')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.action.clearFilters' }))
- expect(await screen.findByText('Ralph Edwards')).toBeInTheDocument()
- })
-
- it('validates, classifies conflicts, and creates an External contact without a request', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.CeMixed))
- await screen.findByText('Ralph Edwards')
-
- await user.click(screen.getByRole('button', { name: 'contacts.directory.addExternal' }))
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.title' })
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.name' }),
- 'Duplicate',
- )
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.email' }),
- )
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.external.result.duplicate_external_contact',
- )
-
- await user.clear(within(dialog).getByRole('textbox', { name: 'contacts.external.name' }))
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.name' }),
- 'New Partner',
- )
- await user.clear(within(dialog).getByRole('textbox', { name: 'contacts.external.email' }))
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.email' }),
+ },
)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
+ api.details
+ .mockReset()
+ .mockImplementation(async ({ params }: { params: { contact_id: string } }) => ({
+ contact: contacts.find((contact) => contact.id === params.contact_id)!,
+ im_binding_details: [],
+ }))
+ api.remove
+ .mockReset()
+ .mockImplementation(async ({ body }: { body: { contact_ids: string[] } }) => {
+ contacts = contacts.filter((contact) => !body.contact_ids.includes(contact.id))
+ return { removed_contact_ids: body.contact_ids }
+ })
+ api.channels.mockReset().mockResolvedValue({ channels: [] })
+ api.identities.mockReset().mockResolvedValue({ data: [], total: 0, limit: 20, page: 1 })
+})
- await waitFor(() =>
- expect(
- screen.queryByRole('dialog', { name: 'contacts.external.title' }),
- ).not.toBeInTheDocument(),
- )
- expect(await screen.findByRole('button', { name: /New Partner/ })).toBeInTheDocument()
- })
+it('names the table, exposes contact emails and channel names, and omits a nested main', async () => {
+ contacts[0] = {
+ ...alice,
+ im_bindings: [{ id: 'binding-1', provider: 'slack', scope: 'workspace' }],
+ }
+ setup()
+ const table = await screen.findByRole('table', { name: 'contacts.directory.title' })
+ expect(screen.queryByRole('main')).not.toBeInTheDocument()
+ expect(within(table).getByRole('button', { name: /Alice [email protected]/ })).toBeInTheDocument()
+ expect(within(table).getByRole('img', { name: 'Slack' })).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: /learnMore/ })).not.toBeInTheDocument()
+})
- it('associates External contact validation and restores focus after cancel', async () => {
+it.each([false, true])(
+ 'moves focus into details and returns to the row when centralized=%s',
+ async (centrallyManaged) => {
const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.CeMixed))
- await screen.findByText('Ralph Edwards')
- const trigger = screen.getByRole('button', { name: 'contacts.directory.addExternal' })
+ setup({ ...managerContext, imCentrallyManaged: centrallyManaged })
+ const trigger = await screen.findByRole('button', { name: /Alice [email protected]/ })
await user.click(trigger)
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.title' })
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
- expect(
- await within(dialog).findByText('contacts.external.validation.name_required'),
- ).toBeInTheDocument()
-
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.name' }),
- 'Partner',
- )
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.email' }),
- 'invalid',
- )
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
- expect(
- await within(dialog).findByText('contacts.external.validation.email_invalid'),
- ).toBeInTheDocument()
-
- await user.click(within(dialog).getByRole('button', { name: 'contacts.action.cancel' }))
+ const heading = await screen.findByRole('heading', { name: 'Alice' })
+ await waitFor(() => expect(heading).toHaveFocus())
+ expect(trigger).toHaveAttribute('aria-expanded', 'true')
+ const panel = screen.getByRole('region', { name: 'Alice' })
+ await user.click(within(panel).getByRole('button', { name: 'contacts.action.close' }))
await waitFor(() => expect(trigger).toHaveFocus())
- })
-
- it('preserves the External contact draft after a recoverable mock failure', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.ExternalFailure))
- await screen.findByText('Ralph Edwards')
- await user.click(screen.getByRole('button', { name: 'contacts.directory.addContact' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.directory.addExternal' }))
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.title' })
- const name = within(dialog).getByRole('textbox', { name: 'contacts.external.name' })
- const email = within(dialog).getByRole('textbox', { name: 'contacts.external.email' })
- await user.type(name, 'Recoverable Partner')
- await user.type(email, '[email protected]')
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.external.result.failed',
- )
- expect(name).toHaveValue('Recoverable Partner')
- expect(email).toHaveValue('[email protected]')
- })
-
- it('adds multiple available Platform contacts while excluding existing contacts', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.EeMixed))
- await screen.findByText('Ralph Edwards')
-
- await user.click(screen.getByRole('button', { name: 'contacts.directory.addContact' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.directory.addFromPlatform' }))
- const dialog = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- expect(within(dialog).queryByText('[email protected]')).not.toBeInTheDocument()
- await user.click(within(dialog).getByRole('checkbox', { name: /Ada Lovelace/ }))
- await user.click(within(dialog).getByRole('checkbox', { name: /Grace Hopper/ }))
- await user.click(within(dialog).getByRole('button', { name: 'contacts.platformPicker.add' }))
-
- expect(await screen.findByText('Ada Lovelace')).toBeInTheDocument()
- expect(screen.getByText('Grace Hopper')).toBeInTheDocument()
- })
-
- it('keeps Platform contact selection after a recoverable add failure', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.AddPlatformFailure))
- await screen.findByText('Ralph Edwards')
- await user.click(screen.getByRole('button', { name: 'contacts.directory.addContact' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.directory.addFromPlatform' }))
- const dialog = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- const option = await within(dialog).findByRole('checkbox', { name: /Ada Lovelace/ })
- await user.click(option)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.platformPicker.add' }))
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.platformPicker.addFailed',
- )
- expect(option).toBeChecked()
- expect(screen.getAllByText('Ada Lovelace')).toHaveLength(1)
- })
-
- it('shows a retryable available Platform contact query failure', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.PlatformContactsFailure))
- await screen.findByText('Ralph Edwards')
- await user.click(screen.getByRole('button', { name: 'contacts.directory.addContact' }))
- await user.click(screen.getByRole('menuitem', { name: 'contacts.directory.addFromPlatform' }))
- const dialog = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.platformPicker.error',
- )
- expect(
- within(dialog).getByRole('button', { name: 'contacts.action.retry' }),
- ).toBeInTheDocument()
- })
-
- it('disables workspace selection and removes only selected Platform and External contacts', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.EeMixed))
- await screen.findByText('Ralph Edwards')
-
- const workspace = screen.getByRole('checkbox', { name: /Ralph Edwards/ })
- const platform = screen.getByRole('checkbox', { name: /Leslie Alexander/ })
- const external = screen.getByRole('checkbox', { name: /Courtney Henry/ })
- expect(workspace).toHaveAttribute('aria-disabled', 'true')
- expect(platform).not.toHaveAttribute('aria-disabled', 'true')
- expect(external).not.toHaveAttribute('aria-disabled', 'true')
-
- await user.click(screen.getByRole('checkbox', { name: 'contacts.directory.selectAll' }))
- expect(workspace).not.toBeChecked()
- expect(platform).toBeChecked()
- expect(external).toBeChecked()
- expect(screen.getByText('contacts.directory.selected')).toBeInTheDocument()
- expect(screen.getByText('2')).toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'contacts.directory.removeSelected' }))
- await confirmContactRemoval(user)
- await waitFor(() => expect(screen.queryByText('Leslie Alexander')).not.toBeInTheDocument())
- expect(screen.queryByText('Courtney Henry')).not.toBeInTheDocument()
- expect(screen.getByText('Ralph Edwards')).toBeInTheDocument()
- })
-
- it('keeps selected contacts after a recoverable removal failure', async () => {
- const user = userEvent.setup()
- renderDirectory(createContactsMockScenario(ContactsMockScenario.ContactRemovalFailure))
- await screen.findByText('Courtney Henry')
-
- const external = screen.getByRole('checkbox', { name: /Courtney Henry/ })
- await user.click(external)
- await user.click(screen.getByRole('button', { name: 'contacts.directory.removeSelected' }))
- await confirmContactRemoval(user)
-
- expect(await screen.findByRole('alert')).toHaveTextContent('contacts.directory.removalFailed')
- expect(external).toBeChecked()
- expect(screen.getByText('Courtney Henry')).toBeInTheDocument()
- })
-
- it('does not render contact data without view permission', () => {
- renderDirectory(createContactsMockScenario(ContactsMockScenario.NoAccess))
-
- expect(screen.getByText('contacts.directory.noAccessTitle')).toBeInTheDocument()
- expect(screen.queryByText('Ralph Edwards')).not.toBeInTheDocument()
- })
-
- it('distinguishes an empty directory, a read-only role, and an initial failure', async () => {
- const { unmount } = renderDirectory(createContactsMockScenario(ContactsMockScenario.Empty))
- expect(await screen.findByText('contacts.directory.externalEmptyTitle')).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'contacts.directory.addExternal' }),
- ).toBeInTheDocument()
- unmount()
-
- const readOnly = renderDirectory(createContactsMockScenario(ContactsMockScenario.ReadOnly))
- expect(await screen.findByText('Ralph Edwards')).toBeInTheDocument()
- expect(screen.getByText('contacts.directory.viewOnly')).toBeInTheDocument()
- expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'contacts.directory.addContact' }),
- ).not.toBeInTheDocument()
- readOnly.unmount()
-
- renderDirectory(createContactsMockScenario(ContactsMockScenario.DirectoryFailure))
- expect(await screen.findByText('contacts.directory.errorTitle')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'contacts.action.retry' })).toBeInTheDocument()
- })
-
- describe('automatic pagination', () => {
- let intersect: () => void
-
- beforeEach(() => {
- const observers = new Set<MockIntersectionObserver>()
- class MockIntersectionObserver implements IntersectionObserver {
- readonly root: Element | Document | null = null
- readonly rootMargin = '0px'
- readonly scrollMargin = '0px'
- readonly thresholds = [0]
- private readonly targets = new Set<Element>()
- private readonly callback: IntersectionObserverCallback
-
- constructor(callback: IntersectionObserverCallback) {
- this.callback = callback
- observers.add(this)
- }
-
- observe(target: Element) {
- this.targets.add(target)
- }
-
- unobserve(target: Element) {
- this.targets.delete(target)
- }
-
- disconnect() {
- this.targets.clear()
- }
-
- takeRecords(): IntersectionObserverEntry[] {
- return []
- }
-
- intersect() {
- const entries = [...this.targets].map((target) => ({
- boundingClientRect: target.getBoundingClientRect(),
- intersectionRatio: 1,
- intersectionRect: target.getBoundingClientRect(),
- isIntersecting: true,
- rootBounds: null,
- target,
- time: 0,
- }))
- if (entries.length) this.callback(entries, this)
- }
- }
- vi.stubGlobal('IntersectionObserver', MockIntersectionObserver)
- intersect = () => act(() => observers.forEach((observer) => observer.intersect()))
- })
-
- afterEach(() => vi.unstubAllGlobals())
-
- it('loads subsequent contacts automatically, stops at the end, and restores loaded pages from the URL', async () => {
- const scenario = createContactsMockScenario(ContactsMockScenario.Paginated)
- const repository = createContactsMockRepository({ scenario })
- const listContacts = vi.spyOn(repository, 'listContacts')
- const listPages = () =>
- listContacts.mock.calls.filter(([query]) => query.limit === 20).map(([query]) => query.page)
- const { onUrlUpdate, unmount } = renderDirectory(scenario, '', repository)
- expect(await screen.findByText('Partner 17')).toBeInTheDocument()
- expect(screen.queryByText('Partner 18')).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'contacts.action.loadMore' }),
- ).not.toBeInTheDocument()
-
- intersect()
-
- expect(await screen.findByText('Partner 20')).toBeInTheDocument()
- expect(screen.getAllByRole('row')).toHaveLength(scenario.contacts.length + 1)
- for (const contact of scenario.contacts)
- expect(screen.getAllByText(contact.name)).toHaveLength(1)
- expect(listPages()).toEqual([1, 2])
- await waitFor(() => {
- expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('contact_pages')).toBe('2')
- })
- intersect()
- expect(listPages()).toEqual([1, 2])
-
- unmount()
- listContacts.mockClear()
- renderDirectory(scenario, '?contact_pages=2', repository)
- expect(await screen.findByText('Partner 20')).toBeInTheDocument()
- expect(screen.getAllByRole('row')).toHaveLength(scenario.contacts.length + 1)
- expect(listPages()).toEqual([1, 2])
- })
-
- it('keeps loaded rows after an automatic page failure and waits for an explicit retry', async () => {
- const user = userEvent.setup()
- const scenario = createContactsMockScenario(ContactsMockScenario.Paginated)
- const repository = createContactsMockRepository({ scenario })
- const list = repository.listContacts
- let failNextPage = true
- const listContacts = vi.spyOn(repository, 'listContacts').mockImplementation((query) => {
- if (query.page === 2 && failNextPage) {
- failNextPage = false
- return Promise.reject(new Error('contacts_next_page_failed'))
- }
- return list(query)
- })
- const nextPageCalls = () => listContacts.mock.calls.filter(([query]) => query.page === 2)
- renderDirectory(scenario, '', repository)
- expect(await screen.findByText('Ralph Edwards')).toBeInTheDocument()
-
- intersect()
-
- expect(await screen.findByRole('alert')).toHaveTextContent('contacts.directory.pageError')
- expect(screen.getByText('Ralph Edwards')).toBeInTheDocument()
- expect(screen.queryByText('Partner 18')).not.toBeInTheDocument()
- intersect()
- expect(nextPageCalls()).toHaveLength(1)
-
- await user.click(screen.getByRole('button', { name: 'contacts.action.retry' }))
-
- expect(await screen.findByText('Partner 20')).toBeInTheDocument()
- expect(screen.queryByRole('alert')).not.toBeInTheDocument()
- expect(screen.getAllByRole('row')).toHaveLength(scenario.contacts.length + 1)
- expect(nextPageCalls()).toHaveLength(2)
- })
- })
+ if (centrallyManaged) expect(api.channels).not.toHaveBeenCalled()
+ },
+)
+
+it('returns focus to search when closing a deep-linked contact without an opening row', async () => {
+ const user = userEvent.setup()
+ setup(managerContext, `?contact_id=${alice.id}`)
+ const panel = await screen.findByRole('region', { name: 'Alice' })
+ await user.click(within(panel).getByRole('button', { name: 'contacts.action.close' }))
+ await waitFor(() =>
+ expect(screen.getByRole('searchbox', { name: 'contacts.directory.search' })).toHaveFocus(),
+ )
})
-describe('Contact IM binding controls', () => {
- const identity: ContactIMIdentity = {
- id: 'identity-1',
- provider: 'feishu',
- provider_user_id: 'feishu-user-1',
- display_name: 'Synced Member',
- email: '[email protected]',
- binding_status: 'unbound',
- }
-
- function setup(scope?: 'organization' | 'workspace', centrallyManaged = true) {
- const scenario = {
- ...createContactsMockScenario(ContactsMockScenario.CeMixed),
- imCentrallyManaged: centrallyManaged,
- }
- let contact: ContactView = {
- ...scenario.contacts.find((item) => item.type === 'workspace')!,
- im_bindings: scope ? [{ id: 'binding-1', provider: 'feishu', scope }] : [],
- }
- const listIMChannels = vi.fn(async (): Promise<ContactIMChannel[]> => [
- { id: 'channel-feishu', provider: 'feishu' },
- ])
- const repository: ContactsManagementRepository = {
- ...createContactsMockRepository({ scenario }),
- supportsIMBindings: true,
- getContact: vi.fn(async () => contact),
- listIMChannels,
- listIMIdentities: vi.fn(async ({ page, limit }) => ({
- data: [identity],
- page,
- limit,
- total: 1,
- has_more: false,
- })),
- setIMBinding: vi.fn(async ({ override }) => {
- contact = {
- ...contact,
- im_bindings: [
- { id: 'binding-1', provider: 'feishu', scope: override ? 'workspace' : 'organization' },
- ],
- }
- return contact
- }),
- removeIMBinding: vi.fn(async () => {
- contact = {
- ...contact,
- im_bindings: [{ id: 'organization-binding', provider: 'feishu', scope: 'organization' }],
- }
- }),
- unbindIMBinding: vi.fn(async () => {
- contact = { ...contact, im_bindings: [], im_binding_details: [] }
- }),
- }
- return { scenario, repository, contact, listIMChannels }
- }
-
- async function openEditor(
- user: ReturnType<typeof userEvent.setup>,
- contact: ContactView,
- provider = 'Feishu',
- ) {
- const details = await findLoadedDetails(contact.name)
- await user.click(
- await within(details).findByRole('button', {
- name: contact.im_bindings.length
- ? new RegExp(`^contacts\\.imBinding\\.changeTitle.*${provider}`)
- : 'contacts.imBinding.bind',
- }),
- )
- return screen.findByRole('dialog', { name: /^contacts\.imBinding\.changeTitle/ })
- }
-
- async function chooseIdentity(
- user: ReturnType<typeof userEvent.setup>,
- dialog: HTMLElement,
- name = 'Synced Member',
- ) {
- await user.click(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.workspaceMode' }),
- )
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- await user.click(picker)
- await user.click(await screen.findByRole('option', { name: new RegExp(name) }))
- await waitFor(() => expect(picker).toHaveAttribute('aria-expanded', 'false'))
- return picker
- }
-
- function renderBindingPanel(
- { scenario, repository, contact }: ReturnType<typeof setup>,
- centrallyManaged: boolean | undefined,
- ) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
- })
- const panel = (capability: boolean | undefined) => (
- <QueryClientProvider client={queryClient}>
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: capability,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }}
- repository={repository}
- >
- <ContactDetailsPanel
- contact={contact}
- onClose={vi.fn()}
- onEdit={vi.fn()}
- onRemove={vi.fn()}
- />
- </ContactsManagementProvider>
- </QueryClientProvider>
- )
- const result = render(panel(centrallyManaged))
- return {
- ...result,
- changeCapability: (next: boolean | undefined) => result.rerender(panel(next)),
- }
- }
-
- it('does not expose binding controls or request IM data before the management capability is known', async () => {
- const state = setup('organization')
- renderBindingPanel(state, undefined)
- const details = await findLoadedDetails(state.contact.name)
-
- expect(
- within(details).queryByRole('button', { name: 'contacts.imBinding.bind' }),
- ).not.toBeInTheDocument()
- expect(
- within(details).queryByRole('button', { name: /^contacts\.imBinding\.changeTitle/ }),
- ).not.toBeInTheDocument()
- expect(state.repository.listIMChannels).not.toHaveBeenCalled()
- expect(state.repository.listIMIdentities).not.toHaveBeenCalled()
- expect(state.repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('resets the open editor when management mode changes and hides it while the capability is unknown', async () => {
- const state = setup('organization')
- const user = userEvent.setup()
- const { changeCapability } = renderBindingPanel(state, true)
- let dialog = await openEditor(user, state.contact)
- await chooseIdentity(user, dialog)
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeEnabled()
-
- changeCapability(false)
- dialog = screen.getByRole('dialog', { name: /^contacts\.imBinding\.changeTitle/ })
- expect(within(dialog).queryAllByRole('radio')).toHaveLength(0)
- expect(
- within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' }),
- ).not.toHaveTextContent('Synced Member')
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- expect(state.repository.setIMBinding).not.toHaveBeenCalled()
-
- changeCapability(undefined)
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(state.repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('does not offer a binding action when no IM channel is configured', async () => {
- const { scenario, repository, contact, listIMChannels } = setup(undefined, false)
- listIMChannels.mockResolvedValue([])
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- await waitFor(() => expect(listIMChannels).toHaveBeenCalled())
-
- expect(within(details).queryByText('Feishu')).not.toBeInTheDocument()
- expect(
- within(details).queryByRole('button', { name: 'contacts.imBinding.bind' }),
- ).not.toBeInTheDocument()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it.each(['ce', 'saas', 'ee'] as const)(
- 'uses a direct identity picker and a normal binding when centrally managed IM bindings are disabled on %s',
- async (deployment) => {
- const { scenario, repository, contact } = setup(undefined, false)
- const user = userEvent.setup()
- renderDirectory({ ...scenario, deployment }, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- expect(within(dialog).queryAllByRole('radio')).toHaveLength(0)
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- await user.click(
- within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' }),
- )
- await user.click(await screen.findByRole('option', { name: /Synced Member/ }))
- await user.click(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- )
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(repository.setIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- identityId: identity.id,
- override: false,
- })
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- expect(
- within(await findLoadedDetails(contact.name)).queryByText('contacts.imBinding.customized'),
- ).not.toBeInTheDocument()
- },
+it('focuses a surviving row after a single removal and names only the removal target', async () => {
+ const user = userEvent.setup()
+ setup()
+ await user.click(await screen.findByRole('button', { name: /Alice [email protected]/ }))
+ await user.click(screen.getByRole('button', { name: 'contacts.details.more' }))
+ await user.click(await screen.findByRole('menuitem', { name: 'contacts.details.remove' }))
+ const dialog = await screen.findByRole('alertdialog')
+ expect(dialog).toHaveTextContent('contacts.directory.removalSingleTitle')
+ await user.click(
+ within(dialog).getByRole('button', { name: 'contacts.directory.removeSelected' }),
)
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(api.remove).toHaveBeenCalledWith({ body: { contact_ids: [alice.id] } })
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /Bob [email protected]/ })).toHaveFocus(),
+ )
+})
- it('preselects and edits the default binding directly when centrally managed IM bindings are disabled', async () => {
- const { scenario, repository, contact } = setup('organization', false)
- const boundIdentity = {
- id: 'identity-original',
- display_name: 'Original Member',
- email: '[email protected]',
- provider_user_id: 'feishu-original',
- }
- vi.mocked(repository.getContact).mockResolvedValue({
- ...contact,
- im_binding_details: [{ ...contact.im_bindings[0]!, identity: boundIdentity }],
- })
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- expect(picker).toHaveTextContent(boundIdentity.display_name)
- expect(within(dialog).queryAllByRole('radio')).toHaveLength(0)
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- await user.click(picker)
- await user.click(await screen.findByRole('option', { name: /Synced Member/ }))
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
-
- await waitFor(() =>
- expect(repository.setIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- identityId: identity.id,
- override: false,
- }),
- )
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- })
-
- it('exposes the identity name, email, and provider user ID in the picker and selected value', async () => {
- const { scenario, repository, contact } = setup(undefined, false)
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- expect(
- within(dialog).queryByRole('button', { name: 'contacts.imBinding.remove' }),
- ).not.toBeInTheDocument()
- await user.click(picker)
- const option = await screen.findByRole('option', { name: /Synced Member/ })
- expect(option).toHaveTextContent(identity.email!)
- expect(option).toHaveTextContent(identity.provider_user_id)
- await user.click(option)
-
- expect(picker).toHaveTextContent(identity.display_name!)
- expect(picker).toHaveTextContent(identity.email!)
- expect(picker).toHaveTextContent(identity.provider_user_id)
- })
-
- it('unbinds the contact default binding and refreshes contact details after a recoverable failure', async () => {
- const { scenario, repository, contact } = setup('organization', false)
- vi.mocked(repository.unbindIMBinding).mockRejectedValueOnce(
- new ContactIMRequestError('im_write_unavailable'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- const dialog = await openEditor(user, contact)
- const unbind = within(dialog).getByRole('button', { name: 'contacts.imBinding.remove' })
- await user.click(unbind)
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent('contacts.imBinding.failed')
- expect(within(details).queryByText('contacts.imBinding.notBound')).not.toBeInTheDocument()
- expect(repository.unbindIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- })
- await user.click(unbind)
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(await within(details).findByText('contacts.imBinding.notBound')).toBeInTheDocument()
- expect(repository.unbindIMBinding).toHaveBeenCalledTimes(2)
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('submits the contact ID without resetting a legacy override when the server rejects unbinding', async () => {
- const { scenario, repository, contact } = setup('workspace', false)
- vi.mocked(repository.unbindIMBinding).mockRejectedValue(
- new ContactIMRequestError('im_binding_not_found'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- const dialog = await openEditor(user, contact)
- const unbind = within(dialog).getByRole('button', { name: 'contacts.imBinding.remove' })
- await user.click(unbind)
-
- expect(repository.unbindIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- })
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.imBinding.notFound',
- )
- expect(unbind).toBeEnabled()
- expect(within(details).queryByText('contacts.imBinding.notBound')).not.toBeInTheDocument()
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('prevents duplicate unbinds, saves, and dismissal while deleting the binding', async () => {
- const { scenario, repository, contact } = setup('organization', false)
- let finishUnbind: (() => void) | undefined
- vi.mocked(repository.unbindIMBinding).mockImplementationOnce(
- () =>
- new Promise<void>((resolve) => {
- finishUnbind = resolve
- }),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const unbind = within(dialog).getByRole('button', { name: 'contacts.imBinding.remove' })
- await user.click(unbind)
- await user.click(unbind)
-
- expect(unbind).toHaveAttribute('aria-disabled', 'true')
- expect(within(dialog).getByRole('button', { name: 'contacts.action.cancel' })).toBeDisabled()
- expect(within(dialog).getByRole('button', { name: 'contacts.action.close' })).toBeDisabled()
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- await user.keyboard('{Escape}')
- expect(dialog).toBeInTheDocument()
- expect(repository.unbindIMBinding).toHaveBeenCalledOnce()
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
-
- await act(async () => finishUnbind?.())
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- })
-
- it('replaces a legacy workspace override with a normal binding and retries a failed override reset before closing', async () => {
- const { scenario, repository, contact } = setup('workspace', false)
- const binding = contact.im_bindings[0]!
- const identityDetails = {
- id: identity.id,
- display_name: identity.display_name ?? null,
- email: identity.email ?? null,
- provider_user_id: identity.provider_user_id,
- } satisfies GetContactResponse['im_binding_details'][number]['identity']
- const oldIdentity = {
- ...identityDetails,
- id: 'identity-old',
- display_name: 'Old Workspace Member',
- }
- let current: ContactView = {
- ...contact,
- im_binding_details: [{ ...binding, identity: oldIdentity }],
- }
- vi.mocked(repository.getContact).mockImplementation(async () => current)
- vi.mocked(repository.setIMBinding).mockImplementation(async () => current)
- vi.mocked(repository.removeIMBinding)
- .mockRejectedValueOnce(new ContactIMRequestError('im_write_unavailable'))
- .mockImplementationOnce(async () => {
- const defaultBinding = { ...binding, scope: 'organization' as const }
- current = {
- ...current,
- im_bindings: [defaultBinding],
- im_binding_details: [{ ...defaultBinding, identity: identityDetails }],
- }
- })
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- expect(picker).toHaveTextContent(oldIdentity.display_name)
- expect(within(dialog).queryAllByRole('radio')).toHaveLength(0)
- await user.click(picker)
- await user.click(await screen.findByRole('option', { name: /Synced Member/ }))
- const save = within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' })
- await user.click(save)
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent('contacts.imBinding.failed')
- expect(picker).toHaveTextContent(identity.display_name!)
- expect(repository.setIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- identityId: identity.id,
- override: false,
- })
- expect(repository.removeIMBinding).toHaveBeenCalledWith({ contactId: contact.id, binding })
- expect(vi.mocked(repository.setIMBinding).mock.invocationCallOrder[0]).toBeLessThan(
- vi.mocked(repository.removeIMBinding).mock.invocationCallOrder[0]!,
- )
- await user.click(save)
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- const details = await findLoadedDetails(contact.name)
- expect(await within(details).findByText(identity.display_name!)).toBeInTheDocument()
- expect(within(details).queryByText(oldIdentity.display_name)).not.toBeInTheDocument()
- expect(within(details).queryByText('contacts.imBinding.customized')).not.toBeInTheDocument()
- expect(repository.removeIMBinding).toHaveBeenCalledTimes(2)
- })
-
- it('does not reset a legacy workspace override when saving its replacement default binding fails', async () => {
- const { scenario, repository, contact } = setup('workspace', false)
- vi.mocked(repository.setIMBinding).mockRejectedValueOnce(
- new ContactIMRequestError('im_binding_conflict'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- await user.click(picker)
- await user.click(await screen.findByRole('option', { name: /Synced Member/ }))
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.imBinding.conflict',
- )
- expect(picker).toHaveTextContent(identity.display_name!)
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- })
-
- it('does not discover unbound channels through workspace management in centrally managed mode', async () => {
- const { scenario, repository, contact, listIMChannels } = setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- expect(listIMChannels).not.toHaveBeenCalled()
- expect(within(details).queryByText('Feishu')).not.toBeInTheDocument()
- expect(
- within(details).queryByRole('button', { name: 'contacts.imBinding.bind' }),
- ).not.toBeInTheDocument()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('keeps the organization binding unchanged until a custom identity is submitted', async () => {
- const { scenario, repository, contact } = setup('organization')
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- expect(
- within(dialog).queryByRole('button', { name: 'contacts.imBinding.remove' }),
- ).not.toBeInTheDocument()
- const organization = within(dialog).getByRole('radio', {
- name: 'contacts.imBinding.organizationMode',
- })
- const save = within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' })
- expect(organization).toBeChecked()
- expect(save).toBeDisabled()
- expect(
- within(dialog).queryByRole('combobox', { name: 'contacts.imBinding.contactLabel' }),
- ).not.toBeInTheDocument()
-
- await chooseIdentity(user, dialog)
- expect(save).toBeEnabled()
- await user.click(organization)
-
- expect(save).toBeDisabled()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- })
-
- it('displays and preselects workspace binding details outside the first search page without inventing an organization identity', async () => {
- const { scenario, repository, contact } = setup('workspace')
- const boundIdentity = {
- id: 'identity-outside-first-page',
- display_name: 'Bound Feishu Member',
- email: '[email protected]',
- provider_user_id: 'feishu-bound-user',
- }
- const bindingDetails: GetContactResponse['im_binding_details'] = [
- { ...contact.im_bindings[0]!, identity: boundIdentity },
- ]
- vi.mocked(repository.getContact).mockResolvedValue({
- ...contact,
- im_binding_details: bindingDetails,
- })
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- expect(await within(details).findByText(boundIdentity.display_name)).toBeInTheDocument()
-
- const dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- expect(picker).toHaveTextContent(boundIdentity.display_name)
- expect(picker).toHaveTextContent(boundIdentity.email)
- expect(
- within(dialog).getByText('contacts.imBinding.organizationUnavailable'),
- ).toBeInTheDocument()
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- await user.click(picker)
- expect(await screen.findByRole('option', { name: /Synced Member/ })).toHaveAttribute(
- 'aria-selected',
- 'false',
- )
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('shows the organization binding identity with an email fallback in its own organization row', async () => {
- const { scenario, repository, contact } = setup('organization')
- const boundIdentity = {
- id: 'identity-organization',
- display_name: null,
- email: '[email protected]',
- provider_user_id: 'feishu-organization-user',
- }
- const bindingDetails: GetContactResponse['im_binding_details'] = [
- { ...contact.im_bindings[0]!, identity: boundIdentity },
- ]
- vi.mocked(repository.getContact).mockResolvedValue({
- ...contact,
- im_binding_details: bindingDetails,
- })
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- expect(await within(details).findByText(boundIdentity.email)).toBeInTheDocument()
-
- const dialog = await openEditor(user, contact)
- expect(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
- ).toBeChecked()
- expect(within(dialog).getByText(boundIdentity.email)).toBeInTheDocument()
- expect(
- within(dialog).queryByText('contacts.imBinding.organizationUnavailable'),
- ).not.toBeInTheDocument()
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- })
-
- it('reopens the newly saved binding details without retaining the old or another provider identity', async () => {
- const { scenario, repository, contact } = setup('workspace')
- const otherBinding = {
- id: 'binding-slack',
- provider: 'slack' as const,
- scope: 'organization' as const,
- }
- const otherIdentity = {
- id: 'identity-slack',
- display_name: 'Slack Member',
- email: '[email protected]',
- provider_user_id: 'slack-user',
- }
- const bindingDetails: GetContactResponse['im_binding_details'] = [
- {
- ...contact.im_bindings[0]!,
- identity: {
- id: 'identity-old',
- display_name: 'Old Feishu Member',
- email: '[email protected]',
- provider_user_id: 'feishu-old',
- },
- },
- { ...otherBinding, identity: otherIdentity },
- ]
- let current = {
- ...contact,
- im_bindings: [...contact.im_bindings, otherBinding],
- im_binding_details: bindingDetails,
- }
- vi.mocked(repository.getContact).mockImplementation(async () => current)
- vi.mocked(repository.setIMBinding).mockImplementation(async ({ identityId }) => {
- current = {
- ...current,
- im_binding_details: [
- {
- ...contact.im_bindings[0]!,
- identity: {
- id: identityId,
- display_name: null,
- email: null,
- provider_user_id: identity.provider_user_id,
- },
- },
- { ...otherBinding, identity: otherIdentity },
- ],
- }
- return current
- })
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- let dialog = await openEditor(user, contact)
- await chooseIdentity(user, dialog)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(await within(details).findByText(identity.provider_user_id)).toBeInTheDocument()
- expect(within(details).queryByText('Old Feishu Member')).not.toBeInTheDocument()
- expect(within(details).getByText(otherIdentity.display_name)).toBeInTheDocument()
-
- dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- expect(picker).toHaveTextContent(identity.provider_user_id)
- expect(picker).not.toHaveTextContent('Old Feishu Member')
- expect(picker).not.toHaveTextContent(otherIdentity.display_name)
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- })
-
- it('shows unavailable identities as a recoverable error without allowing an empty save', async () => {
- const { scenario, repository, contact } = setup('organization')
- vi.mocked(repository.listIMIdentities).mockRejectedValue(
- new ContactIMRequestError('im_integration_not_configured'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- await user.click(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.workspaceMode' }),
- )
- await user.click(
- within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' }),
- )
-
- expect(await screen.findByRole('alert')).toHaveTextContent('contacts.imBinding.notConfigured')
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
-
- it('pages through identities, retains a conflicting selection, and updates details after a successful retry', async () => {
- const { scenario, repository, contact } = setup('organization')
- const second = {
- ...identity,
- id: 'identity-2',
- display_name: 'Second Member',
- provider_user_id: 'feishu-user-2',
- }
- vi.mocked(repository.listIMIdentities).mockImplementation(async ({ page, limit }) => ({
- data: [page === 1 ? identity : second],
- page,
- limit,
- total: 21,
- has_more: page === 1,
- }))
- vi.mocked(repository.setIMBinding).mockRejectedValueOnce(
- new ContactIMRequestError('im_binding_conflict'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- const dialog = await openEditor(user, contact)
- await user.click(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.workspaceMode' }),
- )
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- await user.click(picker)
- await user.type(
- await screen.findByRole('combobox', { name: /^contacts\.imBinding\.searchProvider/ }),
- 'Member',
- )
- await user.click(await screen.findByRole('button', { name: 'contacts.action.loadMore' }))
- await user.click(await screen.findByRole('option', { name: /Second Member/ }))
- await waitFor(() => expect(picker).toHaveAttribute('aria-expanded', 'false'))
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.imBinding.conflict',
- )
- expect(picker).toHaveTextContent('Second Member')
- expect(within(details).getByText('contacts.imBinding.identityUnavailable')).toBeInTheDocument()
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(await within(details).findByText('contacts.imBinding.customized')).toBeInTheDocument()
- expect(repository.setIMBinding).toHaveBeenLastCalledWith({
- contactId: contact.id,
- identityId: second.id,
- override: true,
- })
- expect(repository.listIMIdentities).toHaveBeenCalledWith({
- search: 'Member',
- page: 2,
- limit: 20,
- })
- })
-
- it('restores the organization binding only after saving and retains the mode after a recoverable failure', async () => {
- const { scenario, repository, contact } = setup('workspace')
- vi.mocked(repository.removeIMBinding).mockRejectedValueOnce(
- new ContactIMRequestError('im_write_unavailable'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
- let dialog = await openEditor(user, contact)
- const save = within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' })
- expect(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.workspaceMode' }),
- ).toBeChecked()
- expect(save).toBeDisabled()
- await user.click(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
- )
- expect(save).toBeEnabled()
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- await user.click(save)
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent('contacts.imBinding.failed')
- expect(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
- ).toBeChecked()
- expect(within(details).getByText('contacts.imBinding.customized')).toBeInTheDocument()
- await user.click(save)
-
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(repository.removeIMBinding).toHaveBeenLastCalledWith({
- contactId: contact.id,
- binding: contact.im_bindings[0],
- })
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- expect(
- within(await findLoadedDetails(contact.name)).queryByText('contacts.imBinding.customized'),
- ).not.toBeInTheDocument()
- dialog = await openEditor(user, contact)
- expect(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
- ).toBeChecked()
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- })
-
- it('prevents dismissing the editor while restoring the organization binding', async () => {
- const { scenario, repository, contact } = setup('workspace')
- let finishRestore: (() => void) | undefined
- vi.mocked(repository.removeIMBinding).mockImplementationOnce(
- () =>
- new Promise<void>((resolve) => {
- finishRestore = resolve
- }),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- await user.click(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
- )
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
-
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toHaveAttribute('aria-disabled', 'true')
- expect(within(dialog).getByRole('button', { name: 'contacts.action.cancel' })).toBeDisabled()
- expect(within(dialog).getByRole('button', { name: 'contacts.action.close' })).toBeDisabled()
- await user.keyboard('{Escape}')
- expect(
- screen.getByRole('dialog', { name: /^contacts\.imBinding\.changeTitle/ }),
- ).toBeInTheDocument()
-
- await act(async () => finishRestore?.())
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(repository.removeIMBinding).toHaveBeenCalledTimes(1)
- })
-
- it('keeps a selected identity when a later search has no results', async () => {
- const { scenario, repository, contact } = setup('organization')
- vi.mocked(repository.listIMIdentities).mockImplementation(async ({ search, page, limit }) => ({
- data: search === 'Nobody' ? [] : [identity],
- page,
- limit,
- total: search === 'Nobody' ? 0 : 1,
- has_more: false,
- }))
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const picker = await chooseIdentity(user, dialog)
- await user.click(picker)
- const search = await screen.findByRole('combobox', {
- name: /^contacts\.imBinding\.searchProvider/,
- })
- await user.clear(search)
- await user.type(search, 'Nobody')
- expect(await screen.findByText('contacts.imBinding.empty')).toBeInTheDocument()
- await user.keyboard('{Escape}')
- await waitFor(() => expect(picker).toHaveAttribute('aria-expanded', 'false'))
- expect(
- screen.getByRole('dialog', { name: /^contacts\.imBinding\.changeTitle/ }),
- ).toBeInTheDocument()
- expect(picker).toHaveTextContent('Synced Member')
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
- await waitFor(() =>
- expect(repository.setIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- identityId: identity.id,
- override: true,
- }),
- )
- })
-
- it('discards an unsaved selection and stale error when the editor is closed and reopened', async () => {
- const { scenario, repository, contact } = setup('workspace')
- vi.mocked(repository.setIMBinding).mockRejectedValueOnce(
- new ContactIMRequestError('im_binding_conflict'),
- )
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- let dialog = await openEditor(user, contact)
- await chooseIdentity(user, dialog)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.imBinding.conflict',
- )
- await user.click(within(dialog).getByRole('button', { name: 'contacts.action.cancel' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- dialog = await openEditor(user, contact)
-
- expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument()
- expect(
- within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' }),
- ).not.toHaveTextContent('Synced Member')
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- })
-
- it('does not infer the workspace identity from global binding status and excludes other providers', async () => {
- const { scenario, repository, contact } = setup('workspace')
- const defaultIdentity: ContactIMIdentity = { ...identity, binding_status: 'bound' }
- const overrideIdentity: ContactIMIdentity = {
- ...identity,
- id: 'identity-override',
- display_name: 'Workspace Member',
- provider_user_id: 'feishu-user-override',
- }
- const otherProvider: ContactIMIdentity = {
- ...identity,
- id: 'identity-slack',
- provider: 'slack',
- display_name: 'Slack Member',
- }
- vi.mocked(repository.listIMIdentities).mockImplementation(async ({ page, limit }) => ({
- data: [defaultIdentity, overrideIdentity, otherProvider],
- page,
- limit,
- total: 3,
- has_more: false,
- }))
- const user = userEvent.setup()
- renderDirectory(scenario, `?contact_id=${contact.id}`, repository)
- const dialog = await openEditor(user, contact)
- const picker = within(dialog).getByRole('combobox', { name: 'contacts.imBinding.contactLabel' })
- expect(picker).not.toHaveTextContent('Synced Member')
- expect(picker).not.toHaveTextContent('Workspace Member')
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- await user.click(picker)
-
- expect(await screen.findByRole('option', { name: /Synced Member/ })).toHaveAttribute(
- 'aria-selected',
- 'false',
- )
- expect(screen.getByRole('option', { name: /Workspace Member/ })).toHaveAttribute(
- 'aria-selected',
- 'false',
- )
- expect(screen.queryByRole('option', { name: /Slack Member/ })).not.toBeInTheDocument()
- expect(screen.queryByText('contacts.imBinding.bound')).not.toBeInTheDocument()
- })
+it('moves focus before clearing selection and reports selection through one stable status', async () => {
+ const user = userEvent.setup()
+ setup()
+ const status = screen.getByRole('status')
+ await user.click(await screen.findByRole('checkbox', { name: /selectContact.*Alice/ }))
+ expect(screen.getByRole('status')).toBe(status)
+ expect(status).toHaveTextContent('contacts.platformPicker.selected')
+ await user.click(screen.getByRole('button', { name: 'contacts.directory.cancelSelection' }))
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /Alice [email protected]/ })).toHaveFocus(),
+ )
+})
- it('does not offer IM binding for External contacts', async () => {
- const { scenario, repository } = setup()
- const external = {
- ...scenario.contacts.find((contact) => contact.type === 'external')!,
- im_bindings: [],
- }
- vi.mocked(repository.getContact).mockResolvedValue(external)
- renderDirectory(scenario, `?contact_id=${external.id}`, repository)
- const details = await findLoadedDetails(external.name)
+it('keeps a failed bulk selection and restores focus to search after removing the final rows', async () => {
+ const user = userEvent.setup()
+ api.remove.mockRejectedValueOnce(new Error('Unavailable'))
+ setup()
+ const selection = await screen.findByRole('checkbox', { name: 'contacts.directory.selectAll' })
+ await user.click(selection)
+ await user.click(screen.getByRole('button', { name: 'contacts.directory.removeSelected' }))
+ const dialog = await screen.findByRole('alertdialog')
+ const confirm = within(dialog).getByRole('button', { name: 'contacts.directory.removeSelected' })
+ await user.click(confirm)
+ expect(await within(dialog).findByRole('alert')).toHaveTextContent(
+ 'contacts.directory.removalFailed',
+ )
+ expect(selection).toBeChecked()
+ await user.click(confirm)
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ await waitFor(() =>
+ expect(screen.getByRole('searchbox', { name: 'contacts.directory.search' })).toHaveFocus(),
+ )
+})
- expect(within(details).queryByText('Feishu')).not.toBeInTheDocument()
- expect(
- within(details).queryByRole('button', { name: 'contacts.imBinding.bind' }),
- ).not.toBeInTheDocument()
- expect(
- within(details).queryByRole('button', { name: /^contacts\.imBinding\.changeTitle/ }),
- ).not.toBeInTheDocument()
- expect(repository.listIMIdentities).not.toHaveBeenCalled()
- expect(repository.setIMBinding).not.toHaveBeenCalled()
- })
+it('renders the page h1 while denied or resolving capabilities without fetching contacts', () => {
+ const { rerender } = setup({ ...managerContext, imCentrallyManaged: undefined })
+ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('contacts.directory.title')
+ expect(api.list).not.toHaveBeenCalled()
+ rerender(<ContactsDirectoryPage />)
+})
- it('keeps the centrally managed default read-only but permits a workspace customization on Enterprise', async () => {
- const { scenario, repository, contact } = setup('organization')
- const user = userEvent.setup()
- renderDirectory({ ...scenario, deployment: 'ee' }, `?contact_id=${contact.id}`, repository)
- const details = await findLoadedDetails(contact.name)
+it('does not restore URL page counts by repeatedly fetching old pages', async () => {
+ setup(managerContext, '?contact_pages=10')
+ await screen.findByRole('table')
+ const directoryCalls = api.list.mock.calls.filter(([input]) => input.query.limit === 20)
+ expect(directoryCalls).toHaveLength(1)
+})
- expect(within(details).getByText('contacts.imBinding.enterpriseReadOnly')).toBeInTheDocument()
- const dialog = await openEditor(user, contact)
- expect(
- within(dialog).getByRole('radio', { name: 'contacts.imBinding.organizationMode' }),
- ).toBeChecked()
- expect(
- within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }),
- ).toBeDisabled()
- await chooseIdentity(user, dialog)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.imBinding.saveBinding' }))
- await waitFor(() =>
- expect(repository.setIMBinding).toHaveBeenCalledWith({
- contactId: contact.id,
- identityId: identity.id,
- override: true,
- }),
- )
- expect(repository.removeIMBinding).not.toHaveBeenCalled()
- })
+it('mounts a separate alert when contact details fail', async () => {
+ const request = createDeferred<GetContactResponse>()
+ api.details.mockReturnValueOnce(request.promise)
+ const user = userEvent.setup()
+ setup()
+ await user.click(await screen.findByRole('button', { name: /Alice [email protected]/ }))
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+ await act(async () => request.reject(new Error('Unavailable')))
+ expect(await screen.findByRole('alert')).toHaveTextContent('contacts.details.error')
})
diff --git a/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx b/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx
index 29a45cf3017..0bcb208e698 100644
--- a/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx
+++ b/web/features/contacts/management/__tests__/external-contact-dialog.spec.tsx
@@ -1,514 +1,240 @@
-import type { ComponentProps, ReactNode } from 'react'
+import type { ComponentProps } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { consoleClient } from '@/service/console'
-import { ContactsManagementProvider } from '../composition'
+import { useState } from 'react'
+import { createDeferred } from '@/test/deferred'
import { ExternalContactDialog } from '../external-contact-dialog'
-import { createContactsApiRepository } from '../repository'
-import { ContactsManagementMockProvider } from './fixtures/composition'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
-
-const { uploadAvatar } = vi.hoisted(() => ({ uploadAvatar: vi.fn() }))
-
-vi.mock('@/service/console', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/console')>()),
- consoleQuery: {
- files: {
- upload: { post: { mutationOptions: () => ({ mutationFn: uploadAvatar }) } },
- },
- },
- consoleClient: {
- workspaces: {
- current: {
- humanInput: {
- v2: {
- contacts: {
- get: vi.fn(),
- byContactId: { get: vi.fn() },
- external: { post: vi.fn(), byContactId: { patch: vi.fn() } },
- remove: { post: vi.fn() },
- },
- },
- },
- },
- },
- },
-}))
+import { alice } from './fixtures/data'
+
+const api = vi.hoisted(() => ({ create: vi.fn(), update: vi.fn(), upload: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.humanInput.v2.contacts.external.post': api.create,
+ 'workspaces.current.humanInput.v2.contacts.external.byContactId.patch': api.update,
+ 'files.upload.post': api.upload,
+ }),
+ }
+})
-function renderAvatarDialog(contact?: ComponentProps<typeof ExternalContactDialog>['contact']) {
- const scenario = createContactsMockScenario(ContactsMockScenario.CeMixed)
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- function Wrapper({ children }: { children: ReactNode }) {
+function setup(contact?: ComponentProps<typeof ExternalContactDialog>['contact']) {
+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
+ const onCreated = vi.fn()
+ function Host() {
+ const [open, setOpen] = useState(false)
return (
- <QueryClientProvider client={queryClient}>
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }}
- repository={createContactsApiRepository()}
- >
- {children}
- </ContactsManagementProvider>
- </QueryClientProvider>
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Open contact
+ </button>
+ <ExternalContactDialog
+ open={open}
+ onOpenChange={setOpen}
+ contact={contact}
+ onCreated={onCreated}
+ />
+ </>
)
}
- return render(
- <ExternalContactDialog open contact={contact} onCreated={vi.fn()} onOpenChange={vi.fn()} />,
- { wrapper: Wrapper },
+ render(
+ <QueryClientProvider client={queryClient}>
+ <Host />
+ </QueryClientProvider>,
)
+ return { onCreated, queryClient }
}
+async function open(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(screen.getByRole('button', { name: 'Open contact' }))
+ return screen.findByRole('dialog')
+}
+async function fill(
+ user: ReturnType<typeof userEvent.setup>,
+ name = 'Alice',
+ email = '[email protected]',
+) {
+ await user.type(screen.getByRole('textbox', { name: 'contacts.external.name' }), name)
+ await user.type(screen.getByRole('textbox', { name: 'contacts.external.email' }), email)
+}
+beforeEach(() => {
+ api.create.mockReset().mockResolvedValue({ contact: alice })
+ api.update.mockReset().mockResolvedValue({ contact: alice })
+ api.upload.mockReset().mockResolvedValue({ id: 'avatar-file' })
+})
-describe('ExternalContactDialog pending state', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- uploadAvatar.mockReset()
- })
-
- it.each([
- ['[email protected]', 'duplicate_external_contact'],
- ['[email protected]', 'matches_workspace_contact'],
- ['[email protected]', 'matches_platform_contact'],
- ] as const)('renders the typed %s conflict result', async (email, resultKind) => {
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementMockProvider
- scenario={createContactsMockScenario(ContactsMockScenario.EeMixed)}
- >
- <ExternalContactDialog open onCreated={vi.fn()} onOpenChange={vi.fn()} />
- </ContactsManagementMockProvider>
- </QueryClientProvider>,
- )
- const user = userEvent.setup()
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.title' })
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.name' }),
- 'Conflict',
- )
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.email' }),
- email.toUpperCase(),
- )
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- `contacts.external.result.${resultKind}`,
- )
- })
+it('validates required fields and malformed email before calling the generated mutation', async () => {
+ const user = userEvent.setup()
+ setup()
+ await open(user)
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ expect(await screen.findByText('contacts.external.validation.name_required')).toBeInTheDocument()
+ expect(api.create).not.toHaveBeenCalled()
+ await fill(user, 'Alice', '[email protected]')
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ expect(await screen.findByText('contacts.external.validation.email_invalid')).toBeInTheDocument()
+ expect(api.create).not.toHaveBeenCalled()
+})
- it('prevents duplicate submission and never issues a real request', async () => {
- let resolveCreate: (() => void) | undefined
- const wait = () =>
- new Promise<void>((resolve) => {
- resolveCreate = resolve
- })
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onCreated = vi.fn()
- const onOpenChange = vi.fn()
- vi.mocked(globalThis.fetch).mockClear()
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementMockProvider
- scenario={createContactsMockScenario(ContactsMockScenario.CeMixed)}
- wait={wait}
- >
- <ExternalContactDialog open onCreated={onCreated} onOpenChange={onOpenChange} />
- </ContactsManagementMockProvider>
- </QueryClientProvider>,
- )
+it.each(['john<doe>@example.com', '[email protected]'])(
+ 'preserves browser email validation for %s through the Field owner',
+ async (email) => {
const user = userEvent.setup()
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.title' })
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.name' }),
- 'Partner',
- )
- await user.type(
- within(dialog).getByRole('textbox', { name: 'contacts.external.email' }),
- )
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
-
+ setup()
+ await open(user)
+ await fill(user, 'Alice', email)
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
expect(
- within(dialog).getByRole('button', { name: 'contacts.external.adding' }),
- ).toHaveAttribute('aria-disabled', 'true')
- expect(onCreated).not.toHaveBeenCalled()
- expect(globalThis.fetch).not.toHaveBeenCalled()
- await act(async () => resolveCreate?.())
- await waitFor(() => expect(onCreated).toHaveBeenCalledWith('contact-external-created-1'))
- expect(onOpenChange).toHaveBeenCalledWith(false)
+ await screen.findByText('contacts.external.validation.email_invalid'),
+ ).toBeInTheDocument()
+ expect(api.create).not.toHaveBeenCalled()
+ },
+)
+
+it('uses one field error for the duplicate-email 409 and keeps the draft for correction', async () => {
+ const user = userEvent.setup()
+ api.create.mockRejectedValueOnce(Object.assign(new Error('Conflict'), { status: 409 }))
+ setup()
+ await open(user)
+ await fill(user)
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ const duplicate = await screen.findByText('contacts.external.result.duplicate_external_contact')
+ const email = screen.getByRole('textbox', { name: 'contacts.external.email' })
+ expect(email).toHaveAttribute('aria-invalid', 'true')
+ expect(email).toHaveAccessibleDescription('contacts.external.result.duplicate_external_contact')
+ expect(screen.getAllByText(duplicate.textContent!)).toHaveLength(1)
+ expect(email).toHaveValue('[email protected]')
+ await user.clear(email)
+ await user.type(email, '[email protected]')
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(api.create).toHaveBeenLastCalledWith({
+ body: { name: 'Alice', email: '[email protected]' },
})
+})
- it('retains the draft after an API failure and closes only after a successful retry', async () => {
- const createContact = vi.mocked(
- consoleClient.workspaces.current.humanInput.v2.contacts.external.post,
- )
- createContact.mockRejectedValueOnce(
- Object.assign(new Error('Service unavailable'), { status: 503 }),
- )
- createContact.mockResolvedValueOnce({
- contact: {
- avatar_url: '',
- created_at: 1_778_000_000,
- email: '[email protected]',
- id: 'server-created-contact',
- name: 'Partner',
- type: 'external',
- },
- })
- const scenario = createContactsMockScenario(ContactsMockScenario.CeMixed)
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onCreated = vi.fn()
- const onOpenChange = vi.fn()
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }}
- repository={createContactsApiRepository()}
- >
- <ExternalContactDialog open onCreated={onCreated} onOpenChange={onOpenChange} />
- </ContactsManagementProvider>
- </QueryClientProvider>,
- )
- const user = userEvent.setup()
- const dialog = screen.getByRole('dialog', { name: 'contacts.external.title' })
- const name = within(dialog).getByRole('textbox', { name: 'contacts.external.name' })
- const email = within(dialog).getByRole('textbox', { name: 'contacts.external.email' })
- await user.type(name, 'Partner')
- await user.type(email, '[email protected]')
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
-
- expect(await within(dialog).findByRole('alert')).toHaveTextContent(
- 'contacts.external.result.failed',
- )
- expect(name).toHaveValue('Partner')
- expect(email).toHaveValue('[email protected]')
- expect(onCreated).not.toHaveBeenCalled()
- expect(onOpenChange).not.toHaveBeenCalled()
+it('prevents repeated submission and dismissal while pending, then closes on success', async () => {
+ const user = userEvent.setup()
+ const request = createDeferred<{ contact: typeof alice }>()
+ api.create.mockReturnValueOnce(request.promise)
+ const { onCreated } = setup()
+ await open(user)
+ await fill(user)
+ const submit = screen.getByRole('button', { name: 'contacts.external.add' })
+ await user.click(submit)
+ await user.click(submit)
+ await user.keyboard('{Escape}')
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(api.create).toHaveBeenCalledOnce()
+ await act(async () => request.resolve({ contact: alice }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(onCreated).toHaveBeenCalledWith(alice.id)
+})
- await user.click(within(dialog).getByRole('button', { name: 'contacts.external.add' }))
+it('retains the draft through a failed save and starts a new form only after close', async () => {
+ const user = userEvent.setup()
+ api.create.mockRejectedValueOnce(new Error('Service unavailable'))
+ setup()
+ await open(user)
+ await fill(user)
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('contacts.external.result.failed')
+ expect(screen.getByRole('textbox', { name: 'contacts.external.name' })).toHaveValue('Alice')
+ await user.click(screen.getByRole('button', { name: 'contacts.action.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await open(user)
+ expect(screen.getByRole('textbox', { name: 'contacts.external.name' })).toHaveValue('')
+ expect(screen.getByRole('textbox', { name: 'contacts.external.email' })).toHaveValue('')
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+})
- await waitFor(() => expect(onCreated).toHaveBeenCalledWith('server-created-contact'))
- expect(onOpenChange).toHaveBeenCalledWith(false)
- expect(createContact).toHaveBeenCalledTimes(2)
+it('edits through the generated PATCH and preserves an intentional empty name as a validation failure', async () => {
+ const user = userEvent.setup()
+ setup(alice)
+ await open(user)
+ const name = screen.getByRole('textbox', { name: 'contacts.external.name' })
+ await user.clear(name)
+ await user.click(screen.getByRole('button', { name: 'contacts.external.save' }))
+ expect(api.update).not.toHaveBeenCalled()
+ await user.type(name, 'Alice Updated')
+ await user.click(screen.getByRole('button', { name: 'contacts.external.save' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(api.update).toHaveBeenCalledWith({
+ params: { contact_id: alice.id },
+ body: { name: 'Alice Updated', email: alice.email },
})
+})
- it.each(['create', 'edit'] as const)(
- 'uploads an avatar before %s and saves its file ID after retrying a failed upload',
- async (mode) => {
- let rejectUpload: ((error: Error) => void) | undefined
- uploadAvatar.mockImplementationOnce(
- () =>
- new Promise((_resolve, reject) => {
- rejectUpload = reject
- }),
- )
- uploadAvatar.mockResolvedValueOnce({ id: 'uploaded-avatar-id' })
- const savedContact = {
- id: 'avatar-contact',
- name: 'Partner',
- email: '[email protected]',
- avatar_url: 'https://example.com/existing-avatar.png',
- created_at: 1,
- type: 'external' as const,
- }
- const contactsClient = consoleClient.workspaces.current.humanInput.v2.contacts
- vi.mocked(contactsClient.external.post).mockResolvedValue({ contact: savedContact })
- vi.mocked(contactsClient.external.byContactId.patch).mockResolvedValue({
- contact: savedContact,
- })
- const scenario = createContactsMockScenario(ContactsMockScenario.CeMixed)
- render(
- <QueryClientProvider
- client={new QueryClient({ defaultOptions: { mutations: { retry: false } } })}
- >
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }}
- repository={createContactsApiRepository()}
- >
- <ExternalContactDialog
- open
- contact={mode === 'edit' ? savedContact : undefined}
- onCreated={vi.fn()}
- onOpenChange={vi.fn()}
- />
- </ContactsManagementProvider>
- </QueryClientProvider>,
- )
- const user = userEvent.setup()
- if (mode === 'create') {
- await user.type(screen.getByRole('textbox', { name: 'contacts.external.name' }), 'Partner')
- await user.type(
- screen.getByRole('textbox', { name: 'contacts.external.email' }),
- )
- }
- const input = screen.getByLabelText('common.imageUploader.imageUpload')
- const file = new File(['avatar'], 'avatar.png', { type: 'image/png' })
- await user.upload(input, file)
- expect(uploadAvatar).toHaveBeenCalledWith({ body: { file } }, expect.anything())
- const save = screen.getByRole('button', {
- name: `contacts.external.${mode === 'edit' ? 'save' : 'add'}`,
- })
- expect(save).toBeDisabled()
- await act(async () => rejectUpload?.(new Error('Upload failed')))
- expect(await screen.findByRole('alert')).toHaveTextContent(
- 'common.imageUploader.uploadFromComputerUploadError',
- )
- await user.click(save)
- expect(contactsClient.external.post).not.toHaveBeenCalled()
- expect(contactsClient.external.byContactId.patch).not.toHaveBeenCalled()
-
- await user.upload(input, file)
- await waitFor(() => expect(save).toBeEnabled())
- await user.click(save)
- const expectedBody = {
- name: 'Partner',
- email: '[email protected]',
- avatar: 'uploaded-avatar-id',
- }
- await waitFor(() => {
- if (mode === 'create')
- expect(contactsClient.external.post).toHaveBeenCalledWith(
- { body: expectedBody },
- expect.anything(),
- )
- else
- expect(contactsClient.external.byContactId.patch).toHaveBeenCalledWith(
- { params: { contact_id: savedContact.id }, body: expectedBody },
- expect.anything(),
- )
- })
- expect(uploadAvatar).toHaveBeenCalledTimes(2)
- },
- )
-
- it('updates the initial avatar while editing the name without overwriting the saved avatar', async () => {
- const contact = {
- id: 'existing-contact',
- name: 'Alice',
- email: '[email protected]',
- avatar_url: '',
- }
- const updateContact = vi.mocked(
- consoleClient.workspaces.current.humanInput.v2.contacts.external.byContactId.patch,
- )
- updateContact.mockResolvedValue({
- contact: { ...contact, name: 'Evan', created_at: 1, type: 'external' },
- })
- renderAvatarDialog(contact)
+it.each(['create', 'edit'] as const)(
+ 'rejects an overlong name before %s and allows correcting the Unicode boundary',
+ async (mode) => {
const user = userEvent.setup()
- const avatar = screen.getByRole('button', { name: 'common.avatar.editAction' })
- expect(within(avatar).getByText('A')).toBeInTheDocument()
- expect(within(avatar).queryByRole('presentation')).not.toBeInTheDocument()
-
+ setup(mode === 'edit' ? alice : undefined)
+ await open(user)
const name = screen.getByRole('textbox', { name: 'contacts.external.name' })
+ const save = screen.getByRole('button', {
+ name: `contacts.external.${mode === 'edit' ? 'save' : 'add'}`,
+ })
+ if (mode === 'create')
+ await user.type(
+ screen.getByRole('textbox', { name: 'contacts.external.email' }),
+ alice.email!,
+ )
await user.clear(name)
- await user.type(name, 'Evan')
- expect(within(avatar).getByText('E')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.external.save' }))
+ await user.click(name)
+ await user.paste('中'.repeat(256))
+ await user.click(save)
- await waitFor(() =>
- expect(updateContact).toHaveBeenCalledWith(
- {
- params: { contact_id: contact.id },
- body: { name: 'Evan', email: contact.email },
- },
- expect.anything(),
- ),
- )
- expect(uploadAvatar).not.toHaveBeenCalled()
- })
+ await waitFor(() => expect(name).toHaveFocus())
+ expect(name).toHaveAccessibleDescription(/contacts\.external\.validation\.name_too_long/)
+ expect(name).toHaveAttribute('aria-invalid', 'true')
+ expect(api.create).not.toHaveBeenCalled()
+ expect(api.update).not.toHaveBeenCalled()
- it('derives a new contact avatar from the name and restores the portrait when cleared', async () => {
- renderAvatarDialog()
- const user = userEvent.setup()
- const avatar = screen.getByRole('button', { name: 'common.avatar.editAction' })
- expect(within(avatar).getByRole('presentation')).toHaveAttribute(
- 'src',
- expect.stringMatching(/^data:image\/svg\+xml;base64,/),
- )
- const name = screen.getByRole('textbox', { name: 'contacts.external.name' })
- await user.type(name, ' Evan')
- expect(within(avatar).getByText('E')).toBeInTheDocument()
- expect(within(avatar).queryByRole('presentation')).not.toBeInTheDocument()
+ const validName = '😀'.repeat(255)
await user.clear(name)
- expect(within(avatar).getByRole('presentation')).toBeInTheDocument()
- })
-
- it.each(['create', 'edit'] as const)(
- 'rejects an overlong name before %s and allows correcting the Unicode boundary',
- async (mode) => {
- const contacts = consoleClient.workspaces.current.humanInput.v2.contacts
- const contact = {
- id: 'name-boundary-contact',
- name: 'Partner',
- email: '[email protected]',
- avatar_url: '',
- created_at: 1,
- type: 'external' as const,
- }
- vi.mocked(contacts.external.post).mockResolvedValue({ contact })
- vi.mocked(contacts.external.byContactId.patch).mockResolvedValue({ contact })
- renderAvatarDialog(mode === 'edit' ? contact : undefined)
- const user = userEvent.setup()
- const name = screen.getByRole('textbox', { name: 'contacts.external.name' })
- const email = screen.getByRole('textbox', { name: 'contacts.external.email' })
- const save = screen.getByRole('button', {
- name: `contacts.external.${mode === 'edit' ? 'save' : 'add'}`,
- })
- if (mode === 'create') await user.type(email, contact.email)
- await user.clear(name)
- await user.click(name)
- await user.paste('中'.repeat(256))
- await user.click(save)
-
- await waitFor(() => expect(name).toHaveFocus())
- expect(name).toHaveAccessibleDescription(/contacts\.external\.validation\.name_too_long/)
- expect(name).toHaveAttribute('aria-invalid', 'true')
- expect(contacts.external.post).not.toHaveBeenCalled()
- expect(contacts.external.byContactId.patch).not.toHaveBeenCalled()
-
- const validName = '😀'.repeat(255)
- await user.clear(name)
- await user.click(name)
- await user.paste(` ${validName} `)
- await user.click(save)
- const body = { name: validName, email: contact.email }
- await waitFor(() => {
- if (mode === 'create')
- expect(contacts.external.post).toHaveBeenCalledWith({ body }, expect.anything())
- else
- expect(contacts.external.byContactId.patch).toHaveBeenCalledWith(
- { params: { contact_id: contact.id }, body },
- expect.anything(),
- )
- })
- },
- )
-
- 'rejects malformed local parts without sending %s to the server',
- async (email) => {
- renderAvatarDialog()
- const user = userEvent.setup()
- await user.type(screen.getByRole('textbox', { name: 'contacts.external.name' }), 'Evan')
- const emailInput = screen.getByRole<HTMLInputElement>('textbox', {
- name: 'contacts.external.email',
- })
- await user.type(emailInput, email)
- // Chrome accepts these local parts; happy-dom would otherwise bypass our form validation.
- const validity = vi.spyOn(emailInput, 'validity', 'get').mockReturnValue({
- valid: true,
- badInput: false,
- customError: false,
- patternMismatch: false,
- rangeOverflow: false,
- rangeUnderflow: false,
- stepMismatch: false,
- tooLong: false,
- tooShort: false,
- typeMismatch: false,
- valueMissing: false,
- })
- try {
- await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
- expect(await screen.findByText('contacts.external.validation.email_invalid')).toBeVisible()
- expect(
- consoleClient.workspaces.current.humanInput.v2.contacts.external.post,
- ).not.toHaveBeenCalled()
- } finally {
- validity.mockRestore()
- }
- },
- )
-
- 'keeps accepting the valid email %s',
- async (email) => {
- const contacts = consoleClient.workspaces.current.humanInput.v2.contacts
- vi.mocked(contacts.external.post).mockResolvedValue({
- contact: {
- id: 'valid-email-contact',
- name: 'Evan',
- email,
- avatar_url: '',
- created_at: 1,
- type: 'external',
- },
- })
- renderAvatarDialog()
- const user = userEvent.setup()
- await user.type(screen.getByRole('textbox', { name: 'contacts.external.name' }), 'Evan')
- await user.type(screen.getByRole('textbox', { name: 'contacts.external.email' }), email)
- await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
-
- await waitFor(() =>
- expect(contacts.external.post).toHaveBeenCalledWith(
- { body: { name: 'Evan', email } },
- expect.anything(),
- ),
- )
- },
+ await user.click(name)
+ await user.paste(` ${validName} `)
+ await user.click(save)
+
+ const body = { name: validName, email: alice.email }
+ await waitFor(() => {
+ if (mode === 'create') expect(api.create).toHaveBeenCalledWith({ body })
+ else expect(api.update).toHaveBeenCalledWith({ params: { contact_id: alice.id }, body })
+ })
+ },
+)
+
+it('uploads a valid avatar and submits its file ID without exposing the blob URL', async () => {
+ const user = userEvent.setup()
+ setup()
+ const dialog = await open(user)
+ await fill(user)
+ const upload = within(dialog).getByLabelText('common.imageUploader.imageUpload')
+ await user.upload(upload, new File(['image'], 'avatar.png', { type: 'image/png' }))
+ await waitFor(() => expect(api.upload).toHaveBeenCalledOnce())
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ await waitFor(() =>
+ expect(api.create).toHaveBeenCalledWith({
+ body: { name: 'Alice', email: '[email protected]', avatar: 'avatar-file' },
+ }),
)
+})
- it.each(['load', 'error'] as const)(
- 'shows no fallback while the existing avatar loads, then handles its %s result',
- async (result) => {
- const complete = vi
- .spyOn(HTMLImageElement.prototype, 'complete', 'get')
- .mockReturnValue(false)
- try {
- const contact = {
- id: 'existing-contact',
- name: 'Alice',
- email: '[email protected]',
- avatar_url: 'https://example.com/alice.png',
- }
- renderAvatarDialog(contact)
- const avatar = screen.getByRole('button', { name: 'common.avatar.editAction' })
- const photo = within(avatar).getByAltText('Alice')
- expect(within(avatar).queryByText('A')).not.toBeInTheDocument()
- expect(within(avatar).queryByRole('presentation')).not.toBeInTheDocument()
-
- if (result === 'load') fireEvent.load(photo)
- else fireEvent.error(photo)
-
- if (result === 'load') {
- expect(await within(avatar).findByRole('img', { name: 'Alice' })).toHaveAttribute(
- 'src',
- contact.avatar_url,
- )
- expect(within(avatar).queryByText('A')).not.toBeInTheDocument()
- } else {
- expect(await within(avatar).findByText('A')).toBeInTheDocument()
- expect(within(avatar).queryByRole('img', { name: 'Alice' })).not.toBeInTheDocument()
- expect(within(avatar).queryByRole('presentation')).not.toBeInTheDocument()
- }
- } finally {
- complete.mockRestore()
- }
- },
- )
+it('keeps invalid avatar files local and blocks submit until reset', async () => {
+ const user = userEvent.setup()
+ setup()
+ await open(user)
+ await fill(user)
+ const file = new File(['bad'], 'avatar.exe', { type: 'application/octet-stream' })
+ fireEvent.change(screen.getByLabelText('common.imageUploader.imageUpload'), {
+ target: { files: [file] },
+ })
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.imageInput.supportedFormats')
+ expect(api.upload).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'common.operation.reset' }))
+ await user.click(screen.getByRole('button', { name: 'contacts.external.add' }))
+ await waitFor(() => expect(api.create).toHaveBeenCalledOnce())
})
diff --git a/web/features/contacts/management/__tests__/fixtures/composition.tsx b/web/features/contacts/management/__tests__/fixtures/composition.tsx
deleted file mode 100644
index 2eac487ad16..00000000000
--- a/web/features/contacts/management/__tests__/fixtures/composition.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { ReactNode } from 'react'
-import type { ContactsFeatureContextValue } from '../../types'
-import type { ContactsMockScenarioDefinition } from './scenarios'
-import { useMemo } from 'react'
-import { ContactsManagementProvider } from '../../composition'
-import { createContactsMockRepository } from './repository'
-
-export function ContactsManagementMockProvider({
- children,
- scenario,
- wait,
-}: {
- children: ReactNode
- scenario: ContactsMockScenarioDefinition
- wait?: () => Promise<void>
-}) {
- const context = useMemo<ContactsFeatureContextValue>(
- () => ({
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- }),
- [scenario],
- )
- const repository = useMemo(
- () => createContactsMockRepository({ scenario, wait }),
- [scenario, wait],
- )
-
- return (
- <ContactsManagementProvider context={context} repository={repository}>
- {children}
- </ContactsManagementProvider>
- )
-}
diff --git a/web/features/contacts/management/__tests__/fixtures/data.ts b/web/features/contacts/management/__tests__/fixtures/data.ts
new file mode 100644
index 00000000000..afea4cc5dcf
--- /dev/null
+++ b/web/features/contacts/management/__tests__/fixtures/data.ts
@@ -0,0 +1,27 @@
+import type { HumanInputContact } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ContactsFeatureContextValue } from '../../types'
+
+export const managerContext: ContactsFeatureContextValue = {
+ deployment: 'ce',
+ imCentrallyManaged: false,
+ workspaceId: 'workspace-1',
+ permissions: { canViewContacts: true, canManageContacts: true, canManageMembers: true },
+}
+
+export const alice: HumanInputContact = {
+ id: '01a18a00-0000-7000-8000-000000000001',
+ name: 'Alice',
+ email: '[email protected]',
+ type: 'external',
+ created_at: 1780000000,
+ im_bindings: [],
+}
+
+export const bob: HumanInputContact = {
+ id: '01a18a00-0000-7000-8000-000000000002',
+ name: 'Bob',
+ email: '[email protected]',
+ type: 'external',
+ created_at: 1780000000,
+ im_bindings: [],
+}
diff --git a/web/features/contacts/management/__tests__/fixtures/repository.ts b/web/features/contacts/management/__tests__/fixtures/repository.ts
deleted file mode 100644
index 3d5db051cd5..00000000000
--- a/web/features/contacts/management/__tests__/fixtures/repository.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-import type { ContactsManagementRepository } from '../../repository'
-import type { ContactPage } from '../../types'
-import type { ContactsMockScenarioDefinition } from './scenarios'
-
-type CreateContactsMockRepositoryOptions = {
- scenario: ContactsMockScenarioDefinition
- wait?: () => Promise<void>
-}
-
-const normalizeEmail = (email: string) => email.trim().toLocaleLowerCase()
-const MOCK_CREATED_AT = Date.parse('2026-07-17T00:00:00.000Z') / 1000
-
-const matchesSearch = (search: string, ...values: string[]) => {
- const normalizedSearch = search.trim().toLocaleLowerCase()
- return (
- !normalizedSearch ||
- values.some((value) => value.toLocaleLowerCase().includes(normalizedSearch))
- )
-}
-
-function paginate<T>(items: T[], page: number, limit: number): ContactPage<T> {
- const offset = (page - 1) * limit
- const data = items.slice(offset, offset + limit)
-
- return {
- data: structuredClone(data),
- has_more: offset + data.length < items.length,
- limit,
- page,
- total: items.length,
- }
-}
-
-export function createContactsMockRepository({
- scenario,
- wait = async () => {},
-}: CreateContactsMockRepositoryOptions): ContactsManagementRepository {
- let contacts = structuredClone(scenario.contacts)
- const availablePlatformContacts = structuredClone(scenario.availablePlatformContacts)
- let createdExternalCount = 0
-
- const getUnavailablePlatformContactIds = () =>
- new Set(contacts.filter((contact) => contact.type !== 'external').map((contact) => contact.id))
- const getUnavailablePlatformContactEmails = () =>
- new Set(
- contacts.flatMap((contact) =>
- contact.type !== 'external' && contact.email ? [normalizeEmail(contact.email)] : [],
- ),
- )
- const getWorkspaceContact = (memberId: string) => {
- const contactId = scenario.memberContactIds[memberId]
- return contacts.find((contact) => contact.id === contactId && contact.type === 'workspace')
- }
-
- return {
- supportsIMBindings: false,
- async listIMChannels() {
- await wait()
- const providers = new Set(
- scenario.contacts.flatMap((contact) =>
- contact.type === 'external' ? [] : contact.im_bindings.map((binding) => binding.provider),
- ),
- )
- return [...providers].map((provider) => ({ id: `channel-${provider}`, provider }))
- },
- async listIMIdentities() {
- throw new Error('IM identity fixtures are not configured')
- },
- async setIMBinding() {
- throw new Error('IM identity fixtures are not configured')
- },
- async removeIMBinding() {
- throw new Error('IM identity fixtures are not configured')
- },
- async unbindIMBinding() {
- throw new Error('IM identity fixtures are not configured')
- },
- async getContact(contactId) {
- await wait()
- const contact = contacts.find((item) => item.id === contactId)
- return contact ? structuredClone(contact) : null
- },
- async findExternalContactsByEmails(command) {
- await wait()
- const emails = new Set(command.emails.map(normalizeEmail))
-
- return contacts.flatMap((contact) => {
- if (
- contact.type !== 'external' ||
- !contact.email ||
- !emails.has(normalizeEmail(contact.email))
- ) {
- return []
- }
-
- return [{ email: contact.email, id: contact.id, name: contact.name }]
- })
- },
-
- async listContacts(query) {
- await wait()
- if (scenario.failures.directory) throw new Error('contacts_directory_failed')
- if (query.page > 1 && scenario.failures.nextPage) throw new Error('contacts_next_page_failed')
-
- const filtered = contacts.filter((contact) => {
- const matchesKind = query.kind === 'all' || contact.type === query.kind
- return matchesKind && matchesSearch(query.search, contact.name, contact.email ?? '')
- })
-
- return paginate(filtered, query.page, query.limit)
- },
-
- async createExternalContact(command) {
- await wait()
- if (scenario.failures.createExternal) return { kind: 'failed' }
-
- const email = normalizeEmail(command.email)
- const contact = contacts.find((item) => item.email && normalizeEmail(item.email) === email)
- if (contact?.type === 'external') {
- return { contactId: contact.id, kind: 'duplicate_external_contact' }
- }
- if (contact?.type === 'workspace') {
- return { contactId: contact.id, kind: 'matches_workspace_contact' }
- }
- if (contact?.type === 'platform') {
- return { contactId: contact.id, kind: 'matches_platform_contact' }
- }
-
- const availablePlatformContact = availablePlatformContacts.find(
- (item) => normalizeEmail(item.email) === email,
- )
- if (availablePlatformContact) {
- return { contactId: availablePlatformContact.id, kind: 'matches_platform_contact' }
- }
-
- createdExternalCount += 1
- const contactId = `contact-external-created-${createdExternalCount}`
- contacts = [
- ...contacts,
- {
- avatar_url: '',
- created_at: MOCK_CREATED_AT,
- email,
- id: contactId,
- im_bindings: [],
- name: command.displayName.trim(),
- type: 'external',
- },
- ]
- return { contactId, kind: 'created' }
- },
-
- async updateExternalContact(command) {
- await wait()
- if (scenario.failures.createExternal) return { kind: 'failed' }
-
- const email = normalizeEmail(command.email)
- const target = contacts.find(
- (contact) => contact.id === command.contactId && contact.type === 'external',
- )
- if (!target) return { kind: 'failed' }
-
- const conflict = contacts.find(
- (contact) =>
- contact.id !== command.contactId &&
- contact.email &&
- normalizeEmail(contact.email) === email,
- )
- if (conflict?.type === 'external') {
- return { contactId: conflict.id, kind: 'duplicate_external_contact' }
- }
- if (conflict?.type === 'workspace') {
- return { contactId: conflict.id, kind: 'matches_workspace_contact' }
- }
- if (conflict?.type === 'platform') {
- return { contactId: conflict.id, kind: 'matches_platform_contact' }
- }
-
- const availablePlatformContact =
- target.email && normalizeEmail(target.email) === email
- ? undefined
- : availablePlatformContacts.find((contact) => normalizeEmail(contact.email) === email)
- if (availablePlatformContact) {
- return { contactId: availablePlatformContact.id, kind: 'matches_platform_contact' }
- }
-
- contacts = contacts.map((contact) =>
- contact.id === command.contactId
- ? { ...contact, email, name: command.displayName.trim() }
- : contact,
- )
- return { contactId: command.contactId, kind: 'updated' }
- },
-
- async listAvailablePlatformContacts(query) {
- await wait()
- if (scenario.failures.platformContacts) throw new Error('platform_contacts_failed')
-
- const existingContactIds = getUnavailablePlatformContactIds()
- const existingEmails = getUnavailablePlatformContactEmails()
- const filtered = availablePlatformContacts.filter((contact) => {
- const isExisting =
- existingContactIds.has(contact.id) || existingEmails.has(normalizeEmail(contact.email))
- return !isExisting && matchesSearch(query.search, contact.name, contact.email)
- })
- return paginate(filtered, query.page, query.limit)
- },
-
- async addPlatformContacts(command) {
- await wait()
- if (scenario.failures.addPlatform) return { kind: 'failed' }
-
- const selectedContacts = availablePlatformContacts.filter((contact) =>
- command.contactIds.includes(contact.id),
- )
- const conflicts = selectedContacts.flatMap((platformContact) => {
- const existingContact = contacts.find(
- (contact) =>
- contact.type === 'external' &&
- contact.email &&
- normalizeEmail(contact.email) === normalizeEmail(platformContact.email),
- )
- if (!existingContact?.email) return []
- return [
- {
- contactId: existingContact.id,
- email: existingContact.email,
- platformContactId: platformContact.id,
- },
- ]
- })
- if (conflicts.length > 0 && !command.upgradeExternalContacts) {
- return { conflicts, kind: 'requires_external_contact_upgrade' }
- }
-
- const nextContacts = [...contacts]
- const contactIds: string[] = []
- for (const platformContact of selectedContacts) {
- const existingIndex = nextContacts.findIndex(
- (contact) =>
- contact.email &&
- normalizeEmail(contact.email) === normalizeEmail(platformContact.email),
- )
- const existingContact = nextContacts[existingIndex]
- if (existingContact) {
- if (existingContact.type === 'external' && command.upgradeExternalContacts) {
- nextContacts[existingIndex] = { ...existingContact, type: 'platform' }
- contactIds.push(existingContact.id)
- }
- continue
- }
-
- nextContacts.push({
- avatar_url: platformContact.avatar_url ?? '',
- created_at: MOCK_CREATED_AT,
- email: platformContact.email,
- id: platformContact.id,
- im_bindings: [],
- name: platformContact.name,
- type: 'platform' as const,
- })
- contactIds.push(platformContact.id)
- }
-
- contacts = nextContacts
- return { contactIds, kind: 'added' }
- },
-
- async removeContacts(command) {
- await wait()
- if (scenario.failures.contactRemoval) return { kind: 'failed' }
-
- const selectedIds = new Set(command.contactIds)
- const removedContactIds = contacts
- .filter((contact) => contact.type !== 'workspace' && selectedIds.has(contact.id))
- .map((contact) => contact.id)
- const removedIds = new Set(removedContactIds)
- contacts = contacts.filter((contact) => !removedIds.has(contact.id))
-
- return { kind: 'removed', removedContactIds }
- },
-
- async removeMember(command) {
- await wait()
- if (scenario.failures.removal) return { kind: 'failed' }
-
- const contact = getWorkspaceContact(command.memberId)
- if (!contact) {
- return { contactId: null, contactOutcome: 'not_found', kind: 'removed' }
- }
-
- if (scenario.imCentrallyManaged && command.keepAsPlatformContact) {
- contacts = contacts.map((item) => {
- if (item.id !== contact.id) return item
- return {
- ...item,
- type: 'platform',
- }
- })
- return {
- contactId: contact.id,
- contactOutcome: 'converted_to_platform',
- kind: 'removed',
- }
- }
-
- contacts = contacts.filter((item) => item.id !== contact.id)
- return { contactId: contact.id, contactOutcome: 'removed', kind: 'removed' }
- },
-
- async upgradeExternalContactsToWorkspace(command) {
- await wait()
- const selectedIds = new Set(command.contactIds)
- const contactIds: string[] = []
-
- contacts = contacts.map((contact) => {
- if (contact.type !== 'external' || !selectedIds.has(contact.id)) return contact
- contactIds.push(contact.id)
- return { ...contact, type: 'workspace' }
- })
-
- return { contactIds, kind: 'upgraded' }
- },
- }
-}
diff --git a/web/features/contacts/management/__tests__/fixtures/scenarios.ts b/web/features/contacts/management/__tests__/fixtures/scenarios.ts
deleted file mode 100644
index 7faa76fd236..00000000000
--- a/web/features/contacts/management/__tests__/fixtures/scenarios.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import type {
- AvailablePlatformContact,
- ContactsDeployment,
- ContactsPermissions,
- ContactView,
-} from '../../types'
-
-export const ContactsMockScenario = {
- AddPlatformFailure: 'add-platform-failure',
- CeMixed: 'ce-mixed',
- ContactRemovalFailure: 'contact-removal-failure',
- DirectoryFailure: 'directory-failure',
- EeMixed: 'ee-mixed',
- Empty: 'empty',
- ExternalFailure: 'external-failure',
- NextPageFailure: 'next-page-failure',
- NoAccess: 'no-access',
- Paginated: 'paginated',
- PlatformContactsFailure: 'platform-contacts-failure',
- ReadOnly: 'read-only',
- RemovalFailure: 'removal-failure',
- SaasMixed: 'saas-mixed',
-} as const
-
-export type ContactsMockScenario = (typeof ContactsMockScenario)[keyof typeof ContactsMockScenario]
-
-type ContactsMockFailurePlan = {
- addPlatform?: boolean
- contactRemoval?: boolean
- createExternal?: boolean
- directory?: boolean
- nextPage?: boolean
- platformContacts?: boolean
- removal?: boolean
-}
-
-export type ContactsMockScenarioDefinition = {
- contacts: ContactView[]
- deployment: ContactsDeployment
- imCentrallyManaged: boolean
- failures: ContactsMockFailurePlan
- availablePlatformContacts: AvailablePlatformContact[]
- memberContactIds: Record<string, string>
- permissions: ContactsPermissions
- workspaceId: string
-}
-
-const workspaceContact: ContactView = {
- avatar_url: '',
- created_at: Date.parse('2026-01-12T08:00:00.000Z') / 1000,
- email: '[email protected]',
- id: 'contact-owner',
- im_bindings: [{ id: 'binding-owner-slack', provider: 'slack', scope: 'workspace' }],
- name: 'Ralph Edwards',
- type: 'workspace',
-}
-
-const platformContact: ContactView = {
- avatar_url: '',
- created_at: Date.parse('2026-02-04T08:00:00.000Z') / 1000,
- email: '[email protected]',
- id: 'contact-platform',
- im_bindings: [{ id: 'binding-platform-feishu', provider: 'feishu', scope: 'organization' }],
- name: 'Leslie Alexander',
- type: 'platform',
-}
-
-const externalContact: ContactView = {
- avatar_url: '',
- created_at: Date.parse('2026-03-20T08:00:00.000Z') / 1000,
- email: '[email protected]',
- id: 'contact-external',
- im_bindings: [
- { id: 'binding-external-feishu', provider: 'feishu', scope: 'organization' },
- { id: 'binding-external-slack', provider: 'slack', scope: 'workspace' },
- ],
- name: 'Courtney Henry',
- type: 'external',
-}
-
-const availablePlatformContacts: AvailablePlatformContact[] = [
- {
- avatar_url: null,
- departmentPath: ['Dev Team', 'Mobile Dev', 'Frontend Team'],
- email: '[email protected]',
- id: 'available-platform-ada',
- name: 'Ada Lovelace',
- },
- {
- avatar_url: null,
- departmentPath: ['Dev Team', 'Mobile Dev', 'Backend Team'],
- email: '[email protected]',
- id: 'available-platform-grace',
- name: 'Grace Hopper',
- },
- {
- avatar_url: null,
- departmentPath: ['Dev Team', 'Mobile Dev'],
- email: '[email protected]',
- id: 'available-platform-external',
- name: 'Courtney Henry',
- },
- {
- avatar_url: null,
- departmentPath: ['Dev Team', 'Mobile Dev'],
- email: '[email protected]',
- id: 'available-platform-owner',
- name: 'Ralph Edwards',
- },
-]
-
-const managerPermissions: ContactsPermissions = {
- canManageContacts: true,
- canManageMembers: true,
- canViewContacts: true,
-}
-
-const clone = <T>(value: T): T => structuredClone(value)
-
-function mixedContacts(deployment: ContactsDeployment): ContactView[] {
- if (deployment === 'ee') return clone([workspaceContact, platformContact, externalContact])
-
- return clone([workspaceContact, externalContact])
-}
-
-function paginatedContacts(): ContactView[] {
- const contacts = mixedContacts('ee')
- for (let index = 1; index <= 20; index += 1) {
- contacts.push({
- avatar_url: '',
- created_at: Date.parse('2026-04-01T08:00:00.000Z') / 1000,
- email: `partner-${index}@example.com`,
- id: `contact-partner-${index}`,
- im_bindings: [],
- name: `Partner ${index}`,
- type: 'external',
- })
- }
- return contacts
-}
-
-export function createContactsMockScenario(
- scenario: ContactsMockScenario,
-): ContactsMockScenarioDefinition {
- const base: ContactsMockScenarioDefinition = {
- availablePlatformContacts: clone(availablePlatformContacts),
- contacts: mixedContacts('ee'),
- deployment: 'ee',
- imCentrallyManaged: true,
- failures: {},
- memberContactIds: { 'member-owner': 'contact-owner' },
- permissions: clone(managerPermissions),
- workspaceId: 'workspace-1',
- }
-
- switch (scenario) {
- case ContactsMockScenario.CeMixed:
- return {
- ...base,
- contacts: mixedContacts('ce'),
- deployment: 'ce',
- imCentrallyManaged: false,
- }
- case ContactsMockScenario.SaasMixed:
- return {
- ...base,
- contacts: mixedContacts('saas'),
- deployment: 'saas',
- imCentrallyManaged: false,
- }
- case ContactsMockScenario.Empty:
- return { ...base, contacts: [] }
- case ContactsMockScenario.DirectoryFailure:
- return { ...base, failures: { directory: true } }
- case ContactsMockScenario.NextPageFailure:
- return { ...base, contacts: paginatedContacts(), failures: { nextPage: true } }
- case ContactsMockScenario.Paginated:
- return { ...base, contacts: paginatedContacts() }
- case ContactsMockScenario.ExternalFailure:
- return { ...base, failures: { createExternal: true } }
- case ContactsMockScenario.PlatformContactsFailure:
- return { ...base, failures: { platformContacts: true } }
- case ContactsMockScenario.AddPlatformFailure:
- return { ...base, failures: { addPlatform: true } }
- case ContactsMockScenario.ContactRemovalFailure:
- return { ...base, failures: { contactRemoval: true } }
- case ContactsMockScenario.RemovalFailure:
- return { ...base, failures: { removal: true } }
- case ContactsMockScenario.ReadOnly:
- return {
- ...base,
- permissions: {
- canManageContacts: false,
- canManageMembers: false,
- canViewContacts: true,
- },
- }
- case ContactsMockScenario.NoAccess:
- return {
- ...base,
- permissions: {
- canManageContacts: false,
- canManageMembers: false,
- canViewContacts: false,
- },
- }
- case ContactsMockScenario.EeMixed:
- return base
- }
-}
diff --git a/web/features/contacts/management/__tests__/member-removal-content.spec.tsx b/web/features/contacts/management/__tests__/member-removal-content.spec.tsx
deleted file mode 100644
index 1e185f17319..00000000000
--- a/web/features/contacts/management/__tests__/member-removal-content.spec.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-import type { AccountWithRoleResponse as Member } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ContactsFeatureContextValue } from '../types'
-import { AlertDialog, AlertDialogContent } from '@langgenius/dify-ui/alert-dialog'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { act, render, screen, waitFor } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { useState } from 'react'
-import { ContactsManagementProvider } from '../composition'
-import { useRemoveContactMember } from '../hooks'
-import { MemberRemovalContactImpactContent } from '../member-removal-content'
-import { createContactsMockRepository } from './fixtures/repository'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
-
-const member: Member = {
- avatar: '',
- avatar_url: '',
- created_at: 1731000000,
- email: '[email protected]',
- id: 'member-owner',
- last_active_at: 1731000000,
- last_login_at: 1731000000,
- name: 'Ralph Edwards',
- role: 'admin',
- roles: [],
- status: 'active',
-}
-
-function renderDialog(
- scenarioName: ContactsMockScenario,
- wait?: () => Promise<void>,
- imCentrallyManaged?: boolean,
- capabilityState: Partial<
- Pick<
- ContactsFeatureContextValue,
- 'imCentrallyManaged' | 'imCapabilityError' | 'retryIMCapability'
- >
- > = {},
-) {
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onOpenChange = vi.fn()
- const onRemoved = vi.fn()
- const baseScenario = createContactsMockScenario(scenarioName)
- const scenario = {
- ...baseScenario,
- imCentrallyManaged: imCentrallyManaged ?? baseScenario.imCentrallyManaged,
- }
- const repository = createContactsMockRepository({ scenario, wait })
- const removeMember = vi.spyOn(repository, 'removeMember')
- function RemovalDialog() {
- const removal = useRemoveContactMember()
- const [open, setOpen] = useState(true)
- return (
- <AlertDialog
- open={open}
- onOpenChange={(nextOpen) => {
- onOpenChange(nextOpen)
- setOpen(nextOpen)
- }}
- >
- <AlertDialogContent>
- <MemberRemovalContactImpactContent
- member={member}
- removal={removal}
- onRemoved={() => {
- onRemoved()
- setOpen(false)
- }}
- />
- </AlertDialogContent>
- </AlertDialog>
- )
- }
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementProvider
- context={{
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- workspaceId: scenario.workspaceId,
- ...capabilityState,
- }}
- repository={repository}
- >
- <RemovalDialog />
- </ContactsManagementProvider>
- </QueryClientProvider>,
- )
- return { onOpenChange, onRemoved, removeMember }
-}
-
-describe('MemberRemovalContactImpactContent', () => {
- it('does not allow removal before the binding capability is known', async () => {
- const user = userEvent.setup()
- const { removeMember, onRemoved } = renderDialog(
- ContactsMockScenario.CeMixed,
- undefined,
- undefined,
- {
- imCentrallyManaged: undefined,
- },
- )
- const remove = screen.getByRole('button', { name: 'contacts.memberRemoval.remove' })
-
- expect(remove).toBeDisabled()
- await user.click(remove)
-
- expect(removeMember).not.toHaveBeenCalled()
- expect(onRemoved).not.toHaveBeenCalled()
- })
-
- it('offers retry after a capability failure without submitting a member removal', async () => {
- const user = userEvent.setup()
- const retry = vi.fn()
- const { removeMember, onRemoved } = renderDialog(
- ContactsMockScenario.EeMixed,
- undefined,
- undefined,
- {
- imCentrallyManaged: undefined,
- imCapabilityError: new Error('Features unavailable'),
- retryIMCapability: retry,
- },
- )
-
- expect(screen.getByRole('button', { name: 'contacts.memberRemoval.remove' })).toBeDisabled()
- expect(screen.getByRole('alert')).toHaveTextContent('contacts.directory.errorTitle')
- expect(screen.queryByText('contacts.memberRemoval.failed')).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.action.retry' }))
-
- expect(retry).toHaveBeenCalledOnce()
- expect(removeMember).not.toHaveBeenCalled()
- expect(onRemoved).not.toHaveBeenCalled()
- })
-
- it('defaults EE retention to selected and submits the visible choice', async () => {
- const user = userEvent.setup()
- const { onRemoved, removeMember } = renderDialog(ContactsMockScenario.EeMixed)
- const retention = screen.getByRole('checkbox', {
- name: /contacts\.memberRemoval\.keepPlatform/,
- })
- expect(retention).toBeChecked()
- await user.click(retention)
- expect(retention).not.toBeChecked()
- await user.click(screen.getByRole('button', { name: 'contacts.memberRemoval.remove' }))
-
- await waitFor(() => expect(onRemoved).toHaveBeenCalledOnce())
- await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(removeMember).toHaveBeenCalledWith({ keepAsPlatformContact: false, memberId: member.id })
- })
-
- it('offers retention in Community edition when bindings are centrally managed', async () => {
- const user = userEvent.setup()
- const { removeMember, onRemoved } = renderDialog(ContactsMockScenario.CeMixed, undefined, true)
-
- expect(
- screen.getByRole('checkbox', { name: /contacts\.memberRemoval\.keepPlatform/ }),
- ).toBeChecked()
- expect(screen.getByText('contacts.memberRemoval.eeDescription')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.memberRemoval.remove' }))
-
- await waitFor(() => expect(onRemoved).toHaveBeenCalledOnce())
- expect(removeMember).toHaveBeenCalledWith({ keepAsPlatformContact: true, memberId: member.id })
- })
-
- it('does not retain a platform contact in Enterprise edition when bindings are workspace-managed', async () => {
- const user = userEvent.setup()
- const { removeMember, onRemoved } = renderDialog(ContactsMockScenario.EeMixed, undefined, false)
-
- expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
- expect(screen.getByText('contacts.memberRemoval.standardDescription')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'contacts.memberRemoval.remove' }))
-
- await waitFor(() => expect(onRemoved).toHaveBeenCalledOnce())
- expect(removeMember).toHaveBeenCalledWith({ keepAsPlatformContact: false, memberId: member.id })
- })
-
- it.each([ContactsMockScenario.CeMixed, ContactsMockScenario.SaasMixed])(
- 'does not offer retention in %s',
- (scenario) => {
- renderDialog(scenario)
-
- expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
- expect(screen.getByText('contacts.memberRemoval.standardDescription')).toBeInTheDocument()
- },
- )
-
- it('keeps the dialog and selection after a recoverable failure', async () => {
- const user = userEvent.setup()
- const { onOpenChange, onRemoved } = renderDialog(ContactsMockScenario.RemovalFailure)
- await user.click(screen.getByRole('button', { name: 'contacts.memberRemoval.remove' }))
-
- expect(await screen.findByRole('alert')).toHaveTextContent('contacts.memberRemoval.failed')
- expect(screen.getByRole('checkbox')).toBeChecked()
- expect(onOpenChange).not.toHaveBeenCalled()
- expect(onRemoved).not.toHaveBeenCalled()
- })
-
- it('disables duplicate confirmation while the removal is pending', async () => {
- let resolveRemoval: (() => void) | undefined
- const wait = () =>
- new Promise<void>((resolve) => {
- resolveRemoval = resolve
- })
- const user = userEvent.setup()
- const { onRemoved } = renderDialog(ContactsMockScenario.EeMixed, wait)
- await user.click(screen.getByRole('button', { name: 'contacts.memberRemoval.remove' }))
-
- const pendingButton = screen.getByRole('button', {
- name: 'contacts.memberRemoval.removing',
- })
- expect(pendingButton).toHaveAttribute('aria-disabled', 'true')
- expect(onRemoved).not.toHaveBeenCalled()
- await act(async () => resolveRemoval?.())
- await waitFor(() => expect(onRemoved).toHaveBeenCalledOnce())
- })
-})
diff --git a/web/features/contacts/management/__tests__/mock-repository.spec.ts b/web/features/contacts/management/__tests__/mock-repository.spec.ts
deleted file mode 100644
index a38bb6ecdcf..00000000000
--- a/web/features/contacts/management/__tests__/mock-repository.spec.ts
+++ /dev/null
@@ -1,864 +0,0 @@
-import type { GetContactResponse } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { ContactsManagementRepository } from '../repository'
-import type { ContactsFeatureContextValue } from '../types'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { consoleClient } from '@/service/console'
-import { createContactsApiRepository } from '../repository'
-import { createContactsMockRepository } from './fixtures/repository'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
-
-vi.mock('@/service/console', () => ({
- consoleClient: {
- workspaces: {
- current: {
- humanInput: {
- v2: {
- channels: { get: vi.fn() },
- contacts: {
- get: vi.fn(),
- batch: { get: vi.fn() },
- platform: { post: vi.fn() },
- byContactId: {
- get: vi.fn(),
- imBindings: { put: vi.fn(), delete: vi.fn() },
- imOverride: { put: vi.fn(), delete: vi.fn() },
- },
- external: { post: vi.fn(), byContactId: { patch: vi.fn() } },
- remove: { post: vi.fn() },
- },
- imIdentities: { get: vi.fn() },
- organizationCandidates: { get: vi.fn() },
- },
- },
- },
- },
- },
-}))
-
-function listContacts(repository: ContactsManagementRepository, page = 1) {
- return repository.listContacts({
- deployment: 'ee',
- kind: 'all',
- limit: 20,
- page,
- search: '',
- })
-}
-
-describe('contacts mock repository', () => {
- it('returns generic contacts with backend pagination and timestamp fields', async () => {
- const repository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- const result = await listContacts(repository)
-
- expect(result).toMatchObject({ has_more: false, limit: 20, page: 1, total: 3 })
- expect(result.data.map((contact) => contact.type)).toEqual([
- 'workspace',
- 'platform',
- 'external',
- ])
- expect(result.data.every((contact) => Number.isInteger(contact.created_at))).toBe(true)
- })
-
- it.each([
- ['[email protected]', 'duplicate_external_contact'],
- ['[email protected]', 'matches_workspace_contact'],
- ['[email protected]', 'matches_platform_contact'],
- ] as const)('classifies the full lower-case email match for %s', async (email, resultKind) => {
- const repository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- await expect(
- repository.createExternalContact({
- displayName: 'Conflict',
- email: email.toUpperCase(),
- }),
- ).resolves.toMatchObject({ kind: resultKind })
- })
-
- it('removes CE workspace contacts and converts retained EE contacts with a stable id', async () => {
- const ceRepository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.CeMixed),
- })
- const eeRepository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- await expect(
- ceRepository.removeMember({ keepAsPlatformContact: false, memberId: 'member-owner' }),
- ).resolves.toMatchObject({ contactOutcome: 'removed', kind: 'removed' })
- expect((await listContacts(ceRepository)).data.map((contact) => contact.id)).not.toContain(
- 'contact-owner',
- )
-
- await expect(
- eeRepository.removeMember({ keepAsPlatformContact: true, memberId: 'member-owner' }),
- ).resolves.toMatchObject({
- contactId: 'contact-owner',
- contactOutcome: 'converted_to_platform',
- kind: 'removed',
- })
- expect((await listContacts(eeRepository)).data).toContainEqual(
- expect.objectContaining({ id: 'contact-owner', type: 'platform' }),
- )
- })
-
- it('finds External Contact invite conflicts and upgrades them with a stable id', async () => {
- const repository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- const conflicts = await repository.findExternalContactsByEmails({
- })
-
- expect(conflicts).toEqual([
- expect.objectContaining({
- email: '[email protected]',
- id: 'contact-external',
- name: 'Courtney Henry',
- }),
- ])
-
- await expect(
- repository.upgradeExternalContactsToWorkspace({
- contactIds: conflicts.map((contact) => contact.id),
- }),
- ).resolves.toEqual({ contactIds: ['contact-external'], kind: 'upgraded' })
- expect((await listContacts(repository)).data).toContainEqual(
- expect.objectContaining({
- email: '[email protected]',
- id: 'contact-external',
- name: 'Courtney Henry',
- type: 'workspace',
- }),
- )
- })
-
- it('excludes Workspace and Platform contacts while retaining External conflicts', async () => {
- const repository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- const result = await repository.listAvailablePlatformContacts({
- limit: 20,
- page: 1,
- search: '',
- })
-
- expect(result).toMatchObject({ has_more: false, limit: 20, page: 1, total: 3 })
- expect(result.data.map((contact) => contact.email)).toEqual([
- ])
- })
-
- it('requires confirmation before upgrading an External Contact to Platform with a stable id', async () => {
- const repository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- await expect(
- repository.listAvailablePlatformContacts({ limit: 20, page: 1, search: '' }),
- ).resolves.toEqual(
- expect.objectContaining({
- data: expect.arrayContaining([
- expect.objectContaining({ id: 'available-platform-external' }),
- ]),
- }),
- )
- await expect(
- repository.addPlatformContacts({
- contactIds: ['available-platform-ada', 'available-platform-external'],
- upgradeExternalContacts: false,
- }),
- ).resolves.toEqual({
- conflicts: [
- {
- contactId: 'contact-external',
- email: '[email protected]',
- platformContactId: 'available-platform-external',
- },
- ],
- kind: 'requires_external_contact_upgrade',
- })
- expect((await listContacts(repository)).data).toContainEqual(
- expect.objectContaining({ id: 'contact-external', type: 'external' }),
- )
- expect((await listContacts(repository)).data).not.toContainEqual(
- expect.objectContaining({ id: 'available-platform-ada' }),
- )
-
- await expect(
- repository.addPlatformContacts({
- contactIds: ['available-platform-ada', 'available-platform-external'],
- upgradeExternalContacts: true,
- }),
- ).resolves.toEqual({
- contactIds: ['available-platform-ada', 'contact-external'],
- kind: 'added',
- })
- expect((await listContacts(repository)).data).toContainEqual(
- expect.objectContaining({
- email: '[email protected]',
- id: 'contact-external',
- name: 'Courtney Henry',
- type: 'platform',
- }),
- )
- expect((await listContacts(repository)).data).not.toContainEqual(
- expect.objectContaining({ id: 'available-platform-external' }),
- )
- })
-
- it('removes only Platform and External contacts', async () => {
- const repository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.EeMixed),
- })
-
- await expect(
- repository.removeContacts({
- contactIds: ['contact-owner', 'contact-platform', 'contact-external'],
- }),
- ).resolves.toEqual({
- kind: 'removed',
- removedContactIds: ['contact-platform', 'contact-external'],
- })
- expect((await listContacts(repository)).data).toEqual([
- expect.objectContaining({ id: 'contact-owner', type: 'workspace' }),
- ])
- })
-
- it('uses page metadata and fails only the requested next page', async () => {
- const paginatedRepository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.Paginated),
- })
- const firstPage = await listContacts(paginatedRepository)
- const secondPage = await listContacts(paginatedRepository, 2)
-
- expect(firstPage).toMatchObject({ has_more: true, limit: 20, page: 1, total: 23 })
- expect(firstPage.data).toHaveLength(20)
- expect(secondPage).toMatchObject({ has_more: false, limit: 20, page: 2, total: 23 })
- expect(secondPage.data).toHaveLength(3)
-
- const failingRepository = createContactsMockRepository({
- scenario: createContactsMockScenario(ContactsMockScenario.NextPageFailure),
- })
- await expect(listContacts(failingRepository, 2)).rejects.toThrow('contacts_next_page_failed')
- })
-})
-
-describe('Enterprise Platform contact API repository', () => {
- const client = consoleClient.workspaces.current.humanInput.v2
- const context: ContactsFeatureContextValue = {
- deployment: 'ee',
- imCentrallyManaged: true,
- workspaceId: 'workspace-ee',
- permissions: { canViewContacts: true, canManageContacts: true, canManageMembers: true },
- }
- const candidate = { id: 'candidate-1', name: 'Platform Member', email: '[email protected]' }
- const query = { search: ' member ', page: 2, limit: 20 }
- const command = { contactIds: [candidate.id], upgradeExternalContacts: false }
-
- beforeEach(() => vi.resetAllMocks())
-
- it.each(['ce', 'saas'] as const)(
- 'queries and imports Platform contacts on %s when centrally managed',
- async (deployment) => {
- vi.mocked(client.organizationCandidates.get).mockResolvedValue({
- data: [candidate],
- page: 1,
- limit: 20,
- total: 1,
- })
- vi.mocked(client.contacts.batch.get).mockResolvedValue({ data: [] })
- vi.mocked(client.contacts.platform.post).mockResolvedValue({
- data: [{ ...candidate, type: 'platform', avatar_url: '', created_at: 1 }],
- })
- const repository = createContactsApiRepository(client, { ...context, deployment })
-
- await expect(repository.listAvailablePlatformContacts(query)).resolves.toMatchObject({
- data: [{ ...candidate, avatar_url: null }],
- })
- await expect(repository.addPlatformContacts(command)).resolves.toEqual({
- kind: 'added',
- contactIds: [candidate.id],
- })
- expect(client.contacts.platform.post).toHaveBeenCalledWith(
- { body: { candidate_ids: [candidate.id] } },
- { context: { silent: true } },
- )
- },
- )
-
- it('excludes existing contacts per server page without losing the next page when all candidates already exist', async () => {
- vi.mocked(client.organizationCandidates.get).mockResolvedValue({
- data: [candidate],
- page: 2,
- limit: 20,
- total: 41,
- })
- vi.mocked(client.contacts.batch.get).mockResolvedValue({
- data: [{ id: candidate.id, name: candidate.name, avatar_url: '', created_at: 1 }],
- })
- const repository = createContactsApiRepository(client, context)
- expect(repository.supportsPlatformImport).toBe(true)
- await expect(repository.listAvailablePlatformContacts(query)).resolves.toEqual({
- data: [],
- page: 2,
- limit: 20,
- total: 41,
- has_more: true,
- })
- expect(client.organizationCandidates.get).toHaveBeenCalledWith(
- { query: { keyword: 'member', page: 2, limit: 20 } },
- { context: { silent: true } },
- )
- expect(client.contacts.batch.get).toHaveBeenCalledWith(
- { query: { contact_ids: [candidate.id] } },
- { context: { silent: true } },
- )
- vi.mocked(client.organizationCandidates.get).mockResolvedValue({
- data: [candidate],
- page: 3,
- limit: 20,
- total: 41,
- })
- vi.mocked(client.contacts.batch.get).mockResolvedValue({ data: [] })
- await expect(
- repository.listAvailablePlatformContacts({ ...query, search: ' ', page: 3 }),
- ).resolves.toEqual({
- data: [{ ...candidate, avatar_url: null }],
- page: 3,
- limit: 20,
- total: 41,
- has_more: false,
- })
- expect(client.organizationCandidates.get).toHaveBeenLastCalledWith(
- { query: { keyword: undefined, page: 3, limit: 20 } },
- { context: { silent: true } },
- )
- })
-
- it('preserves candidate and membership lookup failures instead of showing unverified available contacts', async () => {
- const failure = new Error('offline')
- const repository = createContactsApiRepository(client, context)
- vi.mocked(client.organizationCandidates.get).mockRejectedValueOnce(failure)
- await expect(repository.listAvailablePlatformContacts(query)).rejects.toBe(failure)
- expect(client.contacts.batch.get).not.toHaveBeenCalled()
- vi.mocked(client.organizationCandidates.get).mockResolvedValue({
- data: [candidate],
- page: 1,
- limit: 20,
- total: 1,
- })
- vi.mocked(client.contacts.batch.get).mockRejectedValueOnce(failure)
- await expect(repository.listAvailablePlatformContacts(query)).rejects.toBe(failure)
- vi.mocked(client.organizationCandidates.get).mockResolvedValue({
- data: [],
- page: 1,
- limit: 20,
- total: 0,
- })
- await expect(repository.listAvailablePlatformContacts(query)).resolves.toMatchObject({
- data: [],
- has_more: false,
- })
- expect(client.contacts.batch.get).toHaveBeenCalledTimes(1)
- })
-
- it.each<ContactsFeatureContextValue | undefined>([
- undefined,
- { ...context, imCentrallyManaged: undefined },
- { ...context, imCentrallyManaged: false },
- { ...context, workspaceId: '' },
- { ...context, permissions: { ...context.permissions, canManageContacts: false } },
- ])(
- 'never requests Platform APIs without centrally managed import access',
- async (unavailableContext) => {
- const repository = createContactsApiRepository(client, unavailableContext)
- expect(repository.supportsPlatformImport).toBe(false)
- await expect(repository.listAvailablePlatformContacts(query)).rejects.toThrow('not available')
- await expect(repository.addPlatformContacts(command)).resolves.toEqual({ kind: 'forbidden' })
- expect(client.organizationCandidates.get).not.toHaveBeenCalled()
- expect(client.contacts.platform.post).not.toHaveBeenCalled()
- },
- )
-
- it('imports only candidate IDs and returns the server-confirmed contacts without claiming an External upgrade', async () => {
- vi.mocked(client.contacts.platform.post).mockResolvedValue({
- data: [{ ...candidate, type: 'platform', avatar_url: '', created_at: 1 }],
- })
- const repository = createContactsApiRepository(client, context)
- expect(repository.supportsExternalContactUpgrade).toBe(false)
- await expect(
- repository.addPlatformContacts({ ...command, contactIds: [candidate.id, candidate.id] }),
- ).resolves.toEqual({
- kind: 'added',
- contactIds: [candidate.id],
- })
- expect(client.contacts.platform.post).toHaveBeenCalledWith(
- { body: { candidate_ids: [candidate.id] } },
- { context: { silent: true } },
- )
- await expect(
- repository.addPlatformContacts({ ...command, upgradeExternalContacts: true }),
- ).resolves.toEqual({ kind: 'external_upgrade_unsupported' })
- await expect(repository.addPlatformContacts({ ...command, contactIds: [] })).resolves.toEqual({
- kind: 'failed',
- })
- expect(client.contacts.platform.post).toHaveBeenCalledTimes(1)
- })
-
- it.each([
- [403, 'forbidden'],
- [409, 'conflict'],
- [422, 'failed'],
- [503, 'failed'],
- ] as const)(
- 'keeps HTTP %s as a failed import without fabricated contacts or upgrade metadata',
- async (status, kind) => {
- vi.mocked(client.contacts.platform.post).mockRejectedValue(
- Object.assign(new Error('server details'), { status }),
- )
- await expect(
- createContactsApiRepository(client, context).addPlatformContacts(command),
- ).resolves.toEqual({ kind })
- },
- )
-
- it('does not report success when the response confirms no contacts', async () => {
- vi.mocked(client.contacts.platform.post).mockResolvedValue({ data: [] })
- await expect(
- createContactsApiRepository(client, context).addPlatformContacts(command),
- ).resolves.toEqual({ kind: 'failed' })
- })
-})
-
-describe('contacts API repository', () => {
- const contacts = consoleClient.workspaces.current.humanInput.v2.contacts
- const externalContact = {
- avatar_url: '',
- created_at: 1_778_000_000,
- id: 'contact-api-external',
- name: 'API Partner',
- type: 'external' as const,
- }
-
- beforeEach(() => {
- vi.resetAllMocks()
- })
-
- it('maps directory filters and pagination to the generated endpoint and preserves server metadata', async () => {
- vi.mocked(contacts.get).mockResolvedValue({
- data: [externalContact],
- limit: 2,
- page: 2,
- total: 3,
- })
- const repository = createContactsApiRepository()
-
- const result = await repository.listContacts({
- deployment: 'ee',
- kind: 'external',
- limit: 2,
- page: 2,
- search: 'Partner',
- })
-
- expect(vi.mocked(contacts.get).mock.calls[0]?.[0]).toEqual({
- query: { group: 'external', keyword: 'Partner', limit: 2, page: 2 },
- })
- expect(result).toEqual({
- data: [{ ...externalContact, avatar_url: '', email: null, im_bindings: [] }],
- has_more: false,
- limit: 2,
- page: 2,
- total: 3,
- })
- })
-
- it('derives another page from total and omits an all-types filter from the API query', async () => {
- vi.mocked(contacts.get).mockResolvedValue({
- data: [externalContact],
- limit: 1,
- page: 1,
- total: 2,
- })
- const repository = createContactsApiRepository()
-
- const result = await repository.listContacts({
- deployment: 'ce',
- kind: 'all',
- limit: 1,
- page: 1,
- search: '',
- })
-
- expect(result.has_more).toBe(true)
- expect(vi.mocked(contacts.get).mock.calls[0]?.[0]?.query?.group).toBeUndefined()
- })
-
- it('fetches details independently and distinguishes not-found from an unavailable API', async () => {
- const repository = createContactsApiRepository()
- vi.mocked(contacts.byContactId.get).mockResolvedValueOnce({
- contact: externalContact,
- im_binding_details: [],
- })
-
- await expect(repository.getContact(externalContact.id)).resolves.toEqual({
- ...externalContact,
- avatar_url: '',
- email: null,
- im_binding_details: [],
- im_bindings: [],
- })
- expect(vi.mocked(contacts.byContactId.get).mock.calls[0]?.[0]).toEqual({
- params: { contact_id: externalContact.id },
- })
- expect(contacts.get).not.toHaveBeenCalled()
-
- vi.mocked(contacts.byContactId.get).mockRejectedValueOnce(
- Object.assign(new Error('Not found'), { status: 404 }),
- )
- await expect(repository.getContact('deleted-contact')).resolves.toBeNull()
- const unavailable = Object.assign(new Error('API unavailable'), { status: 503 })
- vi.mocked(contacts.byContactId.get).mockRejectedValueOnce(unavailable)
- await expect(repository.getContact(externalContact.id)).rejects.toBe(unavailable)
- })
-
- it('preserves complete IM binding details from the generated contact endpoint', async () => {
- const bindingDetails: GetContactResponse['im_binding_details'] = [
- {
- id: 'binding-feishu',
- provider: 'feishu',
- scope: 'workspace',
- identity: {
- id: 'identity-feishu',
- display_name: 'Feishu Member',
- email: '[email protected]',
- provider_user_id: 'feishu-user',
- },
- },
- {
- id: 'binding-slack',
- provider: 'slack',
- scope: 'organization',
- identity: {
- id: 'identity-slack',
- display_name: null,
- email: null,
- provider_user_id: 'slack-user',
- },
- },
- ]
- const contact = {
- ...externalContact,
- type: 'workspace' as const,
- im_bindings: bindingDetails.map(({ id, provider, scope }) => ({ id, provider, scope })),
- }
- vi.mocked(contacts.byContactId.get).mockResolvedValue({
- contact,
- im_binding_details: bindingDetails,
- })
-
- await expect(createContactsApiRepository().getContact(contact.id)).resolves.toEqual({
- ...contact,
- email: null,
- im_binding_details: bindingDetails,
- })
- })
-
- it('sends backend field names for creation and editing and returns the server contact ID', async () => {
- const repository = createContactsApiRepository()
- vi.mocked(contacts.external.post).mockResolvedValueOnce({
- contact: externalContact,
- })
- vi.mocked(contacts.external.byContactId.patch).mockResolvedValueOnce({
- contact: externalContact,
- })
- const command = { displayName: 'API Partner', email: '[email protected]' }
-
- await expect(repository.createExternalContact(command)).resolves.toEqual({
- contactId: externalContact.id,
- kind: 'created',
- })
- expect(vi.mocked(contacts.external.post).mock.calls[0]?.[0]).toEqual({
- body: { name: command.displayName, email: command.email },
- })
- expect(vi.mocked(contacts.external.post).mock.calls[0]?.[0].body).not.toHaveProperty('avatar')
- await expect(
- repository.updateExternalContact({ ...command, contactId: externalContact.id }),
- ).resolves.toEqual({
- contactId: externalContact.id,
- kind: 'updated',
- })
- expect(vi.mocked(contacts.external.byContactId.patch).mock.calls[0]?.[0]).toEqual({
- body: { name: command.displayName, email: command.email },
- params: { contact_id: externalContact.id },
- })
- expect(
- vi.mocked(contacts.external.byContactId.patch).mock.calls[0]?.[0].body,
- ).not.toHaveProperty('avatar')
- })
-
- it.each([
- ['uploaded file ID', '00000000-0000-4000-8000-000000000001'],
- ['empty reset value', ''],
- ])('forwards the avatar %s when creating or updating a contact', async (_label, avatar) => {
- const repository = createContactsApiRepository()
- vi.mocked(contacts.external.post).mockResolvedValueOnce({
- contact: externalContact,
- })
- vi.mocked(contacts.external.byContactId.patch).mockResolvedValueOnce({
- contact: externalContact,
- })
- const command = { displayName: 'API Partner', email: '[email protected]', avatar }
-
- await repository.createExternalContact(command)
- await repository.updateExternalContact({ ...command, contactId: externalContact.id })
-
- expect(vi.mocked(contacts.external.post).mock.calls[0]?.[0].body).toEqual({
- name: command.displayName,
- email: command.email,
- avatar,
- })
- expect(vi.mocked(contacts.external.byContactId.patch).mock.calls[0]?.[0].body).toEqual({
- name: command.displayName,
- email: command.email,
- avatar,
- })
- })
-
- it('returns only IDs confirmed by the server after a batch removal', async () => {
- const repository = createContactsApiRepository()
- vi.mocked(contacts.remove.post).mockResolvedValueOnce({
- removed_contact_ids: [externalContact.id],
- })
-
- await expect(
- repository.removeContacts({ contactIds: [externalContact.id, 'other-contact'] }),
- ).resolves.toEqual({
- kind: 'removed',
- removedContactIds: [externalContact.id],
- })
- expect(vi.mocked(contacts.remove.post).mock.calls[0]?.[0]).toEqual({
- body: { contact_ids: [externalContact.id, 'other-contact'] },
- })
- })
-
- it('does not replace failed API reads or writes with mock data or successful mutations', async () => {
- const repository = createContactsApiRepository()
- const failure = Object.assign(new Error('API unavailable'), { status: 503 })
- vi.mocked(contacts.get).mockRejectedValueOnce(failure)
- vi.mocked(contacts.external.post).mockRejectedValueOnce(failure)
- vi.mocked(contacts.external.byContactId.patch).mockRejectedValueOnce(failure)
- vi.mocked(contacts.remove.post).mockRejectedValueOnce(failure)
-
- await expect(listContacts(repository)).rejects.toBe(failure)
- await expect(
- repository.createExternalContact({ displayName: 'Partner', email: '[email protected]' }),
- ).resolves.toEqual({ kind: 'failed' })
- await expect(
- repository.updateExternalContact({
- contactId: externalContact.id,
- displayName: 'Partner',
- email: '[email protected]',
- }),
- ).resolves.toEqual({ kind: 'failed' })
- await expect(repository.removeContacts({ contactIds: [externalContact.id] })).resolves.toEqual({
- kind: 'failed',
- })
- })
-
- it('shows the conflict outcome without inventing an ID absent from a 409 response', async () => {
- const repository = createContactsApiRepository()
- const conflict = Object.assign(new Error('Contact already exists'), { status: 409 })
- vi.mocked(contacts.external.post).mockRejectedValueOnce(conflict)
- vi.mocked(contacts.external.byContactId.patch).mockRejectedValueOnce(conflict)
- const command = { displayName: 'Partner', email: '[email protected]' }
-
- await expect(repository.createExternalContact(command)).resolves.toEqual({
- kind: 'duplicate_external_contact',
- })
- await expect(
- repository.updateExternalContact({ ...command, contactId: externalContact.id }),
- ).resolves.toEqual({ kind: 'duplicate_external_contact' })
- })
-})
-
-describe('contacts IM API repository', () => {
- const client = consoleClient.workspaces.current.humanInput.v2
- const contact = {
- avatar_url: '',
- id: 'contact-workspace',
- name: 'Member',
- type: 'workspace' as const,
- created_at: 1,
- im_bindings: [{ id: 'binding-1', provider: 'feishu' as const, scope: 'organization' as const }],
- }
- beforeEach(() => vi.resetAllMocks())
-
- it('reads configured IM channels without exposing email channels or application identifiers as identities', async () => {
- const channelClient = consoleClient.workspaces.current.humanInput.v2.channels
- const base = {
- config_version: 'version-1',
- created_at: 1,
- display_identifier: 'app-identifier',
- status: 'configured' as const,
- status_description: '',
- updated_at: 1,
- webhook_url: null,
- }
- vi.mocked(channelClient.get).mockResolvedValue({
- channels: [
- { ...base, id: 'email-channel', kind: 'email', provider: 'resend' },
- { ...base, id: 'slack-channel', kind: 'im', provider: 'slack' },
- ],
- })
-
- const repository = createContactsApiRepository()
-
- await expect(repository.listIMChannels?.()).resolves.toEqual([
- { id: 'slack-channel', provider: 'slack' },
- ])
- expect(channelClient.get).toHaveBeenCalledWith(undefined, { context: { silent: true } })
- })
-
- it('searches synced identities with server pagination and preserves binding status', async () => {
- const identity = {
- id: 'identity-1',
- provider: 'feishu' as const,
- provider_user_id: 'user-1',
- binding_status: 'bound' as const,
- }
- vi.mocked(client.imIdentities.get).mockResolvedValue({
- data: [identity],
- page: 2,
- limit: 20,
- total: 21,
- })
- const result = await createContactsApiRepository().listIMIdentities({
- search: ' Member ',
- page: 2,
- limit: 20,
- })
- expect(client.imIdentities.get).toHaveBeenCalledWith(
- { query: { keyword: 'Member', page: 2, limit: 20 } },
- { context: { silent: true } },
- )
- expect(result).toMatchObject({ data: [identity], has_more: false })
- })
-
- it('uses identity IDs for default bindings and workspace overrides', async () => {
- vi.mocked(client.contacts.byContactId.imBindings.put).mockResolvedValue({ contact })
- vi.mocked(client.contacts.byContactId.imOverride.put).mockResolvedValue({ contact })
- const repository = createContactsApiRepository()
- await repository.setIMBinding({
- contactId: contact.id,
- identityId: 'identity-1',
- override: false,
- })
- await repository.setIMBinding({
- contactId: contact.id,
- identityId: 'identity-2',
- override: true,
- })
- expect(client.contacts.byContactId.imBindings.put).toHaveBeenCalledWith(
- { params: { contact_id: contact.id }, body: { identity_id: 'identity-1' } },
- { context: { silent: true } },
- )
- expect(client.contacts.byContactId.imOverride.put).toHaveBeenCalledWith(
- { params: { contact_id: contact.id }, body: { identity_id: 'identity-2' } },
- { context: { silent: true } },
- )
- })
-
- it('deletes default bindings and resets workspace overrides by contact ID through their own endpoints', async () => {
- vi.mocked(client.contacts.byContactId.imBindings.delete).mockResolvedValue({})
- vi.mocked(client.contacts.byContactId.imOverride.delete).mockResolvedValue({ contact })
- const repository = createContactsApiRepository()
- await repository.removeIMBinding({ contactId: contact.id, binding: contact.im_bindings[0]! })
- await repository.removeIMBinding({
- contactId: contact.id,
- binding: { ...contact.im_bindings[0]!, scope: 'workspace' },
- })
- expect(client.contacts.byContactId.imBindings.delete).toHaveBeenCalledWith(
- { params: { contact_id: contact.id } },
- { context: { silent: true } },
- )
- expect(client.contacts.byContactId.imOverride.delete).toHaveBeenCalledWith(
- { params: { contact_id: contact.id } },
- { context: { silent: true } },
- )
- })
-
- it('unbinds the contact default binding without requiring an effective binding ID', async () => {
- vi.mocked(client.contacts.byContactId.imBindings.delete).mockResolvedValue({})
-
- await createContactsApiRepository().unbindIMBinding({
- contactId: contact.id,
- })
-
- expect(client.contacts.byContactId.imBindings.delete).toHaveBeenCalledExactlyOnceWith(
- {
- params: { contact_id: contact.id },
- },
- { context: { silent: true } },
- )
- expect(client.contacts.byContactId.imOverride.delete).not.toHaveBeenCalled()
- expect(client.contacts.byContactId.imBindings.put).not.toHaveBeenCalled()
- expect(client.contacts.byContactId.imOverride.put).not.toHaveBeenCalled()
- })
-
- it.each([
- {
- error: new Response(JSON.stringify({ code: 'im_binding_not_found' }), { status: 404 }),
- code: 'im_binding_not_found',
- },
- {
- error: { data: { body: { code: 'im_write_unavailable', status: 503 } } },
- code: 'im_write_unavailable',
- },
- { error: new Error('Network unavailable'), code: 'im_binding_failed' },
- ])(
- 'normalizes an explicit unbind failure as $code without resetting an override',
- async ({ error, code }) => {
- vi.mocked(client.contacts.byContactId.imBindings.delete).mockRejectedValue(error)
-
- await expect(
- createContactsApiRepository().unbindIMBinding({
- contactId: contact.id,
- }),
- ).rejects.toMatchObject({ code })
-
- expect(client.contacts.byContactId.imBindings.delete).toHaveBeenCalledExactlyOnceWith(
- {
- params: { contact_id: contact.id },
- },
- { context: { silent: true } },
- )
- expect(client.contacts.byContactId.imOverride.delete).not.toHaveBeenCalled()
- },
- )
-
- it('preserves missing-channel and binding-conflict errors without returning success', async () => {
- const repository = createContactsApiRepository()
- vi.mocked(client.imIdentities.get).mockRejectedValue(
- new Response(JSON.stringify({ code: 'im_integration_not_configured' }), { status: 404 }),
- )
- await expect(
- repository.listIMIdentities({ search: '', page: 1, limit: 20 }),
- ).rejects.toMatchObject({ code: 'im_integration_not_configured' })
- vi.mocked(client.contacts.byContactId.imOverride.put).mockRejectedValue({
- data: { body: { code: 'im_binding_conflict', status: 409 } },
- })
- await expect(
- repository.setIMBinding({ contactId: contact.id, identityId: 'identity-1', override: true }),
- ).rejects.toMatchObject({ code: 'im_binding_conflict' })
- })
-})
diff --git a/web/features/contacts/management/__tests__/platform-contact-picker-dialog.spec.tsx b/web/features/contacts/management/__tests__/platform-contact-picker-dialog.spec.tsx
index 523d1ec1c91..7bccc872ff1 100644
--- a/web/features/contacts/management/__tests__/platform-contact-picker-dialog.spec.tsx
+++ b/web/features/contacts/management/__tests__/platform-contact-picker-dialog.spec.tsx
@@ -1,301 +1,269 @@
-import type { ContactsManagementRepository } from '../repository'
-import type { ContactsFeatureContextValue } from '../types'
+import type { OrganizationCandidate } from '@dify/contracts/api/console/workspaces/types.gen'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { act, render, screen, waitFor, within } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { consoleQuery } from '@/service/console'
+import { useState } from 'react'
+import { createDeferred } from '@/test/deferred'
import { ContactsManagementProvider } from '../composition'
import { PlatformContactPickerDialog } from '../platform-contact-picker-dialog'
-import { ContactsManagementMockProvider } from './fixtures/composition'
-import { createContactsMockRepository } from './fixtures/repository'
-import { ContactsMockScenario, createContactsMockScenario } from './fixtures/scenarios'
+import { alice, managerContext } from './fixtures/data'
-describe('PlatformContactPickerDialog', () => {
- it('asks before upgrading an External Contact and keeps the selection after cancellation', async () => {
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onOpenChange = vi.fn()
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementMockProvider
- scenario={createContactsMockScenario(ContactsMockScenario.EeMixed)}
- >
- <PlatformContactPickerDialog open onOpenChange={onOpenChange} />
- </ContactsManagementMockProvider>
- </QueryClientProvider>,
- )
-
- const user = userEvent.setup()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- const option = await within(picker).findByRole('checkbox', { name: /Courtney Henry/ })
- await user.click(option)
- await user.click(within(picker).getByRole('button', { name: 'contacts.platformPicker.add' }))
-
- const confirmation = await screen.findByRole('alertdialog', {
- name: /contacts\.platformPicker\.upgrade\.title/i,
- })
- expect(onOpenChange).not.toHaveBeenCalled()
- await user.click(within(confirmation).getByRole('button', { name: 'contacts.action.cancel' }))
-
- await waitFor(() => {
- expect(
- screen.queryByRole('alertdialog', {
- name: /contacts\.platformPicker\.upgrade\.title/i,
- }),
- ).not.toBeInTheDocument()
- })
- expect(option).toBeChecked()
- expect(onOpenChange).not.toHaveBeenCalled()
+const api = vi.hoisted(() => ({ candidates: vi.fn(), existing: vi.fn(), add: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.humanInput.v2.organizationCandidates.get': api.candidates,
+ 'workspaces.current.humanInput.v2.contacts.batch.get': api.existing,
+ 'workspaces.current.humanInput.v2.contacts.platform.post': api.add,
+ }),
+ }
+})
+const candidate: OrganizationCandidate = { id: alice.id, name: alice.name, email: alice.email! }
+function setup() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
})
-
- it('adds and upgrades the selected External Contact after confirmation', async () => {
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onOpenChange = vi.fn()
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementMockProvider
- scenario={createContactsMockScenario(ContactsMockScenario.EeMixed)}
- >
- <PlatformContactPickerDialog open onOpenChange={onOpenChange} />
- </ContactsManagementMockProvider>
- </QueryClientProvider>,
- )
-
- const user = userEvent.setup()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- await user.click(await within(picker).findByRole('checkbox', { name: /Courtney Henry/ }))
- await user.click(within(picker).getByRole('button', { name: 'contacts.platformPicker.add' }))
-
- const confirmation = await screen.findByRole('alertdialog', {
- name: /contacts\.platformPicker\.upgrade\.title/i,
- })
- await user.click(
- within(confirmation).getByRole('button', {
- name: 'contacts.platformPicker.upgrade.confirm',
- }),
+ function Host() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Open picker
+ </button>
+ <PlatformContactPickerDialog open={open} onOpenChange={setOpen} />
+ </>
)
+ }
+ const content = (workspaceId: string) => (
+ <QueryClientProvider client={queryClient}>
+ <ContactsManagementProvider
+ context={{ ...managerContext, workspaceId, imCentrallyManaged: true }}
+ >
+ <Host />
+ </ContactsManagementProvider>
+ </QueryClientProvider>
+ )
+ const view = render(content(managerContext.workspaceId))
+ return (workspaceId: string) => view.rerender(content(workspaceId))
+}
+async function open(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(screen.getByRole('button', { name: 'Open picker' }))
+ return screen.findByRole('dialog')
+}
+beforeEach(() => {
+ api.candidates.mockReset().mockResolvedValue({ data: [candidate], page: 1, limit: 100, total: 1 })
+ api.existing.mockReset().mockResolvedValue({ data: [] })
+ api.add.mockReset().mockResolvedValue({ data: [{ ...alice, type: 'platform' }] })
+})
- await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
- })
-
- it('keeps selection visible and prevents duplicate add while pending', async () => {
- const waits: Array<() => void> = []
- const wait = () =>
- new Promise<void>((resolve) => {
- waits.push(resolve)
- })
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onOpenChange = vi.fn()
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementMockProvider
- scenario={createContactsMockScenario(ContactsMockScenario.EeMixed)}
- wait={wait}
- >
- <PlatformContactPickerDialog open onOpenChange={onOpenChange} />
- </ContactsManagementMockProvider>
- </QueryClientProvider>,
- )
+it('opens with a visible close control and an always-available Cancel action', async () => {
+ const user = userEvent.setup()
+ setup()
+ await open(user)
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'contacts.action.close' })).toHaveFocus(),
+ )
+ expect(screen.getByRole('button', { name: 'contacts.action.cancel' })).toBeVisible()
+})
- await waitFor(() => expect(waits).toHaveLength(1))
- await act(async () => waits.shift()?.())
- const user = userEvent.setup()
- const dialog = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- const option = await within(dialog).findByRole('checkbox', { name: /Ada Lovelace/ })
- await user.click(option)
- await user.click(within(dialog).getByRole('button', { name: 'contacts.platformPicker.add' }))
- await waitFor(() => expect(waits).toHaveLength(1))
+it('automatically skips imported pages and stops when a selectable contact is found', async () => {
+ const user = userEvent.setup()
+ const next: OrganizationCandidate = { ...candidate, id: 'next-candidate', name: 'Next available' }
+ api.candidates.mockImplementation(async ({ query }: { query: { page: number } }) => ({
+ data: query.page < 3 ? [{ ...candidate, id: `imported-${query.page}` }] : [next],
+ page: query.page,
+ limit: 100,
+ total: 301,
+ }))
+ api.existing.mockImplementation(async ({ query }: { query: { contact_ids: string[] } }) => ({
+ data: query.contact_ids[0]?.startsWith('imported-')
+ ? [{ id: query.contact_ids[0], name: candidate.name, created_at: alice.created_at }]
+ : [],
+ }))
+ setup()
+ await open(user)
+ expect(await screen.findByText('Next available')).toBeInTheDocument()
+ expect(api.candidates.mock.calls.map(([input]) => input.query.page)).toEqual([1, 2, 3])
+ expect(api.existing).toHaveBeenCalledTimes(3)
+ expect(screen.getByRole('button', { name: 'contacts.action.loadMore' })).toBeVisible()
+})
- expect(option).toBeChecked()
- expect(
- within(dialog).getByRole('button', { name: 'contacts.platformPicker.adding' }),
- ).toHaveAttribute('aria-disabled', 'true')
- expect(onOpenChange).not.toHaveBeenCalled()
- await act(async () => waits.shift()?.())
- await waitFor(() => expect(waits).toHaveLength(1))
- await act(async () => waits.shift()?.())
- await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
- })
+it('finishes with an empty state after every remaining candidate was already imported', async () => {
+ const user = userEvent.setup()
+ api.candidates.mockImplementation(async ({ query }: { query: { page: number } }) => ({
+ data: [{ ...candidate, id: `imported-${query.page}` }],
+ page: query.page,
+ limit: 100,
+ total: 101,
+ }))
+ api.existing.mockImplementation(async ({ query }: { query: { contact_ids: string[] } }) => ({
+ data: query.contact_ids.map((id) => ({
+ id,
+ name: candidate.name,
+ created_at: alice.created_at,
+ })),
+ }))
+ setup()
+ await open(user)
+ expect(await screen.findByText('contacts.platformPicker.empty')).toBeInTheDocument()
+ expect(api.candidates.mock.calls.map(([input]) => input.query.page)).toEqual([1, 2])
+ expect(screen.queryByRole('button', { name: 'contacts.action.loadMore' })).not.toBeInTheDocument()
})
-describe('Enterprise Platform contact import', () => {
- const candidate = {
- id: 'candidate-1',
- name: 'Platform Member',
- email: '[email protected]',
- avatar_url: null,
- }
- function setup(overrides: Partial<ContactsFeatureContextValue> = {}) {
- const scenario = createContactsMockScenario(ContactsMockScenario.EeMixed)
- const context = {
- workspaceId: scenario.workspaceId,
- deployment: scenario.deployment,
- imCentrallyManaged: scenario.imCentrallyManaged,
- permissions: scenario.permissions,
- ...overrides,
- }
- const listAvailablePlatformContacts = vi
- .fn<ContactsManagementRepository['listAvailablePlatformContacts']>()
- .mockResolvedValue({
- data: [candidate],
- page: 1,
- limit: 20,
- total: 1,
- has_more: false,
- })
- const addPlatformContacts = vi
- .fn<ContactsManagementRepository['addPlatformContacts']>()
- .mockResolvedValue({ kind: 'added', contactIds: [candidate.id] })
- const repository = {
- ...createContactsMockRepository({ scenario }),
- supportsPlatformImport: true,
- supportsExternalContactUpgrade: false,
- listAvailablePlatformContacts,
- addPlatformContacts,
+it('retries a failed continuation without discarding the already cached imported page', async () => {
+ const user = userEvent.setup()
+ let fail = true
+ api.candidates.mockImplementation(async ({ query }: { query: { page: number } }) => {
+ if (query.page === 2 && fail) {
+ fail = false
+ throw new Error('Temporary candidate failure')
}
- const queryClient = new QueryClient({
- defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
- })
- const onOpenChange = vi.fn()
- const renderPicker = () =>
- render(
- <QueryClientProvider client={queryClient}>
- <ContactsManagementProvider context={context} repository={repository}>
- <PlatformContactPickerDialog open onOpenChange={onOpenChange} />
- </ContactsManagementProvider>
- </QueryClientProvider>,
- )
return {
- context,
- listAvailablePlatformContacts,
- addPlatformContacts,
- queryClient,
- onOpenChange,
- renderPicker,
+ data: query.page === 1 ? [candidate] : [{ ...candidate, id: 'next', name: 'Recovered' }],
+ page: query.page,
+ limit: 100,
+ total: 101,
}
- }
+ })
+ api.existing.mockImplementation(async ({ query }: { query: { contact_ids: string[] } }) => ({
+ data: query.contact_ids.includes(candidate.id)
+ ? [{ id: candidate.id, name: candidate.name, created_at: alice.created_at }]
+ : [],
+ }))
+ setup()
+ await open(user)
+ expect(await screen.findByRole('alert')).toHaveTextContent('contacts.platformPicker.error')
+ await user.click(screen.getByRole('button', { name: 'contacts.action.retry' }))
+ expect(await screen.findByText('Recovered')).toBeVisible()
+ expect(api.candidates.mock.calls.map(([input]) => input.query.page)).toEqual([1, 2, 2])
+})
- it.each(['ce', 'saas'] as const)(
- 'queries and imports Platform contacts on %s when centrally managed',
- async (deployment) => {
- const { addPlatformContacts, onOpenChange, renderPicker } = setup({ deployment })
- renderPicker()
- const user = userEvent.setup()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- await user.click(await within(picker).findByRole('checkbox', { name: /Platform Member/ }))
- await user.click(within(picker).getByRole('button', { name: 'contacts.platformPicker.add' }))
+it('does not treat a failed existing-contact lookup as an empty imported page', async () => {
+ const user = userEvent.setup()
+ api.candidates.mockResolvedValue({ data: [candidate], page: 1, limit: 100, total: 101 })
+ api.existing.mockRejectedValueOnce(new Error('Lookup unavailable'))
+ setup()
+ await open(user)
+ expect(await screen.findByRole('alert')).toHaveTextContent('contacts.platformPicker.error')
+ expect(api.candidates).toHaveBeenCalledTimes(1)
+ expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'contacts.action.retry' }))
+ expect(await screen.findByRole('checkbox', { name: /selectContact.*Alice/ })).toBeVisible()
+})
- await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
- expect(addPlatformContacts).toHaveBeenCalledWith({
- contactIds: [candidate.id],
- upgradeExternalContacts: false,
- })
- },
+it('stops instead of looping when a continuation repeats a previous server page', async () => {
+ const user = userEvent.setup()
+ api.candidates.mockResolvedValue({ data: [candidate], page: 1, limit: 100, total: 101 })
+ api.existing.mockResolvedValue({
+ data: [{ id: candidate.id, name: candidate.name, created_at: alice.created_at }],
+ })
+ setup()
+ await open(user)
+ expect(await screen.findByRole('alert')).toHaveTextContent('contacts.platformPicker.error')
+ expect(api.candidates.mock.calls.map(([input]) => input.query.page)).toEqual([1, 2])
+})
+
+it('does not advance an abandoned search when its delayed candidate page arrives', async () => {
+ const user = userEvent.setup()
+ const oldPage = createDeferred<{
+ data: OrganizationCandidate[]
+ page: number
+ limit: number
+ total: number
+ }>()
+ api.candidates.mockImplementation(({ query }: { query: { keyword?: string } }) =>
+ query.keyword
+ ? Promise.resolve({
+ data: [{ ...candidate, id: 'new', name: 'Current search' }],
+ page: 1,
+ limit: 100,
+ total: 1,
+ })
+ : oldPage.promise,
)
+ setup()
+ await open(user)
+ await waitFor(() => expect(api.candidates).toHaveBeenCalledTimes(1))
+ await user.type(screen.getByRole('searchbox', { name: 'contacts.platformPicker.search' }), 'new')
+ expect(await screen.findByText('Current search')).toBeVisible()
+ await act(async () => oldPage.resolve({ data: [candidate], page: 1, limit: 100, total: 101 }))
+ expect(
+ api.existing.mock.calls.some(([input]) => input.query.contact_ids.includes(candidate.id)),
+ ).toBe(false)
+ expect(api.candidates.mock.calls.some(([input]) => input.query.page > 1)).toBe(false)
+ expect(screen.getByText('Current search')).toBeVisible()
+})
- it('can move past a fully excluded page, retry the next page, and search the server without invented departments', async () => {
- const { listAvailablePlatformContacts, renderPicker } = setup()
- listAvailablePlatformContacts
- .mockResolvedValueOnce({ data: [], page: 1, limit: 20, total: 21, has_more: true })
- .mockRejectedValueOnce(new Error('offline'))
- .mockResolvedValueOnce({ data: [candidate], page: 2, limit: 20, total: 21, has_more: false })
- renderPicker()
- const user = userEvent.setup()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- expect(within(picker).queryByText('contacts.platformPicker.devTeam')).not.toBeInTheDocument()
- await user.click(
- await within(picker).findByRole('button', { name: 'contacts.action.loadMore' }),
- )
- expect(await within(picker).findByRole('alert')).toHaveTextContent(
- 'contacts.platformPicker.error',
- )
- await user.click(within(picker).getByRole('button', { name: 'contacts.action.retry' }))
- await within(picker).findByRole('checkbox', { name: /Platform Member/ })
- expect(listAvailablePlatformContacts.mock.calls.map(([query]) => query.page)).toEqual([1, 2, 2])
- await user.type(
- within(picker).getByRole('searchbox', { name: 'contacts.platformPicker.search' }),
- 'Member',
- )
- await waitFor(() =>
- expect(listAvailablePlatformContacts).toHaveBeenLastCalledWith({
- search: 'Member',
- page: 1,
- limit: 20,
- }),
- )
+it('isolates a new workspace from an old in-flight candidate page', async () => {
+ const user = userEvent.setup()
+ const oldPage = createDeferred<{
+ data: OrganizationCandidate[]
+ page: number
+ limit: number
+ total: number
+ }>()
+ api.candidates.mockReturnValueOnce(oldPage.promise).mockResolvedValue({
+ data: [{ ...candidate, id: 'new-workspace', name: 'Current workspace' }],
+ page: 1,
+ limit: 100,
+ total: 1,
})
+ const switchWorkspace = setup()
+ await open(user)
+ await waitFor(() => expect(api.candidates).toHaveBeenCalledTimes(1))
+ switchWorkspace('workspace-2')
+ expect(await screen.findByText('Current workspace')).toBeVisible()
+ await act(async () => oldPage.resolve({ data: [candidate], page: 1, limit: 100, total: 101 }))
+ expect(
+ api.existing.mock.calls.some(([input]) => input.query.contact_ids.includes(candidate.id)),
+ ).toBe(false)
+ expect(api.candidates.mock.calls.some(([input]) => input.query.page > 1)).toBe(false)
+ expect(screen.getByText('Current workspace')).toBeVisible()
+})
- it('imports selected candidates and invalidates contacts, workflow options, and platform candidates after success', async () => {
- const { context, addPlatformContacts, queryClient, onOpenChange, renderPicker } = setup()
- const keys = [
- ['contacts-management', context.workspaceId, 'directory'],
- consoleQuery.workspaces.current.humanInput.v2.contacts.key(),
- consoleQuery.workspaces.current.humanInput.v2.contactOptions.key(),
- consoleQuery.workspaces.current.humanInput.v2.organizationCandidates.key(),
- ]
- keys.forEach((key) => queryClient.setQueryData(key, { data: [] }))
- renderPicker()
- const user = userEvent.setup()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- expect(
- within(picker).getByText('contacts.platformPicker.noExternalUpgrade'),
- ).toBeInTheDocument()
- await user.click(await within(picker).findByRole('checkbox', { name: /Platform Member/ }))
- await user.click(within(picker).getByRole('button', { name: 'contacts.platformPicker.add' }))
- await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
- expect(addPlatformContacts).toHaveBeenCalledWith({
- contactIds: [candidate.id],
- upgradeExternalContacts: false,
- })
- keys.forEach((key) => expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true))
- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
- })
+it('adds selected IDs through the real generated mutation shape', async () => {
+ const user = userEvent.setup()
+ setup()
+ await open(user)
+ await user.click(await screen.findByRole('checkbox', { name: /selectContact.*Alice/ }))
+ await user.click(screen.getByRole('button', { name: 'contacts.platformPicker.add' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(api.add).toHaveBeenCalledWith({ body: { candidate_ids: [alice.id] } })
+})
- it.each([
- ['conflict', 'platformPicker.addConflict'],
- ['forbidden', 'platformPicker.addForbidden'],
- ['external_upgrade_unsupported', 'platformPicker.externalUpgradeUnsupported'],
- ['failed', 'platformPicker.addFailed'],
- ] as const)(
- 'keeps selection and the picker open after %s without offering a fake upgrade',
- async (kind, errorKey) => {
- const { addPlatformContacts, onOpenChange, renderPicker } = setup()
- addPlatformContacts.mockResolvedValue({ kind })
- renderPicker()
- const user = userEvent.setup()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- const option = await within(picker).findByRole('checkbox', { name: /Platform Member/ })
- await user.click(option)
- await user.click(within(picker).getByRole('button', { name: 'contacts.platformPicker.add' }))
- expect(await within(picker).findByRole('alert')).toHaveTextContent(`contacts.${errorKey}`)
- expect(option).toBeChecked()
- expect(onOpenChange).not.toHaveBeenCalled()
- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
- },
- )
+it('refreshes candidates and retains the selection on conflict, clearing it only after closing the session', async () => {
+ const user = userEvent.setup()
+ api.add.mockRejectedValueOnce(Object.assign(new Error('Conflict'), { status: 409 }))
+ setup()
+ await open(user)
+ await user.click(await screen.findByRole('checkbox', { name: /selectContact.*Alice/ }))
+ const candidateRequests = api.candidates.mock.calls.length
+ await user.click(screen.getByRole('button', { name: 'contacts.platformPicker.add' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('contacts.platformPicker.addConflict')
+ expect(screen.getByRole('checkbox', { name: /selectContact.*Alice/ })).toBeChecked()
+ await waitFor(() => expect(api.candidates.mock.calls.length).toBeGreaterThan(candidateRequests))
+ await user.click(screen.getByRole('button', { name: 'contacts.action.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await open(user)
+ expect(await screen.findByRole('checkbox', { name: /selectContact.*Alice/ })).not.toBeChecked()
+})
- it.each<Partial<ContactsFeatureContextValue>>([
- { imCentrallyManaged: undefined },
- { imCentrallyManaged: false },
- { workspaceId: '' },
- { permissions: { canViewContacts: true, canManageContacts: false, canManageMembers: false } },
- ])(
- 'does not query or expose selectable candidates without centrally managed import access',
- async (overrides) => {
- const { listAvailablePlatformContacts, addPlatformContacts, renderPicker } = setup(overrides)
- renderPicker()
- const picker = screen.getByRole('dialog', { name: 'contacts.platformPicker.title' })
- expect(within(picker).getByRole('alert')).toHaveTextContent(
- 'contacts.platformPicker.addForbidden',
- )
- expect(within(picker).queryByRole('checkbox')).not.toBeInTheDocument()
- expect(listAvailablePlatformContacts).not.toHaveBeenCalled()
- expect(addPlatformContacts).not.toHaveBeenCalled()
- },
- )
+it('blocks closing during a pending import and does not add duplicates', async () => {
+ const user = userEvent.setup()
+ const request = createDeferred<{ data: [] }>()
+ api.add.mockReturnValueOnce(request.promise)
+ setup()
+ await open(user)
+ await user.click(await screen.findByRole('checkbox', { name: /selectContact.*Alice/ }))
+ const add = screen.getByRole('button', { name: 'contacts.platformPicker.add' })
+ await user.click(add)
+ await user.click(add)
+ await user.keyboard('{Escape}')
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(api.add).toHaveBeenCalledOnce()
+ await act(async () => request.resolve({ data: [] }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
diff --git a/web/features/contacts/management/assets/avatar-inner-ring.svg b/web/features/contacts/management/assets/avatar-inner-ring.svg
new file mode 100644
index 00000000000..49c60a3bf4f
--- /dev/null
+++ b/web/features/contacts/management/assets/avatar-inner-ring.svg
@@ -0,0 +1,3 @@
+<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="124" height="124" viewBox="0 0 124 124" fill="none" xmlns="http://www.w3.org/2000/svg">
+<circle id="Ellipse 1" opacity="0.6" cx="62" cy="62" r="61.5" stroke="#101828" stroke-opacity="0.04"/>
+</svg>
diff --git a/web/features/contacts/management/assets/avatar-outer-ring.svg b/web/features/contacts/management/assets/avatar-outer-ring.svg
new file mode 100644
index 00000000000..7de03971d75
--- /dev/null
+++ b/web/features/contacts/management/assets/avatar-outer-ring.svg
@@ -0,0 +1,3 @@
+<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="156" height="156" viewBox="0 0 156 156" fill="none" xmlns="http://www.w3.org/2000/svg">
+<circle id="Ellipse 2" opacity="0.4" cx="78" cy="78" r="77.5" stroke="#101828" stroke-opacity="0.04"/>
+</svg>
diff --git a/web/features/contacts/management/assets/default-avatar.svg b/web/features/contacts/management/assets/default-avatar.svg
new file mode 100644
index 00000000000..ca4850e3f7f
--- /dev/null
+++ b/web/features/contacts/management/assets/default-avatar.svg
@@ -0,0 +1,16 @@
+<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="72" height="116.571" viewBox="0 0 72 116.571" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g id="People">
+<circle id="Head" cx="36" cy="18.8571" r="18.8571" fill="url(#paint0_radial_0_1917)"/>
+<circle id="Body" cx="36" cy="80.5714" r="36" fill="url(#paint1_radial_0_1917)"/>
+</g>
+<defs>
+<radialGradient id="paint0_radial_0_1917" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(27.4286 7.71428) rotate(54.6375) scale(32.5827)">
+<stop stop-color="white" stop-opacity="0.9"/>
+<stop offset="1" stop-color="white" stop-opacity="0.3"/>
+</radialGradient>
+<radialGradient id="paint1_radial_0_1917" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(24.8571 55.7143) rotate(62.1524) scale(51.3785)">
+<stop stop-color="white" stop-opacity="0.7"/>
+<stop offset="1" stop-color="white" stop-opacity="0.3"/>
+</radialGradient>
+</defs>
+</svg>
diff --git a/web/features/contacts/management/assets/wecom.svg b/web/features/contacts/management/assets/wecom.svg
new file mode 100644
index 00000000000..d36c888f610
--- /dev/null
+++ b/web/features/contacts/management/assets/wecom.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="31" height="26" viewBox="0 0 31 26"><g fill="none" fill-rule="evenodd"><path fill="#0082F0" d="M24.27 6.9a10.746 10.746 0 00-1.945-2.764C20.295 2.034 17.453.68 14.322.323a14.773 14.773 0 00-1.656-.096c-.511 0-1.044.03-1.585.089-3.144.342-6.002 1.69-8.047 3.792a10.757 10.757 0 00-1.955 2.757 9.634 9.634 0 00-1.003 4.277c0 1.909.58 3.79 1.678 5.442a14.96 14.96 0 002.302 2.634v.002l-.378 2.974c-.015.04-.031.08-.04.123-.01.039-.012.079-.016.119-.002.03-.01.06-.01.091 0 .033.008.065.01.098.05.489.458.872.96.872.175 0 .337-.05.478-.131l.014-.008c.02-.012.042-.023.062-.036l.903-.454 2.69-1.352a13.93 13.93 0 002.35.453 14.54 14.54 0 003.243-.009 14.092 14.092 0 003.173-.742 1.752 1.752 0 01-1.192-1.832c-.72.23-1.472.393-2.25.482a12.172 12.172 0 01-2.716.008c-.09-.01-.182-.025-.274-.037a11.976 11.976 0 01-1.78-.373 1.217 1.217 0 00-.37-.057c-.2 0-.392.053-.588.154-.026.014-.05.025-.076.04l-2.21 1.303-.096.057-.003.001c-.047.028-.075.039-.1.039a.15.15 0 01-.146-.153l.085-.345.098-.375.162-.614.179-.686a.93.93 0 00-.334-1.033 9.906 9.906 0 01-.923-.777c-.5-.475-.94-.994-1.31-1.55-.869-1.308-1.328-2.792-1.328-4.293 0-1.164.266-2.297.79-3.366a8.633 8.633 0 011.569-2.21c1.68-1.728 4.045-2.837 6.656-3.12.454-.05.901-.075 1.328-.075.449 0 .916.027 1.388.08 2.599.296 4.949 1.41 6.617 3.138a8.618 8.618 0 011.56 2.215 7.584 7.584 0 01.778 3.338c0 .12-.007.24-.013.36a1.746 1.746 0 012.149.251c.03.03.054.062.08.093a9.11 9.11 0 00.031-.739 9.634 9.634 0 00-.986-4.243" /><path fill="#FB6500" d="M24.149 22.148a1.7 1.7 0 00-.21-.035 5.377 5.377 0 01-2.996-1.67v.001a.418.418 0 10-.534.64c.041.04.082.078.121.118a5.39 5.39 0 011.478 2.761 1.715 1.715 0 00.059.356 1.749 1.749 0 002.926.777 1.754 1.754 0 00-.844-2.948" /><path fill="#0082F0" d="M29.944 17.673a1.75 1.75 0 00-2.98 1.056 5.388 5.388 0 01-1.667 2.999.419.419 0 10.641.534l.117-.121a5.376 5.376 0 012.758-1.48 1.71 1.71 0 00.355-.058 1.754 1.754 0 00.776-2.93" /><path fill="#2DBC00" d="M22.53 12.717a1.754 1.754 0 001.054 2.982 5.376 5.376 0 012.996 1.67.419.419 0 10.534-.641 5.389 5.389 0 01-1.6-2.879 1.625 1.625 0 00-.058-.355 1.75 1.75 0 00-2.926-.777" /><path fill="#FC0" d="M20.543 19.19a1.93 1.93 0 00.015-.106 5.393 5.393 0 011.668-3 .42.42 0 10-.64-.534 5.375 5.375 0 01-2.876 1.6 1.73 1.73 0 00-.355.06 1.754 1.754 0 00-.776 2.93 1.75 1.75 0 002.964-.95" /></g></svg>
\ No newline at end of file
diff --git a/web/features/contacts/management/available-platform-candidates.ts b/web/features/contacts/management/available-platform-candidates.ts
new file mode 100644
index 00000000000..72fafe48f2a
--- /dev/null
+++ b/web/features/contacts/management/available-platform-candidates.ts
@@ -0,0 +1,68 @@
+import type { QueryClient } from '@tanstack/react-query'
+import { infiniteQueryOptions } from '@tanstack/react-query'
+import { consoleQuery } from '@/service/console'
+
+export function availablePlatformCandidatesOptions(
+ queryClient: QueryClient,
+ workspaceId: string,
+ keyword: string,
+) {
+ const api = consoleQuery.workspaces.current.humanInput.v2
+ const query = { keyword: keyword.trim() || undefined, page: 1, limit: 100 }
+ return infiniteQueryOptions({
+ queryKey: [
+ ...api.organizationCandidates.get.queryKey({ input: { query } }),
+ { workspaceId, view: 'available-contacts' },
+ ],
+ initialPageParam: 1,
+ queryFn: async ({ pageParam, signal }) => {
+ let page = pageParam
+ let finalPage: number | undefined
+ while (true) {
+ signal.throwIfAborted()
+ const candidateInput = { query: { ...query, page } }
+ const response = await queryClient.query(
+ api.organizationCandidates.get.queryOptions({
+ input: candidateInput,
+ queryKey: [
+ ...api.organizationCandidates.get.queryKey({ input: candidateInput }),
+ { workspaceId },
+ ],
+ context: { silent: true },
+ staleTime: 30_000,
+ }),
+ )
+ signal.throwIfAborted()
+ if (response.page !== page || response.limit <= 0)
+ throw new Error('Invalid organization candidate pagination')
+ finalPage ??= Math.ceil(response.total / response.limit)
+ const nextPage = response.page + 1
+ const hasMore = response.page * response.limit < response.total
+ if (hasMore && (!response.data.length || nextPage > finalPage))
+ throw new Error('Organization candidate pagination did not advance')
+ const batchInput = {
+ query: { contact_ids: response.data.map((candidate) => candidate.id) },
+ }
+ const existing = response.data.length
+ ? await queryClient.query(
+ api.contacts.batch.get.queryOptions({
+ input: batchInput,
+ queryKey: [
+ ...api.contacts.batch.get.queryKey({ input: batchInput }),
+ { workspaceId },
+ ],
+ context: { silent: true },
+ staleTime: 30_000,
+ }),
+ )
+ : undefined
+ signal.throwIfAborted()
+ const existingIds = new Set(existing?.data.map((contact) => contact.id))
+ const data = response.data.filter((candidate) => !existingIds.has(candidate.id))
+ if (data.length || !hasMore) return { ...response, data }
+ page = nextPage
+ }
+ },
+ getNextPageParam: (page) => (page.page * page.limit < page.total ? page.page + 1 : undefined),
+ })
+}
diff --git a/web/features/contacts/management/channel-icon.tsx b/web/features/contacts/management/channel-icon.tsx
index da241848a13..87a0417571f 100644
--- a/web/features/contacts/management/channel-icon.tsx
+++ b/web/features/contacts/management/channel-icon.tsx
@@ -3,10 +3,7 @@ import DingTalkIcon from './assets/dingtalk.svg'
import EmailIcon from './assets/email.svg'
import FeishuIcon from './assets/feishu.svg'
import SlackIcon from './assets/slack.svg'
-
-// Original WeCom brand mark from work.weixin.qq.com, embedded to keep the asset local.
-const weComIcon =
- 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMSIgaGVpZ2h0PSIyNiIgdmlld0JveD0iMCAwIDMxIDI2Ij48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGZpbGw9IiMwMDgyRjAiIGQ9Ik0yNC4yNyA2LjlhMTAuNzQ2IDEwLjc0NiAwIDAwLTEuOTQ1LTIuNzY0QzIwLjI5NSAyLjAzNCAxNy40NTMuNjggMTQuMzIyLjMyM2ExNC43NzMgMTQuNzczIDAgMDAtMS42NTYtLjA5NmMtLjUxMSAwLTEuMDQ0LjAzLTEuNTg1LjA4OS0zLjE0NC4zNDItNi4wMDIgMS42OS04LjA0NyAzLjc5MmExMC43NTcgMTAuNzU3IDAgMDAtMS45NTUgMi43NTcgOS42MzQgOS42MzQgMCAwMC0xLjAwMyA0LjI3N2MwIDEuOTA5LjU4IDMuNzkgMS42NzggNS40NDJhMTQuOTYgMTQuOTYgMCAwMDIuMzAyIDIuNjM0di4wMDJsLS4zNzggMi45NzRjLS4wMTUuMDQtLjAzMS4wOC0uMDQuMTIzLS4wMS4wMzktLjAxMi4wNzktLjAxNi4xMTktLjAwMi4wMy0uMDEuMDYtLjAxLjA5MSAwIC4wMzMuMDA4LjA2NS4wMS4wOTguMDUuNDg5LjQ1OC44NzIuOTYuODcyLjE3NSAwIC4zMzctLjA1LjQ3OC0uMTMxbC4wMTQtLjAwOGMuMDItLjAxMi4wNDItLjAyMy4wNjItLjAzNmwuOTAzLS40NTQgMi42OS0xLjM1MmExMy45MyAxMy45MyAwIDAwMi4zNS40NTMgMTQuNTQgMTQuNTQgMCAwMDMuMjQzLS4wMDkgMTQuMDkyIDE0LjA5MiAwIDAwMy4xNzMtLjc0MiAxLjc1MiAxLjc1MiAwIDAxLTEuMTkyLTEuODMyYy0uNzIuMjMtMS40NzIuMzkzLTIuMjUuNDgyYTEyLjE3MiAxMi4xNzIgMCAwMS0yLjcxNi4wMDhjLS4wOS0uMDEtLjE4Mi0uMDI1LS4yNzQtLjAzN2ExMS45NzYgMTEuOTc2IDAgMDEtMS43OC0uMzczIDEuMjE3IDEuMjE3IDAgMDAtLjM3LS4wNTdjLS4yIDAtLjM5Mi4wNTMtLjU4OC4xNTQtLjAyNi4wMTQtLjA1LjAyNS0uMDc2LjA0bC0yLjIxIDEuMzAzLS4wOTYuMDU3LS4wMDMuMDAxYy0uMDQ3LjAyOC0uMDc1LjAzOS0uMS4wMzlhLjE1LjE1IDAgMDEtLjE0Ni0uMTUzbC4wODUtLjM0NS4wOTgtLjM3NS4xNjItLjYxNC4xNzktLjY4NmEuOTMuOTMgMCAwMC0uMzM0LTEuMDMzIDkuOTA2IDkuOTA2IDAgMDEtLjkyMy0uNzc3Yy0uNS0uNDc1LS45NC0uOTk0LTEuMzEtMS41NS0uODY5LTEuMzA4LTEuMzI4LTIuNzkyLTEuMzI4LTQuMjkzIDAtMS4xNjQuMjY2LTIuMjk3Ljc5LTMuMzY2YTguNjMzIDguNjMzIDAgMDExLjU2OS0yLjIxYzEuNjgtMS43MjggNC4wNDUtMi44MzcgNi42NTYtMy4xMi40NTQtLjA1LjkwMS0uMDc1IDEuMzI4LS4wNzUuNDQ5IDAgLjkxNi4wMjcgMS4zODguMDggMi41OTkuMjk2IDQuOTQ5IDEuNDEgNi42MTcgMy4xMzhhOC42MTggOC42MTggMCAwMTEuNTYgMi4yMTUgNy41ODQgNy41ODQgMCAwMS43NzggMy4zMzhjMCAuMTItLjAwNy4yNC0uMDEzLjM2YTEuNzQ2IDEuNzQ2IDAgMDEyLjE0OS4yNTFjLjAzLjAzLjA1NC4wNjIuMDguMDkzYTkuMTEgOS4xMSAwIDAwLjAzMS0uNzM5IDkuNjM0IDkuNjM0IDAgMDAtLjk4Ni00LjI0MyIgLz48cGF0aCBmaWxsPSIjRkI2NTAwIiBkPSJNMjQuMTQ5IDIyLjE0OGExLjcgMS43IDAgMDAtLjIxLS4wMzUgNS4zNzcgNS4zNzcgMCAwMS0yLjk5Ni0xLjY3di4wMDFhLjQxOC40MTggMCAxMC0uNTM0LjY0Yy4wNDEuMDQuMDgyLjA3OC4xMjEuMTE4YTUuMzkgNS4zOSAwIDAxMS40NzggMi43NjEgMS43MTUgMS43MTUgMCAwMC4wNTkuMzU2IDEuNzQ5IDEuNzQ5IDAgMDAyLjkyNi43NzcgMS43NTQgMS43NTQgMCAwMC0uODQ0LTIuOTQ4IiAvPjxwYXRoIGZpbGw9IiMwMDgyRjAiIGQ9Ik0yOS45NDQgMTcuNjczYTEuNzUgMS43NSAwIDAwLTIuOTggMS4wNTYgNS4zODggNS4zODggMCAwMS0xLjY2NyAyLjk5OS40MTkuNDE5IDAgMTAuNjQxLjUzNGwuMTE3LS4xMjFhNS4zNzYgNS4zNzYgMCAwMTIuNzU4LTEuNDggMS43MSAxLjcxIDAgMDAuMzU1LS4wNTggMS43NTQgMS43NTQgMCAwMC43NzYtMi45MyIgLz48cGF0aCBmaWxsPSIjMkRCQzAwIiBkPSJNMjIuNTMgMTIuNzE3YTEuNzU0IDEuNzU0IDAgMDAxLjA1NCAyLjk4MiA1LjM3NiA1LjM3NiAwIDAxMi45OTYgMS42Ny40MTkuNDE5IDAgMTAuNTM0LS42NDEgNS4zODkgNS4zODkgMCAwMS0xLjYtMi44NzkgMS42MjUgMS42MjUgMCAwMC0uMDU4LS4zNTUgMS43NSAxLjc1IDAgMDAtMi45MjYtLjc3NyIgLz48cGF0aCBmaWxsPSIjRkMwIiBkPSJNMjAuNTQzIDE5LjE5YTEuOTMgMS45MyAwIDAwLjAxNS0uMTA2IDUuMzkzIDUuMzkzIDAgMDExLjY2OC0zIC40Mi40MiAwIDEwLS42NC0uNTM0IDUuMzc1IDUuMzc1IDAgMDEtMi44NzYgMS42IDEuNzMgMS43MyAwIDAwLS4zNTUuMDYgMS43NTQgMS43NTQgMCAwMC0uNzc2IDIuOTMgMS43NSAxLjc1IDAgMDAyLjk2NC0uOTUiIC8+PC9nPjwvc3ZnPg=='
+import WeComIcon from './assets/wecom.svg'
export function ContactChannelIcon({
className,
@@ -24,8 +21,8 @@ export function ContactChannelIcon({
feishu: FeishuIcon.src,
lark: FeishuIcon.src,
slack: SlackIcon.src,
- we_com: weComIcon,
- wecom: weComIcon,
+ we_com: WeComIcon.src,
+ wecom: WeComIcon.src,
}[normalizedProvider]
if (icon) {
diff --git a/web/features/contacts/management/composition-context.ts b/web/features/contacts/management/composition-context.ts
index 437eb210d3b..527d2f8aa6d 100644
--- a/web/features/contacts/management/composition-context.ts
+++ b/web/features/contacts/management/composition-context.ts
@@ -1,28 +1,12 @@
'use client'
-import type { ContactsManagementRepository } from './repository'
import type { ContactsFeatureContextValue } from './types'
import { createContext, use } from 'react'
-export const ContactsManagementRepositoryContext =
- createContext<ContactsManagementRepository | null>(null)
export const ContactsFeatureContext = createContext<ContactsFeatureContextValue | null>(null)
-export function useContactsManagementRepository() {
- const repository = use(ContactsManagementRepositoryContext)
- if (!repository) throw new Error('ContactsManagementProvider is required')
- return repository
-}
-
export function useContactsFeatureContext() {
const context = use(ContactsFeatureContext)
if (!context) throw new Error('ContactsManagementProvider is required')
return context
}
-
-export function useOptionalContactsManagement() {
- return {
- context: use(ContactsFeatureContext),
- repository: use(ContactsManagementRepositoryContext),
- }
-}
diff --git a/web/features/contacts/management/composition.tsx b/web/features/contacts/management/composition.tsx
index 2cc2a28a82e..0b02d406b01 100644
--- a/web/features/contacts/management/composition.tsx
+++ b/web/features/contacts/management/composition.tsx
@@ -1,7 +1,6 @@
'use client'
import type { ReactNode } from 'react'
-import type { ContactsManagementRepository } from './repository'
import type { ContactsFeatureContextValue } from './types'
import { useQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
@@ -10,25 +9,16 @@ import { currentWorkspaceIdAtom, isCurrentWorkspaceManagerAtom } from '@/context
import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
import { selectIMCentrallyManaged } from '../im-capability'
-import { ContactsFeatureContext, ContactsManagementRepositoryContext } from './composition-context'
-import { createContactsApiRepository } from './repository'
+import { ContactsFeatureContext } from './composition-context'
export function ContactsManagementProvider({
children,
context,
- repository,
}: {
children: ReactNode
context: ContactsFeatureContextValue
- repository: ContactsManagementRepository
}) {
- return (
- <ContactsFeatureContext value={context}>
- <ContactsManagementRepositoryContext value={repository}>
- {children}
- </ContactsManagementRepositoryContext>
- </ContactsFeatureContext>
- )
+ return <ContactsFeatureContext value={context}>{children}</ContactsFeatureContext>
}
export function ContactsManagementRuntimeProvider({ children }: { children: ReactNode }) {
@@ -66,11 +56,5 @@ export function ContactsManagementRuntimeProvider({ children }: { children: Reac
}),
[canManage, capabilityError, refetchCapability, deployment, imCentrallyManaged, workspaceId],
)
- const repository = useMemo(() => createContactsApiRepository(undefined, context), [context])
-
- return (
- <ContactsManagementProvider context={context} repository={repository}>
- {children}
- </ContactsManagementProvider>
- )
+ return <ContactsManagementProvider context={context}>{children}</ContactsManagementProvider>
}
diff --git a/web/features/contacts/management/contact-avatar.tsx b/web/features/contacts/management/contact-avatar.tsx
new file mode 100644
index 00000000000..290f5aa9510
--- /dev/null
+++ b/web/features/contacts/management/contact-avatar.tsx
@@ -0,0 +1,55 @@
+import type { AvatarProps } from '@langgenius/dify-ui/avatar'
+import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
+import { cn } from '@langgenius/dify-ui/cn'
+import DefaultAvatar from './assets/default-avatar.svg'
+
+export function ContactAvatar({
+ avatar,
+ className,
+ name,
+ size = 'md',
+}: Pick<AvatarProps, 'size' | 'className'> & { avatar?: string | null; name: string }) {
+ return (
+ <Avatar
+ size={size}
+ aria-hidden
+ className={cn('data-loading:bg-background-section-burn', className)}
+ render={(props, { imageLoadingStatus }) => (
+ <span
+ {...props}
+ data-loading={
+ avatar && (imageLoadingStatus === 'idle' || imageLoadingStatus === 'loading')
+ ? ''
+ : undefined
+ }
+ />
+ )}
+ >
+ {avatar && (
+ <AvatarImage
+ key={avatar.split('?')[0]}
+ keepMounted
+ src={avatar}
+ alt=""
+ className="data-error:invisible"
+ />
+ )}
+ <AvatarFallback
+ render={(props, { imageLoadingStatus }) => (
+ <span {...props} aria-hidden>
+ {(!avatar || imageLoadingStatus === 'error') &&
+ (name ? (
+ [...name][0]?.toLocaleUpperCase()
+ ) : (
+ <img
+ alt=""
+ src={DefaultAvatar.src}
+ className="absolute inset-s-1/8 top-[21.43%] h-[121.43%] w-3/4 max-w-none"
+ />
+ ))}
+ </span>
+ )}
+ />
+ </Avatar>
+ )
+}
diff --git a/web/features/contacts/management/contact-details-panel.tsx b/web/features/contacts/management/contact-details-panel.tsx
index ed2f935adcc..8b16c850d40 100644
--- a/web/features/contacts/management/contact-details-panel.tsx
+++ b/web/features/contacts/management/contact-details-panel.tsx
@@ -1,8 +1,9 @@
'use client'
-import type { AvatarProps } from '@langgenius/dify-ui/avatar'
-import type { ContactIMBinding, ContactIMIdentity, ContactView } from './types'
-import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
+import type { ImBinding, ImIdentity } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { Ref } from 'react'
+import type { ContactView } from './types'
+import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -25,69 +26,32 @@ import {
DialogDescription,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
+import { Field, FieldDescription, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
+import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Menu, MenuContent, MenuItem, MenuTrigger } from '@langgenius/dify-ui/menu'
import { Radio, RadioGroup } from '@langgenius/dify-ui/radio-group'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { useState } from 'react'
+import { ORPCError } from '@orpc/client'
+import { skipToken, useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'
+import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { consoleQuery } from '@/service/console'
import { ContactChannelIcon } from './channel-icon'
import { getContactChannelLabel } from './channel-utils'
-import { useContactsFeatureContext, useContactsManagementRepository } from './composition-context'
-import {
- useContactIMChannels,
- useContactIMIdentities,
- useRemoveContactIMBinding,
- useSetContactIMBinding,
- useUnbindContactIMBinding,
-} from './hooks'
+import { useContactsFeatureContext } from './composition-context'
+import { ContactAvatar } from './contact-avatar'
import { formatContactRelativeTime } from './relative-time'
-import { ContactIMRequestError } from './repository'
-
-export function ContactAvatar({
- avatar,
- className,
- name,
- size = 'md',
-}: Pick<AvatarProps, 'size' | 'className'> & { avatar: string | null; name: string }) {
- return (
- <Avatar
- size={size}
- className={cn('data-loading:bg-background-section-burn', className)}
- render={(props, { imageLoadingStatus }) => (
- <span
- {...props}
- data-loading={
- avatar && (imageLoadingStatus === 'idle' || imageLoadingStatus === 'loading')
- ? ''
- : undefined
- }
- />
- )}
- >
- {avatar && (
- <AvatarImage
- key={avatar.split('?')[0]}
- keepMounted
- src={avatar}
- alt={name}
- className="data-error:invisible"
- />
- )}
- <AvatarFallback
- render={(props, { imageLoadingStatus }) => (
- <span {...props}>
- {(!avatar || imageLoadingStatus === 'error') && name?.[0]?.toLocaleUpperCase()}
- </span>
- )}
- />
- </Avatar>
- )
-}
function imErrorKey(error: unknown, loading = false) {
- const code = error instanceof ContactIMRequestError ? error.code : undefined
+ const code =
+ error instanceof ORPCError &&
+ error.data &&
+ typeof error.data === 'object' &&
+ 'code' in error.data
+ ? error.data.code
+ : undefined
if (code === 'im_integration_not_configured') return 'imBinding.notConfigured'
if (code === 'im_binding_conflict') return 'imBinding.conflict'
if (
@@ -113,12 +77,9 @@ const imIdentityAvatarColors = [
'bg-components-icon-bg-midnight-solid',
] as const
-type IMIdentityOption = Pick<
- ContactIMIdentity,
- 'id' | 'display_name' | 'email' | 'provider_user_id'
->
+type IMIdentityOption = Pick<ImIdentity, 'id' | 'display_name' | 'email' | 'provider_user_id'>
-function getBoundIMIdentity(contact: ContactView, binding?: ContactIMBinding) {
+function getBoundIMIdentity(contact: ContactView, binding?: ImBinding) {
if (!binding) return undefined
return contact.im_binding_details?.find(
(detail) =>
@@ -149,6 +110,7 @@ function IMIdentityAvatar({
)}
>
<AvatarFallback
+ aria-hidden
className={cn(
'bg-linear-to-br from-components-avatar-bg-mask-stop-0 to-components-avatar-bg-mask-stop-100 leading-[1.2] font-semibold',
size === 'sm' ? 'text-[13px]' : 'text-xs',
@@ -179,7 +141,7 @@ function IMIdentityDetails({ identity }: { identity: IMIdentityOption }) {
)
}
-function ContactIMBindingEditor({
+function ImBindingEditor({
contact,
provider,
binding,
@@ -192,7 +154,7 @@ function ContactIMBindingEditor({
}: {
contact: ContactView
provider: string
- binding?: ContactIMBinding
+ binding?: ImBinding
saving: boolean
unbinding: boolean
error: unknown
@@ -213,7 +175,17 @@ function ContactIMBindingEditor({
const [identity, setIdentity] = useState<IMIdentityOption | null>(() =>
!centrallyManaged || binding?.scope === 'workspace' ? (boundIdentity ?? null) : null,
)
- const identities = useContactIMIdentities(search)
+ const identityDescriptionId = useId()
+ const identities = useInfiniteQuery(
+ consoleQuery.workspaces.current.humanInput.v2.imIdentities.get.infiniteOptions({
+ input: (page: number) => ({
+ query: { keyword: search.trim() || undefined, page, limit: 20 },
+ }),
+ initialPageParam: 1,
+ getNextPageParam: (page) => (page.page * page.limit < page.total ? page.page + 1 : undefined),
+ context: { silent: true },
+ }),
+ )
const options = [
...new Map<string, IMIdentityOption>(
[
@@ -266,48 +238,59 @@ function ContactIMBindingEditor({
/>
<div className="px-6 pt-2">
{centrallyManaged && (
- <RadioGroup
- aria-label={t(($) => $['imBinding.modeLabel'])}
- className="flex-col items-stretch gap-5"
- value={mode}
- onValueChange={(value) => {
- setMode(value)
- setPickerOpen(false)
- }}
- disabled={saving}
- >
- <div className="space-y-1.5">
- <label className="flex min-h-5 cursor-pointer items-center gap-2 system-sm-medium text-text-secondary">
- <Radio value="organization" />
- {t(($) => $['imBinding.organizationMode'])}
- </label>
- <div className="ms-6 flex h-9 items-center gap-1.5 rounded-lg bg-components-input-bg-normal px-2.5 system-xs-regular text-text-tertiary">
- {organizationIdentity ? (
- <>
- <IMIdentityAvatar identity={organizationIdentity} size="xs" />
- <span className="truncate text-text-secondary">
- {organizationIdentity.display_name ||
- organizationIdentity.email ||
- organizationIdentity.provider_user_id}
- </span>
- {organizationIdentity.display_name && (
- <span className="truncate">{organizationIdentity.email}</span>
- )}
- </>
- ) : binding ? (
- t(($) => $['imBinding.organizationUnavailable'])
- ) : (
- t(($) => $['imBinding.noOrganizationBinding'])
- )}
- </div>
- </div>
- <div className="space-y-1.5">
- <label className="flex min-h-5 cursor-pointer items-center gap-2 system-sm-medium text-text-secondary">
- <Radio value="workspace" />
- {t(($) => $['imBinding.workspaceMode'])}
- </label>
- </div>
- </RadioGroup>
+ <Field>
+ <Fieldset
+ render={
+ <RadioGroup
+ className="flex-col items-stretch gap-5"
+ value={mode}
+ onValueChange={(value) => {
+ setMode(value)
+ setPickerOpen(false)
+ }}
+ disabled={saving}
+ />
+ }
+ >
+ <FieldsetLegend className="sr-only">
+ {t(($) => $['imBinding.modeLabel'])}
+ </FieldsetLegend>
+ <FieldItem className="space-y-1.5">
+ <FieldLabel className="flex min-h-5 cursor-pointer items-center gap-2 system-sm-medium text-text-secondary">
+ <Radio value="organization" aria-describedby={identityDescriptionId} />
+ {t(($) => $['imBinding.organizationMode'])}
+ </FieldLabel>
+ <FieldDescription
+ id={identityDescriptionId}
+ className="ms-6 flex h-9 items-center gap-1.5 rounded-lg bg-components-input-bg-normal px-2.5 system-xs-regular text-text-tertiary"
+ >
+ {organizationIdentity ? (
+ <>
+ <IMIdentityAvatar identity={organizationIdentity} size="xs" />
+ <span className="truncate text-text-secondary">
+ {organizationIdentity.display_name ||
+ organizationIdentity.email ||
+ organizationIdentity.provider_user_id}
+ </span>
+ {organizationIdentity.display_name && (
+ <span className="truncate">{organizationIdentity.email}</span>
+ )}
+ </>
+ ) : binding ? (
+ t(($) => $['imBinding.organizationUnavailable'])
+ ) : (
+ t(($) => $['imBinding.noOrganizationBinding'])
+ )}
+ </FieldDescription>
+ </FieldItem>
+ <FieldItem className="space-y-1.5">
+ <FieldLabel className="flex min-h-5 cursor-pointer items-center gap-2 system-sm-medium text-text-secondary">
+ <Radio value="workspace" />
+ {t(($) => $['imBinding.workspaceMode'])}
+ </FieldLabel>
+ </FieldItem>
+ </Fieldset>
+ </Field>
)}
{(!centrallyManaged || mode === 'workspace') && (
<div className={cn(centrallyManaged && 'ms-6 mt-1.5')}>
@@ -476,25 +459,39 @@ function ContactIMChannels({
}) {
const { t } = useTranslation(['contacts'])
const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
const [editingProvider, setEditingProvider] = useState<string | null>(null)
const [open, setOpen] = useState(false)
- const save = useSetContactIMBinding()
- const remove = useRemoveContactIMBinding()
- const unbind = useUnbindContactIMBinding()
+ const api = consoleQuery.workspaces.current.humanInput.v2
+ const defaultSave = useMutation(
+ api.contacts.byContactId.imBindings.put.mutationOptions({ context: { silent: true } }),
+ )
+ const overrideSave = useMutation(
+ api.contacts.byContactId.imOverride.put.mutationOptions({ context: { silent: true } }),
+ )
+ const save = context.imCentrallyManaged ? overrideSave : defaultSave
+ const remove = useMutation(
+ api.contacts.byContactId.imOverride.delete.mutationOptions({ context: { silent: true } }),
+ )
+ const unbind = useMutation(
+ api.contacts.byContactId.imBindings.delete.mutationOptions({ context: { silent: true } }),
+ )
const canBind =
- canManage &&
- context.imCentrallyManaged !== undefined &&
- repository.supportsIMBindings === true &&
- contact.type !== 'external'
- const configured = useContactIMChannels(canBind)
+ canManage && context.imCentrallyManaged !== undefined && contact.type !== 'external'
+ const configured = useQuery(
+ api.channels.get.queryOptions({
+ input: canBind && context.imCentrallyManaged === false ? undefined : skipToken,
+ select: (response) => response.channels.filter((channel) => channel.kind === 'im'),
+ retry: false,
+ context: { silent: true },
+ }),
+ )
const busy = save.isPending || remove.isPending || unbind.isPending || removing
- const bindings = contact.type === 'external' ? [] : contact.im_bindings
+ const bindings = contact.type === 'external' ? [] : (contact.im_bindings ?? [])
const providers = [
...new Set([
'email',
...bindings.map((binding) => binding.provider),
- ...(canBind ? configured.data.map((channel) => channel.provider) : []),
+ ...(canBind ? (configured.data ?? []).map((channel) => channel.provider) : []),
]),
]
const editingBinding = bindings.find((binding) => binding.provider === editingProvider)
@@ -536,7 +533,12 @@ function ContactIMChannels({
<span className="flex size-5 shrink-0 items-center justify-center">
<ContactChannelIcon provider={provider} />
</span>
- <span className="system-sm-medium text-text-secondary">{label}</span>
+ <span
+ id={`contact-channel-${contact.id}-${provider}`}
+ className="system-sm-medium text-text-secondary"
+ >
+ {label}
+ </span>
</div>
<div className="flex min-w-0 flex-1 items-center justify-end gap-1.5">
{provider === 'email' ? (
@@ -567,6 +569,7 @@ function ContactIMChannels({
<Button
variant="ghost-accent"
size="small"
+ aria-describedby={`contact-channel-${contact.id}-${provider}`}
disabled={busy}
onClick={() => openEditor(provider)}
>
@@ -623,7 +626,7 @@ function ContactIMChannels({
>
<DialogContent className="w-140">
{editingProvider && (
- <ContactIMBindingEditor
+ <ImBindingEditor
key={`${editingProvider}:${context.imCentrallyManaged}`}
contact={contact}
provider={editingProvider}
@@ -637,7 +640,10 @@ function ContactIMChannels({
if (!canBind || busy) return
save.reset()
remove.reset()
- unbind.mutate({ contactId: contact.id }, { onSuccess: () => setOpen(false) })
+ unbind.mutate(
+ { params: { contact_id: contact.id } },
+ { onSuccess: () => setOpen(false) },
+ )
}
: undefined
}
@@ -646,15 +652,14 @@ function ContactIMChannels({
unbind.reset()
save.mutate(
{
- contactId: contact.id,
- identityId,
- override: context.imCentrallyManaged,
+ params: { contact_id: contact.id },
+ body: { identity_id: identityId },
},
{
onSuccess: () => {
if (!context.imCentrallyManaged && editingBinding?.scope === 'workspace') {
remove.mutate(
- { contactId: contact.id, binding: editingBinding },
+ { params: { contact_id: contact.id } },
{ onSuccess: () => setOpen(false) },
)
} else setOpen(false)
@@ -669,7 +674,7 @@ function ContactIMChannels({
editingBinding?.scope === 'workspace'
) {
remove.mutate(
- { contactId: contact.id, binding: editingBinding },
+ { params: { contact_id: contact.id } },
{ onSuccess: () => setOpen(false) },
)
}
@@ -689,7 +694,11 @@ export function ContactDetailsPanel({
onEdit,
onClose,
onRemove,
+ id,
+ headingRef,
}: {
+ id?: string
+ headingRef?: Ref<HTMLHeadingElement>
contact: ContactView
canManage?: boolean
removing?: boolean
@@ -698,10 +707,12 @@ export function ContactDetailsPanel({
onRemove: () => void
}) {
const { i18n, t } = useTranslation(['contacts'])
+ const headingId = useId()
return (
- <aside
- aria-label={t(($) => $['details.title'])}
+ <section
+ id={id}
+ aria-labelledby={headingId}
className="relative z-20 flex h-full w-80 max-w-full shrink-0 flex-col overflow-hidden rounded-lg bg-components-panel-bg"
>
<div className="absolute inset-e-2 top-2 z-10 flex items-center gap-1">
@@ -744,7 +755,7 @@ export function ContactDetailsPanel({
className="pointer-events-none absolute inset-x-1 top-1 h-25 overflow-hidden rounded-lg"
>
<ContactAvatar
- avatar={contact.avatar_url || null}
+ avatar={contact.avatar_url}
className="absolute -top-19 left-1/2 size-80 -translate-x-1/2 opacity-20 blur-[80px]"
name={contact.name}
size="3xl"
@@ -754,14 +765,19 @@ export function ContactDetailsPanel({
</div>
<div className="relative size-24 shrink-0 rounded-full border-2 border-components-panel-bg">
<ContactAvatar
- avatar={contact.avatar_url || null}
+ avatar={contact.avatar_url}
className="size-full inset-ring-[0.5px] inset-ring-divider-regular"
name={contact.name}
size="3xl"
/>
</div>
<div className="relative flex w-full flex-col items-center gap-0.5">
- <h2 className="max-w-full system-xl-medium wrap-anywhere text-text-primary">
+ <h2
+ id={headingId}
+ ref={headingRef}
+ tabIndex={-1}
+ className="max-w-full system-xl-medium wrap-anywhere text-text-primary outline-hidden"
+ >
{contact.name}
</h2>
{contact.email && (
@@ -788,6 +804,6 @@ export function ContactDetailsPanel({
{t(($) => $['details.joined'])}{' '}
{formatContactRelativeTime(contact.created_at, i18n.resolvedLanguage ?? 'en')}
</p>
- </aside>
+ </section>
)
}
diff --git a/web/features/contacts/management/directory-page.tsx b/web/features/contacts/management/directory-page.tsx
index 3a02654bea4..ef8e4745682 100644
--- a/web/features/contacts/management/directory-page.tsx
+++ b/web/features/contacts/management/directory-page.tsx
@@ -26,31 +26,33 @@ import {
ScrollAreaThumb,
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
-import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import {
- parseAsInteger,
- parseAsString,
- parseAsStringLiteral,
- useQueryState,
- useQueryStates,
-} from 'nuqs'
-import { useEffect, useRef, useState } from 'react'
+ SegmentedControl,
+ SegmentedControlDivider,
+ SegmentedControlItem,
+} from '@langgenius/dify-ui/segmented-control'
+import {
+ skipToken,
+ useInfiniteQuery,
+ useMutation,
+ useQueries,
+ useQuery,
+} from '@tanstack/react-query'
+import { parseAsString, parseAsStringLiteral, useQueryState, useQueryStates } from 'nuqs'
+import { Fragment, useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { InfiniteScrollSentinel } from '@/app/components/base/infinite-scroll-sentinel'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { SearchInput } from '@/app/components/base/search-input'
+import { consoleQuery } from '@/service/console'
+import { isNotFoundError } from '@/service/http-error'
import UserCommunityIcon from './assets/user-community.svg'
import { ContactChannelIcon } from './channel-icon'
import { getContactChannelLabel } from './channel-utils'
-import { useContactsFeatureContext, useContactsManagementRepository } from './composition-context'
-import { ContactAvatar, ContactDetailsPanel } from './contact-details-panel'
+import { useContactsFeatureContext } from './composition-context'
+import { ContactAvatar } from './contact-avatar'
+import { ContactDetailsPanel } from './contact-details-panel'
import { ExternalContactDialog } from './external-contact-dialog'
-import {
- useContactCounts,
- useContactDetails,
- useContactsDirectory,
- useRemoveContacts,
-} from './hooks'
import { PlatformContactPickerDialog } from './platform-contact-picker-dialog'
import { formatContactRelativeTime } from './relative-time'
@@ -58,7 +60,6 @@ const contactKindFilters = ['all', 'workspace', 'platform', 'external'] as const
const searchParser = parseAsString.withDefault('')
const kindParser = parseAsStringLiteral(contactKindFilters).withDefault('all')
const contactIdParser = parseAsString
-const loadedPagesParser = parseAsInteger.withDefault(1)
function ContactTypeLabel({ type }: { type: ContactView['type'] }) {
const { t } = useTranslation(['contacts'])
@@ -75,6 +76,8 @@ function ContactRow({
selected,
selectionPending,
selectionEnabled,
+ expanded,
+ panelId,
}: {
contact: ContactView
onOpen: () => void
@@ -83,30 +86,34 @@ function ContactRow({
selected: boolean
selectionPending: boolean
selectionEnabled: boolean
+ expanded: boolean
+ panelId: string
}) {
const { i18n, t } = useTranslation(['contacts'])
return (
<tr className="relative isolate h-12 shadow-[inset_0_-1px_0_0_var(--color-divider-subtle)] hover:bg-state-base-hover">
{selectionEnabled && (
<td className="relative z-10 w-8 px-2 py-2 text-center">
- <Checkbox
- aria-label={t(($) => $['directory.selectContact'], { name: contact.name })}
- checked={selected}
- disabled={contact.type === 'workspace' || selectionPending}
- onCheckedChange={onSelectedChange}
- />
+ {contact.type !== 'workspace' && (
+ <Checkbox
+ aria-label={t(($) => $['directory.selectContact'], { name: contact.name })}
+ checked={selected}
+ disabled={selectionPending}
+ onCheckedChange={onSelectedChange}
+ />
+ )}
</td>
)}
<td className="p-0">
- {/* Stretch the native details button across the row; independent controls stay above it. */}
<button
ref={registerTrigger}
type="button"
- aria-label={t(($) => $['directory.openDetails'], { name: contact.name })}
+ aria-controls={panelId}
+ aria-expanded={expanded}
className="flex h-12 w-full min-w-64 cursor-pointer items-center gap-2.5 py-1 ps-3 pe-2 text-start after:absolute after:inset-0 after:content-[''] focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden focus-visible:ring-inset"
onClick={onOpen}
>
- <ContactAvatar avatar={contact.avatar_url || null} name={contact.name} size="md" />
+ <ContactAvatar avatar={contact.avatar_url} name={contact.name} size="md" />
<span className="min-w-0 py-0.5">
<span className="block truncate system-md-medium text-text-secondary">
{contact.name}
@@ -123,14 +130,16 @@ function ContactRow({
<td className="px-3 py-2">
<span className="flex items-center gap-2 text-text-tertiary">
<span
+ role="img"
aria-label={t(($) => $['directory.channel.email'])}
className="flex size-6 items-center justify-center rounded-md border border-divider-regular bg-components-panel-on-panel-item-bg backdrop-blur-[4px]"
>
<ContactChannelIcon provider="email" />
</span>
- {contact.im_bindings.map((binding) => (
+ {(contact.im_bindings ?? []).map((binding) => (
<span
key={binding.id}
+ role="img"
aria-label={getContactChannelLabel(binding.provider)}
className="flex size-6 items-center justify-center rounded-md border border-divider-regular bg-components-panel-on-panel-item-bg backdrop-blur-[4px]"
>
@@ -183,13 +192,8 @@ function DirectoryState({
}
function DirectoryLoading() {
- const { t } = useTranslation(['contacts'])
return (
- <div
- role="status"
- aria-label={t(($) => $['directory.loading'])}
- className="space-y-2 rounded-xl border border-divider-subtle p-3"
- >
+ <div aria-busy="true" className="space-y-2 rounded-xl border border-divider-subtle p-3">
{[0, 1, 2, 3, 4].map((key) => (
<div key={key} className="h-12 animate-pulse rounded-lg bg-background-default-subtle" />
))}
@@ -201,39 +205,102 @@ export function ContactsDirectoryPage() {
const { t } = useTranslation(['contacts'])
const { t: tCommon } = useTranslation(['common'])
const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
const [browsing, setBrowsing] = useQueryStates({
contact_kind: kindParser,
- contact_pages: loadedPagesParser,
contact_search: searchParser,
})
const search = browsing.contact_search
const platformFilterUnavailable =
browsing.contact_kind === 'platform' && context.imCentrallyManaged === false
const kind = platformFilterUnavailable ? 'all' : browsing.contact_kind
- const loadedPages = platformFilterUnavailable ? 1 : browsing.contact_pages
const [contactId, setContactId] = useQueryState('contact_id', contactIdParser)
const [externalDialogOpen, setExternalDialogOpen] = useState(false)
const [editingContact, setEditingContact] = useState<ContactView | null>(null)
const [platformDialogOpen, setPlatformDialogOpen] = useState(false)
const [selectedContactIds, setSelectedContactIds] = useState<string[]>([])
- const [removalTargetIds, setRemovalTargetIds] = useState<string[] | null>(null)
+ const [removalTargetIds, setRemovalTargetIds] = useState<string[]>([])
+ const [removalOpen, setRemovalOpen] = useState(false)
+ const [removalContactName, setRemovalContactName] = useState<string>()
const [removalError, setRemovalError] = useState(false)
+ const pageHeadingId = useId()
+ const detailsPanelId = useId()
+ const searchRef = useRef<HTMLInputElement>(null)
+ const detailsHeadingRef = useRef<HTMLHeadingElement>(null)
const scrollContainerRef = useRef<HTMLDivElement>(null)
const rowTriggersRef = useRef(new Map<string, HTMLButtonElement>())
const selectedContactIdRef = useRef<string | null>(null)
- const directoryQuery = useContactsDirectory({ kind, limit: 20, search })
- const detailsQuery = useContactDetails(contactId)
- const contactCounts = useContactCounts()
- const removeContacts = useRemoveContacts()
+ const api = consoleQuery.workspaces.current.humanInput.v2.contacts
+ const directoryQuery = useInfiniteQuery(
+ api.get.infiniteOptions({
+ input: (page: number) => ({
+ query: {
+ page,
+ limit: 20,
+ group: kind === 'all' ? undefined : kind,
+ keyword: search.trim() || undefined,
+ },
+ }),
+ initialPageParam: 1,
+ getNextPageParam: (page) => (page.page * page.limit < page.total ? page.page + 1 : undefined),
+ enabled:
+ Boolean(context.workspaceId) &&
+ context.permissions.canViewContacts &&
+ context.imCentrallyManaged !== undefined,
+ context: { silent: true },
+ }),
+ )
+ const contacts = [
+ ...new Map(
+ (directoryQuery.data?.pages.flatMap((page) => page.data) ?? []).map((contact) => [
+ contact.id,
+ contact,
+ ]),
+ ).values(),
+ ]
+ const detailsQuery = useQuery(
+ api.byContactId.get.queryOptions({
+ input:
+ contactId && context.workspaceId && context.permissions.canViewContacts
+ ? { params: { contact_id: contactId } }
+ : skipToken,
+ select: (response) => ({
+ ...response.contact,
+ im_binding_details: response.im_binding_details,
+ }),
+ retry: false,
+ context: { silent: true },
+ }),
+ )
+ const kinds = ['workspace', 'platform', 'external'] as const
+ const counts = useQueries({
+ queries: kinds.map((group) =>
+ api.get.queryOptions({
+ input: { query: { group, page: 1, limit: 1 } },
+ enabled:
+ Boolean(context.workspaceId) &&
+ context.permissions.canViewContacts &&
+ context.imCentrallyManaged !== undefined &&
+ (group !== 'platform' || context.imCentrallyManaged === true),
+ select: (page) => page.total,
+ context: { silent: true },
+ }),
+ ),
+ })
+ const contactCounts = {
+ workspace: counts[0]?.data,
+ platform: counts[1]?.data,
+ external: counts[2]?.data,
+ }
+ const removeContacts = useMutation(api.remove.post.mutationOptions({ context: { silent: true } }))
const fetchNextPage = directoryQuery.fetchNextPage
const filters = contactKindFilters.filter(
(filter) => filter !== 'platform' || context.imCentrallyManaged,
)
const hasFilters = Boolean(search) || kind !== 'all'
- const currentPageCount = directoryQuery.data?.pages.length ?? 0
const selectedContact = detailsQuery.data
- const removableContactIds = directoryQuery.contacts
+ const detailsFailed = detailsQuery.isError && !isNotFoundError(detailsQuery.error)
+ const selectedContactId = selectedContact?.id
+ const removableContactIds = contacts
.filter((contact) => contact.type !== 'workspace')
.map((contact) => contact.id)
const selectedRemovableCount = removableContactIds.filter((id) =>
@@ -246,35 +313,29 @@ export function ContactsDirectoryPage() {
useEffect(() => {
if (platformFilterUnavailable) {
// oxlint-disable-next-line eslint-react/set-state-in-effect -- The resolved server capability removes unsupported filters from the external URL query state.
- void setBrowsing({ contact_kind: null, contact_pages: null })
+ void setBrowsing({ contact_kind: null })
}
}, [platformFilterUnavailable, setBrowsing])
useEffect(() => {
- if (
- context.imCentrallyManaged !== undefined &&
- currentPageCount > 0 &&
- currentPageCount < loadedPages &&
- directoryQuery.hasNextPage &&
- !directoryQuery.isFetching &&
- !directoryQuery.isFetchNextPageError
- ) {
- void fetchNextPage()
- }
- }, [
- context.imCentrallyManaged,
- currentPageCount,
- directoryQuery.hasNextPage,
- directoryQuery.isFetchNextPageError,
- directoryQuery.isFetching,
- fetchNextPage,
- loadedPages,
- ])
+ if (contactId && selectedContactId) detailsHeadingRef.current?.focus()
+ }, [contactId, selectedContactId])
+
+ function focusDirectory(exclude: readonly string[] = []) {
+ const next = contacts.find((contact) => !exclude.includes(contact.id))
+ const trigger = next ? rowTriggersRef.current.get(next.id) : null
+ return trigger?.isConnected ? trigger : searchRef.current
+ }
+
+ function openCreateContact() {
+ setEditingContact(null)
+ setExternalDialogOpen(true)
+ }
function updateSearch(value: string) {
setSelectedContactIds([])
setRemovalError(false)
- void setBrowsing({ contact_pages: null, contact_search: value || null })
+ void setBrowsing({ contact_search: value || null })
}
function updateKind(value: ContactTypeFilter) {
@@ -282,7 +343,6 @@ export function ContactsDirectoryPage() {
setRemovalError(false)
void setBrowsing({
contact_kind: value === 'all' ? null : value,
- contact_pages: null,
})
}
@@ -295,13 +355,16 @@ export function ContactsDirectoryPage() {
const trigger = selectedContactIdRef.current
? rowTriggersRef.current.get(selectedContactIdRef.current)
: null
- void setContactId(null).then(() => trigger?.focus())
+ void setContactId(null).then(() => {
+ if (trigger?.isConnected) trigger.focus()
+ else searchRef.current?.focus()
+ })
}
function clearFilters() {
setSelectedContactIds([])
setRemovalError(false)
- void setBrowsing({ contact_kind: null, contact_pages: null, contact_search: null })
+ void setBrowsing({ contact_kind: null, contact_search: null })
}
function toggleContact(contactId: string, selected: boolean) {
@@ -329,67 +392,70 @@ export function ContactsDirectoryPage() {
return
setRemovalError(false)
try {
- const result = await removeContacts.mutateAsync({ contactIds: removalTargetIds })
- if (result.kind !== 'removed') {
- setRemovalError(true)
- return
- }
+ const result = await removeContacts.mutateAsync({ body: { contact_ids: removalTargetIds } })
setSelectedContactIds((current) =>
- current.filter((id) => !result.removedContactIds.includes(id)),
+ current.filter((id) => !result.removed_contact_ids.includes(id)),
)
- if (contactId && result.removedContactIds.includes(contactId)) closeDetails()
- setRemovalTargetIds(null)
+ if (contactId && result.removed_contact_ids.includes(contactId)) void setContactId(null)
+ setRemovalOpen(false)
} catch {
setRemovalError(true)
}
}
async function loadMore() {
- const nextResult = await fetchNextPage({ cancelRefetch: false })
- if (!nextResult.isFetchNextPageError)
- void setBrowsing({ contact_pages: nextResult.data?.pages.length ?? loadedPages })
+ await fetchNextPage({ cancelRefetch: false })
}
+ const stateHeader = (
+ <h1 id={pageHeadingId} className="px-8 pt-4 title-2xl-semi-bold text-text-primary">
+ {t(($) => $['directory.title'])}
+ </h1>
+ )
if (!context.permissions.canViewContacts) {
return (
- <DirectoryState
- description={t(($) => $['directory.noAccessDescription'])}
- icon="i-ri-lock-2-line"
- title={t(($) => $['directory.noAccessTitle'])}
- />
+ <div className="flex h-full flex-col">
+ {stateHeader}
+ <DirectoryState
+ description={t(($) => $['directory.noAccessDescription'])}
+ icon="i-ri-lock-2-line"
+ title={t(($) => $['directory.noAccessTitle'])}
+ />
+ </div>
)
}
if (context.imCentrallyManaged === undefined) {
if (context.imCapabilityError) {
return (
- <DirectoryState
- action={
- <Button onClick={context.retryIMCapability}>{t(($) => $['action.retry'])}</Button>
- }
- description={t(($) => $['directory.errorDescription'])}
- icon="i-ri-error-warning-line"
- title={t(($) => $['directory.errorTitle'])}
- />
+ <div className="flex h-full flex-col">
+ {stateHeader}
+ <DirectoryState
+ action={
+ <Button onClick={context.retryIMCapability}>{t(($) => $['action.retry'])}</Button>
+ }
+ description={t(($) => $['directory.errorDescription'])}
+ icon="i-ri-error-warning-line"
+ title={t(($) => $['directory.errorTitle'])}
+ />
+ </div>
)
}
- return <DirectoryLoading />
+ return (
+ <div className="flex h-full flex-col">
+ {stateHeader}
+ <DirectoryLoading />
+ </div>
+ )
}
return (
- <main className="relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-background-body">
- <header className="shrink-0 px-4 pt-4 pb-2 sm:px-8">
+ <div className="relative flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-background-body">
+ <div className="shrink-0 px-4 pt-4 pb-2 sm:px-8">
<div className="flex h-6 items-center gap-2">
- <h1 className="title-2xl-semi-bold text-text-primary">
+ <h1 id={pageHeadingId} className="title-2xl-semi-bold text-text-primary">
{t(($) => $['directory.title'])}
</h1>
- <a
- href="#contacts-help"
- className="ms-auto inline-flex items-center gap-0.5 system-xs-regular text-text-tertiary hover:text-text-secondary hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- >
- {t(($) => $['directory.learnMore'])}
- <span aria-hidden className="i-ri-external-link-line size-3" />
- </a>
</div>
<div className="mt-3.5 flex min-w-0 flex-col gap-2 lg:flex-row lg:items-center">
<SegmentedControl
@@ -399,28 +465,23 @@ export function ContactsDirectoryPage() {
onValueChange={updateKind}
>
{filters.map((filter, index) => (
- <SegmentedControlItem
- key={filter}
- aria-label={t(($) => $[`filter.${filter}`])}
- value={filter}
- className={cn(
- 'gap-1 border-0 px-2.5 data-checked:text-text-primary data-checked:inset-ring-[0.5px] data-checked:inset-ring-components-segmented-control-item-active-border',
- index < filters.length - 1 &&
- kind !== filter &&
- kind !== filters[index + 1] &&
- 'after:absolute after:inset-y-1.75 after:inset-e-0 after:w-px after:bg-divider-regular',
- )}
- >
- <span>{t(($) => $[`filter.${filter}`])}</span>
- {filter !== 'all' && (
- <span className="flex h-4 min-w-4 shrink-0 items-center justify-center rounded-[5px] bg-components-badge-bg-dimm px-1 system-2xs-medium-uppercase text-text-tertiary inset-ring-1 inset-ring-divider-deep">
- {contactCounts[filter] ?? '—'}
- </span>
+ <Fragment key={filter}>
+ <SegmentedControlItem value={filter} className="gap-1 px-2.5">
+ <span>{t(($) => $[`filter.${filter}`])}</span>
+ {filter !== 'all' && (
+ <span className="flex h-4 min-w-4 shrink-0 items-center justify-center rounded-[5px] bg-components-badge-bg-dimm px-1 system-2xs-medium-uppercase text-text-tertiary inset-ring-1 inset-ring-divider-deep">
+ {contactCounts[filter] ?? '—'}
+ </span>
+ )}
+ </SegmentedControlItem>
+ {index < filters.length - 1 && (
+ <SegmentedControlDivider className="has-[+_[data-checked]]:invisible [input:checked+&]:invisible" />
)}
- </SegmentedControlItem>
+ </Fragment>
))}
</SegmentedControl>
<SearchInput
+ ref={searchRef}
aria-label={t(($) => $['directory.search'])}
className="h-8 min-w-0 lg:w-50 lg:shrink-0"
placeholder={t(($) => $['directory.search'])}
@@ -429,7 +490,7 @@ export function ContactsDirectoryPage() {
/>
{context.permissions.canManageContacts && (
<div className="flex shrink-0 lg:ms-auto">
- {context.imCentrallyManaged && repository.supportsPlatformImport !== false ? (
+ {context.imCentrallyManaged ? (
<Menu>
<MenuTrigger render={<Button variant="primary" />}>
<span aria-hidden className="me-1 i-ri-add-line size-4" />
@@ -444,7 +505,7 @@ export function ContactsDirectoryPage() {
/>
{t(($) => $['directory.addFromPlatform'])}
</MenuItem>
- <MenuItem className="gap-2" onClick={() => setExternalDialogOpen(true)}>
+ <MenuItem className="gap-2" onClick={openCreateContact}>
<span
aria-hidden
className="i-ri-contacts-book-line size-4 text-text-tertiary"
@@ -454,7 +515,7 @@ export function ContactsDirectoryPage() {
</MenuContent>
</Menu>
) : (
- <Button variant="primary" onClick={() => setExternalDialogOpen(true)}>
+ <Button variant="primary" onClick={openCreateContact}>
<span aria-hidden className="me-1 i-ri-add-line size-4" />
{t(($) => $['directory.addExternal'])}
</Button>
@@ -467,13 +528,20 @@ export function ContactsDirectoryPage() {
{t(($) => $['directory.viewOnly'])}
</p>
)}
- </header>
+ </div>
<div className="flex min-h-0 flex-1 gap-1 overflow-hidden px-4 pt-1 pb-1 sm:px-8">
<ScrollArea className="min-h-0 min-w-0 flex-1 overflow-hidden rounded-xl bg-components-panel-bg">
- <ScrollAreaViewport ref={scrollContainerRef} className="overscroll-contain">
- <ScrollAreaContent className="flex min-h-full flex-col">
+ <ScrollAreaViewport
+ ref={scrollContainerRef}
+ role="region"
+ aria-labelledby={pageHeadingId}
+ className="overscroll-contain"
+ >
+ <ScrollAreaContent
+ className={cn('flex min-h-full flex-col', selectedContactIds.length > 0 && 'pb-24')}
+ >
{directoryQuery.isPending && <DirectoryLoading />}
- {directoryQuery.isError && !directoryQuery.contacts.length && (
+ {directoryQuery.isError && !contacts.length && (
<DirectoryState
action={
<Button onClick={() => directoryQuery.refetch()}>
@@ -485,50 +553,49 @@ export function ContactsDirectoryPage() {
title={t(($) => $['directory.errorTitle'])}
/>
)}
- {!directoryQuery.isPending &&
- !directoryQuery.isError &&
- !directoryQuery.contacts.length && (
- <DirectoryState
- action={
- hasFilters && !(kind === 'external' && !search) ? (
- <Button onClick={clearFilters}>{t(($) => $['action.clearFilters'])}</Button>
- ) : context.permissions.canManageContacts ? (
- <Button onClick={() => setExternalDialogOpen(true)}>
- <span aria-hidden className="i-ri-add-line size-4" />
- {t(($) => $['directory.addExternal'])}
- </Button>
- ) : undefined
- }
- className={cn(
- !(hasFilters && !(kind === 'external' && !search)) && 'pt-1 pb-12',
- )}
- description={t(
- ($) =>
- $[
- hasFilters && !(kind === 'external' && !search)
- ? 'directory.noResultsDescription'
- : 'directory.externalEmptyDescription'
- ],
- )}
- icon={hasFilters && !(kind === 'external' && !search) ? 'i-ri-search-line' : ''}
- iconSrc={
- hasFilters && !(kind === 'external' && !search)
- ? undefined
- : UserCommunityIcon.src
- }
- title={t(
- ($) =>
- $[
- hasFilters && !(kind === 'external' && !search)
- ? 'directory.noResultsTitle'
- : 'directory.externalEmptyTitle'
- ],
- )}
- />
- )}
- {directoryQuery.contacts.length > 0 && (
+ {!directoryQuery.isPending && !directoryQuery.isError && !contacts.length && (
+ <DirectoryState
+ action={
+ hasFilters && !(kind === 'external' && !search) ? (
+ <Button onClick={clearFilters}>{t(($) => $['action.clearFilters'])}</Button>
+ ) : context.permissions.canManageContacts ? (
+ <Button onClick={openCreateContact}>
+ <span aria-hidden className="i-ri-add-line size-4" />
+ {t(($) => $['directory.addExternal'])}
+ </Button>
+ ) : undefined
+ }
+ className={cn(!(hasFilters && !(kind === 'external' && !search)) && 'pt-1 pb-12')}
+ description={t(
+ ($) =>
+ $[
+ hasFilters && !(kind === 'external' && !search)
+ ? 'directory.noResultsDescription'
+ : 'directory.externalEmptyDescription'
+ ],
+ )}
+ icon={hasFilters && !(kind === 'external' && !search) ? 'i-ri-search-line' : ''}
+ iconSrc={
+ hasFilters && !(kind === 'external' && !search)
+ ? undefined
+ : UserCommunityIcon.src
+ }
+ title={t(
+ ($) =>
+ $[
+ hasFilters && !(kind === 'external' && !search)
+ ? 'directory.noResultsTitle'
+ : 'directory.externalEmptyTitle'
+ ],
+ )}
+ />
+ )}
+ {contacts.length > 0 && (
<div className="min-h-full overflow-hidden rounded-xl bg-components-panel-bg px-1 pt-1.5">
- <table className="w-full min-w-180 border-collapse">
+ <table
+ aria-labelledby={pageHeadingId}
+ className="w-full min-w-180 border-collapse"
+ >
<colgroup>
{context.permissions.canManageContacts && <col className="w-8" />}
<col />
@@ -564,10 +631,12 @@ export function ContactsDirectoryPage() {
</tr>
</thead>
<tbody>
- {directoryQuery.contacts.map((contact) => (
+ {contacts.map((contact) => (
<ContactRow
key={contact.id}
contact={contact}
+ panelId={detailsPanelId}
+ expanded={contact.id === contactId}
selected={selectedContactIds.includes(contact.id)}
selectionEnabled={context.permissions.canManageContacts}
selectionPending={removeContacts.isPending}
@@ -596,9 +665,7 @@ export function ContactsDirectoryPage() {
)}
<InfiniteScrollSentinel
canLoadMore={
- !directoryQuery.isFetching &&
- !directoryQuery.isFetchNextPageError &&
- currentPageCount >= loadedPages
+ !directoryQuery.isFetching && !directoryQuery.isFetchNextPageError
}
onLoadMore={() => void loadMore()}
preloadDistance={100}
@@ -621,6 +688,8 @@ export function ContactsDirectoryPage() {
{selectedContact && (
<ContactDetailsPanel
contact={selectedContact}
+ id={detailsPanelId}
+ headingRef={detailsHeadingRef}
canManage={context.permissions.canManageContacts}
removing={removeContacts.isPending}
onClose={closeDetails}
@@ -631,53 +700,65 @@ export function ContactsDirectoryPage() {
onRemove={() => {
setRemovalError(false)
setRemovalTargetIds([selectedContact.id])
+ setRemovalContactName(selectedContact.name)
+ setRemovalOpen(true)
}}
/>
)}
{contactId && !selectedContact && (
- <aside
+ <section
+ id={detailsPanelId}
aria-label={t(($) => $['details.title'])}
className="flex h-full w-80 max-w-full shrink-0 flex-col rounded-xl border border-divider-subtle bg-components-panel-bg p-4"
>
<Button className="self-end" variant="ghost" onClick={closeDetails}>
{t(($) => $['action.close'])}
</Button>
- <p
- role={detailsQuery.isError ? 'alert' : 'status'}
- className="my-auto text-center system-sm-regular text-text-tertiary"
- >
- {t(
- ($) =>
- $[
- detailsQuery.isPending
- ? 'details.loading'
- : detailsQuery.isError
- ? 'details.error'
- : 'details.notFound'
- ],
- )}
- </p>
- {detailsQuery.isError && (
+ {detailsQuery.isPending ? (
+ <div aria-busy="true" className="my-auto space-y-4">
+ <div className="mx-auto size-24 animate-pulse rounded-full bg-background-default-subtle" />
+ <div className="h-6 animate-pulse rounded-lg bg-background-default-subtle" />
+ <div className="h-12 animate-pulse rounded-lg bg-background-default-subtle" />
+ </div>
+ ) : (
+ <p
+ role={detailsQuery.isError ? 'alert' : undefined}
+ className="my-auto text-center system-sm-regular text-text-tertiary"
+ >
+ {t(($) => $[detailsFailed ? 'details.error' : 'details.notFound'])}
+ </p>
+ )}
+ {detailsFailed && (
<Button onClick={() => detailsQuery.refetch()}>{t(($) => $['action.retry'])}</Button>
)}
- </aside>
+ </section>
)}
</div>
+ <p role="status" aria-atomic="true" className="sr-only">
+ {selectedContactIds.length
+ ? t(($) => $['platformPicker.selected'], { count: selectedContactIds.length })
+ : !directoryQuery.isPending && !directoryQuery.isError
+ ? t(($) => $['directory.resultCount'], {
+ count: directoryQuery.data?.pages[0]?.total ?? 0,
+ })
+ : ''}
+ </p>
<AlertDialog
- open={Boolean(removalTargetIds)}
+ open={removalOpen}
onOpenChange={(open) => {
if (removeContacts.isPending) return
setRemovalError(false)
- setRemovalTargetIds(open ? [...selectedContactIds] : null)
+ setRemovalOpen(open)
+ if (open) {
+ setRemovalTargetIds([...selectedContactIds])
+ setRemovalContactName(undefined)
+ }
}}
>
{selectedContactIds.length > 0 && (
<div className="pointer-events-none absolute inset-s-0 inset-e-0 bottom-6 z-20 flex justify-center px-4">
<div className="pointer-events-auto flex flex-col items-center gap-1">
- <div
- aria-live="polite"
- className="flex items-center gap-1 rounded-[10px] border border-components-actionbar-border-accent bg-components-actionbar-bg-accent p-1 shadow-xl shadow-shadow-shadow-5 backdrop-blur-[5px]"
- >
+ <div className="flex items-center gap-1 rounded-[10px] border border-components-actionbar-border-accent bg-components-actionbar-bg-accent p-1 shadow-xl shadow-shadow-shadow-5 backdrop-blur-[5px]">
<div className="inline-flex items-center gap-2 py-1 ps-2 pe-3">
<span className="flex size-5 items-center justify-center rounded-md bg-text-accent system-xs-medium text-text-primary-on-surface">
{selectedContactIds.length}
@@ -705,6 +786,7 @@ export function ContactsDirectoryPage() {
className="px-3"
disabled={removeContacts.isPending}
onClick={() => {
+ focusDirectory()?.focus()
setSelectedContactIds([])
setRemovalError(false)
}}
@@ -715,17 +797,33 @@ export function ContactsDirectoryPage() {
</div>
</div>
)}
- <AlertDialogContent backdropProps={{ forceRender: true }}>
+ <AlertDialogContent
+ finalFocus={() => focusDirectory(removalTargetIds)}
+ backdropProps={{ forceRender: true }}
+ >
<AlertDialogHeader>
- <AlertDialogTitle>{t(($) => $['directory.removalTitle'])}</AlertDialogTitle>
+ <AlertDialogTitle>
+ {removalContactName
+ ? t(($) => $['directory.removalSingleTitle'], { name: removalContactName })
+ : t(($) => $['directory.removalCountTitle'], { count: removalTargetIds.length })}
+ </AlertDialogTitle>
<AlertDialogDescription>
- {t(($) => $['directory.removalDescription'])}
+ {removalContactName
+ ? t(($) => $['directory.removalSingleDescription'], { name: removalContactName })
+ : t(($) => $['directory.removalDescription'])}
</AlertDialogDescription>
</AlertDialogHeader>
{removalError && (
<AlertDialogBody>
<p role="alert" className="system-sm-regular text-text-destructive">
- {t(($) => $['directory.removalFailed'])}
+ {t(
+ ($) =>
+ $[
+ removalContactName
+ ? 'directory.removalSingleFailed'
+ : 'directory.removalFailed'
+ ],
+ )}
</p>
</AlertDialogBody>
)}
@@ -740,21 +838,19 @@ export function ContactsDirectoryPage() {
</AlertDialogContent>
</AlertDialog>
<ExternalContactDialog
- key={editingContact?.id ?? 'create-external-contact'}
contact={editingContact ?? undefined}
open={externalDialogOpen}
onOpenChange={(open) => {
setExternalDialogOpen(open)
- if (!open) setEditingContact(null)
}}
onCreated={openDetails}
/>
- {context.imCentrallyManaged && repository.supportsPlatformImport !== false && (
+ {context.imCentrallyManaged && (
<PlatformContactPickerDialog
open={platformDialogOpen}
onOpenChange={setPlatformDialogOpen}
/>
)}
- </main>
+ </div>
)
}
diff --git a/web/features/contacts/management/external-contact-dialog.tsx b/web/features/contacts/management/external-contact-dialog.tsx
index 34e0e114fe9..0407773b8fa 100644
--- a/web/features/contacts/management/external-contact-dialog.tsx
+++ b/web/features/contacts/management/external-contact-dialog.tsx
@@ -1,31 +1,27 @@
'use client'
+import type { ExternalContactCreateRequest } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ContactView } from './types'
-import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
import {
Dialog,
- DialogClose,
DialogContent,
DialogDescription,
+ DialogHeader,
+ DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { useMutation } from '@tanstack/react-query'
-import { useEffect, useRef, useState } from 'react'
+import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { consoleQuery } from '@/service/console'
import { ALLOW_FILE_EXTENSIONS } from '@/types/app'
-import { useCreateExternalContact, useUpdateExternalContact } from './hooks'
-
-type ExternalContactDraft = {
- displayName: string
- email: string
-}
+import AvatarInnerRing from './assets/avatar-inner-ring.svg'
+import AvatarOuterRing from './assets/avatar-outer-ring.svg'
+import { ContactAvatar } from './contact-avatar'
type ExternalContactDialogProps = {
onCreated: (contactId: string) => void
@@ -34,133 +30,67 @@ type ExternalContactDialogProps = {
contact?: Pick<ContactView, 'avatar_url' | 'email' | 'id' | 'name'>
}
-// Original artwork exported from Figma node 1303:66983.
-const defaultAvatarPeople =
- 'data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjcyIiBoZWlnaHQ9IjExNi41NzEiIHZpZXdCb3g9IjAgMCA3MiAxMTYuNTcxIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8ZyBpZD0iUGVvcGxlIj4KPGNpcmNsZSBpZD0iSGVhZCIgY3g9IjM2IiBjeT0iMTguODU3MSIgcj0iMTguODU3MSIgZmlsbD0idXJsKCNwYWludDBfcmFkaWFsXzBfMTkxNykiLz4KPGNpcmNsZSBpZD0iQm9keSIgY3g9IjM2IiBjeT0iODAuNTcxNCIgcj0iMzYiIGZpbGw9InVybCgjcGFpbnQxX3JhZGlhbF8wXzE5MTcpIi8+CjwvZz4KPGRlZnM+CjxyYWRpYWxHcmFkaWVudCBpZD0icGFpbnQwX3JhZGlhbF8wXzE5MTciIGN4PSIwIiBjeT0iMCIgcj0iMSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGdyYWRpZW50VHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjcuNDI4NiA3LjcxNDI4KSByb3RhdGUoNTQuNjM3NSkgc2NhbGUoMzIuNTgyNykiPgo8c3RvcCBzdG9wLWNvbG9yPSJ3aGl0ZSIgc3RvcC1vcGFjaXR5PSIwLjkiLz4KPHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSJ3aGl0ZSIgc3RvcC1vcGFjaXR5PSIwLjMiLz4KPC9yYWRpYWxHcmFkaWVudD4KPHJhZGlhbEdyYWRpZW50IGlkPSJwYWludDFfcmFkaWFsXzBfMTkxNyIgY3g9IjAiIGN5PSIwIiByPSIxIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgZ3JhZGllbnRUcmFuc2Zvcm09InRyYW5zbGF0ZSgyNC44NTcxIDU1LjcxNDMpIHJvdGF0ZSg2Mi4xNTI0KSBzY2FsZSg1MS4zNzg1KSI+CjxzdG9wIHN0b3AtY29sb3I9IndoaXRlIiBzdG9wLW9wYWNpdHk9IjAuNyIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IndoaXRlIiBzdG9wLW9wYWNpdHk9IjAuMyIvPgo8L3JhZGlhbEdyYWRpZW50Pgo8L2RlZnM+Cjwvc3ZnPgo='
-const avatarInnerRing =
- 'data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjEyNCIgaGVpZ2h0PSIxMjQiIHZpZXdCb3g9IjAgMCAxMjQgMTI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8Y2lyY2xlIGlkPSJFbGxpcHNlIDEiIG9wYWNpdHk9IjAuNiIgY3g9IjYyIiBjeT0iNjIiIHI9IjYxLjUiIHN0cm9rZT0iIzEwMTgyOCIgc3Ryb2tlLW9wYWNpdHk9IjAuMDQiLz4KPC9zdmc+Cg=='
-const avatarOuterRing =
- 'data:image/svg+xml;base64,PHN2ZyBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiBvdmVyZmxvdz0idmlzaWJsZSIgc3R5bGU9ImRpc3BsYXk6IGJsb2NrOyIgd2lkdGg9IjE1NiIgaGVpZ2h0PSIxNTYiIHZpZXdCb3g9IjAgMCAxNTYgMTU2IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8Y2lyY2xlIGlkPSJFbGxpcHNlIDIiIG9wYWNpdHk9IjAuNCIgY3g9Ijc4IiBjeT0iNzgiIHI9Ijc3LjUiIHN0cm9rZT0iIzEwMTgyOCIgc3Ryb2tlLW9wYWNpdHk9IjAuMDQiLz4KPC9zdmc+Cg=='
-
-const emptyDraft: ExternalContactDraft = { displayName: '', email: '' }
const maxContactNameLength = 255
function isValidEmail(value: string) {
+ const input = document.createElement('input')
+ input.type = 'email'
+ input.value = value
const parts = value.split('@')
if (parts.length !== 2) return false
const [local, domain] = parts
return Boolean(
+ input.validity.valid &&
local &&
local.split('.').every((part) => part.length > 0) &&
domain &&
- !value.includes(' ') &&
+ !/\s/.test(value) &&
domain.includes('.') &&
!domain.startsWith('.') &&
!domain.endsWith('.'),
)
}
-function ContactAvatar({
- avatar,
- className,
- fallbackName,
- name,
-}: {
- avatar: string | null
- className?: string
- fallbackName?: string
- name: string
-}) {
- return (
- <Avatar
- className={cn(
- 'size-24 border-2 border-components-panel-bg data-loading:bg-background-section-burn',
- fallbackName ? 'bg-text-accent' : 'bg-components-avatar-default-avatar-bg',
- className,
- )}
- render={(props, { imageLoadingStatus }) => (
- <span
- {...props}
- data-loading={
- avatar && (imageLoadingStatus === 'idle' || imageLoadingStatus === 'loading')
- ? ''
- : undefined
- }
- />
- )}
- >
- {avatar && (
- <AvatarImage
- key={avatar.split('?')[0]}
- keepMounted
- src={avatar}
- alt={name}
- className="data-error:invisible"
- />
- )}
- <AvatarFallback
- className={cn(
- 'relative overflow-hidden rounded-full inset-ring-[0.5px] inset-ring-divider-regular',
- fallbackName && 'text-5xl leading-[1.2] font-semibold',
- !fallbackName &&
- 'bg-linear-to-br from-components-avatar-bg-mask-stop-0/50 to-components-avatar-bg-mask-stop-100/50 backdrop-blur-xs',
- )}
- render={(props, { imageLoadingStatus }) => (
- <span {...props}>
- {(!avatar || imageLoadingStatus === 'error') &&
- (fallbackName ? (
- [...fallbackName][0]?.toLocaleUpperCase()
- ) : (
- <img
- alt=""
- src={defaultAvatarPeople}
- className="absolute inset-s-1/8 top-[21.43%] h-[121.43%] w-3/4 max-w-none"
- />
- ))}
- </span>
- )}
- />
- </Avatar>
- )
-}
-
-export function ExternalContactDialog({
+function ExternalContactForm({
contact,
onCreated,
onOpenChange,
- open,
-}: ExternalContactDialogProps) {
+ onBusyChange,
+}: Omit<ExternalContactDialogProps, 'open'> & { onBusyChange: (busy: boolean) => void }) {
const { t } = useTranslation(['contacts', 'common'])
- const createExternalContact = useCreateExternalContact()
- const updateExternalContact = useUpdateExternalContact()
- const uploadAvatar = useMutation(consoleQuery.files.upload.post.mutationOptions())
+ const create = useMutation(
+ consoleQuery.workspaces.current.humanInput.v2.contacts.external.post.mutationOptions({
+ context: { silent: true },
+ }),
+ )
+ const update = useMutation(
+ consoleQuery.workspaces.current.humanInput.v2.contacts.external.byContactId.patch.mutationOptions(
+ { context: { silent: true } },
+ ),
+ )
+ const uploadAvatar = useMutation(
+ consoleQuery.files.upload.post.mutationOptions({ context: { silent: true } }),
+ )
const avatarInputRef = useRef<HTMLInputElement>(null)
const [uploadedAvatar, setUploadedAvatar] = useState<{ id: string; url: string }>()
const [avatarError, setAvatarError] = useState<string | null>(null)
- const initialDraft = contact
- ? { displayName: contact.name, email: contact.email ?? '' }
- : emptyDraft
- const [draft, setDraft] = useState<ExternalContactDraft>(initialDraft)
- const [fieldError, setFieldError] = useState<
- 'name_required' | 'name_too_long' | 'email_required' | 'email_invalid' | null
- >(null)
- const [resultError, setResultError] = useState<string | null>(null)
- const resetMutation = createExternalContact.reset
- const pending = createExternalContact.isPending || updateExternalContact.isPending
+ const [name, setName] = useState(contact?.name ?? '')
+ const [emailError, setEmailError] = useState<string>()
+ const avatarErrorId = useId()
+ const pending = create.isPending || update.isPending
const busy = pending || uploadAvatar.isPending
- const avatarUrl = uploadedAvatar?.url ?? contact?.avatar_url ?? null
+ const error = create.error ?? update.error
+ const avatarUrl = uploadedAvatar?.url ?? contact?.avatar_url
useEffect(() => {
- return () => {
+ onBusyChange(busy)
+ }, [busy, onBusyChange])
+ useEffect(
+ () => () => {
if (uploadedAvatar) URL.revokeObjectURL(uploadedAvatar.url)
- }
- }, [uploadedAvatar])
-
- function resetAvatar() {
- setUploadedAvatar(undefined)
- setAvatarError(null)
- uploadAvatar.reset()
- }
+ },
+ [uploadedAvatar],
+ )
function handleAvatarUpload(file: File) {
if (busy) return
@@ -188,257 +118,216 @@ export function ExternalContactDialog({
)
}
- function resetDialog() {
- setDraft(initialDraft)
- setFieldError(null)
- setResultError(null)
- resetMutation()
- updateExternalContact.reset()
- resetAvatar()
- }
-
- function closeDialog() {
- if (busy) return
- onOpenChange(false)
- resetDialog()
- }
-
- function updateDraft(field: keyof ExternalContactDraft, value: string) {
- setDraft((current) => ({ ...current, [field]: value }))
- setFieldError(null)
- setResultError(null)
- }
-
- async function handleSubmit() {
+ function handleSubmit(values: ExternalContactCreateRequest) {
if (busy || avatarError) return
- if (!draft.displayName.trim()) {
- setFieldError('name_required')
- return
- }
- if ([...draft.displayName.trim()].length > maxContactNameLength) {
- setFieldError('name_too_long')
- return
- }
- if (!draft.email.trim()) {
- setFieldError('email_required')
- return
- }
- if (!isValidEmail(draft.email.trim())) {
- setFieldError('email_invalid')
- return
- }
-
- const values = {
- displayName: draft.displayName.trim(),
- email: draft.email.trim(),
+ const body = {
+ name: values.name.trim(),
+ email: values.email.trim(),
...(uploadedAvatar ? { avatar: uploadedAvatar.id } : {}),
}
- const result = contact
- ? await updateExternalContact.mutateAsync({ ...values, contactId: contact.id })
- : await createExternalContact.mutateAsync(values)
- if (result.kind === 'created' || result.kind === 'updated') {
- onOpenChange(false)
- onCreated(result.contactId)
- resetDialog()
- return
+ const callbacks = {
+ onSuccess: ({ contact }: { contact: ContactView }) => {
+ onOpenChange(false)
+ onCreated(contact.id)
+ },
+ onError: (error: Error) => {
+ if ('status' in error && error.status === 409)
+ setEmailError(t(($) => $['external.result.duplicate_external_contact']))
+ },
}
-
- setResultError(result.kind)
+ if (contact) update.mutate({ params: { contact_id: contact.id }, body }, callbacks)
+ else create.mutate({ body }, callbacks)
}
- const nameError = fieldError === 'name_required' || fieldError === 'name_too_long'
- const fieldErrorMessage = fieldError
- ? t(
- ($) => $[`external.validation.${fieldError}`],
- fieldError === 'name_too_long' ? { maxLength: maxContactNameLength } : undefined,
- )
- : null
- const resultErrorMessage = (() => {
- switch (resultError) {
- case 'duplicate_external_contact':
- return t(($) => $['external.result.duplicate_external_contact'])
- case 'matches_workspace_contact':
- return t(($) => $['external.result.matches_workspace_contact'])
- case 'matches_platform_contact':
- return t(($) => $['external.result.matches_platform_contact'])
- case 'failed':
- return contact
- ? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' })
- : t(($) => $['external.result.failed'])
- default:
- return null
- }
- })()
-
return (
- <Dialog
- open={open}
- onOpenChange={(nextOpen) => !nextOpen && closeDialog()}
- disablePointerDismissal={busy}
- >
- <DialogContent className="w-104 max-w-[calc(100vw-2rem)]">
- <DialogClose
- render={
- <IconButton
- aria-label={t(($) => $['action.close'])}
- className="absolute inset-e-5 top-5"
- disabled={busy}
- size="lg"
- >
- <span aria-hidden className="i-ri-close-line size-4.5" />
- </IconButton>
- }
- />
- <div className="h-14.5 ps-6 pe-14 pt-6 pb-3">
- <DialogTitle>
- {t(($) => $[contact ? 'external.editTitle' : 'external.title'])}
- </DialogTitle>
- <DialogDescription className="sr-only">
- {t(($) => $[contact ? 'external.editDescription' : 'external.description'])}
- </DialogDescription>
- </div>
- <Form<ExternalContactDraft>
- errors={
- fieldError && fieldErrorMessage
- ? { [nameError ? 'displayName' : 'email']: fieldErrorMessage }
- : undefined
- }
- onFormSubmit={handleSubmit}
- >
- <div className="relative flex flex-col items-center gap-2 px-4 pt-10 pb-2">
- <div
- aria-hidden
- className="pointer-events-none absolute inset-x-6 top-1 h-25 overflow-hidden rounded-lg"
- >
- <ContactAvatar
- avatar={avatarUrl}
- fallbackName={draft.displayName.trim()}
- name=""
- className="absolute inset-s-0 -top-33 size-108 opacity-20 blur-[80px]"
- />
- <img alt="" src={avatarInnerRing} className="absolute inset-s-38.5 top-5.5 size-31" />
- <img alt="" src={avatarOuterRing} className="absolute inset-s-34.5 top-1.5 size-39" />
- </div>
- <button
- type="button"
- aria-label={t(($) => $['avatar.editAction'], { ns: 'common' })}
- aria-describedby={avatarError ? 'external-avatar-error' : undefined}
- className="relative size-24 rounded-full outline-hidden focus-visible:ring-2 focus-visible:ring-components-input-border-hover disabled:cursor-wait"
- disabled={busy}
- onClick={() => avatarInputRef.current?.click()}
- >
- <ContactAvatar
- avatar={avatarUrl}
- fallbackName={draft.displayName.trim()}
- name={draft.displayName}
- />
- <span className="absolute inset-e-0 bottom-0 flex size-8 items-center justify-center rounded-full border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg text-components-button-secondary-text shadow-xs backdrop-blur-[5px]">
- <span
- aria-hidden
- className={
- uploadAvatar.isPending
- ? 'i-ri-loader-4-line size-4 animate-spin'
- : 'i-ri-edit-line size-4'
- }
- />
- </span>
- </button>
- <input
- ref={avatarInputRef}
- type="file"
- accept={ALLOW_FILE_EXTENSIONS.map((extension) => `.${extension}`).join(',')}
- aria-label={t(($) => $['imageUploader.imageUpload'], { ns: 'common' })}
- className="hidden"
- disabled={busy}
- onChange={(event) => {
- const file = event.currentTarget.files?.[0]
- event.currentTarget.value = ''
- if (file) handleAvatarUpload(file)
- }}
+ <>
+ <DialogHeader>
+ <DialogTitle>{t(($) => $[contact ? 'external.editTitle' : 'external.title'])}</DialogTitle>
+ <DialogDescription className="sr-only">
+ {t(($) => $[contact ? 'external.editDescription' : 'external.description'])}
+ </DialogDescription>
+ <DialogHeaderCloseButton aria-label={t(($) => $['action.close'])} disabled={busy} />
+ </DialogHeader>
+ <Form<ExternalContactCreateRequest>
+ errors={emailError ? { email: emailError } : undefined}
+ onFormSubmit={handleSubmit}
+ >
+ <div className="relative flex flex-col items-center gap-2 px-4 pt-10 pb-2">
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-6 top-1 h-25 overflow-hidden rounded-lg"
+ >
+ <ContactAvatar
+ avatar={avatarUrl}
+ name={name.trim()}
+ className="absolute inset-s-0 -top-33 size-108 bg-components-avatar-default-avatar-bg opacity-20 blur-[80px]"
+ />
+ <img
+ alt=""
+ src={AvatarInnerRing.src}
+ className="absolute inset-s-38.5 top-5.5 size-31"
+ />
+ <img
+ alt=""
+ src={AvatarOuterRing.src}
+ className="absolute inset-s-34.5 top-1.5 size-39"
/>
- {uploadAvatar.isPending && (
- <span role="status" className="system-xs-regular text-text-tertiary">
- {t(($) => $.loading, { ns: 'common' })}
- </span>
- )}
- {avatarError && (
- <p
- id="external-avatar-error"
- role="alert"
- className="system-xs-regular text-text-destructive"
- >
- {avatarError}
- </p>
- )}
- {(uploadedAvatar || avatarError) && (
- <Button size="small" disabled={busy} onClick={resetAvatar}>
- {t(($) => $['operation.reset'], { ns: 'common' })}
- </Button>
- )}
</div>
- <div className="space-y-4 px-6 py-3">
- <Field name="displayName">
- <FieldLabel>{t(($) => $['external.name'])}</FieldLabel>
- <Input
- autoComplete="name"
- placeholder={t(($) => $['external.namePlaceholder'])}
- disabled={busy}
- required
- value={draft.displayName}
- onChange={(event) => updateDraft('displayName', event.currentTarget.value)}
- />
- {nameError && <FieldError match>{fieldErrorMessage}</FieldError>}
- <FieldError match="valueMissing">
- {t(($) => $['external.validation.name_required'])}
- </FieldError>
- </Field>
- <Field name="email">
- <FieldLabel>{t(($) => $['external.email'])}</FieldLabel>
- <Input
- autoComplete="email"
- placeholder={t(($) => $['external.email'])}
- disabled={busy}
- required
- type="email"
- value={draft.email}
- onChange={(event) => updateDraft('email', event.currentTarget.value)}
+ <button
+ type="button"
+ aria-label={t(($) => $['avatar.editAction'], { ns: 'common' })}
+ aria-describedby={avatarError ? avatarErrorId : undefined}
+ className="relative size-24 rounded-full outline-hidden focus-visible:ring-2 focus-visible:ring-components-input-border-hover disabled:cursor-wait"
+ disabled={busy}
+ onClick={() => avatarInputRef.current?.click()}
+ >
+ <ContactAvatar
+ avatar={avatarUrl}
+ name={name.trim()}
+ className="size-24 border-2 border-components-panel-bg bg-text-accent text-5xl font-semibold"
+ />
+ <span className="absolute inset-e-0 bottom-0 flex size-8 items-center justify-center rounded-full border border-components-button-secondary-border bg-components-button-secondary-bg text-components-button-secondary-text shadow-xs backdrop-blur-[5px]">
+ <span
+ aria-hidden
+ className={
+ uploadAvatar.isPending
+ ? 'i-ri-loader-4-line size-4 animate-spin'
+ : 'i-ri-edit-line size-4'
+ }
/>
- {fieldError?.startsWith('email') && (
- <FieldError match>{fieldErrorMessage}</FieldError>
- )}
- <FieldError match="valueMissing">
- {t(($) => $['external.validation.email_required'])}
- </FieldError>
- <FieldError match="typeMismatch">
- {t(($) => $['external.validation.email_invalid'])}
- </FieldError>
- </Field>
- </div>
- {resultErrorMessage && (
- <div
- role="alert"
- className="mx-6 mt-4 rounded-lg bg-state-destructive-hover p-3 system-sm-regular text-text-destructive"
- >
- {resultErrorMessage}
- </div>
+ </span>
+ </button>
+ <input
+ ref={avatarInputRef}
+ type="file"
+ accept={ALLOW_FILE_EXTENSIONS.map((extension) => `.${extension}`).join(',')}
+ aria-label={t(($) => $['imageUploader.imageUpload'], { ns: 'common' })}
+ className="hidden"
+ disabled={busy}
+ onChange={(event) => {
+ const file = event.currentTarget.files?.[0]
+ event.currentTarget.value = ''
+ if (file) handleAvatarUpload(file)
+ }}
+ />
+ {avatarError && (
+ <p id={avatarErrorId} role="alert" className="system-xs-regular text-text-destructive">
+ {avatarError}
+ </p>
)}
- <div className="flex justify-end gap-2 px-6 pt-5 pb-6">
- <Button className="min-w-18" disabled={busy} onClick={closeDialog}>
- {t(($) => $['action.cancel'])}
- </Button>
+ {(uploadedAvatar || avatarError) && (
<Button
- type="submit"
- className="min-w-18"
- variant="primary"
- loading={pending}
- disabled={uploadAvatar.isPending || Boolean(avatarError)}
+ size="small"
+ disabled={busy}
+ onClick={() => {
+ setUploadedAvatar(undefined)
+ setAvatarError(null)
+ uploadAvatar.reset()
+ }}
>
- {pending
- ? t(($) => $[contact ? 'external.saving' : 'external.adding'])
- : t(($) => $[contact ? 'external.save' : 'external.add'])}
+ {t(($) => $['operation.reset'], { ns: 'common' })}
</Button>
- </div>
- </Form>
+ )}
+ </div>
+ <div className="space-y-4 px-6 py-3">
+ <Field
+ name="name"
+ validate={(value) =>
+ typeof value !== 'string' || !value.trim()
+ ? t(($) => $['external.validation.name_required'])
+ : [...value.trim()].length > maxContactNameLength
+ ? t(($) => $['external.validation.name_too_long'], {
+ maxLength: maxContactNameLength,
+ })
+ : null
+ }
+ >
+ <FieldLabel>{t(($) => $['external.name'])}</FieldLabel>
+ <Input
+ autoComplete="name"
+ placeholder={t(($) => $['external.namePlaceholder'])}
+ disabled={busy}
+ value={name}
+ onValueChange={setName}
+ />
+ <FieldError />
+ </Field>
+ <Field
+ name="email"
+ validate={(value) =>
+ typeof value !== 'string' || !value.trim()
+ ? t(($) => $['external.validation.email_required'])
+ : !isValidEmail(value.trim())
+ ? t(($) => $['external.validation.email_invalid'])
+ : null
+ }
+ >
+ <FieldLabel>{t(($) => $['external.email'])}</FieldLabel>
+ <Input
+ autoComplete="email"
+ inputMode="email"
+ placeholder={t(($) => $['external.email'])}
+ disabled={busy}
+ defaultValue={contact?.email ?? ''}
+ onValueChange={() => {
+ setEmailError(undefined)
+ create.reset()
+ update.reset()
+ }}
+ />
+ <FieldError />
+ </Field>
+ </div>
+ {error && !emailError && (
+ <p
+ role="alert"
+ className="mx-6 mt-4 rounded-lg bg-state-destructive-hover p-3 system-sm-regular text-text-destructive"
+ >
+ {contact
+ ? t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' })
+ : t(($) => $['external.result.failed'])}
+ </p>
+ )}
+ <div className="flex justify-end gap-2 px-6 pt-5 pb-6">
+ <Button className="min-w-18" disabled={busy} onClick={() => onOpenChange(false)}>
+ {t(($) => $['action.cancel'])}
+ </Button>
+ <Button
+ type="submit"
+ className="min-w-18"
+ variant="primary"
+ loading={pending}
+ disabled={uploadAvatar.isPending || Boolean(avatarError)}
+ >
+ {t(($) => $[contact ? 'external.save' : 'external.add'])}
+ </Button>
+ </div>
+ </Form>
+ </>
+ )
+}
+
+export function ExternalContactDialog({
+ open,
+ onOpenChange,
+ ...props
+}: ExternalContactDialogProps) {
+ const [busy, setBusy] = useState(false)
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!busy) onOpenChange(nextOpen)
+ }}
+ disablePointerDismissal={busy}
+ >
+ <DialogContent className="w-104">
+ <ExternalContactForm
+ key={props.contact?.id ?? 'create'}
+ {...props}
+ onOpenChange={onOpenChange}
+ onBusyChange={setBusy}
+ />
</DialogContent>
</Dialog>
)
diff --git a/web/features/contacts/management/hooks.ts b/web/features/contacts/management/hooks.ts
deleted file mode 100644
index 2a290d6371d..00000000000
--- a/web/features/contacts/management/hooks.ts
+++ /dev/null
@@ -1,388 +0,0 @@
-'use client'
-
-import type {
- AddPlatformContactsCommand,
- AvailablePlatformContactsQuery,
- ContactIMChannel,
- ContactsListQuery,
- ContactView,
- CreateExternalContactCommand,
- FindExternalContactsByEmailsCommand,
- RemoveContactIMBindingCommand,
- RemoveContactsCommand,
- RemoveMemberCommand,
- SetContactIMBindingCommand,
- UnbindContactIMBindingCommand,
- UpdateExternalContactCommand,
- UpgradeExternalContactsToWorkspaceCommand,
-} from './types'
-import {
- infiniteQueryOptions,
- mutationOptions,
- queryOptions,
- skipToken,
- useInfiniteQuery,
- useMutation,
- useQueries,
- useQuery,
- useQueryClient,
-} from '@tanstack/react-query'
-import { invalidateHumanInputContactQueries } from '@/service/console'
-import {
- useContactsFeatureContext,
- useContactsManagementRepository,
- useOptionalContactsManagement,
-} from './composition-context'
-import { contactsManagementQueryKeys } from './query-keys'
-
-function mergeContactPages(pages: ContactView[][]): ContactView[] {
- const contacts = new Map<string, ContactView>()
- for (const page of pages) {
- for (const contact of page) contacts.set(contact.id, contact)
- }
- return [...contacts.values()]
-}
-
-export function useContactsDirectory(query: Omit<ContactsListQuery, 'deployment' | 'page'>) {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const result = useInfiniteQuery(
- infiniteQueryOptions({
- enabled:
- Boolean(context.workspaceId) &&
- context.permissions.canViewContacts &&
- context.imCentrallyManaged !== undefined,
- initialPageParam: 1,
- queryFn: ({ pageParam }) =>
- repository.listContacts({ ...query, deployment: context.deployment, page: pageParam }),
- queryKey: [...contactsManagementQueryKeys.directory(context, query), repository] as const,
- getNextPageParam: (lastPage) => (lastPage.has_more ? lastPage.page + 1 : undefined),
- }),
- )
-
- return {
- contacts: mergeContactPages(result.data?.pages.map((page) => page.data) ?? []),
- data: result.data,
- error: result.error,
- fetchNextPage: result.fetchNextPage,
- hasNextPage: result.hasNextPage,
- isError: result.isError,
- isFetchNextPageError: result.isFetchNextPageError,
- isFetching: result.isFetching,
- isFetchingNextPage: result.isFetchingNextPage,
- isPending: result.isPending,
- refetch: result.refetch,
- }
-}
-
-export function useContactDetails(contactId: string | null) {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- return useQuery(
- queryOptions({
- queryKey: contactsManagementQueryKeys.detail(context.workspaceId, contactId),
- queryFn:
- contactId && context.workspaceId && context.permissions.canViewContacts
- ? () => repository.getContact(contactId)
- : skipToken,
- retry: false,
- }),
- )
-}
-
-export function useContactCounts() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const kinds = ['workspace', 'platform', 'external'] as const
- const results = useQueries({
- queries: kinds.map((kind) =>
- queryOptions({
- queryKey: [
- ...contactsManagementQueryKeys.all(context.workspaceId),
- 'count',
- context.deployment,
- kind,
- ],
- queryFn: () =>
- repository.listContacts({
- deployment: context.deployment,
- kind,
- page: 1,
- limit: 1,
- search: '',
- }),
- enabled:
- Boolean(context.workspaceId) &&
- context.permissions.canViewContacts &&
- (kind !== 'platform' || context.imCentrallyManaged === true),
- select: (page) => page.total,
- }),
- ),
- })
- return { workspace: results[0]?.data, platform: results[1]?.data, external: results[2]?.data }
-}
-
-export function useAvailablePlatformContacts(
- query: Omit<AvailablePlatformContactsQuery, 'page'>,
- enabled: boolean,
-) {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const result = useInfiniteQuery(
- infiniteQueryOptions({
- enabled:
- enabled &&
- Boolean(context.workspaceId) &&
- context.permissions.canManageContacts &&
- context.imCentrallyManaged === true &&
- repository.supportsPlatformImport !== false,
- initialPageParam: 1,
- queryFn: ({ pageParam }) =>
- repository.listAvailablePlatformContacts({ ...query, page: pageParam }),
- queryKey: [
- ...contactsManagementQueryKeys.availablePlatformContacts(context.workspaceId, query),
- repository,
- ] as const,
- getNextPageParam: (lastPage) => (lastPage.has_more ? lastPage.page + 1 : undefined),
- }),
- )
-
- return {
- contacts: [
- ...new Map(
- (result.data?.pages.flatMap((page) => page.data) ?? []).map((contact) => [
- contact.id,
- contact,
- ]),
- ).values(),
- ],
- error: result.error,
- fetchNextPage: result.fetchNextPage,
- hasNextPage: result.hasNextPage,
- isError: result.isError,
- isFetchNextPageError: result.isFetchNextPageError,
- isFetchingNextPage: result.isFetchingNextPage,
- isPending: result.isPending,
- refetch: result.refetch,
- }
-}
-
-export function useCreateExternalContact() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
-
- return useMutation(
- mutationOptions({
- mutationFn: (command: CreateExternalContactCommand) =>
- repository.createExternalContact(command),
- onSuccess: (result) => {
- if (result.kind !== 'created') return
- return invalidateHumanInputContactQueries(queryClient, context.workspaceId)
- },
- }),
- )
-}
-
-export function useUpdateExternalContact() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
-
- return useMutation(
- mutationOptions({
- mutationFn: (command: UpdateExternalContactCommand) =>
- repository.updateExternalContact(command),
- onSuccess: (result) => {
- if (result.kind !== 'updated') return
- return invalidateHumanInputContactQueries(queryClient, context.workspaceId)
- },
- }),
- )
-}
-
-export function useAddPlatformContacts() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
-
- return useMutation(
- mutationOptions({
- mutationFn: (command: AddPlatformContactsCommand) => {
- if (
- !context.workspaceId ||
- !context.imCentrallyManaged ||
- !context.permissions.canManageContacts ||
- repository.supportsPlatformImport === false
- )
- return Promise.resolve({ kind: 'forbidden' as const })
- return repository.addPlatformContacts(command)
- },
- onSuccess: (result) => {
- if (result.kind !== 'added') return
- return invalidateHumanInputContactQueries(queryClient, context.workspaceId)
- },
- }),
- )
-}
-
-export function useRemoveContacts() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
-
- return useMutation(
- mutationOptions({
- mutationFn: (command: RemoveContactsCommand) => repository.removeContacts(command),
- onSuccess: (result) => {
- if (result.kind !== 'removed') return
- return invalidateHumanInputContactQueries(queryClient, context.workspaceId)
- },
- }),
- )
-}
-
-export function useRemoveContactMember() {
- const { context, repository } = useOptionalContactsManagement()
- const queryClient = useQueryClient()
- return useMutation(
- mutationOptions({
- mutationFn: (command: RemoveMemberCommand) => {
- if (!context || !repository) throw new Error('ContactsManagementProvider is required')
- return repository.removeMember(command)
- },
- onSuccess: (result) => {
- if (result.kind !== 'removed' || !context) return
- void invalidateHumanInputContactQueries(queryClient, context.workspaceId)
- },
- }),
- )
-}
-
-const emptyIMChannels: ContactIMChannel[] = []
-
-export function useContactIMChannels(enabled = true) {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const listIMChannels = repository.listIMChannels
- const query = useQuery(
- queryOptions({
- queryKey: [
- ...contactsManagementQueryKeys.all(context.workspaceId),
- 'im-channels',
- context.imCentrallyManaged,
- repository,
- ],
- queryFn: listIMChannels ? () => listIMChannels() : skipToken,
- enabled:
- enabled &&
- Boolean(context.workspaceId) &&
- context.imCentrallyManaged === false &&
- context.permissions.canManageContacts,
- retry: false,
- }),
- )
- return {
- data: query.data ?? emptyIMChannels,
- error: query.error,
- isError: query.isError,
- isFetching: query.isFetching,
- isPending: query.isPending,
- refetch: query.refetch,
- }
-}
-
-export function useContactIMIdentities(search: string) {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- return useInfiniteQuery(
- infiniteQueryOptions({
- queryKey: [...contactsManagementQueryKeys.all(context.workspaceId), 'im-identities', search],
- queryFn: ({ pageParam }) =>
- repository.listIMIdentities({ search, page: pageParam, limit: 20 }),
- initialPageParam: 1,
- getNextPageParam: (page) => (page.has_more ? page.page + 1 : undefined),
- enabled:
- Boolean(context.workspaceId) &&
- context.imCentrallyManaged !== undefined &&
- context.permissions.canManageContacts &&
- repository.supportsIMBindings === true,
- retry: false,
- }),
- )
-}
-
-export function useSetContactIMBinding() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
- return useMutation(
- mutationOptions({
- mutationFn: (command: SetContactIMBindingCommand) => repository.setIMBinding(command),
- onSuccess: () => invalidateHumanInputContactQueries(queryClient, context.workspaceId),
- }),
- )
-}
-
-export function useRemoveContactIMBinding() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
- return useMutation(
- mutationOptions({
- mutationFn: (command: RemoveContactIMBindingCommand) => repository.removeIMBinding(command),
- onSuccess: () => invalidateHumanInputContactQueries(queryClient, context.workspaceId),
- }),
- )
-}
-
-export function useUnbindContactIMBinding() {
- const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
- const queryClient = useQueryClient()
- return useMutation(
- mutationOptions({
- mutationFn: (command: UnbindContactIMBindingCommand) => repository.unbindIMBinding(command),
- onSuccess: () => invalidateHumanInputContactQueries(queryClient, context.workspaceId),
- }),
- )
-}
-
-export function useOptionalMemberInviteContactUpgrade() {
- const contactsManagement = useOptionalContactsManagement()
- const queryClient = useQueryClient()
- const findConflicts = useMutation(
- mutationOptions({
- mutationFn: async (command: FindExternalContactsByEmailsCommand) => {
- if (!contactsManagement.repository) return []
- return contactsManagement.repository.findExternalContactsByEmails(command)
- },
- }),
- )
- const upgradeContacts = useMutation(
- mutationOptions({
- mutationFn: async (command: UpgradeExternalContactsToWorkspaceCommand) => {
- if (!contactsManagement.repository) return { contactIds: [], kind: 'upgraded' as const }
- return contactsManagement.repository.upgradeExternalContactsToWorkspace(command)
- },
- onSuccess: (result) => {
- if (!contactsManagement.context || result.contactIds.length === 0) return
- void queryClient.invalidateQueries({
- queryKey: contactsManagementQueryKeys.all(contactsManagement.context.workspaceId),
- })
- },
- }),
- )
-
- return {
- available: Boolean(
- contactsManagement.context &&
- contactsManagement.repository &&
- contactsManagement.repository.supportsMemberManagement !== false,
- ),
- findConflicts: findConflicts.mutateAsync,
- isChecking: findConflicts.isPending,
- isUpgrading: upgradeContacts.isPending,
- upgradeContacts: upgradeContacts.mutateAsync,
- }
-}
diff --git a/web/features/contacts/management/member-invite-contact-upgrade-dialog.tsx b/web/features/contacts/management/member-invite-contact-upgrade-dialog.tsx
deleted file mode 100644
index 3bc21c43292..00000000000
--- a/web/features/contacts/management/member-invite-contact-upgrade-dialog.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-'use client'
-
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
-import { useTranslation } from 'react-i18next'
-
-export function MemberInviteContactUpgradeDialog({
- conflictCount,
- onConfirm,
- onOpenChange,
- open,
- pending,
-}: {
- conflictCount: number
- onConfirm: () => void
- onOpenChange: (open: boolean) => void
- open: boolean
- pending: boolean
-}) {
- const { t } = useTranslation(['contacts'])
-
- return (
- <AlertDialog open={open} onOpenChange={onOpenChange}>
- <AlertDialogContent backdropProps={{ forceRender: true }}>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['memberInviteUpgrade.title'], { count: conflictCount })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $['memberInviteUpgrade.description'], { count: conflictCount })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton variant="secondary" disabled={pending}>
- {t(($) => $['action.cancel'])}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- tone="default"
- loading={pending}
- disabled={pending}
- onClick={onConfirm}
- >
- {t(($) => $['memberInviteUpgrade.confirm'])}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )
-}
diff --git a/web/features/contacts/management/member-removal-content.tsx b/web/features/contacts/management/member-removal-content.tsx
deleted file mode 100644
index b9af2c49472..00000000000
--- a/web/features/contacts/management/member-removal-content.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-'use client'
-
-import type { AccountWithRoleResponse as Member } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { useRemoveContactMember } from './hooks'
-import {
- AlertDialogBody,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
-import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
-import { Button } from '@langgenius/dify-ui/button'
-import { Checkbox } from '@langgenius/dify-ui/checkbox'
-import { useId, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { useContactsFeatureContext } from './composition-context'
-
-export function MemberRemovalContactImpactContent({
- member,
- removal,
- onRemoved,
-}: {
- member: Member
- removal: ReturnType<typeof useRemoveContactMember>
- onRemoved: () => void
-}) {
- const { t } = useTranslation(['contacts'])
- const context = useContactsFeatureContext()
- const [keepAsPlatformContact, setKeepAsPlatformContact] = useState(true)
- const removeLabelId = useId()
- const failed = removal.isError || removal.data?.kind === 'failed'
- const { imCentrallyManaged, imCapabilityError, retryIMCapability } = context
- const capabilityReady = imCentrallyManaged !== undefined
-
- function handleRemove() {
- if (removal.isPending || !capabilityReady) return
- removal.mutate(
- {
- keepAsPlatformContact: imCentrallyManaged && keepAsPlatformContact,
- memberId: member.id,
- },
- {
- onSuccess: (result) => {
- if (result.kind === 'removed') onRemoved()
- },
- },
- )
- }
-
- return (
- <>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['memberRemoval.title'], { memberName: member.name || member.email })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(
- ($) =>
- $[
- imCentrallyManaged
- ? 'memberRemoval.eeDescription'
- : 'memberRemoval.standardDescription'
- ],
- )}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogBody className="flex flex-col gap-4">
- <div className="flex items-center gap-3 rounded-xl border border-divider-subtle bg-background-default-subtle p-3">
- <Avatar size="lg">
- <AvatarImage
- src={(member.avatar_url || null) ?? undefined}
- alt={member.name || member.email}
- />
- <AvatarFallback>
- {(member.name || member.email)?.[0]?.toLocaleUpperCase()}
- </AvatarFallback>
- </Avatar>
- <span className="min-w-0">
- <span className="block truncate system-sm-medium text-text-secondary">
- {member.name || member.email}
- </span>
- <span className="block truncate system-xs-regular text-text-tertiary">
- {member.email}
- </span>
- </span>
- </div>
- {imCentrallyManaged && (
- <div className="flex items-start gap-2 rounded-lg p-1 focus-within:ring-2 focus-within:ring-state-accent-solid">
- <Checkbox
- aria-labelledby="member-removal-keep-platform-label"
- checked={keepAsPlatformContact}
- disabled={removal.isPending}
- onCheckedChange={setKeepAsPlatformContact}
- />
- <span>
- <span
- id="member-removal-keep-platform-label"
- className="block system-sm-medium text-text-secondary"
- >
- {t(($) => $['memberRemoval.keepPlatform'])}
- </span>
- <span className="block system-xs-regular text-text-tertiary">
- {t(($) => $['memberRemoval.keepPlatformDescription'])}
- </span>
- </span>
- </div>
- )}
- {failed && (
- <p
- role="alert"
- className="rounded-lg bg-state-destructive-hover p-3 system-sm-regular text-text-destructive"
- >
- {t(($) => $['memberRemoval.failed'])}
- </p>
- )}
- {imCapabilityError && (
- <div
- role="alert"
- className="rounded-lg bg-state-destructive-hover p-3 system-sm-regular text-text-destructive"
- >
- <p>{t(($) => $['directory.errorTitle'])}</p>
- {retryIMCapability && (
- <Button variant="secondary" onClick={retryIMCapability}>
- {t(($) => $['action.retry'])}
- </Button>
- )}
- </div>
- )}
- </AlertDialogBody>
- <AlertDialogFooter>
- <AlertDialogCancelButton disabled={removal.isPending}>
- {t(($) => $['action.cancel'])}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- loading={removal.isPending}
- disabled={!capabilityReady}
- aria-labelledby={removeLabelId}
- onClick={handleRemove}
- >
- <span id={removeLabelId}>
- {removal.isPending
- ? t(($) => $['memberRemoval.removing'])
- : t(($) => $['memberRemoval.remove'])}
- </span>
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </>
- )
-}
diff --git a/web/features/contacts/management/platform-contact-picker-dialog.tsx b/web/features/contacts/management/platform-contact-picker-dialog.tsx
index c3c6fd5e599..9e5399bf3bf 100644
--- a/web/features/contacts/management/platform-contact-picker-dialog.tsx
+++ b/web/features/contacts/management/platform-contact-picker-dialog.tsx
@@ -1,306 +1,236 @@
'use client'
-import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import {
Dialog,
- DialogBackdrop,
- DialogClose,
+ DialogContent,
DialogDescription,
- DialogPopup,
- DialogPortal,
+ DialogHeader,
+ DialogHeaderCloseButton,
DialogTitle,
- DialogViewport,
} from '@langgenius/dify-ui/dialog'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
-import { useState } from 'react'
+import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
-import { useContactsFeatureContext, useContactsManagementRepository } from './composition-context'
-import { useAddPlatformContacts, useAvailablePlatformContacts } from './hooks'
-import { PlatformContactUpgradeDialog } from './platform-contact-upgrade-dialog'
+import { consoleQuery } from '@/service/console'
+import { availablePlatformCandidatesOptions } from './available-platform-candidates'
+import { useContactsFeatureContext } from './composition-context'
+import { ContactAvatar } from './contact-avatar'
-export function PlatformContactPickerDialog({
+function PlatformContactPickerContent({
onOpenChange,
- open,
+ onBusyChange,
}: {
onOpenChange: (open: boolean) => void
- open: boolean
+ onBusyChange: (busy: boolean) => void
}) {
const { t } = useTranslation(['contacts'])
const context = useContactsFeatureContext()
- const repository = useContactsManagementRepository()
const [search, setSearch] = useState('')
const [selectedIds, setSelectedIds] = useState<string[]>([])
- const [mutationError, setMutationError] = useState<
- | 'platformPicker.addFailed'
- | 'platformPicker.addConflict'
- | 'platformPicker.addForbidden'
- | 'platformPicker.externalUpgradeUnsupported'
- | null
- >(null)
- const [upgradeConflictCount, setUpgradeConflictCount] = useState<number | null>(null)
- const availableContactsQuery = useAvailablePlatformContacts({ limit: 20, search }, open)
- const addPlatformContacts = useAddPlatformContacts()
- const resetMutation = addPlatformContacts.reset
+ const searchRef = useRef<HTMLInputElement>(null)
const canImport = Boolean(
- context.workspaceId &&
- context.imCentrallyManaged &&
- context.permissions.canManageContacts &&
- repository.supportsPlatformImport !== false,
+ context.workspaceId && context.imCentrallyManaged && context.permissions.canManageContacts,
)
+ const api = consoleQuery.workspaces.current.humanInput.v2
+ const queryClient = useQueryClient()
+ const candidates = useInfiniteQuery({
+ ...availablePlatformCandidatesOptions(queryClient, context.workspaceId, search),
+ enabled: canImport,
+ })
+ const contacts = candidates.data?.pages.flatMap((page) => page.data) ?? []
+ const pending = candidates.isPending
+ const error = candidates.error
+ const add = useMutation(api.contacts.platform.post.mutationOptions({ context: { silent: true } }))
+ useEffect(() => {
+ onBusyChange(add.isPending)
+ }, [add.isPending, onBusyChange])
- function resetDialog() {
- setSearch('')
- setSelectedIds([])
- setMutationError(null)
- setUpgradeConflictCount(null)
- resetMutation()
- }
-
- function closeDialog() {
- if (addPlatformContacts.isPending) return
- onOpenChange(false)
- resetDialog()
- }
-
- function toggleContact(contactId: string, checked: boolean) {
- setMutationError(null)
+ function toggleContact(id: string, checked: boolean) {
+ add.reset()
setSelectedIds((current) =>
- checked ? [...new Set([...current, contactId])] : current.filter((id) => id !== contactId),
+ checked ? [...new Set([...current, id])] : current.filter((candidate) => candidate !== id),
)
}
+ const errorKey =
+ add.error && 'status' in add.error && add.error.status === 403
+ ? 'platformPicker.addForbidden'
+ : add.error && 'status' in add.error && add.error.status === 409
+ ? 'platformPicker.addConflict'
+ : 'platformPicker.addFailed'
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t(($) => $['platformPicker.title'])}</DialogTitle>
+ <DialogDescription className="sr-only">
+ {t(($) => $['platformPicker.description'])}
+ </DialogDescription>
+ <DialogHeaderCloseButton
+ aria-label={t(($) => $['action.close'])}
+ disabled={add.isPending}
+ />
+ </DialogHeader>
+ <div className="shrink-0 px-2 pt-2 pb-1">
+ <SearchInput
+ ref={searchRef}
+ aria-label={t(($) => $['platformPicker.search'])}
+ className="h-8 bg-components-input-bg-normal shadow-none"
+ disabled={add.isPending || !canImport}
+ placeholder={t(($) => $['platformPicker.search'])}
+ value={search}
+ onValueChange={setSearch}
+ />
+ </div>
+ <div className="flex h-7 shrink-0 items-center px-3 system-xs-regular text-text-tertiary">
+ {t(($) => $['platformPicker.allMembers'])}
+ </div>
+ <p role="status" aria-atomic="true" className="sr-only">
+ {selectedIds.length
+ ? t(($) => $['platformPicker.selected'], { count: selectedIds.length })
+ : !pending && !error
+ ? t(($) => $['directory.resultCount'], { count: contacts.length })
+ : ''}
+ </p>
+ <div className="min-h-0 flex-1 overflow-y-auto p-1" aria-busy={pending}>
+ {!canImport && (
+ <p role="alert" className="p-3 system-sm-regular">
+ {t(($) => $['platformPicker.addForbidden'])}
+ </p>
+ )}
+ {canImport && pending && (
+ <div className="space-y-2 p-3">
+ {[0, 1, 2].map((key) => (
+ <div
+ key={key}
+ className="h-12 animate-pulse rounded-lg bg-background-default-subtle"
+ />
+ ))}
+ </div>
+ )}
+ {error && !candidates.isFetchNextPageError && (
+ <div
+ role="alert"
+ className="flex min-h-40 flex-col items-center justify-center gap-3 text-center"
+ >
+ <p className="system-sm-regular text-text-secondary">
+ {t(($) => $['platformPicker.error'])}
+ </p>
+ <Button
+ size="small"
+ onClick={() => {
+ void candidates.refetch()
+ }}
+ >
+ {t(($) => $['action.retry'])}
+ </Button>
+ </div>
+ )}
+ {canImport && !pending && !error && contacts.length === 0 && (
+ <p className="flex min-h-24 items-center justify-center p-3 text-center system-sm-regular text-text-tertiary">
+ {t(($) => $['platformPicker.empty'])}
+ </p>
+ )}
+ {canImport &&
+ !pending &&
+ contacts.map((contact) => (
+ <label
+ key={contact.id}
+ className="group flex min-h-8 cursor-pointer items-center gap-2 rounded-lg py-1 ps-2 pe-3 focus-within:ring-2 focus-within:ring-state-accent-solid hover:bg-state-base-hover"
+ >
+ <Checkbox
+ aria-label={t(($) => $['platformPicker.selectContact'], { name: contact.name })}
+ checked={selectedIds.includes(contact.id)}
+ disabled={add.isPending}
+ onCheckedChange={(checked) => toggleContact(contact.id, checked)}
+ />
+ <ContactAvatar avatar={contact.avatar_url} name={contact.name} size="sm" />
+ <span className="min-w-0 flex-1 truncate system-sm-medium text-text-secondary">
+ {contact.name}
+ </span>
+ <span className="max-w-[55%] shrink-0 truncate system-xs-regular text-text-quaternary group-hover:text-text-tertiary">
+ {contact.email}
+ </span>
+ </label>
+ ))}
+ {canImport && candidates.hasNextPage && (
+ <div className="p-2">
+ {candidates.isFetchNextPageError && (
+ <p role="alert" className="mb-2 system-xs-regular text-text-destructive">
+ {t(($) => $['platformPicker.error'])}
+ </p>
+ )}
+ <Button
+ disabled={add.isPending}
+ loading={candidates.isFetchingNextPage}
+ onClick={() => {
+ void candidates.fetchNextPage().then((result) => {
+ if (!result.hasNextPage) searchRef.current?.focus()
+ })
+ }}
+ >
+ {candidates.isFetchNextPageError
+ ? t(($) => $['action.retry'])
+ : t(($) => $['action.loadMore'])}
+ </Button>
+ </div>
+ )}
+ </div>
+ <div className="shrink-0 border-t border-divider-subtle px-3 py-2">
+ {add.isError && (
+ <p role="alert" className="mb-3 system-sm-regular text-text-destructive">
+ {t(($) => $[errorKey])}
+ </p>
+ )}
+ <div className="flex items-center justify-between gap-3">
+ <span className="system-xs-regular text-text-tertiary">
+ {t(($) => $['platformPicker.selected'], { count: selectedIds.length })}
+ </span>
+ <div className="flex gap-2">
+ <Button disabled={add.isPending} onClick={() => onOpenChange(false)}>
+ {t(($) => $['action.cancel'])}
+ </Button>
+ <Button
+ variant="primary"
+ disabled={!canImport || !selectedIds.length}
+ loading={add.isPending}
+ onClick={() => {
+ if (canImport && selectedIds.length)
+ add.mutate(
+ { body: { candidate_ids: selectedIds } },
+ { onSuccess: () => onOpenChange(false) },
+ )
+ }}
+ >
+ {t(($) => $['platformPicker.add'])}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </>
+ )
+}
- async function handleAdd(upgradeExternalContacts: boolean) {
- if (!canImport || !selectedIds.length || addPlatformContacts.isPending) return
- setMutationError(null)
- let result
- try {
- result = await addPlatformContacts.mutateAsync({
- contactIds: selectedIds,
- upgradeExternalContacts,
- })
- } catch {
- setMutationError('platformPicker.addFailed')
- return
- }
- if (result.kind === 'requires_external_contact_upgrade') {
- if (repository.supportsExternalContactUpgrade === false) {
- setMutationError('platformPicker.externalUpgradeUnsupported')
- return
- }
- setUpgradeConflictCount(result.conflicts.length)
- return
- }
- if (result.kind === 'added') {
- onOpenChange(false)
- resetDialog()
- return
- }
- setUpgradeConflictCount(null)
- setMutationError(
- result.kind === 'forbidden'
- ? 'platformPicker.addForbidden'
- : result.kind === 'conflict'
- ? 'platformPicker.addConflict'
- : result.kind === 'external_upgrade_unsupported'
- ? 'platformPicker.externalUpgradeUnsupported'
- : 'platformPicker.addFailed',
- )
- }
-
- function handleUpgradeDialogOpenChange(nextOpen: boolean) {
- if (nextOpen || addPlatformContacts.isPending) return
- setUpgradeConflictCount(null)
- }
-
+export function PlatformContactPickerDialog({
+ onOpenChange,
+ open,
+}: {
+ onOpenChange: (open: boolean) => void
+ open: boolean
+}) {
+ const [busy, setBusy] = useState(false)
return (
<Dialog
open={open}
- onOpenChange={(nextOpen) => !nextOpen && closeDialog()}
- disablePointerDismissal={addPlatformContacts.isPending}
+ onOpenChange={(nextOpen) => {
+ if (!busy) onOpenChange(nextOpen)
+ }}
+ disablePointerDismissal={busy}
>
- <DialogPortal>
- <DialogBackdrop />
- <DialogViewport className="flex items-center justify-center p-4">
- <DialogPopup className="flex h-[336px] max-h-[calc(100dvh-2rem)] w-[346px] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-xl border-0 bg-components-panel-bg-blur shadow-lg inset-ring-[0.5px] inset-ring-components-panel-border backdrop-blur-[5px]">
- <DialogClose
- render={
- <IconButton
- aria-label={t(($) => $['action.close'])}
- className="sr-only"
- disabled={addPlatformContacts.isPending}
- size="lg"
- >
- <span aria-hidden className="i-ri-close-line size-4" />
- </IconButton>
- }
- />
- <div className="shrink-0 bg-components-panel-bg-blur">
- <DialogTitle className="sr-only">{t(($) => $['platformPicker.title'])}</DialogTitle>
- <DialogDescription className="sr-only">
- {t(($) => $['platformPicker.description'])}
- </DialogDescription>
- <div className="px-2 pt-2 pb-1">
- <SearchInput
- aria-label={t(($) => $['platformPicker.search'])}
- className="h-8 bg-components-input-bg-normal shadow-none"
- disabled={addPlatformContacts.isPending || !canImport}
- placeholder={t(($) => $['platformPicker.search'])}
- value={search}
- onValueChange={setSearch}
- />
- </div>
- <div className="flex h-7 items-center px-3 system-xs-regular text-text-tertiary">
- {t(($) => $['platformPicker.allMembers'])}
- </div>
- {repository.supportsExternalContactUpgrade === false && (
- <p className="px-3 pb-2 system-xs-regular text-text-tertiary">
- {t(($) => $['platformPicker.noExternalUpgrade'])}
- </p>
- )}
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto p-1">
- {!canImport && (
- <p role="alert" className="p-3 system-sm-regular">
- {t(($) => $['platformPicker.addForbidden'])}
- </p>
- )}
- {canImport && availableContactsQuery.isPending && (
- <div
- role="status"
- className="space-y-2 p-3"
- aria-label={t(($) => $['platformPicker.loading'])}
- >
- {[0, 1, 2].map((key) => (
- <div
- key={key}
- className="h-12 animate-pulse rounded-lg bg-background-default-subtle"
- />
- ))}
- </div>
- )}
- {availableContactsQuery.isError && !availableContactsQuery.isFetchNextPageError && (
- <div
- role="alert"
- className="flex min-h-40 flex-col items-center justify-center gap-3 text-center"
- >
- <p className="system-sm-regular text-text-secondary">
- {t(($) => $['platformPicker.error'])}
- </p>
- <Button size="small" onClick={() => availableContactsQuery.refetch()}>
- {t(($) => $['action.retry'])}
- </Button>
- </div>
- )}
- {canImport &&
- !availableContactsQuery.isPending &&
- !availableContactsQuery.isError &&
- !availableContactsQuery.hasNextPage &&
- !availableContactsQuery.contacts.length && (
- <div className="flex min-h-40 items-center justify-center system-sm-regular text-text-tertiary">
- {t(($) => $['platformPicker.empty'])}
- </div>
- )}
- {canImport &&
- availableContactsQuery.contacts.map((contact) => {
- const selected = selectedIds.includes(contact.id)
- return (
- <label
- key={contact.id}
- htmlFor={`platform-contact-${contact.id}`}
- className="group flex h-8 cursor-pointer items-center gap-2 rounded-lg py-1 ps-2 pe-3 focus-within:ring-2 focus-within:ring-state-accent-solid hover:bg-state-base-hover"
- >
- <Checkbox
- id={`platform-contact-${contact.id}`}
- aria-label={t(($) => $['platformPicker.selectContact'], {
- name: contact.name,
- })}
- checked={selected}
- className="sr-only"
- disabled={addPlatformContacts.isPending}
- onCheckedChange={(checked) => toggleContact(contact.id, checked)}
- />
- <Avatar
- className="inset-ring-[0.5px] inset-ring-divider-regular [&>span]:text-[13px] [&>span]:font-semibold"
- size="sm"
- >
- <AvatarImage src={contact.avatar_url ?? undefined} alt={contact.name} />
- <AvatarFallback>{contact.name?.[0]?.toLocaleUpperCase()}</AvatarFallback>
- </Avatar>
- <span className="min-w-0 flex-1 truncate system-sm-medium text-text-secondary">
- {contact.name}
- </span>
- <span className="max-w-[55%] shrink-0 truncate system-xs-regular text-text-quaternary group-hover:text-text-tertiary">
- {contact.email}
- </span>
- {selected && (
- <span aria-hidden className="i-ri-check-line size-4 text-text-accent" />
- )}
- </label>
- )
- })}
- {canImport && availableContactsQuery.hasNextPage && (
- <div className="p-2">
- {availableContactsQuery.isFetchNextPageError && (
- <p role="alert" className="mb-2 system-xs-regular text-text-destructive">
- {t(($) => $['platformPicker.error'])}
- </p>
- )}
- <Button
- disabled={addPlatformContacts.isPending}
- loading={availableContactsQuery.isFetchingNextPage}
- onClick={() => {
- void availableContactsQuery.fetchNextPage()
- }}
- >
- {availableContactsQuery.isFetchNextPageError
- ? t(($) => $['action.retry'])
- : t(($) => $['action.loadMore'])}
- </Button>
- </div>
- )}
- </div>
- {(selectedIds.length > 0 || mutationError) && (
- <div className="shrink-0 border-t border-divider-subtle px-3 py-2">
- {mutationError && (
- <p role="alert" className="mb-3 system-sm-regular text-text-destructive">
- {t(($) => $[mutationError])}
- </p>
- )}
- <div className="flex items-center justify-between gap-3">
- <span aria-live="polite" className="system-xs-regular text-text-tertiary">
- {t(($) => $['platformPicker.selected'], { count: selectedIds.length })}
- </span>
- <div className="flex gap-2">
- <Button disabled={addPlatformContacts.isPending} onClick={closeDialog}>
- {t(($) => $['action.cancel'])}
- </Button>
- <Button
- variant="primary"
- disabled={!canImport || !selectedIds.length}
- loading={addPlatformContacts.isPending}
- onClick={() => handleAdd(false)}
- >
- {addPlatformContacts.isPending
- ? t(($) => $['platformPicker.adding'])
- : t(($) => $['platformPicker.add'])}
- </Button>
- </div>
- </div>
- </div>
- )}
- </DialogPopup>
- </DialogViewport>
- </DialogPortal>
- <PlatformContactUpgradeDialog
- conflictCount={upgradeConflictCount ?? 0}
- open={repository.supportsExternalContactUpgrade !== false && upgradeConflictCount !== null}
- pending={addPlatformContacts.isPending}
- onOpenChange={handleUpgradeDialogOpenChange}
- onConfirm={() => handleAdd(true)}
- />
+ <DialogContent className="h-84 w-86.5 overflow-hidden">
+ <PlatformContactPickerContent onOpenChange={onOpenChange} onBusyChange={setBusy} />
+ </DialogContent>
</Dialog>
)
}
diff --git a/web/features/contacts/management/platform-contact-upgrade-dialog.tsx b/web/features/contacts/management/platform-contact-upgrade-dialog.tsx
deleted file mode 100644
index 40006999304..00000000000
--- a/web/features/contacts/management/platform-contact-upgrade-dialog.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-'use client'
-
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@langgenius/dify-ui/alert-dialog'
-import { useTranslation } from 'react-i18next'
-
-export function PlatformContactUpgradeDialog({
- conflictCount,
- onConfirm,
- onOpenChange,
- open,
- pending,
-}: {
- conflictCount: number
- onConfirm: () => void
- onOpenChange: (open: boolean) => void
- open: boolean
- pending: boolean
-}) {
- const { t } = useTranslation(['contacts'])
-
- return (
- <AlertDialog open={open} onOpenChange={onOpenChange}>
- <AlertDialogContent backdropProps={{ forceRender: true }}>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['platformPicker.upgrade.title'], { count: conflictCount })}
- </AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $['platformPicker.upgrade.description'], { count: conflictCount })}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton variant="secondary" disabled={pending}>
- {t(($) => $['action.cancel'])}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- tone="default"
- loading={pending}
- disabled={pending}
- onClick={onConfirm}
- >
- {t(($) => $['platformPicker.upgrade.confirm'])}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )
-}
diff --git a/web/features/contacts/management/query-keys.ts b/web/features/contacts/management/query-keys.ts
deleted file mode 100644
index 64ecb3d0658..00000000000
--- a/web/features/contacts/management/query-keys.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type {
- AvailablePlatformContactsQuery,
- ContactsFeatureContextValue,
- ContactsListQuery,
-} from './types'
-
-export const contactsManagementQueryKeys = {
- all: (workspaceId: string) => ['contacts-management', workspaceId] as const,
- detail: (workspaceId: string, contactId: string | null) =>
- [...contactsManagementQueryKeys.all(workspaceId), 'detail', contactId] as const,
- directory: (
- context: Pick<ContactsFeatureContextValue, 'deployment' | 'imCentrallyManaged' | 'workspaceId'>,
- query: Omit<ContactsListQuery, 'deployment' | 'page'>,
- ) =>
- [
- ...contactsManagementQueryKeys.all(context.workspaceId),
- 'directory',
- context.deployment,
- context.imCentrallyManaged,
- query,
- ] as const,
- availablePlatformContacts: (
- workspaceId: string,
- query: Omit<AvailablePlatformContactsQuery, 'page'>,
- ) =>
- [
- ...contactsManagementQueryKeys.all(workspaceId),
- 'available-platform-contacts',
- query,
- ] as const,
-}
diff --git a/web/features/contacts/management/repository.ts b/web/features/contacts/management/repository.ts
deleted file mode 100644
index d9dd3805030..00000000000
--- a/web/features/contacts/management/repository.ts
+++ /dev/null
@@ -1,326 +0,0 @@
-import type { HumanInputContact } from '@dify/contracts/api/console/workspaces/types.gen'
-import type {
- AddPlatformContactsCommand,
- AddPlatformContactsResult,
- AvailablePlatformContact,
- AvailablePlatformContactsQuery,
- ContactIMChannel,
- ContactIMIdentity,
- ContactPage,
- ContactsFeatureContextValue,
- ContactsListQuery,
- ContactView,
- CreateExternalContactCommand,
- CreateExternalContactResult,
- ExternalContactInviteConflict,
- FindExternalContactsByEmailsCommand,
- RemoveContactIMBindingCommand,
- RemoveContactsCommand,
- RemoveContactsResult,
- RemoveMemberCommand,
- RemoveMemberResult,
- SetContactIMBindingCommand,
- UnbindContactIMBindingCommand,
- UpdateExternalContactCommand,
- UpdateExternalContactResult,
- UpgradeExternalContactsToWorkspaceCommand,
- UpgradeExternalContactsToWorkspaceResult,
-} from './types'
-import { consoleClient } from '@/service/console'
-
-/**
- * UI-facing repository boundary. Network-backed implementations map kind to group, search to
- * keyword, displayName to name, and contactIds to the endpoint-specific candidate_ids or
- * contact_ids field.
- */
-export type ContactsManagementRepository = {
- supportsIMBindings?: boolean
- supportsMemberManagement?: boolean
- supportsPlatformImport?: boolean
- supportsExternalContactUpgrade?: boolean
- getContact: (contactId: string) => Promise<ContactView | null>
- listIMChannels?: () => Promise<ContactIMChannel[]>
- listIMIdentities: (query: {
- search: string
- page: number
- limit: number
- }) => Promise<ContactPage<ContactIMIdentity>>
- setIMBinding: (command: SetContactIMBindingCommand) => Promise<ContactView>
- removeIMBinding: (command: RemoveContactIMBindingCommand) => Promise<void>
- unbindIMBinding: (command: UnbindContactIMBindingCommand) => Promise<void>
- addPlatformContacts: (command: AddPlatformContactsCommand) => Promise<AddPlatformContactsResult>
- createExternalContact: (
- command: CreateExternalContactCommand,
- ) => Promise<CreateExternalContactResult>
- findExternalContactsByEmails: (
- command: FindExternalContactsByEmailsCommand,
- ) => Promise<ExternalContactInviteConflict[]>
- listAvailablePlatformContacts: (
- query: AvailablePlatformContactsQuery,
- ) => Promise<ContactPage<AvailablePlatformContact>>
- listContacts: (query: ContactsListQuery) => Promise<ContactPage<ContactView>>
- removeContacts: (command: RemoveContactsCommand) => Promise<RemoveContactsResult>
- removeMember: (command: RemoveMemberCommand) => Promise<RemoveMemberResult>
- updateExternalContact: (
- command: UpdateExternalContactCommand,
- ) => Promise<UpdateExternalContactResult>
- upgradeExternalContactsToWorkspace: (
- command: UpgradeExternalContactsToWorkspaceCommand,
- ) => Promise<UpgradeExternalContactsToWorkspaceResult>
-}
-
-function toContactView(contact: HumanInputContact): ContactView {
- return {
- ...contact,
- avatar_url: contact.avatar_url ?? '',
- email: contact.email ?? null,
- im_bindings: contact.im_bindings ?? [],
- }
-}
-
-function hasStatus(error: unknown, status: number) {
- return typeof error === 'object' && error !== null && 'status' in error && error.status === status
-}
-
-export class ContactIMRequestError extends Error {
- readonly code: string
-
- constructor(code: string) {
- super(code)
- this.name = 'ContactIMRequestError'
- this.code = code
- }
-}
-
-function errorRecord(value: unknown): Record<string, unknown> | undefined {
- return value !== null && typeof value === 'object'
- ? (value as Record<string, unknown>)
- : undefined
-}
-
-async function requestContactIM<T>(request: () => Promise<T>): Promise<T> {
- try {
- return await request()
- } catch (error) {
- const responseBody: unknown =
- error instanceof Response
- ? await error
- .clone()
- .json()
- .catch(() => undefined)
- : undefined
- const record = errorRecord(error)
- const data = errorRecord(record?.data)
- const body = errorRecord(responseBody) ?? errorRecord(data?.body) ?? data ?? record
- throw new ContactIMRequestError(
- typeof body?.code === 'string' ? body.code : 'im_binding_failed',
- )
- }
-}
-
-export function createContactsApiRepository(
- client = consoleClient.workspaces.current.humanInput.v2,
- context?: ContactsFeatureContextValue,
-): ContactsManagementRepository {
- const unsupported = async (): Promise<never> => {
- throw new Error('This contact operation is not connected yet')
- }
- const canImportPlatformContacts = Boolean(
- context?.workspaceId && context.imCentrallyManaged && context.permissions.canManageContacts,
- )
-
- return {
- supportsIMBindings: true,
- supportsMemberManagement: false,
- supportsPlatformImport: canImportPlatformContacts,
- supportsExternalContactUpgrade: false,
- async listIMChannels() {
- const { channels } = await requestContactIM(() =>
- consoleClient.workspaces.current.humanInput.v2.channels.get(undefined, {
- context: { silent: true },
- }),
- )
- return channels
- .filter((channel) => channel.kind === 'im')
- .map(({ id, provider }) => ({ id, provider }))
- },
- async listAvailablePlatformContacts(query) {
- if (!canImportPlatformContacts) throw new Error('Platform contact import is not available')
- const result = await client.organizationCandidates.get(
- {
- query: {
- keyword: query.search.trim() || undefined,
- page: query.page,
- limit: query.limit,
- },
- },
- { context: { silent: true } },
- )
- const existing = result.data.length
- ? await client.contacts.batch.get(
- { query: { contact_ids: result.data.map((candidate) => candidate.id) } },
- { context: { silent: true } },
- )
- : { data: [] }
- const existingIds = new Set(existing.data.map((contact) => contact.id))
- return {
- ...result,
- data: result.data
- .filter((candidate) => !existingIds.has(candidate.id))
- .map((candidate) => ({ ...candidate, avatar_url: candidate.avatar_url ?? null })),
- has_more: result.page * result.limit < result.total,
- }
- },
- async addPlatformContacts(command) {
- if (!canImportPlatformContacts) return { kind: 'forbidden' }
- if (command.upgradeExternalContacts) return { kind: 'external_upgrade_unsupported' }
- if (command.contactIds.length === 0) return { kind: 'failed' }
- try {
- const result = await client.contacts.platform.post(
- { body: { candidate_ids: [...new Set(command.contactIds)] } },
- { context: { silent: true } },
- )
- if (result.data.length === 0) return { kind: 'failed' }
- return { kind: 'added', contactIds: result.data.map((contact) => contact.id) }
- } catch (error) {
- return {
- kind: hasStatus(error, 403) ? 'forbidden' : hasStatus(error, 409) ? 'conflict' : 'failed',
- }
- }
- },
- async listIMIdentities(query) {
- const result = await requestContactIM(() =>
- client.imIdentities.get(
- {
- query: {
- keyword: query.search.trim() || undefined,
- page: query.page,
- limit: query.limit,
- },
- },
- { context: { silent: true } },
- ),
- )
- return { ...result, has_more: result.page * result.limit < result.total }
- },
- async setIMBinding(command) {
- const input = {
- params: { contact_id: command.contactId },
- body: { identity_id: command.identityId },
- }
- const result = await requestContactIM(() =>
- command.override
- ? client.contacts.byContactId.imOverride.put(input, { context: { silent: true } })
- : client.contacts.byContactId.imBindings.put(input, { context: { silent: true } }),
- )
- return toContactView(result.contact)
- },
- async removeIMBinding(command) {
- await requestContactIM(async () => {
- const params = { contact_id: command.contactId }
- if (command.binding.scope === 'workspace') {
- await client.contacts.byContactId.imOverride.delete(
- { params },
- { context: { silent: true } },
- )
- } else {
- await client.contacts.byContactId.imBindings.delete(
- {
- params,
- },
- { context: { silent: true } },
- )
- }
- })
- },
- async unbindIMBinding(command) {
- await requestContactIM(() =>
- client.contacts.byContactId.imBindings.delete(
- {
- params: { contact_id: command.contactId },
- },
- { context: { silent: true } },
- ),
- )
- },
- async listContacts(query) {
- const result = await client.contacts.get(
- {
- query: {
- page: query.page,
- limit: query.limit,
- group: query.kind === 'all' ? undefined : query.kind,
- keyword: query.search.trim() || undefined,
- },
- },
- { context: { silent: true } },
- )
- return {
- ...result,
- data: result.data.map(toContactView),
- has_more: result.page * result.limit < result.total,
- }
- },
- async getContact(contactId) {
- try {
- const result = await client.contacts.byContactId.get(
- { params: { contact_id: contactId } },
- { context: { silent: true } },
- )
- return { ...toContactView(result.contact), im_binding_details: result.im_binding_details }
- } catch (error) {
- if (hasStatus(error, 404)) return null
- throw error
- }
- },
- async createExternalContact(command) {
- try {
- const result = await client.contacts.external.post(
- {
- body: {
- name: command.displayName,
- email: command.email,
- ...(command.avatar !== undefined ? { avatar: command.avatar } : {}),
- },
- },
- { context: { silent: true } },
- )
- return { kind: 'created', contactId: result.contact.id }
- } catch (error) {
- return { kind: hasStatus(error, 409) ? 'duplicate_external_contact' : 'failed' }
- }
- },
- async updateExternalContact(command) {
- try {
- const result = await client.contacts.external.byContactId.patch(
- {
- params: { contact_id: command.contactId },
- body: {
- name: command.displayName,
- email: command.email,
- ...(command.avatar !== undefined ? { avatar: command.avatar } : {}),
- },
- },
- { context: { silent: true } },
- )
- return { kind: 'updated', contactId: result.contact.id }
- } catch (error) {
- return { kind: hasStatus(error, 409) ? 'duplicate_external_contact' : 'failed' }
- }
- },
- async removeContacts(command) {
- try {
- const result = await client.contacts.remove.post(
- { body: { contact_ids: command.contactIds } },
- { context: { silent: true } },
- )
- return { kind: 'removed', removedContactIds: result.removed_contact_ids }
- } catch {
- return { kind: 'failed' }
- }
- },
- findExternalContactsByEmails: unsupported,
- removeMember: unsupported,
- upgradeExternalContactsToWorkspace: unsupported,
- }
-}
diff --git a/web/features/contacts/management/types.ts b/web/features/contacts/management/types.ts
index b9f0d8f72f7..8018d8f6102 100644
--- a/web/features/contacts/management/types.ts
+++ b/web/features/contacts/management/types.ts
@@ -1,16 +1,11 @@
import type {
- ChannelSummary,
- ExternalContactCreateRequest,
GetContactResponse,
- HumanInputContact,
HumanInputContactType,
- ImBinding,
- ImIdentity,
} from '@dify/contracts/api/console/workspaces/types.gen'
-export type ContactsDeployment = 'ce' | 'saas' | 'ee'
+type ContactsDeployment = 'ce' | 'saas' | 'ee'
-export type ContactsPermissions = {
+type ContactsPermissions = {
canManageContacts: boolean
canManageMembers: boolean
canViewContacts: boolean
@@ -25,142 +20,7 @@ export type ContactsFeatureContextValue = {
workspaceId: string
}
-type ContactType = HumanInputContactType
-export type ContactTypeFilter = 'all' | ContactType
+export type ContactTypeFilter = 'all' | HumanInputContactType
-export type ContactIMBinding = ImBinding
-export type ContactIMIdentity = ImIdentity
-export type ContactIMChannel = Pick<ChannelSummary, 'id' | 'provider'>
-
-export type SetContactIMBindingCommand = {
- contactId: string
- identityId: string
- override: boolean
-}
-
-export type RemoveContactIMBindingCommand = {
- contactId: string
- binding: ContactIMBinding
-}
-
-export type UnbindContactIMBindingCommand = {
- contactId: string
-}
-
-export type ContactView = HumanInputContact & {
- avatar_url: string
- email: string | null
- im_bindings: ContactIMBinding[]
- im_binding_details?: GetContactResponse['im_binding_details']
-}
-
-export type AvailablePlatformContact = {
- avatar_url: string | null
- departmentPath?: string[]
- email: string
- id: string
- name: string
-}
-
-export type ContactsListQuery = {
- deployment: ContactsDeployment
- kind: ContactTypeFilter
- limit: number
- page: number
- search: string
-}
-
-export type ContactPage<T> = {
- data: T[]
- has_more: boolean
- limit: number
- page: number
- total: number
-}
-
-export type AvailablePlatformContactsQuery = {
- limit: number
- page: number
- search: string
-}
-
-export type CreateExternalContactCommand = {
- avatar?: ExternalContactCreateRequest['avatar']
- displayName: string
- email: string
-}
-
-export type CreateExternalContactResult =
- | { contactId: string; kind: 'created' }
- | { contactId?: string; kind: 'duplicate_external_contact' }
- | { contactId: string; kind: 'matches_workspace_contact' }
- | { contactId: string; kind: 'matches_platform_contact' }
- | { kind: 'failed' }
-
-export type UpdateExternalContactCommand = CreateExternalContactCommand & {
- contactId: string
-}
-
-export type UpdateExternalContactResult =
- | { contactId: string; kind: 'updated' }
- | { contactId?: string; kind: 'duplicate_external_contact' }
- | { contactId: string; kind: 'matches_workspace_contact' }
- | { contactId: string; kind: 'matches_platform_contact' }
- | { kind: 'failed' }
-
-export type FindExternalContactsByEmailsCommand = {
- emails: string[]
-}
-
-export type ExternalContactInviteConflict = {
- email: string
- id: string
- name: string
-}
-
-export type UpgradeExternalContactsToWorkspaceCommand = {
- contactIds: string[]
-}
-
-export type UpgradeExternalContactsToWorkspaceResult = {
- contactIds: string[]
- kind: 'upgraded'
-}
-
-export type AddPlatformContactsCommand = {
- contactIds: string[]
- upgradeExternalContacts: boolean
-}
-
-type PlatformContactUpgradeConflict = {
- contactId: string
- email: string
- platformContactId: string
-}
-
-export type AddPlatformContactsResult =
- | { contactIds: string[]; kind: 'added' }
- | { conflicts: PlatformContactUpgradeConflict[]; kind: 'requires_external_contact_upgrade' }
- | { kind: 'conflict' | 'external_upgrade_unsupported' | 'forbidden' }
- | { kind: 'failed' }
-
-export type RemoveContactsCommand = {
- contactIds: string[]
-}
-
-export type RemoveContactsResult =
- | { kind: 'removed'; removedContactIds: string[] }
- | { kind: 'failed' }
-
-export type RemoveMemberCommand = {
- keepAsPlatformContact: boolean
- memberId: string
-}
-
-export type RemoveMemberResult =
- | {
- contactId: string | null
- contactOutcome: 'removed' | 'converted_to_platform' | 'not_found'
- kind: 'removed'
- }
- | { kind: 'failed' }
+export type ContactView = GetContactResponse['contact'] &
+ Partial<Pick<GetContactResponse, 'im_binding_details'>>
diff --git a/web/features/human-input/console/__tests__/form.spec.tsx b/web/features/human-input/console/__tests__/form.spec.tsx
index 85d75e364a4..301c659479a 100644
--- a/web/features/human-input/console/__tests__/form.spec.tsx
+++ b/web/features/human-input/console/__tests__/form.spec.tsx
@@ -40,6 +40,11 @@ type FormQueryOptions = Omit<
context: { silent: boolean }
}
+// Load the real code-split renderer before assertions start their interaction deadlines.
+beforeAll(async () => {
+ await import('@/app/components/base/markdown/streamdown-wrapper')
+})
+
vi.mock('@/service/console', () => ({
consoleClient: {
account: { profile: { get: fetchProfile } },
@@ -165,7 +170,7 @@ describe('ConsoleHumanInputForm', () => {
renderForm()
expect(await screen.findByRole('heading', { name: 'Review the request' })).toBeInTheDocument()
- const response = screen.getByRole('textbox', { name: 'response' })
+ const response = screen.getByRole('textbox', { name: 'Review the request' })
expect(response).toHaveValue('Resolved approval notes')
expect(fetchForm).toHaveBeenCalledWith('console-token')
expect(fetchLegacyForm).not.toHaveBeenCalled()
@@ -183,7 +188,7 @@ describe('ConsoleHumanInputForm', () => {
expect(submitLegacyForm).not.toHaveBeenCalled()
expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
expect(screen.getByText('share.humanInput.recorded')).toBeInTheDocument()
- expect(screen.queryByRole('textbox', { name: 'response' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('textbox', { name: 'Review the request' })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'share.humanInput.switchAccount' }),
).not.toBeInTheDocument()
@@ -197,7 +202,7 @@ describe('ConsoleHumanInputForm', () => {
)
renderForm()
- const response = await screen.findByRole('textbox', { name: 'response' })
+ const response = await screen.findByRole('textbox', { name: 'Review the request' })
await user.clear(response)
await user.type(response, 'Keep these approval notes')
await user.click(screen.getByRole('button', { name: 'Approve' }))
@@ -216,6 +221,22 @@ describe('ConsoleHumanInputForm', () => {
expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
})
+ it('maps generated workflow-not-active submission errors without discarding edited input', async () => {
+ const user = userEvent.setup()
+ submitForm.mockRejectedValueOnce({
+ status: 400,
+ data: { body: { code: 'workflow_not_active' } },
+ })
+ renderForm()
+ const response = await screen.findByRole('textbox', { name: 'Review the request' })
+ await user.clear(response)
+ await user.type(response, 'Retained after workflow stops')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.unavailable')
+ expect(response).toHaveValue('Retained after workflow stops')
+ expect(screen.getByRole('button', { name: 'Approve' })).toBeEnabled()
+ })
+
it('disables every action while submitting to prevent duplicate approvals', async () => {
const user = userEvent.setup()
let resolveSubmission: ((value: Record<string, unknown>) => void) | undefined
@@ -228,8 +249,8 @@ describe('ConsoleHumanInputForm', () => {
const approve = await screen.findByRole('button', { name: 'Approve' })
const reject = screen.getByRole('button', { name: 'Reject' })
await user.click(approve)
- expect(approve).toBeDisabled()
- expect(reject).toBeDisabled()
+ expect(approve).toHaveAttribute('aria-disabled', 'true')
+ expect(reject).toHaveAttribute('aria-disabled', 'true')
await user.click(approve)
await user.click(reject)
expect(submitForm).toHaveBeenCalledTimes(1)
@@ -364,11 +385,11 @@ describe('ConsoleHumanInputForm', () => {
await screen.findByText('share.humanInput.currentAccount:{"name":"Approval Reviewer"}'),
).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'share.humanInput.switchAccount' })).toBeEnabled()
- expect(screen.queryByRole('textbox', { name: 'response' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('textbox', { name: 'Review the request' })).not.toBeInTheDocument()
expect(submitForm).toHaveBeenCalledOnce()
})
- it.each([{ status: 409, code: 'already_submitted' }, new Response(null, { status: 409 })])(
+ it.each([{ status: 409, code: 'already_submitted' }])(
'shows the complete already-processed status when opening a resolved form: %j',
async (error) => {
fetchForm.mockRejectedValue(error)
@@ -404,9 +425,7 @@ describe('ConsoleHumanInputForm', () => {
it('shows the complete already-processed status if another recipient approves before submission', async () => {
const user = userEvent.setup()
- submitForm.mockRejectedValue(
- new Response(JSON.stringify({ code: 'already_submitted' }), { status: 409 }),
- )
+ submitForm.mockRejectedValue({ status: 409, code: 'already_submitted' })
renderForm()
await user.click(await screen.findByRole('button', { name: 'Approve' }))
@@ -416,7 +435,7 @@ describe('ConsoleHumanInputForm', () => {
expect(
screen.getByText('share.humanInput.submissionID:{"id":"console-token"}'),
).toBeInTheDocument()
- expect(screen.queryByRole('textbox', { name: 'response' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('textbox', { name: 'Review the request' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.operation.retry' })).not.toBeInTheDocument()
expect(submitForm).toHaveBeenCalledTimes(1)
})
@@ -430,7 +449,7 @@ describe('ConsoleHumanInputForm', () => {
expect(fetchForm).toHaveBeenCalledTimes(1)
await user.click(retry)
- expect(await screen.findByRole('textbox', { name: 'response' })).toHaveValue(
+ expect(await screen.findByRole('textbox', { name: 'Review the request' })).toHaveValue(
'Resolved approval notes',
)
await waitFor(() => expect(fetchForm).toHaveBeenCalledTimes(2))
diff --git a/web/features/human-input/console/form.tsx b/web/features/human-input/console/form.tsx
index 5b50d185c49..52913e35f29 100644
--- a/web/features/human-input/console/form.tsx
+++ b/web/features/human-input/console/form.tsx
@@ -12,22 +12,9 @@ import useDocumentTitle from '@/hooks/use-document-title'
import { consoleQuery } from '@/service/console'
import { useLogout } from '@/service/use-common'
import { basePath } from '@/utils/var'
+import { normalizeHumanInputV2Error } from '../public/errors'
import { normalizeConsoleFormDefinition } from './definition'
-const asRecord = (value: unknown): Record<string, unknown> =>
- value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : {}
-
-const getErrorKind = (error: unknown) => {
- const record = asRecord(error)
- const data = asRecord(record.data)
- const code = asRecord(data.body).code ?? data.code ?? record.code
- if (code === 'expired' || record.status === 410) return 'expired'
- if (code === 'already_submitted') return 'submitted'
- if (record.status === 404 || code === 'not_found') return 'not-found'
- if (record.status === 429) return 'rate-limited'
- return 'unknown'
-}
-
function UnavailableConsoleForm({ formToken }: { formToken: string }) {
const { t } = useTranslation(['share'])
const { data } = useQuery(userProfileQueryOptions())
@@ -61,7 +48,6 @@ function UnavailableConsoleForm({ formToken }: { formToken: string }) {
export default function ConsoleHumanInputForm({ formToken }: { formToken: string }) {
const { t } = useTranslation(['workflow', 'share', 'common'])
useDocumentTitle(t(($) => $['blocks.human-input'], { ns: 'workflow' }))
- const [submitError, setSubmitError] = useState<unknown>()
const [now, setNow] = useState(Date.now)
const form = useQuery(
consoleQuery.form.humanInput.v2.byFormToken.get.queryOptions({
@@ -91,21 +77,19 @@ export default function ConsoleHumanInputForm({ formToken }: { formToken: string
)
const errorKind =
expiresAt !== undefined && expiresAt <= now
- ? 'expired'
- : submitError !== undefined
- ? getErrorKind(submitError)
- : form.error instanceof Response && form.error.status === 409
- ? 'submitted'
- : getErrorKind(form.error)
- const terminal = ['expired', 'submitted', 'not-found'].includes(errorKind)
+ ? 'form-expired'
+ : normalizeHumanInputV2Error(submission.error ?? form.error).category
+ const terminal = ['form-expired', 'already-submitted', 'not-found'].includes(errorKind)
const errorText =
- errorKind === 'expired'
+ errorKind === 'form-expired'
? t(($) => $['humanInput.expired'], { ns: 'share' })
- : errorKind === 'submitted'
+ : errorKind === 'already-submitted'
? t(($) => $['humanInput.completed'], { ns: 'share' })
- : errorKind === 'rate-limited'
+ : errorKind === 'form-rate-limit'
? t(($) => $['humanInput.rateLimitExceeded'], { ns: 'share' })
- : t(($) => $['humanInputV2.unknownError'], { ns: 'share' })
+ : errorKind === 'unavailable'
+ ? t(($) => $['humanInputV2.unavailable'], { ns: 'share' })
+ : t(($) => $['humanInputV2.unknownError'], { ns: 'share' })
if (form.isPending) return <LoadingPlaceholder className="h-full" />
@@ -120,7 +104,7 @@ export default function ConsoleHumanInputForm({ formToken }: { formToken: string
)
}
- if (errorKind === 'submitted') {
+ if (errorKind === 'already-submitted') {
return (
<FormStatusCard
iconClassName="i-ri-information-2-fill text-text-accent"
@@ -140,7 +124,7 @@ export default function ConsoleHumanInputForm({ formToken }: { formToken: string
title={errorText}
subtitle={
!terminal && (
- <Button onClick={() => form.refetch()} disabled={form.isFetching}>
+ <Button onClick={() => form.refetch()} loading={form.isFetching}>
{t(($) => $['operation.retry'], { ns: 'common' })}
</Button>
)
@@ -150,43 +134,30 @@ export default function ConsoleHumanInputForm({ formToken }: { formToken: string
}
return (
- <form className="h-full" onSubmit={(event) => event.preventDefault()}>
+ <div className="h-full">
<LoadedFormContent
definition={form.data}
isSubmitting={submission.isPending}
verificationContent={
- submitError ? (
+ submission.isError ? (
<p role="alert" className="system-sm-regular text-text-destructive">
{errorText}
</p>
) : undefined
}
- onSubmit={async (inputs, action) => {
+ onSubmit={(inputs, action) => {
if (expiresAt !== undefined && expiresAt <= Date.now()) {
setNow(Date.now())
return
}
- setSubmitError(undefined)
- try {
- await submission.mutateAsync({
- params: { form_token: formToken },
- body: { inputs, action },
- })
- } catch (error) {
- const detail: unknown =
- error instanceof Response
- ? {
- status: error.status,
- data: await error
- .clone()
- .json()
- .catch(() => ({})),
- }
- : error
- setSubmitError(detail)
- }
+ return new Promise<void>((resolve) => {
+ submission.mutate(
+ { params: { form_token: formToken }, body: { inputs, action } },
+ { onSettled: () => resolve() },
+ )
+ })
}}
/>
- </form>
+ </div>
)
}
diff --git a/web/features/human-input/form/__tests__/loaded-form-content.spec.tsx b/web/features/human-input/form/__tests__/loaded-form-content.spec.tsx
index 03afcf0e329..dfbb2000f56 100644
--- a/web/features/human-input/form/__tests__/loaded-form-content.spec.tsx
+++ b/web/features/human-input/form/__tests__/loaded-form-content.spec.tsx
@@ -6,6 +6,11 @@ import { InputVarType } from '@/app/components/workflow/types'
import LoadedFormContent from '../loaded-form-content'
import { normalizeLegacyHumanInputForm } from '../normalize-legacy-definition'
+// Load the real code-split renderer before assertions start their interaction deadlines.
+beforeAll(async () => {
+ await import('@/app/components/base/markdown/streamdown-wrapper')
+})
+
vi.mock('@/app/components/base/chat/chat/answer/human-input-content/expiration-time', () => ({
default: ({ expirationTime }: { expirationTime: number }) => (
<div>expiration:{expirationTime}</div>
@@ -97,7 +102,7 @@ describe('LoadedFormContent', () => {
const approve = screen.getByRole('button', { name: 'Approve' })
await user.click(approve)
- expect(approve).toBeDisabled()
+ expect(approve).toHaveAttribute('aria-disabled', 'true')
await user.click(approve)
expect(onSubmit).toHaveBeenCalledTimes(1)
@@ -116,7 +121,11 @@ describe('LoadedFormContent', () => {
formContent: '{{#$output.response#}}\n\n{{#$output.reviewer#}}',
resolvedDefaultValues: { response: ' ' },
inputs: [
- ...inputs,
+ {
+ type: InputVarType.paragraph,
+ output_variable_name: 'response',
+ default: { type: 'constant', value: ' ', selector: [] },
+ },
{
type: InputVarType.select,
output_variable_name: 'reviewer',
@@ -127,12 +136,15 @@ describe('LoadedFormContent', () => {
render(<LoadedFormContent definition={definition} isSubmitting={false} onSubmit={onSubmit} />)
const approve = screen.getByRole('button', { name: 'Approve' })
- expect(approve).toBeDisabled()
+ expect(approve).toBeEnabled()
+ await user.click(approve)
+ expect(onSubmit).not.toHaveBeenCalled()
+ expect(screen.getAllByText(/fieldRequired/)).toHaveLength(2)
const response = screen.getByRole('textbox', { name: 'response' })
await user.clear(response)
await user.type(response, 'Ready for review')
- expect(approve).toBeDisabled()
+ expect(approve).toBeEnabled()
await user.click(screen.getByRole('combobox', { name: 'reviewer' }))
await user.click(await screen.findByRole('option', { name: 'Bob' }))
@@ -144,6 +156,56 @@ describe('LoadedFormContent', () => {
)
})
+ it('retains entered values and exposes a safe error when workflow submission rejects', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('internal transport details'))
+ .mockResolvedValue(undefined)
+ render(<LoadedFormContent definition={v2Definition} isSubmitting={false} onSubmit={onSubmit} />)
+ const response = screen.getByRole('textbox', { name: 'response' })
+ await user.clear(response)
+ await user.type(response, 'Keep this draft')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.api.actionFailed')
+ expect(screen.queryByText('internal transport details')).not.toBeInTheDocument()
+ expect(response).toHaveValue('Keep this draft')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(onSubmit).toHaveBeenLastCalledWith({ response: 'Keep this draft' }, 'approve')
+ })
+
+ it('gives repeated placeholders distinct label associations while retaining a shared wire value', async () => {
+ const user = userEvent.setup()
+ const onSubmit = vi.fn()
+ render(
+ <LoadedFormContent
+ definition={{
+ ...v2Definition,
+ formContent:
+ 'First review\n\n{{#$output.response#}}\n\nSecond review\n\n{{#$output.response#}}',
+ }}
+ isSubmitting={false}
+ onSubmit={onSubmit}
+ />,
+ )
+ const first = screen.getByRole('textbox', { name: 'First review' })
+ const second = screen.getByRole('textbox', { name: 'Second review' })
+ const firstLabelId = first.getAttribute('aria-labelledby')!
+ const secondLabelId = second.getAttribute('aria-labelledby')!
+ expect(firstLabelId).not.toBe(secondLabelId)
+ expect(document.querySelectorAll('[id]')).toHaveLength(
+ new Set([...document.querySelectorAll('[id]')].map((element) => element.id)).size,
+ )
+ expect(screen.getByText('Second review', { selector: 'label' })).toHaveClass('sr-only')
+ await user.click(screen.getByText('Second review', { selector: 'label' }))
+ expect(second).toHaveFocus()
+ await user.clear(second)
+ await user.type(second, 'One shared response')
+ expect(first).toHaveValue('One shared response')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(onSubmit).toHaveBeenCalledWith({ response: 'One shared response' }, 'approve')
+ })
+
it('preserves Markdown content alongside the editable fields', async () => {
const definition: HumanInputFormDefinition = {
...v2Definition,
diff --git a/web/features/human-input/form/branding-footer.tsx b/web/features/human-input/form/branding-footer.tsx
index 70c8f741a56..e09cfb5b939 100644
--- a/web/features/human-input/form/branding-footer.tsx
+++ b/web/features/human-input/form/branding-footer.tsx
@@ -1,9 +1,8 @@
-import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from 'react-i18next'
import { DifyLogo } from '@/app/components/base/logo/dify-logo'
type BrandingFooterProps = {
- variant?: 'form' | 'status'
+ variant?: 'form' | 'status' | 'legacy-status'
removeWebappBrand?: boolean
replaceWebappLogo?: string | null
}
@@ -18,8 +17,14 @@ const BrandingFooter = ({
if (removeWebappBrand) return null
return (
- <div className="flex flex-row-reverse px-2 py-3">
- <div className={cn('flex shrink-0 items-center', variant === 'status' ? 'gap-2' : 'gap-1.5')}>
+ <div
+ data-variant={variant}
+ className="flex flex-row-reverse px-2 py-3 data-[variant=legacy-status]:px-1"
+ >
+ <div
+ data-variant={variant}
+ className="flex shrink-0 items-center gap-1.5 data-[variant=legacy-status]:gap-2 data-[variant=status]:gap-2"
+ >
<div className="system-2xs-medium-uppercase text-text-tertiary">
{t(($) => $['chat.poweredBy'], { ns: 'share' })}
</div>
diff --git a/web/features/human-input/form/form-status-card.tsx b/web/features/human-input/form/form-status-card.tsx
index 3c01aa3ded1..cb5ad5624fc 100644
--- a/web/features/human-input/form/form-status-card.tsx
+++ b/web/features/human-input/form/form-status-card.tsx
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
+import { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import BrandingFooter from './branding-footer'
@@ -12,6 +13,7 @@ type FormStatusCardProps = {
submissionID?: string
removeWebappBrand?: boolean
replaceWebappLogo?: string | null
+ legacy?: boolean
}
const FormStatusCard = ({
@@ -23,18 +25,31 @@ const FormStatusCard = ({
submissionID,
removeWebappBrand,
replaceWebappLogo,
+ legacy = false,
}: FormStatusCardProps) => {
const { t } = useTranslation(['share'])
+ const titleRef = useRef<HTMLHeadingElement>(null)
+ useEffect(() => {
+ if (!legacy) titleRef.current?.focus({ preventScroll: true })
+ }, [legacy])
return (
- <div className="flex size-full flex-col items-center justify-center p-8 pb-32">
+ <div
+ data-legacy={legacy}
+ className="flex size-full flex-col items-center justify-center p-8 pb-32 data-[legacy=true]:p-0"
+ >
<div className="w-full max-w-160">
- <div className="relative flex min-h-80 flex-col gap-4 rounded-[20px] bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs before:pointer-events-none before:absolute before:inset-0 before:rounded-[inherit] before:border-t before:border-divider-subtle">
+ <div
+ data-legacy={legacy}
+ className="relative flex min-h-80 flex-col gap-4 rounded-[20px] bg-chat-bubble-bg p-10 pb-9 shadow-lg backdrop-blur-xs before:pointer-events-none before:absolute before:inset-0 before:rounded-[inherit] before:border-t before:border-divider-subtle data-[legacy=true]:h-80 data-[legacy=true]:min-w-120 data-[legacy=true]:border data-[legacy=true]:border-divider-subtle"
+ >
<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">
<span className={cn('size-8', iconClassName)} />
</div>
<div className="grow">
- <div className="title-4xl-semi-bold text-text-primary">{title}</div>
+ <h1 ref={titleRef} tabIndex={-1} className="title-4xl-semi-bold text-text-primary">
+ {title}
+ </h1>
{!!subtitle && <div className="title-4xl-semi-bold text-text-primary">{subtitle}</div>}
{description !== undefined && (
<div className="mt-3 system-md-regular text-text-secondary">{description}</div>
@@ -42,13 +57,13 @@ const FormStatusCard = ({
</div>
{children}
{submissionID && (
- <div className="shrink-0 system-2xs-regular-uppercase break-words text-text-tertiary">
+ <div className="shrink-0 system-2xs-regular-uppercase wrap-break-word text-text-tertiary">
{t(($) => $['humanInput.submissionID'], { id: submissionID, ns: 'share' })}
</div>
)}
</div>
<BrandingFooter
- variant="status"
+ variant={legacy ? 'legacy-status' : 'status'}
removeWebappBrand={removeWebappBrand}
replaceWebappLogo={replaceWebappLogo}
/>
diff --git a/web/features/human-input/form/loaded-form-content.tsx b/web/features/human-input/form/loaded-form-content.tsx
index b7290fb3483..8119d988a81 100644
--- a/web/features/human-input/form/loaded-form-content.tsx
+++ b/web/features/human-input/form/loaded-form-content.tsx
@@ -1,13 +1,12 @@
-import type { FormProps } from '@langgenius/dify-ui/form'
-import type { ComponentPropsWithoutRef, ReactNode, SubmitEventHandler } from 'react'
+import type { ComponentPropsWithoutRef, ReactNode } from 'react'
import type { HumanInputFormDefinition } from './types'
import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { UnsubmittedHumanInputContentProps } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import type { MarkdownProps } from '@/app/components/base/markdown'
import { Button } from '@langgenius/dify-ui/button'
-import { Form } from '@langgenius/dify-ui/form'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Textarea } from '@langgenius/dify-ui/textarea'
-import { useMemo, useState } from 'react'
+import { useId, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import ExpirationTime from '@/app/components/base/chat/chat/answer/human-input-content/expiration-time'
@@ -24,7 +23,10 @@ import {
} from '@/app/components/base/chat/chat/answer/human-input-content/utils'
import ImagePreview from '@/app/components/base/image-uploader/image-preview'
import { Markdown } from '@/app/components/base/markdown'
-import { isParagraphFormInput } from '@/app/components/workflow/nodes/human-input/types'
+import {
+ isParagraphFormInput,
+ UserActionButtonType,
+} from '@/app/components/workflow/nodes/human-input/types'
import BrandingFooter from './branding-footer'
type LoadedFormContentProps = {
@@ -32,7 +34,6 @@ type LoadedFormContentProps = {
isSubmitting: boolean
actionsDisabled?: boolean
verificationContent?: ReactNode
- errors?: FormProps['errors']
onSubmit: (inputs: Record<string, unknown>, actionID: string) => void | Promise<void>
}
@@ -179,7 +180,12 @@ const createFormMarkdownComponents = (compact: boolean): MarkdownProps['customCo
components.ul = ({ children, node: _node, ...props }) => (
<ul
{...props}
- style={{ ...props.style, margin: 0, paddingLeft: '1.5em', listStylePosition: 'outside' }}
+ style={{
+ ...props.style,
+ margin: 0,
+ paddingInlineStart: '1.5em',
+ listStylePosition: 'outside',
+ }}
>
{children}
</ul>
@@ -187,7 +193,12 @@ const createFormMarkdownComponents = (compact: boolean): MarkdownProps['customCo
components.ol = ({ children, node: _node, ...props }) => (
<ol
{...props}
- style={{ ...props.style, margin: 0, paddingLeft: '1.5em', listStylePosition: 'outside' }}
+ style={{
+ ...props.style,
+ margin: 0,
+ paddingInlineStart: '1.5em',
+ listStylePosition: 'outside',
+ }}
>
{children}
</ol>
@@ -214,7 +225,6 @@ const FormBody = ({
isSubmitting,
actionsDisabled = false,
verificationContent,
- errors,
onSubmit,
layout = 'standalone',
}: FormBodyProps) => {
@@ -222,7 +232,11 @@ const FormBody = ({
const [inputs, setInputs] = useState<Record<string, HumanInputFieldValue>>(() =>
initializeInputs(renderedFormInputs, definition.resolvedDefaultValues),
)
- const [pending, setPending] = useState(false)
+ const { t } = useTranslation(['common'])
+ const labelPrefixId = useId()
+ const [pendingAction, setPendingAction] = useState<string>()
+ const [attempted, setAttempted] = useState(false)
+ const [submissionError, setSubmissionError] = useState(false)
const compact = layout === 'workflow'
const contentList = useMemo(() => {
const contentCounts = new Map<string, number>()
@@ -236,8 +250,19 @@ const FormBody = ({
const changeInput = (name: string, value: HumanInputFieldValue) => {
setInputs((prev) => ({ ...prev, [name]: value }))
}
+ const hasInvalidInput = compact ? hasInvalidSelectOrFileInput : hasInvalidRequiredHumanInput
+ const busy = isSubmitting || pendingAction !== undefined
+ const [firstAction, ...otherActions] = definition.actions
+ const enterSubmitsFirstAction =
+ !otherActions.length ||
+ (firstAction?.button_style === UserActionButtonType.Primary &&
+ otherActions.every((action) => action.button_style !== UserActionButtonType.Primary))
const submit = async (actionID: string) => {
- setPending(true)
+ if (busy || actionsDisabled) return
+ setAttempted(true)
+ if (hasInvalidInput(renderedFormInputs, inputs)) return
+ setPendingAction(actionID)
+ setSubmissionError(false)
try {
await onSubmit(
getProcessedHumanInputFormInputs(
@@ -246,26 +271,26 @@ const FormBody = ({
) || {},
actionID,
)
+ } catch {
+ setSubmissionError(true)
} finally {
- setPending(false)
+ setPendingAction(undefined)
}
}
- const handleSubmit: SubmitEventHandler<HTMLFormElement> = (event) => {
- event.preventDefault()
- const submitter = event.nativeEvent.submitter
- if (submitter instanceof HTMLButtonElement && submitter.value) void submit(submitter.value)
- }
- const hasInvalidInput = compact ? hasInvalidSelectOrFileInput : hasInvalidRequiredHumanInput
- const disabled =
- actionsDisabled || isSubmitting || pending || hasInvalidInput(renderedFormInputs, inputs)
return (
- <Form
- className={compact ? 'flex flex-col gap-2' : 'flex flex-col gap-3'}
- errors={errors}
- onSubmit={handleSubmit}
+ <form
+ noValidate
+ data-layout={layout}
+ className="flex flex-col gap-3 data-[layout=workflow]:gap-2"
+ onSubmit={(event) => {
+ event.preventDefault()
+ const submitter = event.nativeEvent.submitter
+ if (submitter instanceof HTMLButtonElement && submitter.value) void submit(submitter.value)
+ }}
>
- {contentList.map(({ key, content }) => {
+ {!enterSubmitsFirstAction && <button type="submit" disabled hidden />}
+ {contentList.map(({ key, content }, occurrenceIndex) => {
const match = /\{\{#\$output\.([^#]+)#\}\}/.exec(content)
if (!match) {
return (
@@ -281,44 +306,79 @@ const FormBody = ({
const field = definition.inputs.find((item) => item.output_variable_name === match[1])
if (!field) return null
const value = inputs[field.output_variable_name]
- return isParagraphFormInput(field) ? (
- <Textarea
- key={key}
- aria-label={field.output_variable_name}
- data-testid="content-item-textarea"
- size={compact ? 'medium' : 'large'}
- className={
- compact ? 'block h-20' : 'block h-28 text-[15px] leading-6 tracking-[-0.005em]'
- }
- value={typeof value === 'string' ? value : ''}
- onValueChange={(nextValue) => changeInput(field.output_variable_name, nextValue)}
- />
- ) : (
- <HumanInputFieldRenderer
- key={key}
- field={field}
- value={value}
- onChange={(nextValue) => changeInput(field.output_variable_name, nextValue)}
- />
+ const previous = contentList
+ .slice(
+ 0,
+ contentList.findIndex((item) => item.key === key),
+ )
+ .filter((item) => !/\{\{#\$output\./.test(item.content))
+ .at(-1)?.content
+ const precedingLine = previous
+ ?.trim()
+ .split('\n')
+ .at(-1)
+ ?.replace(/^[#>*\s]+|[*`_]/g, '')
+ .trim()
+ const label =
+ (precedingLine && !/^[!|]/.test(precedingLine) ? precedingLine : undefined) ||
+ field.output_variable_name.replace(/[_-]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2')
+ const labelID = `${labelPrefixId}-${field.output_variable_name}-${occurrenceIndex}`
+ const invalid = attempted && hasInvalidInput([field], inputs)
+ return (
+ <Field key={key} name={field.output_variable_name} invalid={invalid}>
+ <FieldLabel id={labelID} className="sr-only">
+ {label}
+ </FieldLabel>
+ {isParagraphFormInput(field) ? (
+ <Textarea
+ aria-labelledby={labelID}
+ data-testid="content-item-textarea"
+ size={compact ? 'medium' : 'large'}
+ data-layout={layout}
+ className="block h-28 text-[15px] leading-6 tracking-[-0.005em] data-[layout=workflow]:h-20"
+ value={typeof value === 'string' ? value : ''}
+ onValueChange={(nextValue) => changeInput(field.output_variable_name, nextValue)}
+ />
+ ) : (
+ <HumanInputFieldRenderer
+ field={field}
+ label={label}
+ value={value}
+ onChange={(nextValue) => changeInput(field.output_variable_name, nextValue)}
+ />
+ )}
+ {invalid && (
+ <FieldError match>
+ {t(($) => $['errorMsg.fieldRequired'], { field: label, ns: 'common' })}
+ </FieldError>
+ )}
+ </Field>
)
})}
{verificationContent}
+ {submissionError && (
+ <p role="alert" className="system-sm-regular text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ )}
<div className="flex flex-wrap gap-1 py-1">
{definition.actions.map((action) => (
<Button
key={action.id}
+ size={compact ? 'small' : 'medium'}
type="submit"
name="action"
value={action.id}
- size={compact ? 'small' : 'medium'}
- disabled={disabled}
+ disabled={actionsDisabled || busy}
+ loading={pendingAction === action.id}
+ focusableWhenDisabled
variant={getButtonStyle(action.button_style)}
>
{action.title}
</Button>
))}
</div>
- </Form>
+ </form>
)
}
@@ -342,7 +402,12 @@ export const WorkflowHumanInputForm = ({
isSubmitting={false}
actionsDisabled={!formData.form_token}
onSubmit={async (inputs, action) => {
- if (formData.form_token) await onSubmit?.(formData.form_token, { inputs, action })
+ if (formData.form_token)
+ await onSubmit?.(formData.form_token, {
+ inputs,
+ action,
+ form_version: formData.form_version,
+ })
}}
/>
{(showEmailTip || showDebugModeTip) && (
@@ -363,9 +428,9 @@ const LoadedFormContent = ({
isSubmitting,
actionsDisabled = false,
verificationContent,
- errors,
onSubmit,
}: LoadedFormContentProps) => {
+ const { t } = useTranslation(['workflow'])
const branding = definition.branding
const removeWebappBrand = branding?.customConfig?.remove_webapp_brand === true
const replaceWebappLogo =
@@ -374,12 +439,15 @@ const LoadedFormContent = ({
: null
return (
- <div className="size-full [scrollbar-gutter:stable_both-edges] overflow-y-auto">
+ <div className="size-full scrollbar-gutter-both overflow-y-auto">
<div className="mx-auto w-full max-w-180 px-4 py-4 sm:px-6">
+ {!branding && !/^#\s/m.test(definition.formContent) && (
+ <h1 className="sr-only">{t(($) => $['blocks.human-input'], { ns: 'workflow' })}</h1>
+ )}
{branding && (
<div className="flex w-full items-center gap-3 py-3">
<AppIcon size="small" icon={branding.site} />
- <div className="grow system-xl-semibold text-text-primary">{branding.site.title}</div>
+ <h1 className="grow system-xl-semibold text-text-primary">{branding.site.title}</h1>
</div>
)}
<div className="relative rounded-[20px] bg-chat-bubble-bg p-4 shadow-lg backdrop-blur-xs before:pointer-events-none before:absolute before:inset-0 before:rounded-[inherit] before:border-t before:border-divider-subtle">
@@ -389,7 +457,6 @@ const LoadedFormContent = ({
isSubmitting={isSubmitting}
actionsDisabled={actionsDisabled}
verificationContent={verificationContent}
- errors={errors}
onSubmit={onSubmit}
/>
<div>
diff --git a/web/features/human-input/public/README.md b/web/features/human-input/public/README.md
index 8a641e5c9a7..44a309896bc 100644
--- a/web/features/human-input/public/README.md
+++ b/web/features/human-input/public/README.md
@@ -7,18 +7,17 @@ test injection.
## Internal Modules
-| Module | Responsibility |
-| -------------------- | ---------------------------------------------------------------------------------- |
-| `types` | Defines v2 definition, challenge, submit, upload, and transport contracts. |
-| `errors` | Normalizes transport failures into redacted UI categories. |
-| `transport-selector` | Selects real or mock transport without URL or failure-based fallback. |
-| `upload` | Adapts the v2 transport to the generic upload strategy at the form owner. |
-| `legacy-upload` | Adapts legacy form-scoped uploads for the existing `/form/[token]` route. |
-| `real-transport` | Maps generated public v2 definition, challenge, submission, and upload-token APIs. |
-| `mock-transport` | Provides deterministic, explicitly injected test behavior. |
-| `session-reducer` | Enforces the local OTP and Challenge session lifecycle. |
-| `use-form-session` | Owns route-session effects, deadlines, stale-response protection, and mutations. |
-| `form` | Composes shared form presentation with v2 verification UI and status states. |
+| Module | Responsibility |
+| ----------------------------------- | ---------------------------------------------------------------------------------- |
+| `types` | Defines v2 definition, challenge, submit, upload, and transport contracts. |
+| `errors` | Normalizes transport failures into redacted UI categories. |
+| `upload` | Adapts the v2 transport to the generic upload strategy at the form owner. |
+| `legacy-upload` | Adapts legacy form-scoped uploads for the existing `/form/[token]` route. |
+| `real-transport` | Maps generated public v2 definition, challenge, submission, and upload-token APIs. |
+| `__tests__/fixtures/mock-transport` | Provides deterministic, explicitly injected test behavior. |
+| `session-reducer` | Enforces the local OTP and Challenge session lifecycle. |
+| `use-form-session` | Owns route-session effects, deadlines, stale-response protection, and mutations. |
+| `form` | Composes shared form presentation with v2 verification UI and status states. |
## External Modules
diff --git a/web/features/human-input/public/__tests__/fixtures/errors.ts b/web/features/human-input/public/__tests__/fixtures/errors.ts
new file mode 100644
index 00000000000..c14ffb75a7d
--- /dev/null
+++ b/web/features/human-input/public/__tests__/fixtures/errors.ts
@@ -0,0 +1,8 @@
+import type { HumanInputV2ErrorCategory } from '../../types'
+import { HumanInputV2TransportError } from '../../errors'
+
+export const createHumanInputV2Error = (
+ category: HumanInputV2ErrorCategory,
+ code = `human_input_${category.replaceAll('-', '_')}`,
+ status?: number,
+) => new HumanInputV2TransportError(category, code, status)
diff --git a/web/features/human-input/public/mock-transport.ts b/web/features/human-input/public/__tests__/fixtures/mock-transport.ts
similarity index 99%
rename from web/features/human-input/public/mock-transport.ts
rename to web/features/human-input/public/__tests__/fixtures/mock-transport.ts
index a7666d47db3..792ba507754 100644
--- a/web/features/human-input/public/mock-transport.ts
+++ b/web/features/human-input/public/__tests__/fixtures/mock-transport.ts
@@ -1,4 +1,4 @@
-import type { HumanInputV2FormTransport, HumanInputV2UploadedFile } from './types'
+import type { HumanInputV2FormTransport, HumanInputV2UploadedFile } from '../../types'
import type { HumanInputFormDefinition } from '@/features/human-input/form/types'
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
diff --git a/web/features/human-input/public/__tests__/form.spec.tsx b/web/features/human-input/public/__tests__/form.spec.tsx
index d41f2e57fdd..919276cf156 100644
--- a/web/features/human-input/public/__tests__/form.spec.tsx
+++ b/web/features/human-input/public/__tests__/form.spec.tsx
@@ -2,207 +2,331 @@ import type { HumanInputV2FormTransport } from '../types'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import HumanInputV2Form from '../form'
+import { createHumanInputV2Error } from './fixtures/errors'
import {
createHumanInputV2MockScenario,
createMockHumanInputV2FormTransport,
HUMAN_INPUT_V2_MOCK_OTP,
-} from '../mock-transport'
+} from './fixtures/mock-transport'
vi.mock('@/next/navigation', () => ({ useParams: () => ({}) }))
-// OTP scenarios use a supported text-only definition; the upload/navigation
-// scenario below retains the attachment definition.
-const createTextFormTransport = () => {
- const { definition } = createHumanInputV2MockScenario()
- return createMockHumanInputV2FormTransport({
- scenario: {
- definition: {
- ...definition,
- formContent: '{{#$output.response#}}',
- inputs: definition.inputs.filter((input) => input.output_variable_name === 'response'),
+vi.mock('@/app/components/base/chat/chat/answer/human-input-content/expiration-time', () => ({
+ default: () => null,
+}))
+
+const createTransport = (overrides: Partial<HumanInputV2FormTransport> = {}) => {
+ const definition = createHumanInputV2MockScenario().definition
+ return {
+ ...createMockHumanInputV2FormTransport({
+ scenario: {
+ definition: {
+ ...definition,
+ formContent: 'Review notes:\n\n{{#$output.response#}}',
+ inputs: definition.inputs.slice(0, 1),
+ },
+ resendAfterSeconds: 0,
},
- },
- })
+ }),
+ ...overrides,
+ }
}
-describe('HumanInputV2Form', () => {
- it('loads the definition, requests one OTP, validates its shape, and submits one atomic payload', async () => {
- const user = userEvent.setup()
- const transport = createTextFormTransport()
- const getForm = vi.spyOn(transport, 'getForm')
- const requestAccess = vi.spyOn(transport, 'requestAccess')
- const submit = vi.spyOn(transport, 'submit')
-
- render(<HumanInputV2Form token="form-token" transport={transport} />)
-
- expect(screen.getByLabelText('common.loading')).toBeInTheDocument()
- const otpInput = await screen.findByLabelText('share.humanInputV2.otpLabel')
- const response = screen.getByRole('textbox', { name: 'response' })
- await user.clear(response)
- await user.type(response, 'approved')
- const approve = screen.getByRole('button', { name: 'Approve' })
- expect(getForm).toHaveBeenCalledWith('form-token')
- expect(requestAccess).toHaveBeenCalledTimes(1)
- expect(approve).toBeDisabled()
- expect(otpInput).toHaveAttribute('autocomplete', 'one-time-code')
-
- await user.type(otpInput, '24681')
- expect(approve).toBeDisabled()
- await user.type(otpInput, '0')
- expect(approve).toBeEnabled()
- await user.click(approve)
-
- await waitFor(() =>
- expect(submit).toHaveBeenCalledWith('form-token', {
- inputs: { response: 'approved' },
+it('does not let Enter choose an action when the first action is not the only primary action', async () => {
+ const user = userEvent.setup()
+ const base = createTransport()
+ const transport: HumanInputV2FormTransport = {
+ ...base,
+ getForm: async (...args) => {
+ const definition = await base.getForm(...args)
+ return { ...definition, actions: [...definition.actions].reverse() }
+ },
+ }
+ const submit = vi.spyOn(transport, 'submit')
+ render(<HumanInputV2Form token="form-token" transport={transport} />)
+ const otp = await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })
+ await user.type(otp, HUMAN_INPUT_V2_MOCK_OTP)
+ await user.keyboard('{Enter}')
+ expect(submit).not.toHaveBeenCalled()
+
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ await waitFor(() =>
+ expect(submit).toHaveBeenCalledWith(
+ 'form-token',
+ expect.objectContaining({ action: 'approve' }),
+ { signal: expect.any(AbortSignal) },
+ ),
+ )
+})
+
+it('keeps incomplete approval available, identifies the invalid OTP, and submits the real form with Enter', async () => {
+ const user = userEvent.setup()
+ const transport = createTransport()
+ const submit = vi.spyOn(transport, 'submit')
+ render(<HumanInputV2Form token="form-token" transport={transport} />)
+ const otp = await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })
+ const notes = screen.getByRole('textbox', { name: 'Review notes:' })
+ const approve = screen.getByRole('button', { name: 'Approve' })
+ expect(approve).toBeEnabled()
+ expect(otp.closest('form')).toBe(notes.closest('form'))
+ await user.type(otp, '123')
+ await user.click(approve)
+ expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.invalidOtp')
+ expect(submit).not.toHaveBeenCalled()
+ expect(otp).toHaveAccessibleDescription(expect.stringContaining('share.humanInputV2.invalidOtp'))
+ await user.clear(otp)
+ await user.type(otp, HUMAN_INPUT_V2_MOCK_OTP)
+ await user.keyboard('{Enter}')
+ await waitFor(() =>
+ expect(submit).toHaveBeenCalledWith(
+ 'form-token',
+ {
+ inputs: { response: 'Looks good' },
action: 'approve',
otp_code: HUMAN_INPUT_V2_MOCK_OTP,
challenge_token: 'mock-challenge-1',
+ },
+ { signal: expect.any(AbortSignal) },
+ ),
+ )
+ expect(await screen.findByRole('heading', { name: 'share.humanInput.thanks' })).toHaveFocus()
+ expect(document.title).toBe('share.humanInput.thanks - Dify')
+})
+
+it('shows the clicked action as loading, preserves its focus, and prevents resend during submission', async () => {
+ const user = userEvent.setup()
+ let complete!: () => void
+ const submit = vi.fn<HumanInputV2FormTransport['submit']>(
+ () =>
+ new Promise<void>((resolve) => {
+ complete = resolve
}),
- )
- expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
- expect(
- screen.getByText('share.humanInput.submissionID:{"id":"form-token"}'),
- ).toBeInTheDocument()
- expect(screen.queryByLabelText('share.humanInputV2.otpLabel')).not.toBeInTheDocument()
- })
+ )
+ render(<HumanInputV2Form token="form-token" transport={createTransport({ submit })} />)
+ await user.type(
+ await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' }),
+ HUMAN_INPUT_V2_MOCK_OTP,
+ )
+ const reject = screen.getByRole('button', { name: 'Reject' })
+ await user.click(reject)
+ expect(reject).toHaveFocus()
+ expect(reject).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.getByRole('button', { name: 'share.humanInputV2.resendCode' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(submit).toHaveBeenCalledTimes(1)
+ await act(async () => complete())
+ expect(await screen.findByRole('heading', { name: 'share.humanInput.thanks' })).toBeVisible()
+})
- it('allows invalid OTP correction while preserving the current challenge', async () => {
- const user = userEvent.setup()
- const transport = createTextFormTransport()
- const requestAccess = vi.spyOn(transport, 'requestAccess')
-
- render(<HumanInputV2Form token="form-token" transport={transport} />)
- const otpInput = await screen.findByLabelText('share.humanInputV2.otpLabel')
- await user.type(otpInput, '000000')
- await user.click(screen.getByRole('button', { name: 'Approve' }))
-
- await waitFor(() => expect(otpInput).toHaveFocus())
- expect(otpInput).toHaveAccessibleDescription('share.humanInputV2.invalidOtp')
- expect(otpInput).toHaveAttribute('aria-invalid', 'true')
- expect(requestAccess).toHaveBeenCalledTimes(1)
- expect(otpInput).toHaveValue('000000')
-
- await user.clear(otpInput)
- await user.type(otpInput, HUMAN_INPUT_V2_MOCK_OTP)
- await user.click(screen.getByRole('button', { name: 'Approve' }))
- expect(await screen.findByText('share.humanInput.thanks')).toBeInTheDocument()
- })
+it('lets the user correct invalid proof in the real OTP and actions composition', async () => {
+ const user = userEvent.setup()
+ const transport = createTransport()
+ const requestAccess = vi.spyOn(transport, 'requestAccess')
+ render(<HumanInputV2Form token="form-token" transport={transport} />)
+ const otp = await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })
+ await user.type(otp, '000000')
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.invalidOtp')
+ await user.clear(otp)
+ await user.type(otp, HUMAN_INPUT_V2_MOCK_OTP)
+ await user.click(screen.getByRole('button', { name: 'Reject' }))
+ expect(await screen.findByRole('heading', { name: 'share.humanInput.thanks' })).toBeVisible()
+ expect(requestAccess).toHaveBeenCalledTimes(1)
+})
+
+it('accepts a pasted verification code containing a separator and submits all six digits', async () => {
+ const user = userEvent.setup()
+ const transport = createTransport()
+ const submit = vi.spyOn(transport, 'submit')
+ render(<HumanInputV2Form token="pasted-code" transport={transport} />)
+ const otp = await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })
+ await user.click(otp)
+ await user.paste(`${HUMAN_INPUT_V2_MOCK_OTP.slice(0, 3)} ${HUMAN_INPUT_V2_MOCK_OTP.slice(3)}`)
+ expect(otp).toHaveValue(HUMAN_INPUT_V2_MOCK_OTP)
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ await waitFor(() =>
+ expect(submit).toHaveBeenCalledWith(
+ 'pasted-code',
+ expect.objectContaining({ otp_code: HUMAN_INPUT_V2_MOCK_OTP }),
+ { signal: expect.any(AbortSignal) },
+ ),
+ )
+ expect(await screen.findByRole('heading', { name: 'share.humanInput.thanks' })).toBeVisible()
+})
- it('locks every action while a submit is pending', async () => {
- const user = userEvent.setup()
- let resolveSubmit!: () => void
- const submitPromise = new Promise<void>((resolve) => {
- resolveSubmit = resolve
- })
- const baseTransport = createTextFormTransport()
- const submit = vi.fn<HumanInputV2FormTransport['submit']>().mockReturnValue(submitPromise)
- const transport = { ...baseTransport, submit }
-
- render(<HumanInputV2Form token="form-token" transport={transport} />)
- const otpInput = await screen.findByLabelText('share.humanInputV2.otpLabel')
- await user.type(otpInput, HUMAN_INPUT_V2_MOCK_OTP)
- const approve = screen.getByRole('button', { name: 'Approve' })
- const reject = screen.getByRole('button', { name: 'Reject' })
- await user.click(approve)
-
- expect(approve).toBeDisabled()
- expect(reject).toBeDisabled()
- await user.click(reject)
- expect(submit).toHaveBeenCalledTimes(1)
-
- await act(async () => resolveSubmit())
+it('announces code delivery and keeps a network failure separate from invalid verification proof', async () => {
+ const user = userEvent.setup()
+ const transport = createTransport({
+ submit: vi
+ .fn<HumanInputV2FormTransport['submit']>()
+ .mockRejectedValue(createHumanInputV2Error('network')),
})
+ render(<HumanInputV2Form token="network-failure" transport={transport} />)
+ const otp = await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })
+ expect(screen.getByRole('status')).toHaveTextContent('share.humanInputV2.codeSent')
+ await user.type(otp, HUMAN_INPUT_V2_MOCK_OTP)
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('share.humanInputV2.networkError')
+ expect(otp).not.toHaveAttribute('aria-invalid', 'true')
+ expect(otp).toHaveValue(HUMAN_INPUT_V2_MOCK_OTP)
+})
- it.each([
- ['not-found', 'share.humanInputV2.formNotFound'],
- ['expired', 'share.humanInputV2.formExpired'],
- ['submitted', 'share.humanInputV2.alreadySubmitted'],
- ['rate-limited', 'share.humanInputV2.formRateLimited'],
- ] as const)(
- 'renders the %s terminal form state without requesting access',
- async (formState, copy) => {
- const transport = createMockHumanInputV2FormTransport({ scenario: { formState } })
- const requestAccess = vi.spyOn(transport, 'requestAccess')
-
- render(<HumanInputV2Form token="form-token" transport={transport} />)
-
- expect(await screen.findByText(copy)).toBeInTheDocument()
- if (formState === 'expired' || formState === 'submitted') {
- expect(screen.getByText('share.humanInput.sorry')).toBeInTheDocument()
- expect(
- screen.getByText('share.humanInput.submissionID:{"id":"form-token"}'),
- ).toBeInTheDocument()
- }
- expect(requestAccess).not.toHaveBeenCalled()
- expect(screen.queryByRole('button', { name: 'Approve' })).not.toBeInTheDocument()
- },
+it.each([
+ ['not-found', 'share.humanInputV2.formNotFound'],
+ ['expired', 'share.humanInputV2.formExpired'],
+ ['submitted', 'share.humanInputV2.alreadySubmitted'],
+ ['rate-limited', 'share.humanInputV2.formRateLimited'],
+] as const)('does not request proof for a %s form', async (formState, text) => {
+ const transport = createMockHumanInputV2FormTransport({ scenario: { formState } })
+ const request = vi.spyOn(transport, 'requestAccess')
+ render(<HumanInputV2Form token="form-token" transport={transport} />)
+ expect(await screen.findByText(text)).toBeVisible()
+ expect(document.title).toBe(`${text} - Dify`)
+ expect(request).not.toHaveBeenCalled()
+})
+
+it.each([
+ ['network', 'share.humanInputV2.networkError'],
+ ['unavailable', 'share.humanInputV2.unavailable'],
+ ['unknown', 'share.humanInputV2.unknownError'],
+] as const)('uses the displayed %s error in the browser title', async (category, text) => {
+ const getForm = vi
+ .fn<HumanInputV2FormTransport['getForm']>()
+ .mockRejectedValue(createHumanInputV2Error(category))
+ const requestAccess = vi.fn<HumanInputV2FormTransport['requestAccess']>()
+ render(
+ <HumanInputV2Form
+ token="failed-form"
+ transport={createTransport({ getForm, requestAccess })}
+ />,
)
+ expect(await screen.findByRole('heading', { name: text })).toBeVisible()
+ expect(document.title).toBe(`${text} - Dify`)
+ expect(requestAccess).not.toHaveBeenCalled()
+})
- it('renders and retries a recoverable unavailable definition state', async () => {
- const baseTransport = createMockHumanInputV2FormTransport()
- const getForm = vi
- .fn<HumanInputV2FormTransport['getForm']>()
- .mockRejectedValueOnce({ code: 'human_input_v2_unavailable' })
- .mockImplementation(baseTransport.getForm)
- const transport = { ...baseTransport, getForm }
- const user = userEvent.setup()
-
- render(<HumanInputV2Form token="form-token" transport={transport} />)
- expect(await screen.findByText('share.humanInputV2.unavailable')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'share.humanInputV2.retry' }))
-
- expect(await screen.findByLabelText('share.humanInputV2.otpLabel')).toBeInTheDocument()
- expect(getForm).toHaveBeenCalledTimes(2)
+it('uses the verification title while loading and awaiting OTP, preserving configured branding', async () => {
+ const transport = createTransport()
+ const form = createDeferred<Awaited<ReturnType<HumanInputV2FormTransport['getForm']>>>()
+ const definition = await transport.getForm('loading-form')
+ const getForm = vi.fn<HumanInputV2FormTransport['getForm']>().mockReturnValue(form.promise)
+ render(<HumanInputV2Form token="loading-form" transport={{ ...transport, getForm }} />, {
+ systemFeatures: { branding: { enabled: true, application_title: 'Acme' } },
})
+ expect(document.title).toBe('share.humanInputV2.otpLabel - Acme')
+ expect(
+ screen.queryByRole('textbox', { name: 'share.humanInputV2.otpLabel' }),
+ ).not.toBeInTheDocument()
+ await act(async () => form.resolve(definition))
+ expect(await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })).toBeVisible()
+ expect(document.title).toBe('share.humanInputV2.otpLabel - Acme')
+})
+
+it('starts fresh and aborts the previous session when the keyed route changes token', async () => {
+ const transport = createTransport()
+ const getForm = vi.spyOn(transport, 'getForm')
+ const user = userEvent.setup()
+ const { rerender } = render(<HumanInputV2Form key="first" token="first" transport={transport} />)
+ await user.type(
+ await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' }),
+ HUMAN_INPUT_V2_MOCK_OTP,
+ )
+ await user.click(screen.getByRole('button', { name: 'Approve' }))
+ await screen.findByRole('heading', { name: 'share.humanInput.thanks' })
+ rerender(<HumanInputV2Form key="second" token="second" transport={transport} />)
+ expect(await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })).toHaveValue(
+ '',
+ )
+ expect(getForm.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)
+ expect(getForm).toHaveBeenLastCalledWith('second', { signal: expect.any(AbortSignal) })
+})
- it('renders a neutral no-branding definition through shared presentation', async () => {
- const transport = createMockHumanInputV2FormTransport()
+it('keeps Send code focused while loading and moves focus to the OTP input when it appears', async () => {
+ const user = userEvent.setup()
+ const access = createDeferred<Awaited<ReturnType<HumanInputV2FormTransport['requestAccess']>>>()
+ const requestAccess = vi
+ .fn<HumanInputV2FormTransport['requestAccess']>()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockReturnValue(access.promise)
+ render(<HumanInputV2Form token="retry-code" transport={createTransport({ requestAccess })} />)
+ const send = await screen.findByRole('button', { name: 'share.humanInputV2.sendCode' })
+ await user.click(send)
+ expect(send).toHaveFocus()
+ expect(send).toHaveAttribute('aria-disabled', 'true')
+ await act(async () =>
+ access.resolve({ challengeToken: 'retried', expiresInSeconds: 600, resendAfterSeconds: 30 }),
+ )
+ expect(await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })).toHaveFocus()
+})
- render(<HumanInputV2Form token="form-token" transport={transport} />)
- await screen.findByLabelText('share.humanInputV2.otpLabel')
+it('keeps retry focus through another failure and restores focus to verification after recovery', async () => {
+ const user = userEvent.setup()
+ const base = createTransport()
+ const definition = await base.getForm('retry-form')
+ const failedRetry = createDeferred<typeof definition>()
+ const pending = createDeferred<typeof definition>()
+ const getForm = vi
+ .fn<HumanInputV2FormTransport['getForm']>()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockReturnValueOnce(failedRetry.promise)
+ .mockReturnValue(pending.promise)
+ render(<HumanInputV2Form token="retry-form" transport={{ ...base, getForm }} />)
+ const retry = await screen.findByRole('button', { name: 'share.humanInputV2.retry' })
+ expect(document.title).toBe('share.humanInputV2.unknownError - Dify')
+ await user.click(retry)
+ expect(retry).toHaveFocus()
+ expect(retry).toHaveAttribute('aria-disabled', 'true')
+ expect(document.title).toBe('share.humanInputV2.unknownError - Dify')
+ await act(async () => failedRetry.reject(new Error('still offline')))
+ expect(retry).toHaveFocus()
+ expect(retry).not.toHaveAttribute('aria-disabled', 'true')
+ expect(document.title).toBe('share.humanInputV2.unknownError - Dify')
+ await user.click(retry)
+ expect(retry).toHaveFocus()
+ await act(async () => pending.resolve(definition))
+ expect(await screen.findByRole('textbox', { name: 'share.humanInputV2.otpLabel' })).toHaveFocus()
+ expect(document.title).toBe('share.humanInputV2.otpLabel - Dify')
+})
- expect(screen.getByRole('textbox', { name: 'response' })).toHaveValue('Looks good')
- expect(screen.getByText('share.chat.poweredBy')).toBeInTheDocument()
- expect(screen.getByRole('img', { name: 'Dify' })).toBeInTheDocument()
+it('scopes attachment uploads to the displayed token and injected transport after navigation', async () => {
+ const user = userEvent.setup()
+ const transport = createMockHumanInputV2FormTransport()
+ const uploadLocalFile = vi.spyOn(transport, 'uploadLocalFile')
+ const uploadRemoteFile = vi.spyOn(transport, 'uploadRemoteFile').mockResolvedValue({
+ id: 'remote-2',
+ name: 'review.txt',
+ mimeType: 'text/plain',
+ size: 6,
+ url: 'https://example.com/review.txt',
})
+ const { rerender } = render(
+ <HumanInputV2Form key="first-form" token="first-form" transport={transport} />,
+ )
- it('scopes attachment uploads to the displayed token and injected transport after navigation', async () => {
- const user = userEvent.setup()
- const transport = createMockHumanInputV2FormTransport()
- const uploadLocalFile = vi.spyOn(transport, 'uploadLocalFile')
- const uploadRemoteFile = vi.spyOn(transport, 'uploadRemoteFile').mockResolvedValue({
- id: 'remote-2',
- name: 'review.txt',
- mimeType: 'text/plain',
- size: 6,
- url: 'https://example.com/review.txt',
- })
- const { rerender } = render(<HumanInputV2Form token="first-form" transport={transport} />)
-
- await screen.findByRole('textbox', { name: 'response' })
- // The native chooser has no accessible label in the current uploader.
- await user.upload(
- document.querySelector<HTMLInputElement>('input[type="file"]')!,
- new File(['review'], 'review.txt', { type: 'text/plain' }),
- )
- await screen.findByText('review.txt')
- await waitFor(() => expect(uploadLocalFile).toHaveBeenCalledOnce())
- expect(uploadLocalFile).toHaveBeenCalledWith('first-form', expect.any(File))
-
- rerender(<HumanInputV2Form token="second-form" transport={transport} />)
- await waitFor(() => expect(screen.queryByText('review.txt')).not.toBeInTheDocument())
- await user.click(
- await screen.findByRole('button', { name: 'common.fileUploader.pasteFileLink' }),
- )
- await user.type(
- screen.getByPlaceholderText('common.fileUploader.pasteFileLinkInputPlaceholder'),
- 'https://example.com/review.txt',
- )
- await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
- await screen.findByText('https://example.com/review.txt')
- await waitFor(() => expect(uploadRemoteFile).toHaveBeenCalledOnce())
- expect(uploadRemoteFile).toHaveBeenCalledWith('second-form', 'https://example.com/review.txt')
- })
+ await screen.findByRole('textbox', { name: 'Please review the request.' })
+ // The native chooser has no accessible label in the current uploader.
+ await user.upload(
+ document.querySelector<HTMLInputElement>('input[type="file"]')!,
+ new File(['review'], 'review.txt', { type: 'text/plain' }),
+ )
+ await screen.findByText('review.txt')
+ await waitFor(() => expect(uploadLocalFile).toHaveBeenCalledOnce())
+ expect(uploadLocalFile).toHaveBeenCalledWith('first-form', expect.any(File))
+
+ rerender(<HumanInputV2Form key="second-form" token="second-form" transport={transport} />)
+ await waitFor(() => expect(screen.queryByText('review.txt')).not.toBeInTheDocument())
+ await user.click(await screen.findByRole('button', { name: 'common.fileUploader.pasteFileLink' }))
+ await user.type(
+ screen.getByPlaceholderText('common.fileUploader.pasteFileLinkInputPlaceholder'),
+ 'https://example.com/review.txt',
+ )
+ await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
+ await screen.findByText('https://example.com/review.txt')
+ await waitFor(() => expect(uploadRemoteFile).toHaveBeenCalledOnce())
+ expect(uploadRemoteFile).toHaveBeenCalledWith('second-form', 'https://example.com/review.txt')
})
diff --git a/web/features/human-input/public/__tests__/locales.spec.ts b/web/features/human-input/public/__tests__/locales.spec.ts
index 0cb1b1b16b6..98101caaa64 100644
--- a/web/features/human-input/public/__tests__/locales.spec.ts
+++ b/web/features/human-input/public/__tests__/locales.spec.ts
@@ -1,4 +1,6 @@
import i18next from 'i18next'
+import { loadI18nResource } from '@/i18n/load-resource'
+import { supportedLocales } from '@/i18n/locale'
import enShare from '@/i18n/locales/en-US/share.json'
import zhHansShare from '@/i18n/locales/zh-Hans/share.json'
@@ -20,7 +22,6 @@ const V2_KEYS = [
'humanInputV2.otpPlaceholder',
'humanInputV2.requestingCode',
'humanInputV2.resendCode',
- 'humanInputV2.resendIn',
'humanInputV2.retry',
'humanInputV2.sendCode',
'humanInputV2.unavailable',
@@ -29,10 +30,8 @@ const V2_KEYS = [
] as const
describe('Human Input v2 form locales', () => {
- it.each([
- ['en-US', enShare],
- ['zh-Hans', zhHansShare],
- ] as const)('resolves every v2 key in %s', async (locale, share) => {
+ it.each(supportedLocales)('resolves every v2 key in %s without fallback', async (locale) => {
+ const { default: share } = await loadI18nResource(locale, 'share')
const i18n = i18next.createInstance()
await i18n.init({
lng: locale,
@@ -43,9 +42,12 @@ describe('Human Input v2 form locales', () => {
})
V2_KEYS.forEach((key) => {
- expect(i18n.getResource(locale, 'share', key)).not.toBe(key)
- expect(i18n.getResource(locale, 'share', key)).not.toBe('')
+ expect(i18n.getResource(locale, 'share', key), key).toEqual(expect.stringMatching(/\S/))
})
+
+ expect(i18n.t(($) => $['humanInputV2.codeExpiresIn'], { ns: 'share', seconds: 42 })).toContain(
+ '42',
+ )
})
it('uses dedicated Simplified Chinese copy without English fallback', () => {
diff --git a/web/features/human-input/public/__tests__/mock-transport.spec.ts b/web/features/human-input/public/__tests__/real-transport.spec.ts
similarity index 51%
rename from web/features/human-input/public/__tests__/mock-transport.spec.ts
rename to web/features/human-input/public/__tests__/real-transport.spec.ts
index 422b9137b85..2dc6888de24 100644
--- a/web/features/human-input/public/__tests__/mock-transport.spec.ts
+++ b/web/features/human-input/public/__tests__/real-transport.spec.ts
@@ -1,15 +1,6 @@
import { normalizeHumanInputV2Error } from '../errors'
-import {
- createHumanInputV2MockScenario,
- createMockHumanInputV2FormTransport,
- HUMAN_INPUT_V2_MOCK_OTP,
-} from '../mock-transport'
import { realHumanInputV2FormTransport } from '../real-transport'
-import {
- defaultHumanInputV2FormTransport,
- selectHumanInputV2FormTransport,
-} from '../transport-selector'
-
+import { HUMAN_INPUT_V2_MOCK_OTP } from './fixtures/mock-transport'
describe('Human Input v2 transports', () => {
afterEach(() => vi.unstubAllGlobals())
it('uses the real adapter in local development and reports backend 501 without mock fallback', async () => {
@@ -22,7 +13,6 @@ describe('Human Input v2 transports', () => {
}),
),
)
- expect(defaultHumanInputV2FormTransport).toBe(realHumanInputV2FormTransport)
const error = await realHumanInputV2FormTransport
.getForm('secret-form-token')
.catch((error) => error)
@@ -164,169 +154,6 @@ describe('Human Input v2 transports', () => {
expect(fetch).toHaveBeenCalledTimes(3)
})
- it('never selects a mock adapter in production', () => {
- const mockTransport = createMockHumanInputV2FormTransport()
- const selected = selectHumanInputV2FormTransport({
- adapter: 'mock',
- environment: 'production',
- mockTransport,
- realTransport: realHumanInputV2FormTransport,
- })
-
- expect(selected).toBe(realHumanInputV2FormTransport)
- expect(selected).not.toBe(mockTransport)
- })
-
- it('selects an explicitly injected mock only outside production', () => {
- const mockTransport = createMockHumanInputV2FormTransport()
-
- expect(
- selectHumanInputV2FormTransport({
- adapter: 'mock',
- environment: 'test',
- mockTransport,
- }),
- ).toBe(mockTransport)
- })
-
- it.each([
- ['not-found', 'not-found'],
- ['expired', 'form-expired'],
- ['submitted', 'already-submitted'],
- ['rate-limited', 'form-rate-limit'],
- ] as const)('models the %s form scenario', async (formState, category) => {
- const transport = createMockHumanInputV2FormTransport({ scenario: { formState } })
-
- await expect(transport.getForm('form-token')).rejects.toMatchObject({ category })
- })
-
- it('issues unique challenges, enforces cooldown, and invalidates replaced proof', async () => {
- let now = 10_000
- const transport = createMockHumanInputV2FormTransport({
- now: () => now,
- scenario: { resendAfterSeconds: 10, expiresInSeconds: 60 },
- })
- const first = await transport.requestAccess('form-token')
-
- await expect(transport.requestAccess('form-token')).rejects.toMatchObject({
- category: 'access-rate-limit',
- })
-
- now += 10_000
- const second = await transport.requestAccess('form-token')
- expect(second.challengeToken).not.toBe(first.challengeToken)
-
- await expect(
- transport.submit('form-token', {
- inputs: { response: 'approved' },
- action: 'approve',
- otp_code: HUMAN_INPUT_V2_MOCK_OTP,
- challenge_token: first.challengeToken,
- }),
- ).rejects.toMatchObject({ category: 'challenge-stale' })
-
- await expect(
- transport.submit('form-token', {
- inputs: { response: 'approved' },
- action: 'approve',
- otp_code: HUMAN_INPUT_V2_MOCK_OTP,
- challenge_token: second.challengeToken,
- }),
- ).resolves.toBeUndefined()
- })
-
- it('validates OTP and challenge expiry without consuming valid proof', async () => {
- let now = 1_000
- const transport = createMockHumanInputV2FormTransport({
- now: () => now,
- scenario: { expiresInSeconds: 5 },
- })
- const challenge = await transport.requestAccess('form-token')
- const payload = {
- inputs: {},
- action: 'approve',
- otp_code: '000000',
- challenge_token: challenge.challengeToken,
- }
-
- await expect(transport.submit('form-token', payload)).rejects.toMatchObject({
- category: 'invalid-otp',
- })
-
- now += 5_000
- await expect(
- transport.submit('form-token', {
- ...payload,
- otp_code: HUMAN_INPUT_V2_MOCK_OTP,
- }),
- ).rejects.toMatchObject({ category: 'challenge-expired' })
- })
-
- it.each([
- ['delivery-failed', 'access-delivery-failed'],
- ['rate-limited', 'access-rate-limit'],
- ] as const)('models the %s access scenario', async (accessState, category) => {
- const transport = createMockHumanInputV2FormTransport({ scenario: { accessState } })
-
- await expect(transport.requestAccess('form-token')).rejects.toMatchObject({ category })
- })
-
- it('supports definition fixtures with optional branding', async () => {
- const definition = createHumanInputV2MockScenario().definition
- const transport = createMockHumanInputV2FormTransport({
- scenario: {
- definition: {
- ...definition,
- branding: undefined,
- resolvedDefaultValues: { response: 'resolved response' },
- },
- },
- })
-
- await expect(transport.getForm('form-token')).resolves.toMatchObject({
- branding: undefined,
- resolvedDefaultValues: { response: 'resolved response' },
- })
- })
-
- it('returns upload tokens and handles local and remote files without network requests', async () => {
- const transport = createMockHumanInputV2FormTransport()
- const file = new File(['content'], 'review.txt', { type: 'text/plain' })
-
- await expect(transport.requestUploadToken('form-token')).resolves.toMatchObject({
- uploadToken: expect.stringMatching(/^mock-upload-token-/),
- })
- await expect(transport.uploadLocalFile('form-token', file)).resolves.toMatchObject({
- name: 'review.txt',
- mimeType: 'text/plain',
- })
- await expect(
- transport.uploadRemoteFile('form-token', 'https://example.com/review.txt'),
- ).resolves.toMatchObject({ url: 'https://example.com/review.txt' })
- })
-
- it('models upload failure and concurrent completion', async () => {
- const uploadTransport = createMockHumanInputV2FormTransport({
- scenario: { uploadState: 'failed' },
- })
- await expect(uploadTransport.requestUploadToken('form-token')).rejects.toMatchObject({
- category: 'upload-failed',
- })
-
- const submitTransport = createMockHumanInputV2FormTransport({
- scenario: { submitState: 'concurrent-completion' },
- })
- const challenge = await submitTransport.requestAccess('form-token')
- await expect(
- submitTransport.submit('form-token', {
- inputs: {},
- action: 'approve',
- otp_code: HUMAN_INPUT_V2_MOCK_OTP,
- challenge_token: challenge.challengeToken,
- }),
- ).rejects.toMatchObject({ category: 'already-submitted' })
- })
-
it('redacts raw error text and proof values during normalization', () => {
const normalized = normalizeHumanInputV2Error({
code: 'human_input_invalid_otp',
diff --git a/web/features/human-input/public/__tests__/session-reducer.spec.ts b/web/features/human-input/public/__tests__/session-reducer.spec.ts
index 61d711560fb..25727e8d806 100644
--- a/web/features/human-input/public/__tests__/session-reducer.spec.ts
+++ b/web/features/human-input/public/__tests__/session-reducer.spec.ts
@@ -1,5 +1,5 @@
-import { createHumanInputV2MockScenario } from '../mock-transport'
import { humanInputV2SessionReducer, initialHumanInputV2SessionState } from '../session-reducer'
+import { createHumanInputV2MockScenario } from './fixtures/mock-transport'
describe('Human Input v2 session reducer', () => {
const definition = createHumanInputV2MockScenario().definition
@@ -136,4 +136,33 @@ describe('Human Input v2 session reducer', () => {
})
expect(terminalState.challenge).toBeUndefined()
})
+
+ it.each(['already-submitted', 'form-expired'] as const)(
+ 'keeps %s terminal until an explicit reset',
+ (error) => {
+ const terminalState = humanInputV2SessionReducer(
+ { ...initialHumanInputV2SessionState, definition },
+ { type: 'submit-terminal-failed', error },
+ )
+ expect(
+ humanInputV2SessionReducer(terminalState, { type: 'access-succeeded', challenge }),
+ ).toBe(terminalState)
+ expect(
+ humanInputV2SessionReducer(terminalState, {
+ type: 'access-failed',
+ error: 'network',
+ preserveChallenge: false,
+ }),
+ ).toBe(terminalState)
+ expect(
+ humanInputV2SessionReducer(terminalState, { type: 'otp-changed', otpCode: '246810' }),
+ ).toBe(terminalState)
+ expect(humanInputV2SessionReducer(terminalState, { type: 'challenge-expired' })).toBe(
+ terminalState,
+ )
+ expect(humanInputV2SessionReducer(terminalState, { type: 'reset' })).toBe(
+ initialHumanInputV2SessionState,
+ )
+ },
+ )
})
diff --git a/web/features/human-input/public/__tests__/upload-strategies.spec.ts b/web/features/human-input/public/__tests__/upload-strategies.spec.ts
index 53b2e0fdac5..30172fd02a0 100644
--- a/web/features/human-input/public/__tests__/upload-strategies.spec.ts
+++ b/web/features/human-input/public/__tests__/upload-strategies.spec.ts
@@ -1,6 +1,6 @@
import { createLegacyFormUploadStrategy } from '../legacy-upload'
-import { createMockHumanInputV2FormTransport } from '../mock-transport'
import { createHumanInputV2UploadStrategy } from '../upload'
+import { createMockHumanInputV2FormTransport } from './fixtures/mock-transport'
const legacyUploads = vi.hoisted(() => ({
local: vi.fn(),
diff --git a/web/features/human-input/public/__tests__/use-form-session.spec.tsx b/web/features/human-input/public/__tests__/use-form-session.spec.tsx
index 2a3e05510aa..12e3e149500 100644
--- a/web/features/human-input/public/__tests__/use-form-session.spec.tsx
+++ b/web/features/human-input/public/__tests__/use-form-session.spec.tsx
@@ -2,13 +2,13 @@ import type { PropsWithChildren } from 'react'
import type { HumanInputV2FormTransport } from '../types'
import { act, renderHook, waitFor } from '@testing-library/react'
import { StrictMode } from 'react'
-import { createHumanInputV2Error } from '../errors'
+import { useHumanInputV2FormSession } from '../use-form-session'
+import { createHumanInputV2Error } from './fixtures/errors'
import {
createHumanInputV2MockScenario,
createMockHumanInputV2FormTransport,
HUMAN_INPUT_V2_MOCK_OTP,
-} from '../mock-transport'
-import { useHumanInputV2FormSession } from '../use-form-session'
+} from './fixtures/mock-transport'
const strictWrapper = ({ children }: PropsWithChildren) => <StrictMode>{children}</StrictMode>
@@ -95,6 +95,31 @@ describe('useHumanInputV2FormSession', () => {
expect(requestAccess).toHaveBeenCalledTimes(2)
})
+ it('keeps the access failure when an action is submitted before a code exists', async () => {
+ const submit = vi.fn<HumanInputV2FormTransport['submit']>()
+ const transport = withOverrides({
+ requestAccess: vi
+ .fn<HumanInputV2FormTransport['requestAccess']>()
+ .mockRejectedValue(createHumanInputV2Error('access-delivery-failed')),
+ submit,
+ })
+ const { result } = renderHook(() =>
+ useHumanInputV2FormSession({
+ token: 'form-token',
+ transport,
+ }),
+ )
+
+ await waitFor(() => expect(result.current.state.phase).toBe('access-error'))
+ await act(() => result.current.submit({}, 'approve'))
+
+ expect(result.current.state).toMatchObject({
+ phase: 'access-error',
+ error: 'access-delivery-failed',
+ })
+ expect(submit).not.toHaveBeenCalled()
+ })
+
it('derives absolute cooldown/expiry deadlines and never auto-resends after expiry', async () => {
vi.useFakeTimers()
let currentTime = 10_000
@@ -115,8 +140,8 @@ describe('useHumanInputV2FormSession', () => {
await act(async () => Promise.resolve())
await act(async () => Promise.resolve())
expect(result.current.state.phase).toBe('awaiting-otp')
- expect(result.current.secondsUntilResend).toBe(10)
- expect(result.current.secondsUntilExpiry).toBe(20)
+ expect(result.current.state.challenge?.resendAt).toBe(20_000)
+ expect(result.current.state.challenge?.expiresAt).toBe(30_000)
currentTime += 20_000
act(() => window.dispatchEvent(new Event('focus')))
@@ -204,12 +229,16 @@ describe('useHumanInputV2FormSession', () => {
})
expect(submit).toHaveBeenCalledTimes(1)
- expect(submit).toHaveBeenCalledWith('form-token', {
- inputs: { response: 'approved' },
- action: 'approve',
- otp_code: HUMAN_INPUT_V2_MOCK_OTP,
- challenge_token: 'mock-challenge-1',
- })
+ expect(submit).toHaveBeenCalledWith(
+ 'form-token',
+ {
+ inputs: { response: 'approved' },
+ action: 'approve',
+ otp_code: HUMAN_INPUT_V2_MOCK_OTP,
+ challenge_token: 'mock-challenge-1',
+ },
+ { signal: expect.any(AbortSignal) },
+ )
await act(async () => submitDeferred.resolve())
expect(result.current.state).toMatchObject({ phase: 'success', otpCode: '' })
@@ -240,12 +269,12 @@ describe('useHumanInputV2FormSession', () => {
await waitFor(() => expect(result.current.state.phase).toBe('awaiting-otp'))
act(() => result.current.setOtpCode(HUMAN_INPUT_V2_MOCK_OTP))
+ act(() => result.current.resendAccess())
+ expect(requestAccess).toHaveBeenCalledTimes(2)
act(() => {
void result.current.submit({ response: 'approved' }, 'approve')
})
expect(result.current.state.phase).toBe('submitting')
- act(() => result.current.resendAccess())
- expect(requestAccess).toHaveBeenCalledTimes(2)
await act(async () => submitDeferred.resolve())
expect(result.current.state.phase).toBe('success')
@@ -266,12 +295,16 @@ describe('useHumanInputV2FormSession', () => {
expect(result.current.state.challenge).toBeUndefined()
expect(result.current.state.error).toBeUndefined()
expect(result.current.canSubmit).toBe(false)
- expect(submit).toHaveBeenCalledWith('form-token', {
- inputs: { response: 'approved' },
- action: 'approve',
- otp_code: HUMAN_INPUT_V2_MOCK_OTP,
- challenge_token: 'original-challenge',
- })
+ expect(submit).toHaveBeenCalledWith(
+ 'form-token',
+ {
+ inputs: { response: 'approved' },
+ action: 'approve',
+ otp_code: HUMAN_INPUT_V2_MOCK_OTP,
+ challenge_token: 'original-challenge',
+ },
+ { signal: expect.any(AbortSignal) },
+ )
},
)
@@ -299,112 +332,22 @@ describe('useHumanInputV2FormSession', () => {
expect(result.current.state.phase).toBe('success')
})
- it('ignores late definition and access responses after the route token changes', async () => {
- const oldDefinition =
- deferred<ReturnType<typeof createHumanInputV2MockScenario>['definition']>()
- const newDefinition =
- deferred<ReturnType<typeof createHumanInputV2MockScenario>['definition']>()
- const baseDefinition = createHumanInputV2MockScenario().definition
- const requestAccess = vi.fn<HumanInputV2FormTransport['requestAccess']>().mockResolvedValue({
- challengeToken: 'new-challenge',
- resendAfterSeconds: 30,
- expiresInSeconds: 300,
- })
- const transport = withOverrides({
- getForm: vi.fn((token: string) =>
- token === 'old-token' ? oldDefinition.promise : newDefinition.promise,
- ),
- requestAccess,
- })
- const { result, rerender } = renderHook(
- ({ token }) => useHumanInputV2FormSession({ token, transport }),
- { initialProps: { token: 'old-token' } },
- )
-
- rerender({ token: 'new-token' })
- await act(async () =>
- newDefinition.resolve({
- ...baseDefinition,
- formContent: 'new definition',
- }),
- )
- await waitFor(() => expect(result.current.state.phase).toBe('awaiting-otp'))
- act(() => result.current.setOtpCode('123456'))
-
- await act(async () =>
- oldDefinition.resolve({
- ...baseDefinition,
- formContent: 'old definition',
- }),
- )
-
- expect(result.current.state.definition?.formContent).toBe('new definition')
- expect(result.current.state.challenge?.challengeToken).toBe('new-challenge')
- expect(requestAccess).toHaveBeenCalledTimes(1)
- expect(requestAccess).toHaveBeenCalledWith('new-token')
- })
-
- it('ignores a late access response from the previous route session', async () => {
- const oldAccess = deferred<{
- challengeToken: string
- resendAfterSeconds: number
- expiresInSeconds: number
- }>()
- const definition = createHumanInputV2MockScenario().definition
- const requestAccess = vi
- .fn<HumanInputV2FormTransport['requestAccess']>()
- .mockImplementation((token) =>
- token === 'old-token'
- ? oldAccess.promise
- : Promise.resolve({
- challengeToken: 'new-challenge',
- resendAfterSeconds: 30,
- expiresInSeconds: 300,
- }),
- )
- const transport = withOverrides({
- getForm: vi.fn().mockResolvedValue(definition),
- requestAccess,
- })
- const { result, rerender } = renderHook(
- ({ token }) => useHumanInputV2FormSession({ token, transport }),
- { initialProps: { token: 'old-token' } },
- )
- await waitFor(() => expect(requestAccess).toHaveBeenCalledWith('old-token'))
-
- rerender({ token: 'new-token' })
- await waitFor(() =>
- expect(result.current.state.challenge?.challengeToken).toBe('new-challenge'),
- )
-
- await act(async () =>
- oldAccess.resolve({
- challengeToken: 'old-challenge',
- resendAfterSeconds: 30,
- expiresInSeconds: 300,
+ it('aborts a pending definition on unmount without sending a verification email afterwards', async () => {
+ const definition = deferred<ReturnType<typeof createHumanInputV2MockScenario>['definition']>()
+ const requestAccess = vi.fn<HumanInputV2FormTransport['requestAccess']>()
+ const getForm = vi
+ .fn<HumanInputV2FormTransport['getForm']>()
+ .mockReturnValue(definition.promise)
+ const { unmount } = renderHook(() =>
+ useHumanInputV2FormSession({
+ token: 'leaving',
+ transport: withOverrides({ getForm, requestAccess }),
}),
)
- expect(result.current.state.challenge?.challengeToken).toBe('new-challenge')
- expect(requestAccess).toHaveBeenCalledTimes(2)
- })
-
- it('starts a clean proof session when the route token changes after success', async () => {
- const transport = createMockHumanInputV2FormTransport()
- const { result, rerender } = renderHook(
- ({ token }) => useHumanInputV2FormSession({ token, transport }),
- { initialProps: { token: 'first-token' } },
- )
- await waitFor(() => expect(result.current.state.phase).toBe('awaiting-otp'))
- const firstChallenge = result.current.state.challenge?.challengeToken
- act(() => result.current.setOtpCode(HUMAN_INPUT_V2_MOCK_OTP))
- await act(async () => result.current.submit({}, 'approve'))
- expect(result.current.state.phase).toBe('success')
-
- rerender({ token: 'second-token' })
- await waitFor(() => expect(result.current.state.phase).toBe('awaiting-otp'))
-
- expect(result.current.state.otpCode).toBe('')
- expect(result.current.state.challenge?.challengeToken).not.toBe(firstChallenge)
+ unmount()
+ expect(getForm.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)
+ await act(async () => definition.resolve(createHumanInputV2MockScenario().definition))
+ expect(requestAccess).not.toHaveBeenCalled()
})
it('does not persist or log OTP and Challenge values', async () => {
@@ -427,4 +370,43 @@ describe('useHumanInputV2FormSession', () => {
consoleLog.mockRestore()
setLocalStorage.mockRestore()
})
+
+ it.each([
+ ['already-submitted', 'success'],
+ ['already-submitted', 'failure'],
+ ['form-expired', 'success'],
+ ['form-expired', 'failure'],
+ ] as const)('keeps terminal %s after a late access %s', async (category, accessOutcome) => {
+ const access = deferred<Awaited<ReturnType<HumanInputV2FormTransport['requestAccess']>>>()
+ const requestAccess = vi
+ .fn<HumanInputV2FormTransport['requestAccess']>()
+ .mockResolvedValueOnce({
+ challengeToken: 'original',
+ resendAfterSeconds: 0,
+ expiresInSeconds: 300,
+ })
+ .mockReturnValueOnce(access.promise)
+ const submit = vi
+ .fn<HumanInputV2FormTransport['submit']>()
+ .mockRejectedValueOnce(createHumanInputV2Error(category))
+ const transport = withOverrides({ requestAccess, submit })
+ const { result } = renderHook(() =>
+ useHumanInputV2FormSession({ token: 'form-token', transport }),
+ )
+ await waitFor(() => expect(result.current.state.phase).toBe('awaiting-otp'))
+ act(() => result.current.setOtpCode(HUMAN_INPUT_V2_MOCK_OTP))
+ act(() => result.current.resendAccess())
+ expect(requestAccess).toHaveBeenCalledTimes(2)
+ await act(async () => result.current.submit({ response: 'reviewed' }, 'approve'))
+ expect(result.current.state).toMatchObject({ phase: 'terminal', error: category, otpCode: '' })
+ await act(async () => {
+ if (accessOutcome === 'success')
+ access.resolve({ challengeToken: 'late', resendAfterSeconds: 30, expiresInSeconds: 300 })
+ else access.reject(createHumanInputV2Error('network'))
+ })
+ expect(result.current.state).toMatchObject({ phase: 'terminal', error: category, otpCode: '' })
+ expect(result.current.state.challenge).toBeUndefined()
+ expect(result.current.canSubmit).toBe(false)
+ expect(submit).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/web/features/human-input/public/errors.ts b/web/features/human-input/public/errors.ts
index 8fcb961d2f0..081f0f9ba30 100644
--- a/web/features/human-input/public/errors.ts
+++ b/web/features/human-input/public/errors.ts
@@ -1,6 +1,10 @@
import type { HumanInputV2ErrorCategory } from './types'
const CATEGORY_BY_CODE: Record<string, HumanInputV2ErrorCategory> = {
+ expired: 'form-expired',
+ already_submitted: 'already-submitted',
+ workflow_not_active: 'unavailable',
+ not_found: 'not-found',
human_input_form_not_found: 'not-found',
human_input_form_expired: 'form-expired',
human_input_form_submitted: 'already-submitted',
@@ -51,12 +55,6 @@ type ErrorLike = {
data?: { code?: unknown; body?: { code?: unknown } }
}
-export const createHumanInputV2Error = (
- category: HumanInputV2ErrorCategory,
- code = `human_input_${category.replaceAll('-', '_')}`,
- status?: number,
-) => new HumanInputV2TransportError(category, code, status)
-
export const normalizeHumanInputV2Error = (error: unknown): HumanInputV2TransportError => {
if (error instanceof HumanInputV2TransportError) return error
@@ -68,6 +66,7 @@ export const normalizeHumanInputV2Error = (error: unknown): HumanInputV2Transpor
CATEGORY_BY_CODE[code] ??
(candidate?.name === 'AbortError' ? 'network' : undefined) ??
(status === 404 ? 'not-found' : undefined) ??
+ (status === 410 ? 'form-expired' : undefined) ??
(status === 429 ? 'form-rate-limit' : undefined) ??
(status === 501 ? 'unavailable' : undefined) ??
(candidate instanceof TypeError ? 'network' : undefined) ??
diff --git a/web/features/human-input/public/form.tsx b/web/features/human-input/public/form.tsx
index 06203b8c194..dfe52a53829 100644
--- a/web/features/human-input/public/form.tsx
+++ b/web/features/human-input/public/form.tsx
@@ -1,7 +1,7 @@
'use client'
import type { HumanInputV2ErrorCategory, HumanInputV2FormTransport } from './types'
import { Button } from '@langgenius/dify-ui/button'
-import { useMemo } from 'react'
+import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
FileUploadContext,
@@ -10,8 +10,9 @@ import {
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import FormStatusCard from '@/features/human-input/form/form-status-card'
import LoadedFormContent from '@/features/human-input/form/loaded-form-content'
+import useDocumentTitle from '@/hooks/use-document-title'
import OtpVerification from './otp-verification'
-import { defaultHumanInputV2FormTransport } from './transport-selector'
+import { realHumanInputV2FormTransport } from './real-transport'
import { createHumanInputV2UploadStrategy } from './upload'
import { useHumanInputV2FormSession } from './use-form-session'
@@ -36,7 +37,7 @@ const getBrandingOptions = (
const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInputV2FormProps) => {
const { t } = useTranslation(['share'])
- const transport = injectedTransport ?? defaultHumanInputV2FormTransport
+ const transport = injectedTransport ?? realHumanInputV2FormTransport
const inheritedUploadContext = useFileUploadContext()
const uploadContext = useMemo(
() => ({
@@ -51,7 +52,8 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
now,
})
const { state } = session
-
+ const [retryError, setRetryError] = useState<HumanInputV2ErrorCategory>()
+ const retryingForm = state.phase === 'loading-form' && retryError !== undefined
const errorCopy = (category?: HumanInputV2ErrorCategory) => {
switch (category) {
case 'not-found':
@@ -83,14 +85,16 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
}
}
- const invalidOtp = state.error === 'invalid-otp'
- const otpErrors = useMemo(
- () =>
- invalidOtp ? { otp: t(($) => $['humanInputV2.invalidOtp'], { ns: 'share' }) } : undefined,
- [invalidOtp, t],
+ useDocumentTitle(
+ state.phase === 'success'
+ ? t(($) => $['humanInput.thanks'], { ns: 'share' })
+ : state.phase === 'terminal' || state.phase === 'form-error' || retryingForm
+ ? errorCopy(state.error ?? retryError)
+ : t(($) => $['humanInputV2.otpLabel'], { ns: 'share' }),
)
- if (state.phase === 'loading-form') return <LoadingPlaceholder className="h-full" />
+ if (state.phase === 'loading-form' && !retryingForm)
+ return <LoadingPlaceholder className="h-full" />
if (state.phase === 'success') {
return (
@@ -104,7 +108,7 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
)
}
- if (state.phase === 'terminal' || state.phase === 'form-error') {
+ if (state.phase === 'terminal' || state.phase === 'form-error' || retryingForm) {
const isResolvedRequest = state.error === 'form-expired' || state.error === 'already-submitted'
return (
@@ -117,13 +121,20 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
title={
isResolvedRequest
? t(($) => $['humanInput.sorry'], { ns: 'share' })
- : errorCopy(state.error)
+ : errorCopy(state.error ?? retryError)
}
subtitle={
isResolvedRequest ? (
errorCopy(state.error)
- ) : state.phase === 'form-error' ? (
- <Button size="small" onClick={session.retryForm}>
+ ) : state.phase === 'form-error' || retryingForm ? (
+ <Button
+ size="small"
+ loading={retryingForm}
+ onClick={() => {
+ setRetryError(state.error)
+ session.retryForm()
+ }}
+ >
{t(($) => $['humanInputV2.retry'], { ns: 'share' })}
</Button>
) : undefined
@@ -136,7 +147,9 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
if (!state.definition) return <LoadingPlaceholder className="h-full" />
- const verificationError = state.error ? errorCopy(state.error) : undefined
+ const verificationError = state.error
+ ? { category: state.error, message: errorCopy(state.error) }
+ : undefined
return (
<FileUploadContext value={uploadContext}>
@@ -144,17 +157,16 @@ const HumanInputV2Form = ({ token, transport: injectedTransport, now }: HumanInp
key={token}
definition={state.definition}
isSubmitting={state.phase === 'submitting'}
- actionsDisabled={!session.canSubmit}
onSubmit={session.submit}
- errors={otpErrors}
verificationContent={
<OtpVerification
+ focusOnMount={retryError !== undefined}
otpCode={state.otpCode}
requesting={state.phase === 'requesting-otp'}
- error={invalidOtp ? undefined : verificationError}
- secondsUntilResend={session.secondsUntilResend}
- secondsUntilExpiry={session.secondsUntilExpiry}
- hasChallenge={Boolean(state.challenge)}
+ error={verificationError}
+ challenge={state.challenge}
+ submitting={state.phase === 'submitting'}
+ now={now}
onOtpChange={session.setOtpCode}
onRetry={session.retryAccess}
onResend={session.resendAccess}
diff --git a/web/features/human-input/public/otp-verification.tsx b/web/features/human-input/public/otp-verification.tsx
index f30166b4422..0755139ec14 100644
--- a/web/features/human-input/public/otp-verification.tsx
+++ b/web/features/human-input/public/otp-verification.tsx
@@ -1,15 +1,18 @@
+import type { HumanInputV2Challenge, HumanInputV2ErrorCategory } from './types'
import { Button } from '@langgenius/dify-ui/button'
-import { Field, FieldError } from '@langgenius/dify-ui/field'
+import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
+import { useEffect, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
type OtpVerificationProps = {
otpCode: string
requesting: boolean
- error?: string
- secondsUntilResend: number
- secondsUntilExpiry: number
- hasChallenge: boolean
+ submitting: boolean
+ error?: { category: HumanInputV2ErrorCategory; message: string }
+ challenge?: HumanInputV2Challenge
+ now?: () => number
+ focusOnMount?: boolean
onOtpChange: (value: string) => void
onRetry: () => void
onResend: () => void
@@ -18,51 +21,83 @@ type OtpVerificationProps = {
const OtpVerification = ({
otpCode,
requesting,
+ submitting,
error,
- secondsUntilResend,
- secondsUntilExpiry,
- hasChallenge,
+ challenge,
+ now = Date.now,
+ focusOnMount = false,
onOtpChange,
onRetry,
onResend,
}: OtpVerificationProps) => {
const { t } = useTranslation(['share'])
+ const resendLabelId = useId()
+ const codeRef = useRef<HTMLInputElement>(null)
+ const focusCodeRef = useRef(focusOnMount)
+ useEffect(() => {
+ if (challenge && focusCodeRef.current) {
+ codeRef.current?.focus()
+ focusCodeRef.current = false
+ }
+ }, [challenge])
+ const [clock, setClock] = useState(now)
+ useEffect(() => {
+ if (!challenge) return
+ const update = () => setClock(now())
+ const timer = window.setInterval(update, 1000)
+ window.addEventListener('focus', update)
+ document.addEventListener('visibilitychange', update)
+ return () => {
+ window.clearInterval(timer)
+ window.removeEventListener('focus', update)
+ document.removeEventListener('visibilitychange', update)
+ }
+ }, [challenge, now])
+ const secondsUntilResend = challenge
+ ? Math.max(0, Math.ceil((challenge.resendAt - clock) / 1000))
+ : 0
+ const secondsUntilExpiry = challenge
+ ? Math.max(0, Math.ceil((challenge.expiresAt - clock) / 1000))
+ : 0
+ const invalidCode = error?.category === 'invalid-otp'
return (
- <div className="flex flex-col gap-3 rounded-xl border border-divider-subtle bg-background-section p-3">
- <div className="flex flex-col gap-1">
- <label htmlFor="human-input-v2-otp" className="system-sm-semibold text-text-primary">
- {t(($) => $['humanInputV2.otpLabel'], { ns: 'share' })}
- </label>
- <div className="system-xs-regular text-text-secondary">
+ <div className="my-3 rounded-xl border border-divider-subtle bg-background-section p-3">
+ <Field name="otp_code" invalid={invalidCode}>
+ <FieldLabel>{t(($) => $['humanInputV2.otpLabel'], { ns: 'share' })}</FieldLabel>
+ <FieldDescription role="status">
{requesting
? t(($) => $['humanInputV2.requestingCode'], { ns: 'share' })
- : hasChallenge
+ : challenge
? t(($) => $['humanInputV2.codeSent'], { ns: 'share' })
: t(($) => $['humanInputV2.codeRequired'], { ns: 'share' })}
- </div>
- </div>
- {hasChallenge && (
- <Field name="otp">
+ </FieldDescription>
+ {challenge && (
<Input
- id="human-input-v2-otp"
+ ref={codeRef}
value={otpCode}
inputMode="numeric"
autoComplete="one-time-code"
- maxLength={6}
+ pattern="[0-9]{6}"
+ required
+ readOnly={submitting}
placeholder={t(($) => $['humanInputV2.otpPlaceholder'], { ns: 'share' })}
onChange={(event) => onOtpChange(event.target.value)}
/>
- <FieldError />
- </Field>
- )}
- {error && (
- <div role="alert" className="system-xs-regular text-text-destructive">
- {error}
- </div>
+ )}
+ {invalidCode && (
+ <FieldError match role="alert">
+ {error.message}
+ </FieldError>
+ )}
+ </Field>
+ {error && !invalidCode && (
+ <p role="alert" className="system-sm-regular text-text-destructive">
+ {error.message}
+ </p>
)}
- <div className="flex items-center justify-between gap-3">
- {hasChallenge ? (
+ <div className="mt-3 flex items-center justify-between gap-3">
+ {challenge ? (
<>
<div className="system-xs-regular text-text-tertiary">
{t(($) => $['humanInputV2.codeExpiresIn'], {
@@ -73,19 +108,28 @@ const OtpVerification = ({
<Button
size="small"
variant="ghost"
- disabled={requesting || secondsUntilResend > 0}
+ loading={requesting}
+ disabled={submitting || secondsUntilResend > 0}
+ focusableWhenDisabled
+ aria-labelledby={resendLabelId}
onClick={onResend}
>
- {secondsUntilResend > 0
- ? t(($) => $['humanInputV2.resendIn'], {
- ns: 'share',
- seconds: secondsUntilResend,
- })
- : t(($) => $['humanInputV2.resendCode'], { ns: 'share' })}
+ <span id={resendLabelId}>
+ {t(($) => $['humanInputV2.resendCode'], { ns: 'share' })}
+ </span>
+ {secondsUntilResend > 0 && <span aria-hidden>({secondsUntilResend})</span>}
</Button>
</>
) : (
- <Button size="small" disabled={requesting} onClick={onRetry}>
+ <Button
+ size="small"
+ loading={requesting}
+ disabled={submitting}
+ onClick={() => {
+ focusCodeRef.current = true
+ onRetry()
+ }}
+ >
{t(($) => $['humanInputV2.sendCode'], { ns: 'share' })}
</Button>
)}
diff --git a/web/features/human-input/public/session-reducer.ts b/web/features/human-input/public/session-reducer.ts
index 89b62afb7cf..499ae421210 100644
--- a/web/features/human-input/public/session-reducer.ts
+++ b/web/features/human-input/public/session-reducer.ts
@@ -46,7 +46,8 @@ export const humanInputV2SessionReducer = (
action: HumanInputV2SessionAction,
): HumanInputV2SessionState => {
// In-flight OTP requests can settle after submission completes in this session.
- if (state.phase === 'success' && action.type !== 'reset') return state
+ if ((state.phase === 'success' || state.phase === 'terminal') && action.type !== 'reset')
+ return state
switch (action.type) {
case 'reset':
diff --git a/web/features/human-input/public/transport-selector.ts b/web/features/human-input/public/transport-selector.ts
deleted file mode 100644
index 5ca161692af..00000000000
--- a/web/features/human-input/public/transport-selector.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { HumanInputV2FormTransport } from './types'
-import { createMockHumanInputV2FormTransport } from './mock-transport'
-import { realHumanInputV2FormTransport } from './real-transport'
-
-type HumanInputV2AdapterKind = 'real' | 'mock'
-
-type SelectTransportOptions = {
- adapter: HumanInputV2AdapterKind
- environment: 'development' | 'test' | 'production'
- mockTransport?: HumanInputV2FormTransport
- realTransport?: HumanInputV2FormTransport
-}
-
-export const selectHumanInputV2FormTransport = ({
- adapter,
- environment,
- mockTransport = createMockHumanInputV2FormTransport(),
- realTransport = realHumanInputV2FormTransport,
-}: SelectTransportOptions): HumanInputV2FormTransport => {
- if (adapter === 'mock' && environment !== 'production') return mockTransport
- return realTransport
-}
-
-const runtimeEnvironment = process.env.NODE_ENV
-
-export const defaultHumanInputV2FormTransport = selectHumanInputV2FormTransport({
- adapter: 'real',
- environment: runtimeEnvironment,
-})
diff --git a/web/features/human-input/public/use-form-session.ts b/web/features/human-input/public/use-form-session.ts
index e385f38a65a..e98b88a3fc5 100644
--- a/web/features/human-input/public/use-form-session.ts
+++ b/web/features/human-input/public/use-form-session.ts
@@ -1,251 +1,180 @@
'use client'
import type { HumanInputV2FormTransport } from './types'
-import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
+import { useCallback, useEffect, useReducer, useState } from 'react'
import { isTerminalFormError, normalizeHumanInputV2Error } from './errors'
import { humanInputV2SessionReducer, initialHumanInputV2SessionState } from './session-reducer'
-type Runtime = {
- token: string
- transport: HumanInputV2FormTransport
- loadStarted: boolean
- autoAccessStarted: boolean
- resetState: boolean
-}
-
type UseHumanInputV2FormSessionOptions = {
token: string
transport: HumanInputV2FormTransport
now?: () => number
}
-const OTP_PATTERN = /^\d{6}$/
-
-const isValidHumanInputV2Otp = (otpCode: string) => OTP_PATTERN.test(otpCode)
-
export const useHumanInputV2FormSession = ({
token,
transport,
now = Date.now,
}: UseHumanInputV2FormSessionOptions) => {
const [state, dispatch] = useReducer(humanInputV2SessionReducer, initialHumanInputV2SessionState)
- const [clock, setClock] = useState(now)
- const runtimeRef = useRef<Runtime | undefined>(undefined)
- const accessLockRef = useRef(false)
- const submitLockRef = useRef(false)
-
- const runtimeChanged = Boolean(
- runtimeRef.current &&
- (runtimeRef.current.token !== token || runtimeRef.current.transport !== transport),
+ const [runtime] = useState(() => ({
+ token,
+ transport,
+ controller: undefined as AbortController | undefined,
+ accessing: false,
+ submitting: false,
+ }))
+ const isCurrent = useCallback(
+ (signal: AbortSignal) => runtime.controller?.signal === signal && !signal.aborted,
+ [runtime],
)
- if (
- !runtimeRef.current ||
- runtimeRef.current.token !== token ||
- runtimeRef.current.transport !== transport
- ) {
- runtimeRef.current = {
- token,
- transport,
- loadStarted: false,
- autoAccessStarted: false,
- resetState: runtimeChanged,
- }
- accessLockRef.current = false
- submitLockRef.current = false
- }
- const runtime = runtimeRef.current
-
- const isCurrentRuntime = useCallback((candidate: Runtime) => runtimeRef.current === candidate, [])
-
- const applyAccessResponse = useCallback(
- (
- candidate: Runtime,
- response: Awaited<ReturnType<HumanInputV2FormTransport['requestAccess']>>,
- ) => {
- if (!isCurrentRuntime(candidate)) return
- const receivedAt = now()
- setClock(receivedAt)
- dispatch({
- type: 'access-succeeded',
- challenge: {
- ...response,
- receivedAt,
- resendAt: receivedAt + response.resendAfterSeconds * 1000,
- expiresAt: receivedAt + response.expiresInSeconds * 1000,
- },
- })
- },
- [isCurrentRuntime, now],
- )
-
- const requestAccessForRuntime = useCallback(
- async (candidate: Runtime, preserveChallenge: boolean) => {
- if (accessLockRef.current) return
- accessLockRef.current = true
+ const requestAccess = useCallback(
+ async (signal: AbortSignal, preserveChallenge: boolean) => {
+ if (!isCurrent(signal) || runtime.accessing || runtime.submitting) return
+ runtime.accessing = true
dispatch({ type: 'access-requested' })
try {
- const response = await candidate.transport.requestAccess(candidate.token)
- applyAccessResponse(candidate, response)
- } catch (error) {
- if (!isCurrentRuntime(candidate)) return
+ const response = await runtime.transport.requestAccess(runtime.token, { signal })
+ if (!isCurrent(signal)) return
+ const receivedAt = now()
dispatch({
- type: 'access-failed',
- error: normalizeHumanInputV2Error(error).category,
- preserveChallenge,
+ type: 'access-succeeded',
+ challenge: {
+ ...response,
+ receivedAt,
+ resendAt: receivedAt + response.resendAfterSeconds * 1000,
+ expiresAt: receivedAt + response.expiresInSeconds * 1000,
+ },
})
+ } catch (error) {
+ if (isCurrent(signal))
+ dispatch({
+ type: 'access-failed',
+ error: normalizeHumanInputV2Error(error).category,
+ preserveChallenge,
+ })
} finally {
- if (isCurrentRuntime(candidate)) accessLockRef.current = false
+ if (isCurrent(signal)) runtime.accessing = false
}
},
- [applyAccessResponse, isCurrentRuntime],
+ [isCurrent, now, runtime],
)
- const loadForm = useCallback(
- async (candidate: Runtime) => {
- if (candidate.loadStarted) return
- candidate.loadStarted = true
+ const load = useCallback(
+ async (signal: AbortSignal) => {
try {
- const definition = await candidate.transport.getForm(candidate.token)
- if (!isCurrentRuntime(candidate)) return
+ const definition = await runtime.transport.getForm(runtime.token, { signal })
+ if (!isCurrent(signal)) return
dispatch({ type: 'form-loaded', definition })
- if (!candidate.autoAccessStarted) {
- candidate.autoAccessStarted = true
- await requestAccessForRuntime(candidate, false)
- }
+ await requestAccess(signal, false)
} catch (error) {
- if (!isCurrentRuntime(candidate)) return
- const normalizedError = normalizeHumanInputV2Error(error)
+ if (!isCurrent(signal)) return
+ const normalized = normalizeHumanInputV2Error(error)
dispatch({
type: 'form-failed',
- error: normalizedError.category,
- terminal: isTerminalFormError(normalizedError.category),
+ error: normalized.category,
+ terminal: isTerminalFormError(normalized.category),
})
}
},
- [isCurrentRuntime, requestAccessForRuntime],
+ [isCurrent, requestAccess, runtime],
)
useEffect(() => {
- if (runtime.resetState) {
- runtime.resetState = false
- dispatch({ type: 'reset' })
- }
- void loadForm(runtime)
- }, [loadForm, runtime])
+ const controller = new AbortController()
+ runtime.controller = controller
+ runtime.accessing = false
+ runtime.submitting = false
+ void load(controller.signal)
+ return () => runtime.controller?.abort()
+ }, [load, runtime])
useEffect(() => {
- if (!state.challenge) return
- const updateClock = () => setClock(now())
- const timer = window.setInterval(updateClock, 1000)
- window.addEventListener('focus', updateClock)
- document.addEventListener('visibilitychange', updateClock)
+ if (!state.challenge || state.phase === 'submitting') return
+ const remaining = state.challenge.expiresAt - now()
+ const expire = () => dispatch({ type: 'challenge-expired' })
+ const checkExpiry = () => {
+ if (now() >= state.challenge!.expiresAt) expire()
+ }
+ window.addEventListener('focus', checkExpiry)
+ document.addEventListener('visibilitychange', checkExpiry)
+ const timer = window.setTimeout(expire, Math.min(Math.max(0, remaining), 2_147_483_647))
return () => {
- window.clearInterval(timer)
- window.removeEventListener('focus', updateClock)
- document.removeEventListener('visibilitychange', updateClock)
+ window.clearTimeout(timer)
+ window.removeEventListener('focus', checkExpiry)
+ document.removeEventListener('visibilitychange', checkExpiry)
}
- }, [now, state.challenge])
-
- useEffect(() => {
- if (state.challenge && clock >= state.challenge.expiresAt)
- dispatch({ type: 'challenge-expired' })
- }, [clock, state.challenge])
+ }, [now, state.challenge, state.phase])
const retryForm = useCallback(() => {
- const nextRuntime: Runtime = {
- token,
- transport,
- loadStarted: false,
- autoAccessStarted: false,
- resetState: false,
- }
- runtimeRef.current = nextRuntime
- accessLockRef.current = false
- submitLockRef.current = false
+ runtime.controller?.abort()
+ const controller = new AbortController()
+ runtime.controller = controller
+ runtime.accessing = false
+ runtime.submitting = false
dispatch({ type: 'reset' })
- void loadForm(nextRuntime)
- }, [loadForm, token, transport])
+ void load(controller.signal)
+ }, [load, runtime])
const retryAccess = useCallback(() => {
- void requestAccessForRuntime(runtimeRef.current!, false)
- }, [requestAccessForRuntime])
-
+ const signal = runtime.controller?.signal
+ if (signal) void requestAccess(signal, false)
+ }, [requestAccess, runtime])
const resendAccess = useCallback(() => {
- const challenge = state.challenge
- if (!challenge || now() < challenge.resendAt) return
- const preserveChallenge = now() < challenge.expiresAt
- void requestAccessForRuntime(runtimeRef.current!, preserveChallenge)
- }, [now, requestAccessForRuntime, state.challenge])
-
+ const signal = runtime.controller?.signal
+ if (!signal || !state.challenge || now() < state.challenge.resendAt) return
+ void requestAccess(signal, now() < state.challenge.expiresAt)
+ }, [now, requestAccess, runtime, state.challenge])
const setOtpCode = useCallback((otpCode: string) => {
dispatch({ type: 'otp-changed', otpCode: otpCode.replace(/\D/g, '').slice(0, 6) })
}, [])
-
const canSubmit = Boolean(
state.challenge &&
- clock < state.challenge.expiresAt &&
- isValidHumanInputV2Otp(state.otpCode) &&
+ now() < state.challenge.expiresAt &&
+ /^\d{6}$/.test(state.otpCode) &&
['awaiting-otp', 'proof-error'].includes(state.phase),
)
-
const submit = useCallback(
async (inputs: Record<string, unknown>, action: string) => {
+ const signal = runtime.controller?.signal
+ if (!signal || !isCurrent(signal) || runtime.submitting) return
const challenge = state.challenge
- if (!challenge || !canSubmit || submitLockRef.current) return
+ if (!challenge) return
if (now() >= challenge.expiresAt) {
dispatch({ type: 'challenge-expired' })
return
}
- const candidate = runtimeRef.current!
- submitLockRef.current = true
+ if (!/^\d{6}$/.test(state.otpCode)) {
+ dispatch({ type: 'submit-proof-failed', error: 'invalid-otp' })
+ return
+ }
+ runtime.submitting = true
dispatch({ type: 'submit-requested' })
try {
- await transport.submit(token, {
- inputs,
- action,
- otp_code: state.otpCode,
- challenge_token: challenge.challengeToken,
- })
- if (!isCurrentRuntime(candidate)) return
- dispatch({ type: 'submit-succeeded' })
+ await runtime.transport.submit(
+ runtime.token,
+ {
+ inputs,
+ action,
+ otp_code: state.otpCode,
+ challenge_token: challenge.challengeToken,
+ },
+ { signal },
+ )
+ if (isCurrent(signal)) dispatch({ type: 'submit-succeeded' })
} catch (error) {
- if (!isCurrentRuntime(candidate)) return
- const normalizedError = normalizeHumanInputV2Error(error)
- if (
- normalizedError.category === 'challenge-expired' ||
- normalizedError.category === 'challenge-stale'
- ) {
- dispatch({ type: 'submit-challenge-failed', error: normalizedError.category })
- } else if (
- normalizedError.category === 'already-submitted' ||
- normalizedError.category === 'form-expired'
- ) {
- dispatch({ type: 'submit-terminal-failed', error: normalizedError.category })
- } else {
- dispatch({ type: 'submit-proof-failed', error: normalizedError.category })
- }
+ if (!isCurrent(signal)) return
+ const category = normalizeHumanInputV2Error(error).category
+ if (category === 'challenge-expired' || category === 'challenge-stale')
+ dispatch({ type: 'submit-challenge-failed', error: category })
+ else if (category === 'already-submitted' || category === 'form-expired')
+ dispatch({ type: 'submit-terminal-failed', error: category })
+ else dispatch({ type: 'submit-proof-failed', error: category })
} finally {
- if (isCurrentRuntime(candidate)) submitLockRef.current = false
+ if (isCurrent(signal)) runtime.submitting = false
}
},
- [canSubmit, isCurrentRuntime, now, state.challenge, state.otpCode, token, transport],
+ [isCurrent, now, runtime, state.challenge, state.otpCode],
)
- const secondsUntilResend = state.challenge
- ? Math.max(0, Math.ceil((state.challenge.resendAt - clock) / 1000))
- : 0
- const secondsUntilExpiry = state.challenge
- ? Math.max(0, Math.ceil((state.challenge.expiresAt - clock) / 1000))
- : 0
-
- return {
- state,
- canSubmit,
- secondsUntilResend,
- secondsUntilExpiry,
- retryForm,
- retryAccess,
- resendAccess,
- setOtpCode,
- submit,
- }
+ return { state, canSubmit, retryForm, retryAccess, resendAccess, setOtpCode, submit }
}
diff --git a/web/i18n/locales/ar-TN/contacts.json b/web/i18n/locales/ar-TN/contacts.json
index 84519d905ba..de8669e6c4e 100644
--- a/web/i18n/locales/ar-TN/contacts.json
+++ b/web/i18n/locales/ar-TN/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "حذف جهات الاتصال ({{count}})؟",
"directory.removalDescription": "ستتم إزالة جهات الاتصال المحددة نهائيًا من مساحة العمل هذه. لا يمكن التراجع عن هذا الإجراء.",
- "directory.removalTitle": "إزالة جهات الاتصال؟",
+ "directory.removalSingleDescription": "سيُحذف {{name}} نهائيًا من مساحة العمل هذه. لا يمكن التراجع عن هذا الإجراء.",
+ "directory.removalSingleFailed": "تعذّر حذف جهة الاتصال. حاول مجددًا.",
+ "directory.removalSingleTitle": "حذف {{name}}؟",
+ "directory.resultCount": "النتائج: {{count}}",
+ "imPlatform.action.configure": "تكوين",
+ "imPlatform.action.configureChannel": "تكوين {{provider}}",
+ "imPlatform.action.connect": "اتصال",
+ "imPlatform.action.copied": "تم النسخ",
+ "imPlatform.action.copyCallback": "نسخ عنوان URL لرد النداء",
+ "imPlatform.action.deleteChannel": "حذف {{provider}}",
+ "imPlatform.action.loadMore": "تحميل المزيد",
+ "imPlatform.action.replace": "يستبدل",
+ "imPlatform.action.retry": "إعادة المحاولة",
+ "imPlatform.action.save": "حفظ",
+ "imPlatform.action.saving": "جارٍ الحفظ",
+ "imPlatform.action.setupGuide": "دليل الإعداد",
+ "imPlatform.action.syncNow": "المزامنة الآن",
+ "imPlatform.action.syncing": "جارٍ المزامنة",
+ "imPlatform.action.testConnection": "اختبار الاتصال",
+ "imPlatform.action.testing": "جارٍ الاختبار",
+ "imPlatform.action.viewDetails": "عرض التفاصيل",
+ "imPlatform.bindingDialog.back": "خلف",
+ "imPlatform.bindingDialog.callback": "عنوان URL لرد الاتصال",
+ "imPlatform.bindingDialog.callbackDescription": "أكمل إعداد ردود النداء في {{provider}} لتفعيل إجراءات البطاقات.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "لإجراءات البطاقات، الصق عنوان URL هذا في <console>وحدة تحكم مطوري Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "الأحداث وردود النداء → إعداد ردود النداء → عنوان URL للطلب",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "لإجراءات البطاقات، الصق عنوان URL هذا في <console>وحدة تحكم مطوري Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "الأحداث وردود النداء → إعداد ردود النداء → عنوان URL للطلب",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "لإجراءات البطاقات، الصق عنوان URL هذا في <console>وحدة تحكم مطوري Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "التفاعل والاختصارات → التفاعل → عنوان URL للطلب",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "لإجراءات البطاقات، الصق عنوان URL هذا في <console>إعداد Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "الإعدادات → التكوين → نقطة نهاية المراسلة",
+ "imPlatform.bindingDialog.callbackStep": "إعداد ردود النداء",
"imPlatform.bindingDialog.clearSavedCredential": "مسح القيمة المحفوظة",
+ "imPlatform.bindingDialog.configureTitle": "تكوين {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "توصيل {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "سيتم مسح هذه القيمة المحفوظة عند الحفظ.",
+ "imPlatform.bindingDialog.credentialsDescription": "اربط تطبيق {{provider}} أولًا، ثم اضبط عنوان URL لرد النداء.",
+ "imPlatform.bindingDialog.credentialsStep": "بيانات اعتماد التطبيق",
+ "imPlatform.bindingDialog.description": "أدخل بيانات اعتماد التطبيق لموفّر المراسلة الفورية هذا.",
+ "imPlatform.bindingDialog.field.agentId": "معرّف الوكيل",
+ "imPlatform.bindingDialog.field.appId": "معرّف التطبيق",
+ "imPlatform.bindingDialog.field.appToken": "رمز التطبيق (اختياري)",
+ "imPlatform.bindingDialog.field.botToken": "رمز الروبوت",
+ "imPlatform.bindingDialog.field.clientId": "معرف العميل",
+ "imPlatform.bindingDialog.field.clientSecret": "سر العميل",
+ "imPlatform.bindingDialog.field.corpId": "معرّف المؤسسة",
+ "imPlatform.bindingDialog.field.encryptKey": "مفتاح التشفير (اختياري)",
+ "imPlatform.bindingDialog.field.genericSecret": "سري",
+ "imPlatform.bindingDialog.field.secret": "سر التطبيق",
+ "imPlatform.bindingDialog.field.signingSecret": "سر التوقيع",
+ "imPlatform.bindingDialog.field.tenantId": "معرّف المستأجر",
+ "imPlatform.bindingDialog.field.verificationToken": "رمز التحقق (اختياري)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "أدخل مفتاح التشفير، إذا كان مفعّلًا",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "أدخل سر التطبيق",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "أدخل رمز التحقق، إذا كان مضبوطًا",
+ "imPlatform.bindingDialog.finish": "إنهاء",
+ "imPlatform.bindingDialog.freshCredentials": "لا يمكن استرجاع الأسرار المحفوظة. أعد إدخال جميع بيانات الاعتماد المطلوبة لاختبار هذا الإعداد أو حفظه.",
+ "imPlatform.bindingDialog.openSetupGuide": "فتح دليل الإعداد",
+ "imPlatform.bindingDialog.replaceTenantTitle": "هل تريد استبدال بيانات اعتماد المستأجر لـ {{identity}}؟",
"imPlatform.bindingDialog.replacementRequired": "بيانات الاعتماد هذه تخص مستأجر IM آخر، ولا يمكن حفظها مباشرةً. يتطلب تبديل المستأجر استبدال قناة IM الحالية، مما يمسح جميع عمليات ربط IM التلقائية واليدوية. أعد مزامنة جهات الاتصال بعد الاستبدال.",
+ "imPlatform.bindingDialog.required": "هذا الحقل مطلوب.",
+ "imPlatform.bindingDialog.saveAndContinue": "حفظ ومتابعة",
+ "imPlatform.bindingDialog.saveFailed": "تعذّر حفظ الإعداد. تحقق من الحقول وحاول مجددًا.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "تم حفظ الإعدادات، لكن تعذّر تحميل تفاصيلها. أغلق مربع الحوار هذا وأعد فتحه.",
- "imPlatform.bindingDialog.undoClearCredential": "التراجع عن المسح"
+ "imPlatform.bindingDialog.secretConfigured": "يوجد سر مضبوط بالفعل. اترك هذا الحقل فارغًا للاحتفاظ به.",
+ "imPlatform.bindingDialog.step": "الخطوة {{step}}",
+ "imPlatform.bindingDialog.testFailed": "فشل اختبار الاتصال. تحقق من الإعداد وحاول مجددًا.",
+ "imPlatform.bindingDialog.undoClearCredential": "التراجع عن المسح",
+ "imPlatform.bindingDialog.viewSetupGuide": "عرض دليل الإعداد",
+ "imPlatform.chooseProvider": "اختر قناة للربط",
+ "imPlatform.configurationUpdated": "تغيّر إعداد هذه القناة. أغلق مربع الحوار هذا وحدّث الصفحة قبل المحاولة مجددًا.",
+ "imPlatform.connectMore": "ربط المزيد من القنوات",
+ "imPlatform.delete.confirm": "حذف",
+ "imPlatform.delete.description": "يؤدي حذف هذه القناة إلى إزالة إعدادها. ستتوقف إشعارات الموافقة ومزامنة الدليل التي تستخدمها.",
+ "imPlatform.delete.failed": "تعذّر حذف القناة. لم يتغيّر شيء؛ حاول مجددًا.",
+ "imPlatform.delete.title": "حذف قناة {{provider}}؟",
+ "imPlatform.description": "اربط قنوات شركتك لتصل طلبات الموافقة إلى الأشخاص حيث يعملون.",
+ "imPlatform.details.column.contact": "جهات الاتصال",
+ "imPlatform.details.column.platform": "منصة المراسلة الفورية",
+ "imPlatform.details.description": "اعرض نتائج آخر عملية مزامنة للقراءة فقط.",
+ "imPlatform.details.downloadFailed": "تعذّر تنزيل التقرير. حاول مجددًا.",
+ "imPlatform.details.downloadReport": "تنزيل التقرير",
+ "imPlatform.details.downloadingReport": "جارٍ تنزيل التقرير…",
+ "imPlatform.details.empty": "لا توجد نتائج في هذه الفئة.",
+ "imPlatform.details.filter.added": "تمت الإضافة",
+ "imPlatform.details.filter.failed": "فاشلة",
+ "imPlatform.details.filter.not_matched": "غير مطابق",
+ "imPlatform.details.filter.removed": "تمت الإزالة",
+ "imPlatform.details.filter.skipped": "تم التخطي",
+ "imPlatform.details.filters": "عوامل تصفية نتائج المزامنة",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "تعذّر تحميل تفاصيل المزامنة.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "تعذّر تحميل المزيد من النتائج. أعد محاولة تحميل هذه الصفحة.",
+ "imPlatform.details.removalReason.binding_invalidated": "تم إبطال الربط",
+ "imPlatform.details.removalReason.binding_replaced": "تم استبدال الربط",
+ "imPlatform.details.removalReason.not_present_in_directory": "لم يعد موجودًا في الدليل",
+ "imPlatform.details.reportChanged": "تغيّرت نتائج المزامنة. أعد فتح تفاصيل آخر مزامنة وحاول مجددًا.",
+ "imPlatform.details.title": "تفاصيل المزامنة",
+ "imPlatform.email.apiKey": "مفتاح API",
+ "imPlatform.email.apiKeyConfigured": "لأسباب أمنية، لا يمكن عرض مفتاح API المحفوظ. اترك هذا الحقل فارغًا للاحتفاظ به.",
+ "imPlatform.email.apiKeyDescription": "لأسباب أمنية، لا يمكن عرض مفتاح API هذا بعد حفظه.",
+ "imPlatform.email.apiKeyPlaceholder": "أدخل مفتاح API الخاص بك في Resend",
+ "imPlatform.email.description": "ينطبق هذا الإعداد على جميع عُقد التدخل البشري في مساحة العمل هذه التي فُعّل فيها خيار <emphasis>إرسال إشعارات تصحيح الأخطاء عبر البريد الإلكتروني</emphasis>.",
+ "imPlatform.email.invalidEmail": "أدخل عنوان بريد إلكتروني صالحًا.",
+ "imPlatform.email.provider": "موفّر البريد الإلكتروني",
+ "imPlatform.email.resendDescription": "سيُشفّر <apiKey>مفتاح API الخاص بك في Resend</apiKey> ولن يمكن عرضه بعد حفظه.<br/>أنشئ حسابًا في <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "إعدادات Resend",
+ "imPlatform.email.senderEmail": "عنوان البريد الإلكتروني للمرسل",
+ "imPlatform.email.senderEmailDescription": "عنوان البريد الإلكتروني الذي يظهر بصفة المرسل. يجب التحقق من نطاقه في Resend.",
+ "imPlatform.email.senderName": "اسم المرسل",
+ "imPlatform.email.senderNameDescription": "الاسم الذي يظهر في صندوق الوارد لدى المستلم.",
+ "imPlatform.email.testSucceeded": "نجح اختبار الاتصال.",
+ "imPlatform.email.title": "إعداد البريد الإلكتروني",
+ "imPlatform.learnMore": "اعرف المزيد",
+ "imPlatform.loadError.description": "حاول مجددًا قراءة الربط الحالي والأذونات.",
+ "imPlatform.loadError.retry": "حاول مجددًا",
+ "imPlatform.loadError.title": "تعذّر تحميل القنوات",
+ "imPlatform.loading": "جارٍ تحميل القنوات",
+ "imPlatform.provider.dingtalkDescription": "اربط تطبيق DingTalk.",
+ "imPlatform.provider.emailDescription": "اضبط خدمة البريد الإلكتروني المستخدمة لإرسال طلبات الموافقة من مساحة العمل هذه.",
+ "imPlatform.provider.feishuDescription": "اربط تطبيق Feishu.",
+ "imPlatform.provider.larkDescription": "اربط تطبيق Lark.",
+ "imPlatform.provider.msTeamsDescription": "اربط تطبيق Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "زامن الأشخاص وهوياتهم في Slack.",
+ "imPlatform.provider.weComDescription": "اربط تطبيق WeCom.",
+ "imPlatform.replacement.confirm": "يستبدل",
+ "imPlatform.replacement.description": "يؤدي استبدال الموفّر النشط إلى إبطال روابط المراسلة الفورية وتخصيصات مساحة العمل الخاصة به. أعد مزامنة دليل الموفّر الجديد بعد الاستبدال.",
+ "imPlatform.replacement.title": "استبدال {{current}} بـ {{next}}؟",
+ "imPlatform.status.configured": "تم التكوين",
+ "imPlatform.status.connected": "متصل",
+ "imPlatform.status.connection_error": "خطأ في الاتصال",
+ "imPlatform.status.permission_issue": "مشكلة في الأذونات",
+ "imPlatform.sync.latestSynced": "آخر مزامنة: {{date}}",
+ "imPlatform.sync.loading": "جارٍ التحقق من وجود مزامنة نشطة.",
+ "imPlatform.sync.noPermission": "يمكن لمالكي مساحة العمل والمسؤولين فقط بدء مزامنة الدليل.",
+ "imPlatform.sync.noRuns": "لم تُنفّذ أي مزامنة للدليل بعد.",
+ "imPlatform.sync.notConnected": "اربط موفّرًا واختبر الاتصال قبل بدء مزامنة الدليل.",
+ "imPlatform.sync.startFailed": "تعذّر بدء مزامنة الدليل أو تحديثها. حاول مجددًا.",
+ "imPlatform.sync.status.failure": "فاشلة",
+ "imPlatform.sync.status.queued": "في قائمة الانتظار",
+ "imPlatform.sync.status.running": "قيد التشغيل",
+ "imPlatform.sync.status.success": "نجاح",
+ "imPlatform.title": "القنوات"
}
diff --git a/web/i18n/locales/ar-TN/share.json b/web/i18n/locales/ar-TN/share.json
index 5eead4cfd19..24ac706f643 100644
--- a/web/i18n/locales/ar-TN/share.json
+++ b/web/i18n/locales/ar-TN/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "شكراً!",
"humanInput.unavailableDescription": "قد يكون الرابط غير متاح أو غير متوافق مع الحساب الذي سجلت الدخول به. افتح النموذج من الإشعار الذي تلقيته، أو جرّب تبديل الحساب.",
"humanInput.unavailableTitle": "تعذّر فتح هذا النموذج",
+ "humanInputV2.accessRateLimited": "تم طلب عدد كبير جدًا من رسائل التحقّق. يُرجى المحاولة لاحقًا.",
+ "humanInputV2.alreadySubmitted": "تم إكمال هذا الطلب بالفعل.",
+ "humanInputV2.challengeExpired": "انتهت صلاحية رمز التحقّق هذا. اطلب رمزًا جديدًا للمتابعة.",
+ "humanInputV2.challengeStale": "تم استبدال رمز التحقّق هذا. اطلب رمزًا جديدًا للمتابعة.",
+ "humanInputV2.codeExpiresIn": "تنتهي صلاحية الرمز خلال {{seconds}} ثانية",
+ "humanInputV2.codeRequired": "اطلب رمز تحقّق للمتابعة.",
+ "humanInputV2.codeSent": "تم إرسال رمز تحقّق إلى بريدك الإلكتروني.",
+ "humanInputV2.deliveryFailed": "تعذّر إرسال رسالة التحقّق. يُرجى المحاولة مجددًا.",
+ "humanInputV2.formExpired": "انتهت صلاحية هذا الطلب.",
+ "humanInputV2.formNotFound": "لم يتم العثور على النموذج.",
+ "humanInputV2.formRateLimited": "تم إرسال عدد كبير جدًا من طلبات النموذج. يُرجى المحاولة لاحقًا.",
+ "humanInputV2.invalidOtp": "رمز التحقّق غير صحيح. تحقّق من الرمز وحاول مجددًا.",
+ "humanInputV2.networkError": "تعذّر إكمال الطلب. تحقّق من اتصالك وحاول مجددًا.",
+ "humanInputV2.otpLabel": "رمز التحقّق عبر البريد الإلكتروني",
+ "humanInputV2.otpPlaceholder": "أدخل الرمز المكوّن من 6 أرقام",
+ "humanInputV2.requestingCode": "جارٍ إرسال رمز التحقّق…",
+ "humanInputV2.resendCode": "إعادة إرسال الرمز",
+ "humanInputV2.retry": "المحاولة مجددًا",
+ "humanInputV2.sendCode": "إرسال رمز جديد",
+ "humanInputV2.unavailable": "هذا النموذج غير متاح مؤقتًا.",
+ "humanInputV2.unknownError": "حدث خطأ. يُرجى المحاولة مجددًا.",
+ "humanInputV2.uploadFailed": "تعذّر رفع الملف. يُرجى المحاولة مجددًا.",
"login.backToHome": "العودة إلى الصفحة الرئيسية"
}
diff --git a/web/i18n/locales/ar-TN/workflow-human-input.json b/web/i18n/locales/ar-TN/workflow-human-input.json
index f689f9dbd9e..381fe98f5cd 100644
--- a/web/i18n/locales/ar-TN/workflow-human-input.json
+++ b/web/i18n/locales/ar-TN/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "قيمة الإجراء",
"nodes.humanInput.userActions.buttonTextTooLong": "يجب أن يكون نص الزر {{maxLength}} حرفاً أو أقل",
"nodes.humanInput.userActions.chooseStyle": "اختر نمط الزر",
+ "nodes.humanInput.userActions.defaultTitle": "نص الزر {{index}}",
"nodes.humanInput.userActions.emptyTip": "انقر فوق الزر '+' لإضافة إجراءات المستخدم",
"nodes.humanInput.userActions.title": "إجراءات المستخدم",
"nodes.humanInput.userActions.tooltip": "حدد الأزرار التي يمكن للمستخدمين النقر عليها للرد على هذا النموذج. يتحكم معرف الإجراء في التفريع. يتم عرض قيمة الإجراء في المرحلة التالية كإخراج مدمج محدد. يجب أن يبدأ معرف الإجراء بحرف أو شرطة سفلية، متبوعاً بأحرف أو أرقام أو شرطات سفلية.",
diff --git a/web/i18n/locales/ar-TN/workflow.json b/web/i18n/locales/ar-TN/workflow.json
index c46b5c8966f..13575c96a32 100644
--- a/web/i18n/locales/ar-TN/workflow.json
+++ b/web/i18n/locales/ar-TN/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "الإخراج",
"blocks.http-request": "طلب HTTP",
"blocks.human-input": "إدخال بشري",
+ "blocks.human-input-v2": "إدخال بشري v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "تكرار",
"blocks.iteration-start": "بداية التكرار",
@@ -45,6 +46,7 @@
"blocksAbout.end": "تحديد الإخراج ونوع النتيجة لسير العمل",
"blocksAbout.http-request": "السماح بإرسال طلبات الخادم عبر بروتوكول HTTP",
"blocksAbout.human-input": "اطلب تأكيداً بشرياً قبل إنشاء الخطوة التالية",
+ "blocksAbout.human-input-v2": "اطلب إدخالًا من جهات الاتصال المُعدّة أو مستلمي البريد الإلكتروني أو مُبادر سير العمل",
"blocksAbout.if-else": "يسمح لك بتقسيم سير العمل إلى فرعين بناءً على شروط if/else",
"blocksAbout.iteration": "تنفيذ خطوات متعددة على كائن قائمة حتى يتم إخراج جميع النتائج.",
"blocksAbout.iteration-start": "نقطة بدء التكرار",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "تجميع متغيرات متعددة الفروع في متغير واحد للتكوين الموحد للعقد النهائية.",
"blocksAbout.variable-assigner": "تجميع متغيرات متعددة الفروع في متغير واحد للتكوين الموحد للعقد النهائية.",
"changeHistory.edgeDelete": "تم قطع اتصال العقدة",
+ "changeHistory.humanInputMigration": "تم ترحيل عُقد الإدخال البشري",
"changeHistory.nodeAdd": "تم إضافة العقدة",
"changeHistory.nodeChange": "تم تغيير العقدة",
"changeHistory.nodeConnect": "تم توصيل العقدة",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "الرجاء تفعيل طريقة تسليم واحدة على الأقل",
"nodes.humanInput.errorMsg.noUserActions": "الرجاء إضافة إجراء مستخدم واحد على الأقل",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} محجوز لفرع انتهاء المهلة. اختر معرّف إجراء آخر.",
+ "nodes.humanInput.output.actionId": "معرّف الإجراء الذي فعّله المستخدم",
+ "nodes.humanInput.output.actionValue": "قيمة الإجراء المحدّد",
+ "nodes.humanInput.output.formInput": "قيمة إدخال النموذج",
+ "nodes.humanInput.output.renderedContent": "المحتوى المعروض",
"nodes.humanInput.timeout.title": "المهلة الزمنية",
+ "nodes.humanInputMigration.action.migrate": "ترحيل",
+ "nodes.humanInputMigration.action.migrateNow": "الترحيل الآن",
+ "nodes.humanInputMigration.action.migrating": "جارٍ الترحيل...",
+ "nodes.humanInputMigration.banner.ariaLabel": "إشعار ترحيل الإدخال البشري",
+ "nodes.humanInputMigration.banner.description": "يستخدم سير العمل هذا عقدة الإدخال البشري القديمة. رحّل جميع العُقد القديمة قبل إضافة عُقد جديدة.",
+ "nodes.humanInputMigration.banner.learnMore": "معرفة المزيد",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "لا تزال إحدى طرق التسليم المعطّلة تحتوي على إعدادات",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "تستخدم طرق البريد الإلكتروني المفعّلة قوالب متعارضة",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "القيمة الافتراضية غير صالحة",
+ "nodes.humanInputMigration.blocker.invalidEmail": "عنوان البريد الإلكتروني لأحد المستلمين غير صالح",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "إعداد إحدى طرق البريد الإلكتروني المفعّلة غير مكتمل",
+ "nodes.humanInputMigration.blocker.missingRecipients": "لا تحتوي العقدة على مستلمين مدعومين",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "تعذّر ربط أحد أعضاء مساحة العمل بجهة اتصال أو بريد إلكتروني تم التحقّق منه",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "إحدى طرق التسليم المفعّلة غير مدعومة في الإدخال البشري v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "لا يمكن ترحيل الحقل {{field}} بعد. يمكنك متابعة استخدام عُقد الإدخال البشري القديمة.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "تحتوي العقدة على قيمة إصدار غير مدعومة",
+ "nodes.humanInputMigration.dialog.description": "سيتم الاحتفاظ بالمستلمين والنموذج والإجراءات.",
+ "nodes.humanInputMigration.dialog.draftNotice": "ستتغيّر هذه المسودة فقط. ستستمر الإصدارات المنشورة في العمل إلى أن تنشر مجددًا.",
+ "nodes.humanInputMigration.dialog.review": "راجع العُقد وانشرها عندما تكون جاهزًا.",
+ "nodes.humanInputMigration.dialog.title": "ترحيل {{count}} من عُقد الإدخال البشري",
+ "nodes.humanInputMigration.disabledBadge": "الترحيل مطلوب",
+ "nodes.humanInputMigration.disabledReason": "رحّل عُقد الإدخال البشري القديمة قبل إضافة عقدة جديدة.",
+ "nodes.humanInputMigration.error.blocked": "تعذّر ترحيل {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "تغير سير العمل أثناء الترحيل. حاول مرة أخرى؛ تم الاحتفاظ بتعديلاتك الحالية.",
+ "nodes.humanInputMigration.error.preflight": "تعذّر التحضير للترحيل. لم يتغيّر سير العمل. يُرجى المحاولة مجددًا.",
"nodes.humanInputMigration.error.sync": "تعذر حفظ سير العمل بعد الترحيل. راجع المسودة الحالية وحاول مرة أخرى.",
+ "nodes.humanInputMigration.incompatibleVersions": "لا يمكن استخدام عقد الإدخال البشري القديمة والجديدة في سير العمل نفسه.",
+ "nodes.humanInputMigration.oldVersion": "إصدار قديم",
+ "nodes.humanInputMigration.preview.author": "بواسطة فريق Dify",
+ "nodes.humanInputMigration.preview.description": "رحّل عُقد الإدخال البشري القديمة قبل إضافة عقدة جديدة.",
+ "nodes.humanInputMigration.success": "تم ترحيل عُقد الإدخال البشري بنجاح",
+ "nodes.humanInputV2.card.configured": "تم إعداد {{count}} من المستلمين",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} من جهات الاتصال",
+ "nodes.humanInputV2.card.empty": "لا يمكن لأحد الموافقة على هذه الخطوة بعد",
+ "nodes.humanInputV2.card.initiatorAndContacts": "المُبادر و{{count}} من جهات الاتصال",
+ "nodes.humanInputV2.card.initiatorOnly": "المُبادر فقط",
+ "nodes.humanInputV2.card.invalid": "يحتاج إعداد المستلمين إلى المراجعة",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "البريد الإلكتروني",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "إعداد وضع التصحيح",
"nodes.humanInputV2.debug.keepOneChannel": "أبقِ قناة واحدة على الأقل مفعّلة",
+ "nodes.humanInputV2.debug.sendVia": "إرسال إشعارات التصحيح عبر",
+ "nodes.humanInputV2.debug.title": "وضع التصحيح",
+ "nodes.humanInputV2.debug.toggle": "تفعيل وضع التصحيح",
+ "nodes.humanInputV2.debug.unsupported": "قنوات مستوردة غير مدعومة: {{channels}}. أزلها أو حدّثها قبل تشغيل سير العمل هذا.",
"nodes.humanInputV2.disabled": "Human Input v2 غير متاح عندما تكون HITL IM معطّلة.",
+ "nodes.humanInputV2.error.bodyRequired": "نص الرسالة مطلوب",
+ "nodes.humanInputV2.error.debugChannelRequired": "حدّد قناة واحدة على الأقل لوضع التصحيح",
+ "nodes.humanInputV2.error.recipientDuplicate": "أزل المستلمين المكرّرين",
+ "nodes.humanInputV2.error.recipientInvalid": "أصلح إعداد المستلمين غير الصالح",
+ "nodes.humanInputV2.error.recipientRequired": "أضف مستلمًا واحدًا على الأقل",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "تعذّر التحقق من المستلمين من جهات الاتصال",
"nodes.humanInputV2.error.requestURLDuplicate": "لا يمكن أن يحتوي نص الرسالة إلا على رابط طلب واحد.",
"nodes.humanInputV2.error.requestURLRequired": "أدرج رابط الطلب في نص الرسالة.",
+ "nodes.humanInputV2.error.subjectRequired": "موضوع الرسالة مطلوب",
+ "nodes.humanInputV2.error.version": "يتطلّب الإدخال البشري v2 أن تكون قيمة الإصدار سلسلة نصية تساوي 2",
+ "nodes.humanInputV2.recipients.addContact": "إضافة جهة اتصال",
+ "nodes.humanInputV2.recipients.addEmail": "إضافة",
+ "nodes.humanInputV2.recipients.addRecipient": "إضافة مستلم",
+ "nodes.humanInputV2.recipients.added": "تمت الإضافة",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "جميع جهات الاتصال في مساحة العمل",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "أرسل إشعارًا إلى جميع جهات الاتصال في مساحة العمل؛ ويمكن لأي منهم الموافقة",
+ "nodes.humanInputV2.recipients.cancel": "إلغاء",
+ "nodes.humanInputV2.recipients.chooseVariable": "اختيار متغيّر",
+ "nodes.humanInputV2.recipients.confirm": "تأكيد",
+ "nodes.humanInputV2.recipients.contactInfo": "تفاصيل جهة الاتصال {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "الكل",
+ "nodes.humanInputV2.recipients.contactSource.external": "خارجي",
+ "nodes.humanInputV2.recipients.contactSource.organization": "المؤسسة",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "مساحة العمل",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "مصدر جهات الاتصال",
"nodes.humanInputV2.recipients.duplicateSource": "تمت الإضافة بالفعل عبر {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "تعديل {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "تعديل المستلم",
"nodes.humanInputV2.recipients.emailAlreadySelected": "يمكن تحديد كل بريد إلكتروني مرة واحدة فقط.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "أدخل عنوان بريد إلكتروني صالحًا لم تتم إضافته من قبل",
+ "nodes.humanInputV2.recipients.emailLabel": "مستلم بريد إلكتروني لمرة واحدة",
+ "nodes.humanInputV2.recipients.empty": "لم يتم إعداد أي مستلمين",
+ "nodes.humanInputV2.recipients.help": "اختر من يمكنه الرد على خطوة الإدخال البشري هذه.",
"nodes.humanInputV2.recipients.initiator": "يمكن للمستخدم الذي يبدأ هذا التشغيل عبر Web App أو CLI الموافقة",
+ "nodes.humanInputV2.recipients.initiatorDescription": "يمكن للشخص الذي يبدأ تشغيل سير العمل هذا الرد.",
"nodes.humanInputV2.recipients.inputHelp": "اكتب أو الصق عدة عناوين بريد إلكتروني مفصولة بفواصل. اضغط على / لإدراج متغير.",
+ "nodes.humanInputV2.recipients.insertVariable": "إدراج متغيّر",
+ "nodes.humanInputV2.recipients.loadError": "تعذّر تحميل جهات الاتصال. تم الاحتفاظ بمعرّفات جهات الاتصال المحفوظة.",
+ "nodes.humanInputV2.recipients.loading": "جارٍ تحميل جهات الاتصال…",
+ "nodes.humanInputV2.recipients.noResults": "لم يتم العثور على جهات اتصال",
+ "nodes.humanInputV2.recipients.placeholder": "ابحث عن جهات اتصال أو أضف عناوين بريد إلكتروني",
+ "nodes.humanInputV2.recipients.remove": "إزالة {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "اضغط على Backspace أو Delete للإزالة.",
+ "nodes.humanInputV2.recipients.resultCount": "عدد المستلمين المطابقين: {{count}}",
+ "nodes.humanInputV2.recipients.search": "البحث عن جهات اتصال",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "البحث بالاسم أو البريد الإلكتروني",
+ "nodes.humanInputV2.recipients.selectionHint": "تم اختيار {{count}} من المستلمين. في بداية حقل الإدخال، اضغط على السهم الأيمن للانتقال إليهم.",
+ "nodes.humanInputV2.recipients.title": "المستلمون",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "جميع جهات الاتصال في مساحة العمل",
+ "nodes.humanInputV2.recipients.type.contact": "جهة اتصال",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "بريد إلكتروني ديناميكي",
+ "nodes.humanInputV2.recipients.type.initiator": "المُبادر",
+ "nodes.humanInputV2.recipients.type.onetime_email": "بريد إلكتروني لمرة واحدة",
+ "nodes.humanInputV2.recipients.typeLabel": "نوع المستلم",
"nodes.humanInputV2.recipients.useThisInstead": "استخدام هذا بدلاً منه",
+ "nodes.humanInputV2.recipients.variableRequired": "اختر متغيّر بريد إلكتروني",
+ "nodes.humanInputV2.template.body": "النص",
+ "nodes.humanInputV2.template.description": "نص احتياطي للبريد الإلكتروني والمراسلة الفورية",
"nodes.humanInputV2.template.insertRequestURL": "إدراج رابط الطلب",
+ "nodes.humanInputV2.template.insertVariable": "إدراج متغيّر",
+ "nodes.humanInputV2.template.notConfigured": "غير مُعدّ",
"nodes.humanInputV2.template.requestURLHint": "يفتح المستلمون نموذج الموافقة باستخدام هذا الرابط. يجب تضمين رابط طلب واحد فقط.",
"nodes.humanInputV2.template.requestURLInserted": "تم إدراج رابط الطلب",
"nodes.humanInputV2.template.saveAndTest": "حفظ واختبار",
+ "nodes.humanInputV2.template.subject": "الموضوع",
+ "nodes.humanInputV2.template.subjectPlaceholder": "أدخل موضوع الرسالة",
"nodes.humanInputV2.template.test": "اختبار الرسالة",
"nodes.humanInputV2.template.testChannel": "قناة الاختبار",
"nodes.humanInputV2.template.testCompleted": "اكتمل طلب الاختبار. تحقّق من الرسالة في القناة المحددة.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "أدخل جميع قيم متغيرات الاختبار.",
"nodes.humanInputV2.template.testSaveFailed": "تعذّر حفظ مسودة سير العمل. لم يتم إرسال الاختبار.",
"nodes.humanInputV2.template.testUnavailable": "هذه البيئة لا تدعم اختبار قوالب الرسائل بعد.",
+ "nodes.humanInputV2.template.title": "قالب الرسالة",
"nodes.ifElse.operator": "المشغل",
"nodes.iteration.currentIteration": "التكرار الحالي",
"nodes.iteration.deleteDesc": "سيؤدي حذف عقدة التكرار إلى حذف جميع العقد الفرعية",
diff --git a/web/i18n/locales/az-AZ/contacts.json b/web/i18n/locales/az-AZ/contacts.json
index 3d5ec445a49..bc34a666377 100644
--- a/web/i18n/locales/az-AZ/contacts.json
+++ b/web/i18n/locales/az-AZ/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Əlaqələr silinsin ({{count}})?",
"directory.removalDescription": "Seçilmiş kontaktlar bu iş sahəsindən həmişəlik silinəcək. Bu əməliyyatı geri qaytarmaq mümkün deyil.",
- "directory.removalTitle": "Kontaktlar silinsin?",
+ "directory.removalSingleDescription": "{{name}} bu iş sahəsindən həmişəlik silinəcək. Bu əməliyyatı geri qaytarmaq mümkün deyil.",
+ "directory.removalSingleFailed": "Əlaqəni silmək mümkün olmadı. Yenidən cəhd edin.",
+ "directory.removalSingleTitle": "{{name}} silinsin?",
+ "directory.resultCount": "Nəticələr: {{count}}",
+ "imPlatform.action.configure": "Konfiqurasiya et",
+ "imPlatform.action.configureChannel": "{{provider}} konfiqurasiyasını qur",
+ "imPlatform.action.connect": "Qoş",
+ "imPlatform.action.copied": "Kopyalandı",
+ "imPlatform.action.copyCallback": "Geri çağırış URL-sini kopyala",
+ "imPlatform.action.deleteChannel": "{{provider}} sil",
+ "imPlatform.action.loadMore": "Daha çox yüklə",
+ "imPlatform.action.replace": "Əvəz et",
+ "imPlatform.action.retry": "Yenidən cəhd et",
+ "imPlatform.action.save": "Saxla",
+ "imPlatform.action.saving": "Saxlanılır",
+ "imPlatform.action.setupGuide": "Quraşdırma təlimatı",
+ "imPlatform.action.syncNow": "İndi sinxronlaşdır",
+ "imPlatform.action.syncing": "Sinxronlaşdırılır",
+ "imPlatform.action.testConnection": "Bağlantını yoxla",
+ "imPlatform.action.testing": "Yoxlanılır",
+ "imPlatform.action.viewDetails": "Ətraflı bax",
+ "imPlatform.bindingDialog.back": "Geri qayıt",
+ "imPlatform.bindingDialog.callback": "Geri çağırış URL-i",
+ "imPlatform.bindingDialog.callbackDescription": "Kart əməliyyatlarını aktivləşdirmək üçün {{provider}} geri çağırış quraşdırmasını tamamlayın.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Kart əməliyyatları üçün bu URL-ni <console>Feishu Tərtibatçı Konsoluna</console> yapışdırın:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Hadisələr və geri çağırışlar → Geri çağırış konfiqurasiyası → Sorğu URL-si",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Kart əməliyyatları üçün bu URL-ni <console>Lark Tərtibatçı Konsoluna</console> yapışdırın:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Hadisələr və geri çağırışlar → Geri çağırış konfiqurasiyası → Sorğu URL-si",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Kart əməliyyatları üçün bu URL-ni <console>Slack Tərtibatçı Konsoluna</console> yapışdırın:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "İnteraktivlik və qısayollar → İnteraktivlik → Sorğu URL-si",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Kart əməliyyatları üçün bu URL-ni <console>Azure Bot konfiqurasiyasına</console> yapışdırın:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Parametrlər → Konfiqurasiya → Mesajlaşma son nöqtəsi",
+ "imPlatform.bindingDialog.callbackStep": "Geri çağırışları konfiqurasiya et",
"imPlatform.bindingDialog.clearSavedCredential": "Saxlanmış dəyəri sil",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} konfiqurasiyasını qur",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}} ilə əlaqə qur",
"imPlatform.bindingDialog.credentialWillBeCleared": "Yadda saxladıqda bu saxlanmış dəyər silinəcək.",
+ "imPlatform.bindingDialog.credentialsDescription": "Əvvəlcə {{provider}} tətbiqinizi qoşun, sonra geri çağırış URL-sini konfiqurasiya edin.",
+ "imPlatform.bindingDialog.credentialsStep": "Tətbiqin giriş məlumatları",
+ "imPlatform.bindingDialog.description": "Bu ani mesajlaşma provayderinin tətbiq giriş məlumatlarını daxil edin.",
+ "imPlatform.bindingDialog.field.agentId": "Agent identifikatoru",
+ "imPlatform.bindingDialog.field.appId": "Tətbiq identifikatoru",
+ "imPlatform.bindingDialog.field.appToken": "Tətbiq tokeni (istəyə bağlı)",
+ "imPlatform.bindingDialog.field.botToken": "Bot tokeni",
+ "imPlatform.bindingDialog.field.clientId": "Müştəri ID-si",
+ "imPlatform.bindingDialog.field.clientSecret": "Müştərinin məxfi açarı",
+ "imPlatform.bindingDialog.field.corpId": "Şirkət identifikatoru",
+ "imPlatform.bindingDialog.field.encryptKey": "Şifrələmə açarı (istəyə bağlı)",
+ "imPlatform.bindingDialog.field.genericSecret": "Məxfi",
+ "imPlatform.bindingDialog.field.secret": "Tətbiqin məxfi açarı",
+ "imPlatform.bindingDialog.field.signingSecret": "İmzalama üçün məxfi açar",
+ "imPlatform.bindingDialog.field.tenantId": "İcarəçi identifikatoru",
+ "imPlatform.bindingDialog.field.verificationToken": "Doğrulama tokeni (istəyə bağlı)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Aktivdirsə, şifrələmə açarını daxil edin",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Tətbiqin məxfi açarını daxil edin",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Konfiqurasiya edilibsə, doğrulama tokenini daxil edin",
+ "imPlatform.bindingDialog.finish": "Bitir",
+ "imPlatform.bindingDialog.freshCredentials": "Saxlanmış məxfi açarları əldə etmək mümkün deyil. Bu konfiqurasiyanı yoxlamaq və ya saxlamaq üçün bütün tələb olunan giriş məlumatlarını yenidən daxil edin.",
+ "imPlatform.bindingDialog.openSetupGuide": "Quraşdırma təlimatını aç",
+ "imPlatform.bindingDialog.replaceTenantTitle": "{{identity}} üçün icarəçi giriş məlumatları dəyişdirilsin?",
"imPlatform.bindingDialog.replacementRequired": "Bu autentifikasiya məlumatları başqa bir IM tenantına aiddir və birbaşa yadda saxlanıla bilməz. Tenantı dəyişmək üçün cari IM kanalını əvəz etmək lazımdır. Bu zaman həm avtomatik, həm də əl ilə yaradılmış bütün IM əlaqələndirmələri silinəcək. Əvəzləmədən sonra kontaktları yenidən sinxronlaşdırın.",
+ "imPlatform.bindingDialog.required": "Bu sahə tələb olunur.",
+ "imPlatform.bindingDialog.saveAndContinue": "Saxla və davam et",
+ "imPlatform.bindingDialog.saveFailed": "Konfiqurasiyanı saxlamaq mümkün olmadı. Sahələri yoxlayın və yenidən cəhd edin.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Konfiqurasiya saxlanıldı, lakin təfərrüatları yükləmək mümkün olmadı. Bu dialoqu bağlayıb yenidən açın.",
- "imPlatform.bindingDialog.undoClearCredential": "Silməni geri al"
+ "imPlatform.bindingDialog.secretConfigured": "Məxfi açar artıq konfiqurasiya edilib. Onu saxlamaq üçün bu sahəni boş buraxın.",
+ "imPlatform.bindingDialog.step": "Addım {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Bağlantı yoxlaması uğursuz oldu. Konfiqurasiyanı yoxlayın və yenidən cəhd edin.",
+ "imPlatform.bindingDialog.undoClearCredential": "Silməni geri al",
+ "imPlatform.bindingDialog.viewSetupGuide": "Quraşdırma təlimatına bax",
+ "imPlatform.chooseProvider": "Qoşulacaq kanalı seçin",
+ "imPlatform.configurationUpdated": "Bu kanalın konfiqurasiyası dəyişib. Yenidən cəhd etməzdən əvvəl bu dialoqu bağlayın və səhifəni yeniləyin.",
+ "imPlatform.connectMore": "Daha çox kanal qoş",
+ "imPlatform.delete.confirm": "Sil",
+ "imPlatform.delete.description": "Bu kanalı silmək onun konfiqurasiyasını aradan qaldırır. Ondan istifadə edən təsdiq bildirişləri və kataloq sinxronizasiyaları dayanacaq.",
+ "imPlatform.delete.failed": "Kanalı silmək mümkün olmadı. Heç nə dəyişməyib; yenidən cəhd edin.",
+ "imPlatform.delete.title": "{{provider}} kanalı silinsin?",
+ "imPlatform.description": "Təsdiq sorğularının insanlara işlədikləri yerdə çatması üçün şirkət kanallarınızı qoşun.",
+ "imPlatform.details.column.contact": "Əlaqələr",
+ "imPlatform.details.column.platform": "Ani mesajlaşma platforması",
+ "imPlatform.details.description": "Ən son sinxronizasiya icrasının yalnız oxuna bilən nəticələrinə baxın.",
+ "imPlatform.details.downloadFailed": "Hesabatı endirmək mümkün olmadı. Yenidən cəhd edin.",
+ "imPlatform.details.downloadReport": "Hesabatı endir",
+ "imPlatform.details.downloadingReport": "Hesabat endirilir…",
+ "imPlatform.details.empty": "Bu kateqoriyada nəticə yoxdur.",
+ "imPlatform.details.filter.added": "Əlavə edilib",
+ "imPlatform.details.filter.failed": "Uğursuz oldu",
+ "imPlatform.details.filter.not_matched": "Uyğunlaşdırılmayıb",
+ "imPlatform.details.filter.removed": "Çıxarıldı",
+ "imPlatform.details.filter.skipped": "Ötürülüb",
+ "imPlatform.details.filters": "Sinxronizasiya nəticələrinin filtrləri",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Sinxronizasiya təfərrüatlarını yükləmək mümkün olmadı.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Daha çox nəticə yükləmək mümkün olmadı. Bu səhifəni yenidən yoxlayın.",
+ "imPlatform.details.removalReason.binding_invalidated": "Əlaqələndirmə etibarsız edildi",
+ "imPlatform.details.removalReason.binding_replaced": "Əlaqələndirmə dəyişdirildi",
+ "imPlatform.details.removalReason.not_present_in_directory": "Artıq kataloqda yoxdur",
+ "imPlatform.details.reportChanged": "Sinxronizasiya nəticələri dəyişib. Ən son sinxronizasiyanın təfərrüatlarını yenidən açın və cəhd edin.",
+ "imPlatform.details.title": "Sinxronizasiya təfərrüatları",
+ "imPlatform.email.apiKey": "API açarı",
+ "imPlatform.email.apiKeyConfigured": "Təhlükəsizlik səbəbindən saxlanmış API açarına baxmaq mümkün deyil. Onu saxlamaq üçün bu sahəni boş buraxın.",
+ "imPlatform.email.apiKeyDescription": "Təhlükəsizlik səbəbindən bu API açarına saxlandıqdan sonra baxmaq mümkün deyil.",
+ "imPlatform.email.apiKeyPlaceholder": "Resend API açarınızı daxil edin",
+ "imPlatform.email.description": "Bu konfiqurasiya bu iş sahəsində <emphasis>Sazlama bildirişlərini e-poçt vasitəsilə göndər</emphasis> seçimi aktiv olan bütün İnsan Müdaxiləsi düyünlərinə tətbiq olunur.",
+ "imPlatform.email.invalidEmail": "Etibarlı e-poçt ünvanı daxil edin.",
+ "imPlatform.email.provider": "E-poçt provayderi",
+ "imPlatform.email.resendDescription": "<apiKey>Resend API açarınız</apiKey> şifrələnəcək və saxlandıqdan sonra ona baxmaq mümkün olmayacaq.<br/><resend>Resend</resend> hesabı yaradın.",
+ "imPlatform.email.resendSettings": "Resend parametrləri",
+ "imPlatform.email.senderEmail": "Göndərənin e-poçt ünvanı",
+ "imPlatform.email.senderEmailDescription": "Göndərən kimi göstərilən e-poçt ünvanı. Onun domeni Resend-də doğrulanmalıdır.",
+ "imPlatform.email.senderName": "Göndərənin adı",
+ "imPlatform.email.senderNameDescription": "Alıcının gələnlər qutusunda göstərilən ad.",
+ "imPlatform.email.testSucceeded": "Bağlantı yoxlaması uğurla tamamlandı.",
+ "imPlatform.email.title": "E-poçtu konfiqurasiya et",
+ "imPlatform.learnMore": "Daha çox öyrən",
+ "imPlatform.loadError.description": "Cari bağlamanı və icazələri oxumaq üçün yenidən cəhd edin.",
+ "imPlatform.loadError.retry": "Yenidən cəhd et",
+ "imPlatform.loadError.title": "Kanalları yükləmək mümkün olmadı",
+ "imPlatform.loading": "Kanallar yüklənir",
+ "imPlatform.provider.dingtalkDescription": "DingTalk tətbiqi qoşun.",
+ "imPlatform.provider.emailDescription": "Bu iş sahəsindən təsdiq sorğuları göndərmək üçün istifadə edilən e-poçt xidmətini konfiqurasiya edin.",
+ "imPlatform.provider.feishuDescription": "Feishu tətbiqi qoşun.",
+ "imPlatform.provider.larkDescription": "Lark tətbiqi qoşun.",
+ "imPlatform.provider.msTeamsDescription": "Microsoft Teams tətbiqi qoşun.",
+ "imPlatform.provider.slackDescription": "İnsanları və onların Slack kimliklərini sinxronizasiya edin.",
+ "imPlatform.provider.weComDescription": "WeCom tətbiqi qoşun.",
+ "imPlatform.replacement.confirm": "Əvəz et",
+ "imPlatform.replacement.description": "Aktiv provayderin əvəzlənməsi onun ani mesajlaşma bağlamalarını və iş sahəsi fərdiləşdirmələrini etibarsız edir. Əvəzlədikdən sonra yeni provayderin kataloqunu yenidən sinxronizasiya edin.",
+ "imPlatform.replacement.title": "{{current}} əvəzinə {{next}} istifadə edilsin?",
+ "imPlatform.status.configured": "Konfiqurasiya edilib",
+ "imPlatform.status.connected": "Bağlıdır",
+ "imPlatform.status.connection_error": "Bağlantı xətası",
+ "imPlatform.status.permission_issue": "İcazə problemi",
+ "imPlatform.sync.latestSynced": "Son sinxronizasiya: {{date}}",
+ "imPlatform.sync.loading": "Aktiv sinxronizasiya yoxlanılır.",
+ "imPlatform.sync.noPermission": "Yalnız iş sahəsinin sahibləri və administratorları kataloq sinxronizasiyasını başlada bilər.",
+ "imPlatform.sync.noRuns": "Hələ heç bir kataloq sinxronizasiyası icra edilməyib.",
+ "imPlatform.sync.notConnected": "Kataloq sinxronizasiyasına başlamazdan əvvəl provayder qoşun və bağlantını yoxlayın.",
+ "imPlatform.sync.startFailed": "Kataloq sinxronizasiyasını başlatmaq və ya yeniləmək mümkün olmadı. Yenidən cəhd edin.",
+ "imPlatform.sync.status.failure": "Uğursuz oldu",
+ "imPlatform.sync.status.queued": "Növbədədir",
+ "imPlatform.sync.status.running": "İcra olunur",
+ "imPlatform.sync.status.success": "Uğurlu",
+ "imPlatform.title": "Kanallar"
}
diff --git a/web/i18n/locales/az-AZ/share.json b/web/i18n/locales/az-AZ/share.json
index 3326eced3ac..3c50f953870 100644
--- a/web/i18n/locales/az-AZ/share.json
+++ b/web/i18n/locales/az-AZ/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Təşəkkürlər!",
"humanInput.unavailableDescription": "Link əlçatan olmaya və ya daxil olduğunuz hesaba uyğun gəlməyə bilər. Formanı aldığınız bildirişdən açın və ya hesabı dəyişməyi sınayın.",
"humanInput.unavailableTitle": "Bu formanı açmaq mümkün deyil",
+ "humanInputV2.accessRateLimited": "Həddindən çox təsdiqləmə e-poçtu tələb edilib. Daha sonra yenidən cəhd edin.",
+ "humanInputV2.alreadySubmitted": "Bu sorğu artıq tamamlanıb.",
+ "humanInputV2.challengeExpired": "Bu təsdiqləmə kodunun müddəti bitib. Davam etmək üçün yeni kod istəyin.",
+ "humanInputV2.challengeStale": "Bu təsdiqləmə kodu yenisi ilə əvəz edilib. Davam etmək üçün yeni kod istəyin.",
+ "humanInputV2.codeExpiresIn": "Kodun müddəti {{seconds}} saniyəyə bitəcək",
+ "humanInputV2.codeRequired": "Davam etmək üçün təsdiqləmə kodu istəyin.",
+ "humanInputV2.codeSent": "E-poçtunuza təsdiqləmə kodu göndərildi.",
+ "humanInputV2.deliveryFailed": "Təsdiqləmə e-poçtunu göndərmək mümkün olmadı. Yenidən cəhd edin.",
+ "humanInputV2.formExpired": "Bu sorğunun müddəti bitib.",
+ "humanInputV2.formNotFound": "Forma tapılmadı.",
+ "humanInputV2.formRateLimited": "Həddindən çox forma sorğusu göndərilib. Daha sonra yenidən cəhd edin.",
+ "humanInputV2.invalidOtp": "Təsdiqləmə kodu yanlışdır. Kodu yoxlayın və yenidən cəhd edin.",
+ "humanInputV2.networkError": "Sorğunu tamamlamaq mümkün olmadı. Bağlantınızı yoxlayın və yenidən cəhd edin.",
+ "humanInputV2.otpLabel": "E-poçt təsdiqləmə kodu",
+ "humanInputV2.otpPlaceholder": "6 rəqəmli kodu daxil edin",
+ "humanInputV2.requestingCode": "Təsdiqləmə kodu göndərilir…",
+ "humanInputV2.resendCode": "Kodu yenidən göndər",
+ "humanInputV2.retry": "Yenidən cəhd et",
+ "humanInputV2.sendCode": "Yeni kod göndər",
+ "humanInputV2.unavailable": "Bu forma müvəqqəti olaraq əlçatan deyil.",
+ "humanInputV2.unknownError": "Xəta baş verdi. Yenidən cəhd edin.",
+ "humanInputV2.uploadFailed": "Faylı yükləmək mümkün olmadı. Yenidən cəhd edin.",
"login.backToHome": "Əsas səhifəyə qayıt"
}
diff --git a/web/i18n/locales/az-AZ/workflow-human-input.json b/web/i18n/locales/az-AZ/workflow-human-input.json
index c8cc44c12a2..6f18d1977e5 100644
--- a/web/i18n/locales/az-AZ/workflow-human-input.json
+++ b/web/i18n/locales/az-AZ/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Əməliyyat dəyəri",
"nodes.humanInput.userActions.buttonTextTooLong": "Düymə mətni ən çox {{maxLength}} simvoldan ibarət olmalıdır",
"nodes.humanInput.userActions.chooseStyle": "Düymə üslubu seçin",
+ "nodes.humanInput.userActions.defaultTitle": "Düymə mətni {{index}}",
"nodes.humanInput.userActions.emptyTip": "İstifadəçi əməliyyatları əlavə etmək üçün '+' düyməsinə basın",
"nodes.humanInput.userActions.title": "İstifadəçi əməliyyatları",
"nodes.humanInput.userActions.tooltip": "İstifadəçilərin bu formaya cavab vermək üçün basa biləcəyi düymələri təyin edin. Əməliyyat ID-si şaxələnməni idarə edir. Əməliyyat dəyəri sonrakı addımlara seçilmiş daxili çıxış kimi ötürülür. Əməliyyat ID-si hərf və ya alt xətlə başlamalı, ardınca hərflər, rəqəmlər və ya alt xətlər gəlməlidir.",
diff --git a/web/i18n/locales/az-AZ/workflow.json b/web/i18n/locales/az-AZ/workflow.json
index fbb0ad4b6cf..3703371dcb3 100644
--- a/web/i18n/locales/az-AZ/workflow.json
+++ b/web/i18n/locales/az-AZ/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Çıxış",
"blocks.http-request": "HTTP sorğusu",
"blocks.human-input": "İnsan girişi",
+ "blocks.human-input-v2": "İnsan girişi v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "Təkrarlama",
"blocks.iteration-start": "Təkrarlama başlanğıcı",
@@ -45,6 +46,7 @@
"blocksAbout.end": "İş axınının çıxışını və nəticə növünü müəyyənləşdirin",
"blocksAbout.http-request": "HTTP protokolu vasitəsilə server sorğularının göndərilməsinə icazə verin",
"blocksAbout.human-input": "Növbəti addımı yaratmazdan əvvəl istifadəçidən təsdiq istəyin",
+ "blocksAbout.human-input-v2": "Konfiqurasiya edilmiş kontaktlardan, e-poçt alıcılarından və ya iş axınını başladan şəxsdən məlumat daxil etməsini istəyin",
"blocksAbout.if-else": "İş axınını əgər/əks halda şərtlərinə əsasən iki qola bölməyə imkan verir",
"blocksAbout.iteration": "Bütün nəticələr çıxarılana qədər siyahı obyekti üzərində bir neçə addım yerinə yetirin.",
"blocksAbout.iteration-start": "Təkrarlama başlanğıcı düyünü",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Sonrakı düyünlərin vahid konfiqurasiyası üçün bir neçə qoldakı dəyişənləri tək dəyişəndə birləşdirin.",
"blocksAbout.variable-assigner": "Sonrakı düyünlərin vahid konfiqurasiyası üçün bir neçə qoldakı dəyişənləri tək dəyişəndə birləşdirin.",
"changeHistory.edgeDelete": "Qovşağın əlaqəsi kəsildi",
+ "changeHistory.humanInputMigration": "İnsan girişi qovşaqları köçürüldü",
"changeHistory.nodeAdd": "Düyün əlavə edildi",
"changeHistory.nodeChange": "Düyün dəyişdirildi",
"changeHistory.nodeConnect": "Düyün qoşuldu",
@@ -361,20 +364,137 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Ən azı bir çatdırılma üsulunu aktivləşdirin",
"nodes.humanInput.errorMsg.noUserActions": "Ən azı bir istifadəçi əməliyyatı əlavə edin",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} vaxt aşımı budağı üçün ayrılıb. Başqa əməliyyat ID-si seçin.",
+ "nodes.humanInput.output.actionId": "İstifadəçinin işə saldığı əməliyyatın ID-si",
+ "nodes.humanInput.output.actionValue": "Seçilmiş əməliyyatın dəyəri",
+ "nodes.humanInput.output.formInput": "Formaya daxil edilmiş dəyər",
+ "nodes.humanInput.output.renderedContent": "Göstərilən məzmun",
"nodes.humanInput.timeout.title": "Vaxt həddi",
+ "nodes.humanInputMigration.action.migrate": "Köçür",
+ "nodes.humanInputMigration.action.migrateNow": "İndi köçür",
+ "nodes.humanInputMigration.action.migrating": "Köçürülür...",
+ "nodes.humanInputMigration.banner.ariaLabel": "İnsan girişinin köçürülməsi barədə bildiriş",
+ "nodes.humanInputMigration.banner.description": "Bu iş axını köhnə İnsan girişi qovşağından istifadə edir. Yeni qovşaqlar əlavə etməzdən əvvəl bütün köhnə qovşaqları köçürün.",
+ "nodes.humanInputMigration.banner.learnMore": "Ətraflı öyrən",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "söndürülmüş çatdırılma üsulunda hələ də konfiqurasiya var",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "aktiv e-poçt üsulları ziddiyyətli şablonlardan istifadə edir",
+ "nodes.humanInputMigration.blocker.invalidDefaultValue": "Etibarsız ilkin dəyər",
+ "nodes.humanInputMigration.blocker.invalidEmail": "alıcının e-poçt ünvanı etibarsızdır",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "aktiv e-poçt üsulunun konfiqurasiyası natamamdır",
+ "nodes.humanInputMigration.blocker.missingRecipients": "qovşaqda dəstəklənən alıcı yoxdur",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "iş sahəsinin üzvünü kontakt və ya təsdiqlənmiş e-poçtla əlaqələndirmək mümkün deyil",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "aktiv çatdırılma üsulu İnsan girişi v2 tərəfindən dəstəklənmir",
"nodes.humanInputMigration.blocker.unsupportedInputType": "{{field}} sahəsi hələ miqrasiya edilə bilmir. Köhnə insan girişi qovşaqlarından istifadə etməyə davam edə bilərsiniz.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "qovşağın versiya dəyəri dəstəklənmir",
+ "nodes.humanInputMigration.dialog.description": "Alıcılarınız, formanız və əməliyyatlarınız saxlanılacaq.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Yalnız bu qaralama dəyişəcək. Yenidən dərc edənədək dərc olunmuş versiyalar işləməyə davam edəcək.",
+ "nodes.humanInputMigration.dialog.review": "Qovşaqları nəzərdən keçirin və hazır olduqda dərc edin.",
+ "nodes.humanInputMigration.dialog.title": "{{count}} İnsan girişi qovşağını köçür",
+ "nodes.humanInputMigration.disabledBadge": "KÖÇÜRMƏ TƏLƏB OLUNUR",
+ "nodes.humanInputMigration.disabledReason": "Yeni qovşaq əlavə etməzdən əvvəl köhnə İnsan girişi qovşaqlarını köçürün.",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} köçürülə bilmədi: {{reason}}.",
+ "nodes.humanInputMigration.error.graphChanged": "Köçürmə zamanı iş axını dəyişdi. Yenidən cəhd edin; cari düzəlişləriniz saxlanılıb.",
+ "nodes.humanInputMigration.error.preflight": "Köçürməni hazırlamaq mümkün olmadı. İş axınınız dəyişdirilmədi. Yenidən cəhd edin.",
+ "nodes.humanInputMigration.error.sync": "Köçürülmüş iş axınını yadda saxlamaq mümkün olmadı. Cari qaralamanı nəzərdən keçirin və yenidən cəhd edin.",
+ "nodes.humanInputMigration.incompatibleVersions": "Köhnə və yeni İnsan Daxiletməsi qovşaqları eyni iş axınında istifadə edilə bilməz.",
+ "nodes.humanInputMigration.oldVersion": "KÖHNƏ VERSİYA",
+ "nodes.humanInputMigration.preview.author": "Dify komandası tərəfindən",
+ "nodes.humanInputMigration.preview.description": "Yeni qovşaq əlavə etməzdən əvvəl köhnə İnsan girişi qovşaqlarını köçürün.",
+ "nodes.humanInputMigration.success": "İnsan girişi qovşaqları uğurla köçürüldü",
+ "nodes.humanInputV2.card.configured": "{{count}} alıcı konfiqurasiya edilib",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} kontakt",
+ "nodes.humanInputV2.card.empty": "Hələ heç kim bu addımı təsdiqləyə bilməz",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Başladan şəxs və {{count}} kontakt",
+ "nodes.humanInputV2.card.initiatorOnly": "Yalnız başladan şəxs",
+ "nodes.humanInputV2.card.invalid": "Alıcı konfiqurasiyasını yoxlamaq lazımdır",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-poçt",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
+ "nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Sazlama rejimini konfiqurasiya et",
+ "nodes.humanInputV2.debug.keepOneChannel": "Ən azı bir kanalı aktiv saxlayın",
+ "nodes.humanInputV2.debug.sendVia": "Sazlama bildirişlərinin göndəriləcəyi kanal",
+ "nodes.humanInputV2.debug.title": "Sazlama rejimi",
+ "nodes.humanInputV2.debug.toggle": "Sazlama rejimini aktivləşdir",
+ "nodes.humanInputV2.debug.unsupported": "İdxal edilmiş kanallar dəstəklənmir: {{channels}}. Bu iş axınını işə salmazdan əvvəl onları silin və ya yeniləyin.",
"nodes.humanInputV2.disabled": "HITL IM söndürüldükdə Human Input v2 əlçatan deyil.",
+ "nodes.humanInputV2.error.bodyRequired": "Mesajın mətni tələb olunur",
+ "nodes.humanInputV2.error.debugChannelRequired": "Ən azı bir sazlama rejimi kanalı seçin",
+ "nodes.humanInputV2.error.recipientDuplicate": "Təkrarlanan alıcıları silin",
+ "nodes.humanInputV2.error.recipientInvalid": "Etibarsız alıcı konfiqurasiyasını düzəldin",
+ "nodes.humanInputV2.error.recipientRequired": "Ən azı bir alıcı əlavə edin",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Kontakt alıcılarını yoxlamaq mümkün olmadı",
"nodes.humanInputV2.error.requestURLDuplicate": "Mesajın mətnində yalnız bir sorğu URL-si ola bilər.",
"nodes.humanInputV2.error.requestURLRequired": "Mesajın mətninə sorğu URL-si əlavə edin.",
+ "nodes.humanInputV2.error.subjectRequired": "Mesajın mövzusu tələb olunur",
+ "nodes.humanInputV2.error.version": "İnsan girişi v2 üçün versiya 2 sətir dəyəri olmalıdır",
+ "nodes.humanInputV2.recipients.addContact": "Kontakt əlavə et",
+ "nodes.humanInputV2.recipients.addEmail": "Əlavə et",
+ "nodes.humanInputV2.recipients.addRecipient": "Alıcı əlavə et",
+ "nodes.humanInputV2.recipients.added": "Əlavə edilib",
+ "nodes.humanInputV2.recipients.allWorkspaceContacts": "İş sahəsindəki bütün kontaktlar",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "İş sahəsindəki bütün kontaktlara bildiriş göndərin; onlardan hər biri təsdiqləyə bilər",
+ "nodes.humanInputV2.recipients.cancel": "Ləğv et",
+ "nodes.humanInputV2.recipients.chooseVariable": "Dəyişən seç",
+ "nodes.humanInputV2.recipients.confirm": "Təsdiqlə",
+ "nodes.humanInputV2.recipients.contactInfo": "{{name}} üçün əlaqə məlumatları",
+ "nodes.humanInputV2.recipients.contactSource.all": "Hamısı",
+ "nodes.humanInputV2.recipients.contactSource.external": "Xarici",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Təşkilat",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "İş sahəsi",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Kontakt mənbəyi",
"nodes.humanInputV2.recipients.duplicateSource": "Artıq {{name}} ({{source}}) vasitəsilə əlavə edilib.",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} alıcısını redaktə et",
+ "nodes.humanInputV2.recipients.editRecipient": "Alıcını redaktə et",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Hər e-poçt yalnız bir dəfə seçilə bilər.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Hələ əlavə edilməmiş etibarlı e-poçt ünvanı daxil edin",
+ "nodes.humanInputV2.recipients.emailLabel": "Birdəfəlik e-poçt alıcısı",
+ "nodes.humanInputV2.recipients.empty": "Heç bir alıcı konfiqurasiya edilməyib",
+ "nodes.humanInputV2.recipients.help": "Bu İnsan girişi addımına kimin cavab verə biləcəyini seçin.",
"nodes.humanInputV2.recipients.initiator": "Bu icranı Web App və ya CLI vasitəsilə başladan istifadəçi təsdiqləyə bilər",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Bu iş axınının icrasını başladan şəxs cavab verə bilər.",
"nodes.humanInputV2.recipients.inputHelp": "Vergüllə ayrılmış bir neçə e-poçt ünvanı yazın və ya yapışdırın. Dəyişən əlavə etmək üçün / düyməsini basın.",
+ "nodes.humanInputV2.recipients.insertVariable": "Dəyişən əlavə et",
+ "nodes.humanInputV2.recipients.loadError": "Kontaktları yükləmək mümkün olmadı. Saxlanılmış kontakt ID-ləri qorunur.",
+ "nodes.humanInputV2.recipients.loading": "Kontaktlar yüklənir…",
+ "nodes.humanInputV2.recipients.noResults": "Kontakt tapılmadı",
+ "nodes.humanInputV2.recipients.placeholder": "Kontaktları axtarın və ya e-poçt əlavə edin",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} alıcısını sil",
+ "nodes.humanInputV2.recipients.removeHint": "Silmək üçün Backspace və ya Delete düyməsini basın.",
+ "nodes.humanInputV2.recipients.resultCount": "Uyğun alıcılar: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Kontaktları axtar",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Ada və ya e-poçta görə axtar",
+ "nodes.humanInputV2.recipients.selectionHint": "Seçilmiş alıcılar: {{count}}. Onlara fokuslanmaq üçün giriş sahəsinin əvvəlində sol ox düyməsini basın.",
+ "nodes.humanInputV2.recipients.title": "Alıcılar",
+ "nodes.humanInputV2.recipients.type.all_workspace_contacts": "İş sahəsindəki bütün kontaktlar",
+ "nodes.humanInputV2.recipients.type.contact": "Kontakt",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Dinamik e-poçt",
+ "nodes.humanInputV2.recipients.type.initiator": "Başladan şəxs",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Birdəfəlik e-poçt",
+ "nodes.humanInputV2.recipients.typeLabel": "Alıcı növü",
"nodes.humanInputV2.recipients.useThisInstead": "Əvəzinə bunu seç",
+ "nodes.humanInputV2.recipients.variableRequired": "E-poçt dəyişəni seçin",
+ "nodes.humanInputV2.template.body": "Mətn",
+ "nodes.humanInputV2.template.description": "E-poçt və ani mesajlaşma üçün ehtiyat mətn",
"nodes.humanInputV2.template.insertRequestURL": "Sorğu URL-si əlavə et",
+ "nodes.humanInputV2.template.insertVariable": "Dəyişən əlavə et",
+ "nodes.humanInputV2.template.notConfigured": "Konfiqurasiya edilməyib",
"nodes.humanInputV2.template.requestURLHint": "Alıcılar təsdiq formasını bu keçidlə açır. Dəqiq bir sorğu URL-si əlavə edin.",
"nodes.humanInputV2.template.requestURLInserted": "Sorğu URL-si əlavə edildi",
+ "nodes.humanInputV2.template.saveAndTest": "Yadda saxla və sına",
+ "nodes.humanInputV2.template.subject": "Mövzu",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Mesajın mövzusunu daxil edin",
+ "nodes.humanInputV2.template.test": "Sınaq mesajı",
+ "nodes.humanInputV2.template.testChannel": "Sınaq kanalı",
+ "nodes.humanInputV2.template.testCompleted": "Sınaq sorğusu tamamlandı. Mesajı seçilmiş kanalda yoxlayın.",
+ "nodes.humanInputV2.template.testDescription": "Cari şablonu yadda saxlayın və seçilmiş kanal vasitəsilə sınaq bildirişi göndərin.",
+ "nodes.humanInputV2.template.testFailed": "Sınaq uğursuz oldu. Kanal konfiqurasiyasını yoxlayın və yenidən cəhd edin.",
+ "nodes.humanInputV2.template.testInputsRequired": "Bütün sınaq dəyişənlərinin dəyərlərini daxil edin.",
+ "nodes.humanInputV2.template.testSaveFailed": "İş axınının qaralamasını yadda saxlamaq mümkün olmadı. Sınaq mesajı göndərilmədi.",
+ "nodes.humanInputV2.template.testUnavailable": "Bu mühitdə mesaj şablonlarının sınağı hələ dəstəklənmir.",
+ "nodes.humanInputV2.template.title": "Mesaj şablonu",
"nodes.ifElse.operator": "Operator",
"nodes.iteration.currentIteration": "Cari iterasiya",
"nodes.iteration.deleteDesc": "Iteration düyününün silinməsi bütün alt düyünləri siləcək",
diff --git a/web/i18n/locales/de-DE/contacts.json b/web/i18n/locales/de-DE/contacts.json
index 148f59012b7..b3fc6f2fc78 100644
--- a/web/i18n/locales/de-DE/contacts.json
+++ b/web/i18n/locales/de-DE/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Kontakte entfernen ({{count}})?",
"directory.removalDescription": "Die ausgewählten Kontakte werden dauerhaft aus diesem Arbeitsbereich entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",
- "directory.removalTitle": "Kontakte entfernen?",
+ "directory.removalSingleDescription": "{{name}} wird dauerhaft aus diesem Arbeitsbereich entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",
+ "directory.removalSingleFailed": "Der Kontakt konnte nicht entfernt werden. Versuche es erneut.",
+ "directory.removalSingleTitle": "{{name}} entfernen?",
+ "directory.resultCount": "Ergebnisse: {{count}}",
+ "imPlatform.action.configure": "Konfigurieren",
+ "imPlatform.action.configureChannel": "{{provider}} konfigurieren",
+ "imPlatform.action.connect": "Verbinden",
+ "imPlatform.action.copied": "Kopiert",
+ "imPlatform.action.copyCallback": "Callback-URL kopieren",
+ "imPlatform.action.deleteChannel": "{{provider}} löschen",
+ "imPlatform.action.loadMore": "Mehr laden",
+ "imPlatform.action.replace": "Ersetzen",
+ "imPlatform.action.retry": "Wiederholen",
+ "imPlatform.action.save": "Speichern",
+ "imPlatform.action.saving": "Wird gespeichert",
+ "imPlatform.action.setupGuide": "Einrichtungsanleitung",
+ "imPlatform.action.syncNow": "Jetzt synchronisieren",
+ "imPlatform.action.syncing": "Wird synchronisiert",
+ "imPlatform.action.testConnection": "Verbindung testen",
+ "imPlatform.action.testing": "Test läuft",
+ "imPlatform.action.viewDetails": "Details anzeigen",
+ "imPlatform.bindingDialog.back": "Zurück",
+ "imPlatform.bindingDialog.callback": "Rückruf-URL",
+ "imPlatform.bindingDialog.callbackDescription": "Schließe die Callback-Einrichtung in {{provider}} ab, um Kartenaktionen zu aktivieren.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Füge diese URL für Kartenaktionen in der <console>Feishu-Entwicklerkonsole</console> ein:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Ereignisse und Callbacks → Callback-Konfiguration → Anfrage-URL",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Füge diese URL für Kartenaktionen in der <console>Lark-Entwicklerkonsole</console> ein:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Ereignisse und Callbacks → Callback-Konfiguration → Anfrage-URL",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Füge diese URL für Kartenaktionen in der <console>Slack-Entwicklerkonsole</console> ein:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interaktivität und Kurzbefehle → Interaktivität → Anfrage-URL",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Füge diese URL für Kartenaktionen in der <console>Azure-Bot-Konfiguration</console> ein:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Einstellungen → Konfiguration → Nachrichtenendpunkt",
+ "imPlatform.bindingDialog.callbackStep": "Callbacks konfigurieren",
"imPlatform.bindingDialog.clearSavedCredential": "Gespeicherten Wert löschen",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} konfigurieren",
+ "imPlatform.bindingDialog.connectTitle": "Verbinden Sie {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Dieser gespeicherte Wert wird beim Speichern gelöscht.",
+ "imPlatform.bindingDialog.credentialsDescription": "Verbinde zuerst deine {{provider}}-App und konfiguriere anschließend ihre Callback-URL.",
+ "imPlatform.bindingDialog.credentialsStep": "App-Zugangsdaten",
+ "imPlatform.bindingDialog.description": "Gib die App-Zugangsdaten für diesen IM-Anbieter ein.",
+ "imPlatform.bindingDialog.field.agentId": "Agent-ID",
+ "imPlatform.bindingDialog.field.appId": "App-ID",
+ "imPlatform.bindingDialog.field.appToken": "App-Token (optional)",
+ "imPlatform.bindingDialog.field.botToken": "Bot-Token",
+ "imPlatform.bindingDialog.field.clientId": "Kunden-ID",
+ "imPlatform.bindingDialog.field.clientSecret": "Client-Geheimnis",
+ "imPlatform.bindingDialog.field.corpId": "Unternehmens-ID",
+ "imPlatform.bindingDialog.field.encryptKey": "Verschlüsselungsschlüssel (optional)",
+ "imPlatform.bindingDialog.field.genericSecret": "Geheim",
+ "imPlatform.bindingDialog.field.secret": "App-Geheimnis",
+ "imPlatform.bindingDialog.field.signingSecret": "Signaturgeheimnis",
+ "imPlatform.bindingDialog.field.tenantId": "Mandanten-ID",
+ "imPlatform.bindingDialog.field.verificationToken": "Verifizierungstoken (optional)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Verschlüsselungsschlüssel eingeben, falls aktiviert",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "App-Geheimnis eingeben",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Verifizierungstoken eingeben, falls konfiguriert",
+ "imPlatform.bindingDialog.finish": "Fertigstellen",
+ "imPlatform.bindingDialog.freshCredentials": "Gespeicherte Geheimnisse können nicht abgerufen werden. Gib alle erforderlichen Zugangsdaten erneut ein, um diese Konfiguration zu testen oder zu speichern.",
+ "imPlatform.bindingDialog.openSetupGuide": "Einrichtungsanleitung öffnen",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Mandanten-Zugangsdaten für {{identity}} ersetzen?",
"imPlatform.bindingDialog.replacementRequired": "Diese Zugangsdaten gehören zu einem anderen IM-Mandanten und können nicht direkt gespeichert werden. Ein Mandantenwechsel erfordert das Ersetzen des aktuellen IM-Kanals. Dabei werden alle automatischen und manuellen IM-Zuordnungen gelöscht. Synchronisieren Sie die Kontakte nach dem Ersetzen erneut.",
+ "imPlatform.bindingDialog.required": "Dieses Feld ist erforderlich.",
+ "imPlatform.bindingDialog.saveAndContinue": "Speichern und fortfahren",
+ "imPlatform.bindingDialog.saveFailed": "Die Konfiguration konnte nicht gespeichert werden. Prüfe die Felder und versuche es erneut.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Die Konfiguration wurde gespeichert, aber ihre Details konnten nicht geladen werden. Schließen Sie diesen Dialog und öffnen Sie ihn erneut.",
- "imPlatform.bindingDialog.undoClearCredential": "Löschen rückgängig machen"
+ "imPlatform.bindingDialog.secretConfigured": "Ein Geheimnis ist bereits konfiguriert. Lass dieses Feld leer, um es beizubehalten.",
+ "imPlatform.bindingDialog.step": "Schritt {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Der Verbindungstest ist fehlgeschlagen. Prüfe die Konfiguration und versuche es erneut.",
+ "imPlatform.bindingDialog.undoClearCredential": "Löschen rückgängig machen",
+ "imPlatform.bindingDialog.viewSetupGuide": "Einrichtungsanleitung anzeigen",
+ "imPlatform.chooseProvider": "Wähle einen Kanal zum Verbinden",
+ "imPlatform.configurationUpdated": "Diese Kanalkonfiguration hat sich geändert. Schließe diesen Dialog und aktualisiere die Seite, bevor du es erneut versuchst.",
+ "imPlatform.connectMore": "Weitere Kanäle verbinden",
+ "imPlatform.delete.confirm": "Löschen",
+ "imPlatform.delete.description": "Beim Löschen dieses Kanals wird seine Konfiguration entfernt. Genehmigungsbenachrichtigungen und Verzeichnissynchronisierungen, die ihn verwenden, werden eingestellt.",
+ "imPlatform.delete.failed": "Der Kanal konnte nicht gelöscht werden. Es wurde nichts geändert. Versuche es erneut.",
+ "imPlatform.delete.title": "Kanal {{provider}} löschen?",
+ "imPlatform.description": "Verbinde deine Unternehmenskanäle, damit Genehmigungsanfragen die Personen an ihrem Arbeitsplatz erreichen.",
+ "imPlatform.details.column.contact": "Kontakte",
+ "imPlatform.details.column.platform": "IM-Plattform",
+ "imPlatform.details.description": "Zeige die schreibgeschützten Ergebnisse des letzten Synchronisierungslaufs an.",
+ "imPlatform.details.downloadFailed": "Der Bericht konnte nicht heruntergeladen werden. Versuche es erneut.",
+ "imPlatform.details.downloadReport": "Bericht herunterladen",
+ "imPlatform.details.downloadingReport": "Bericht wird heruntergeladen…",
+ "imPlatform.details.empty": "Keine Ergebnisse in dieser Kategorie.",
+ "imPlatform.details.filter.added": "Hinzugefügt",
+ "imPlatform.details.filter.failed": "Fehlgeschlagen",
+ "imPlatform.details.filter.not_matched": "Nicht zugeordnet",
+ "imPlatform.details.filter.removed": "Entfernt",
+ "imPlatform.details.filter.skipped": "Übersprungen",
+ "imPlatform.details.filters": "Filter für Synchronisierungsergebnisse",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Die Synchronisierungsdetails konnten nicht geladen werden.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Weitere Ergebnisse konnten nicht geladen werden. Versuche diese Seite erneut.",
+ "imPlatform.details.removalReason.binding_invalidated": "Verknüpfung ungültig",
+ "imPlatform.details.removalReason.binding_replaced": "Verknüpfung ersetzt",
+ "imPlatform.details.removalReason.not_present_in_directory": "Nicht mehr im Verzeichnis",
+ "imPlatform.details.reportChanged": "Die Synchronisierungsergebnisse haben sich geändert. Öffne die Details der letzten Synchronisierung erneut und versuche es noch einmal.",
+ "imPlatform.details.title": "Synchronisierungsdetails",
+ "imPlatform.email.apiKey": "API-Schlüssel",
+ "imPlatform.email.apiKeyConfigured": "Aus Sicherheitsgründen kann der gespeicherte API-Schlüssel nicht angezeigt werden. Lass dieses Feld leer, um ihn beizubehalten.",
+ "imPlatform.email.apiKeyDescription": "Aus Sicherheitsgründen kann dieser API-Schlüssel nach dem Speichern nicht mehr angezeigt werden.",
+ "imPlatform.email.apiKeyPlaceholder": "Deinen Resend-API-Schlüssel eingeben",
+ "imPlatform.email.description": "Diese Konfiguration gilt für alle Human-Input-Knoten in diesem Arbeitsbereich, bei denen <emphasis>Debug-Benachrichtigungen per E-Mail senden</emphasis> aktiviert ist.",
+ "imPlatform.email.invalidEmail": "Gib eine gültige E-Mail-Adresse ein.",
+ "imPlatform.email.provider": "E-Mail-Anbieter",
+ "imPlatform.email.resendDescription": "Dein <apiKey>Resend-API-Schlüssel</apiKey> wird verschlüsselt und kann nach dem Speichern nicht mehr angezeigt werden.<br/>Registriere ein <resend>Resend</resend>-Konto.",
+ "imPlatform.email.resendSettings": "Resend-Einstellungen",
+ "imPlatform.email.senderEmail": "E-Mail-Adresse des Absenders",
+ "imPlatform.email.senderEmailDescription": "Die als Absender angezeigte E-Mail-Adresse. Ihre Domain muss in Resend verifiziert sein.",
+ "imPlatform.email.senderName": "Absendername",
+ "imPlatform.email.senderNameDescription": "Der im Posteingang des Empfängers angezeigte Name.",
+ "imPlatform.email.testSucceeded": "Verbindungstest erfolgreich.",
+ "imPlatform.email.title": "E-Mail konfigurieren",
+ "imPlatform.learnMore": "Mehr erfahren",
+ "imPlatform.loadError.description": "Versuche erneut, die aktuelle Bindung und die Berechtigungen zu laden.",
+ "imPlatform.loadError.retry": "Erneut versuchen",
+ "imPlatform.loadError.title": "Kanäle konnten nicht geladen werden",
+ "imPlatform.loading": "Kanäle werden geladen",
+ "imPlatform.provider.dingtalkDescription": "Verbinde eine DingTalk-Anwendung.",
+ "imPlatform.provider.emailDescription": "Konfiguriere den E-Mail-Dienst zum Versenden von Genehmigungsanfragen aus diesem Arbeitsbereich.",
+ "imPlatform.provider.feishuDescription": "Verbinde eine Feishu-Anwendung.",
+ "imPlatform.provider.larkDescription": "Verbinde eine Lark-Anwendung.",
+ "imPlatform.provider.msTeamsDescription": "Verbinde eine Microsoft-Teams-Anwendung.",
+ "imPlatform.provider.slackDescription": "Synchronisiere Personen und ihre Slack-Identitäten.",
+ "imPlatform.provider.weComDescription": "Verbinde eine WeCom-Anwendung.",
+ "imPlatform.replacement.confirm": "Ersetzen",
+ "imPlatform.replacement.description": "Das Ersetzen des aktiven Anbieters macht seine IM-Bindungen und Arbeitsbereichsanpassungen ungültig. Synchronisiere danach das Verzeichnis des neuen Anbieters erneut.",
+ "imPlatform.replacement.title": "{{current}} durch {{next}} ersetzen?",
+ "imPlatform.status.configured": "Konfiguriert",
+ "imPlatform.status.connected": "Verbunden",
+ "imPlatform.status.connection_error": "Verbindungsfehler",
+ "imPlatform.status.permission_issue": "Berechtigungsproblem",
+ "imPlatform.sync.latestSynced": "Zuletzt synchronisiert am {{date}}",
+ "imPlatform.sync.loading": "Aktive Synchronisierung wird geprüft.",
+ "imPlatform.sync.noPermission": "Nur Eigentümer und Administratoren des Arbeitsbereichs können die Verzeichnissynchronisierung starten.",
+ "imPlatform.sync.noRuns": "Es wurde noch keine Verzeichnissynchronisierung ausgeführt.",
+ "imPlatform.sync.notConnected": "Verbinde einen Anbieter und teste die Verbindung, bevor du die Verzeichnissynchronisierung startest.",
+ "imPlatform.sync.startFailed": "Die Verzeichnissynchronisierung konnte nicht gestartet oder aktualisiert werden. Versuche es erneut.",
+ "imPlatform.sync.status.failure": "Fehlgeschlagen",
+ "imPlatform.sync.status.queued": "In Warteschlange",
+ "imPlatform.sync.status.running": "Wird ausgeführt",
+ "imPlatform.sync.status.success": "Erfolgreich",
+ "imPlatform.title": "Kanäle"
}
diff --git a/web/i18n/locales/de-DE/share.json b/web/i18n/locales/de-DE/share.json
index 3fa959c69fc..c90008d4f1a 100644
--- a/web/i18n/locales/de-DE/share.json
+++ b/web/i18n/locales/de-DE/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Danke!",
"humanInput.unavailableDescription": "Der Link ist möglicherweise nicht verfügbar oder passt nicht zu dem Konto, mit dem Sie angemeldet sind. Öffnen Sie das Formular über die erhaltene Benachrichtigung oder wechseln Sie das Konto.",
"humanInput.unavailableTitle": "Dieses Formular kann nicht geöffnet werden",
+ "humanInputV2.accessRateLimited": "Es wurden zu viele Bestätigungs-E-Mails angefordert. Versuchen Sie es später erneut.",
+ "humanInputV2.alreadySubmitted": "Diese Anfrage wurde bereits abgeschlossen.",
+ "humanInputV2.challengeExpired": "Dieser Bestätigungscode ist abgelaufen. Fordern Sie einen neuen Code an, um fortzufahren.",
+ "humanInputV2.challengeStale": "Dieser Bestätigungscode wurde ersetzt. Fordern Sie einen neuen Code an, um fortzufahren.",
+ "humanInputV2.codeExpiresIn": "Code läuft in {{seconds}} s ab",
+ "humanInputV2.codeRequired": "Fordern Sie einen Bestätigungscode an, um fortzufahren.",
+ "humanInputV2.codeSent": "Ein Bestätigungscode wurde an Ihre E-Mail-Adresse gesendet.",
+ "humanInputV2.deliveryFailed": "Die Bestätigungs-E-Mail konnte nicht gesendet werden. Versuchen Sie es erneut.",
+ "humanInputV2.formExpired": "Diese Anfrage ist abgelaufen.",
+ "humanInputV2.formNotFound": "Formular nicht gefunden.",
+ "humanInputV2.formRateLimited": "Zu viele Formularanfragen. Versuchen Sie es später erneut.",
+ "humanInputV2.invalidOtp": "Der Bestätigungscode ist falsch. Prüfen Sie den Code und versuchen Sie es erneut.",
+ "humanInputV2.networkError": "Die Anfrage konnte nicht abgeschlossen werden. Prüfen Sie Ihre Verbindung und versuchen Sie es erneut.",
+ "humanInputV2.otpLabel": "E-Mail-Bestätigungscode",
+ "humanInputV2.otpPlaceholder": "6-stelligen Code eingeben",
+ "humanInputV2.requestingCode": "Bestätigungscode wird gesendet…",
+ "humanInputV2.resendCode": "Code erneut senden",
+ "humanInputV2.retry": "Erneut versuchen",
+ "humanInputV2.sendCode": "Neuen Code senden",
+ "humanInputV2.unavailable": "Dieses Formular ist vorübergehend nicht verfügbar.",
+ "humanInputV2.unknownError": "Ein Fehler ist aufgetreten. Versuchen Sie es erneut.",
+ "humanInputV2.uploadFailed": "Die Datei konnte nicht hochgeladen werden. Versuchen Sie es erneut.",
"login.backToHome": "Zurück zur Startseite"
}
diff --git a/web/i18n/locales/de-DE/workflow-human-input.json b/web/i18n/locales/de-DE/workflow-human-input.json
index 5f6341a61ac..20c106582eb 100644
--- a/web/i18n/locales/de-DE/workflow-human-input.json
+++ b/web/i18n/locales/de-DE/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Aktionswert",
"nodes.humanInput.userActions.buttonTextTooLong": "Schaltflächentext darf höchstens {{maxLength}} Zeichen lang sein",
"nodes.humanInput.userActions.chooseStyle": "Wählen Sie einen Schaltflächenstil",
+ "nodes.humanInput.userActions.defaultTitle": "Schaltflächentext {{index}}",
"nodes.humanInput.userActions.emptyTip": "Klicken Sie auf die '+'-Schaltfläche, um Benutzeraktionen hinzuzufügen",
"nodes.humanInput.userActions.title": "Benutzeraktionen",
"nodes.humanInput.userActions.tooltip": "Definieren Sie Schaltflächen, auf die Benutzer klicken können, um auf dieses Formular zu reagieren. Die Aktions-ID steuert die Verzweigung. Der Aktionswert wird nachgelagert als ausgewählte integrierte Ausgabe bereitgestellt. Aktions-ID muss mit einem Buchstaben oder Unterstrich beginnen, gefolgt von Buchstaben, Zahlen oder Unterstrichen.",
diff --git a/web/i18n/locales/de-DE/workflow.json b/web/i18n/locales/de-DE/workflow.json
index e0256a2d910..d13e3250f70 100644
--- a/web/i18n/locales/de-DE/workflow.json
+++ b/web/i18n/locales/de-DE/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Ausgabe",
"blocks.http-request": "HTTP-Anfrage",
"blocks.human-input": "Menschliche Eingabe",
+ "blocks.human-input-v2": "Menschliche Eingabe v2",
"blocks.if-else": "WENN/SONST",
"blocks.iteration": "Iteration",
"blocks.iteration-start": "Iterationsstart",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Definieren Sie die Ausgabe und den Ergebnistyp eines Workflows",
"blocksAbout.http-request": "Ermöglichen, dass Serveranforderungen über das HTTP-Protokoll gesendet werden",
"blocksAbout.human-input": "Um menschliche Bestätigung bitten, bevor der nächste Schritt generiert wird",
+ "blocksAbout.human-input-v2": "Eingaben von konfigurierten Kontakten, E-Mail-Empfängern oder dem Workflow-Initiator anfordern",
"blocksAbout.if-else": "Ermöglicht das Aufteilen des Workflows in zwei Zweige basierend auf if/else-Bedingungen",
"blocksAbout.iteration": "Mehrere Schritte an einem Listenobjekt ausführen, bis alle Ergebnisse ausgegeben wurden.",
"blocksAbout.iteration-start": "Startknoten der Iteration",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Variablen aus mehreren Zweigen in eine einzige Variable zusammenführen, um eine einheitliche Konfiguration der nachgelagerten Knoten zu ermöglichen.",
"blocksAbout.variable-assigner": "Variablen aus mehreren Zweigen in eine einzige Variable zusammenführen, um eine einheitliche Konfiguration der nachgelagerten Knoten zu ermöglichen.",
"changeHistory.edgeDelete": "Knoten getrennt",
+ "changeHistory.humanInputMigration": "Knoten für menschliche Eingaben migriert",
"changeHistory.nodeAdd": "Knoten hinzugefügt",
"changeHistory.nodeChange": "Knoten geändert",
"changeHistory.nodeConnect": "Node verbunden",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Bitte aktivieren Sie mindestens eine Zustellmethode",
"nodes.humanInput.errorMsg.noUserActions": "Bitte fügen Sie mindestens eine Benutzeraktion hinzu",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} ist für den Zeitüberschreitungszweig reserviert. Wähle eine andere Aktions-ID.",
+ "nodes.humanInput.output.actionId": "ID der vom Benutzer ausgelösten Aktion",
+ "nodes.humanInput.output.actionValue": "Wert der ausgewählten Aktion",
+ "nodes.humanInput.output.formInput": "Wert der Formulareingabe",
+ "nodes.humanInput.output.renderedContent": "Gerenderter Inhalt",
"nodes.humanInput.timeout.title": "Zeitüberschreitung",
+ "nodes.humanInputMigration.action.migrate": "Migrieren",
+ "nodes.humanInputMigration.action.migrateNow": "Jetzt migrieren",
+ "nodes.humanInputMigration.action.migrating": "Migration läuft...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Hinweis zur Migration menschlicher Eingaben",
+ "nodes.humanInputMigration.banner.description": "Dieser Workflow verwendet den alten Knoten für menschliche Eingaben. Migrieren Sie alle alten Knoten, bevor Sie neue hinzufügen.",
+ "nodes.humanInputMigration.banner.learnMore": "Mehr erfahren",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "eine deaktivierte Zustellmethode enthält noch Konfigurationen",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "aktivierte E-Mail-Methoden verwenden widersprüchliche Vorlagen",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Ungültiger Standardwert",
+ "nodes.humanInputMigration.blocker.invalidEmail": "eine Empfänger-E-Mail-Adresse ist ungültig",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "eine aktivierte E-Mail-Methode ist unvollständig",
+ "nodes.humanInputMigration.blocker.missingRecipients": "der Knoten hat keine unterstützten Empfänger",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "ein Mitglied des Arbeitsbereichs kann keinem Kontakt und keiner verifizierten E-Mail-Adresse zugeordnet werden",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "eine aktivierte Zustellmethode wird von Human Input v2 nicht unterstützt",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Das Feld {{field}} kann noch nicht migriert werden. Sie können die bisherigen Human-Input-Knoten weiterhin verwenden.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "der Knoten hat einen nicht unterstützten Versionswert",
+ "nodes.humanInputMigration.dialog.description": "Ihre Empfänger, Ihr Formular und Ihre Aktionen werden übernommen.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Nur dieser Entwurf wird geändert. Veröffentlichte Versionen laufen weiter, bis Sie erneut veröffentlichen.",
+ "nodes.humanInputMigration.dialog.review": "Prüfen Sie die Knoten und veröffentlichen Sie, wenn Sie bereit sind.",
+ "nodes.humanInputMigration.dialog.title": "{{count}} Knoten für menschliche Eingaben migrieren",
+ "nodes.humanInputMigration.disabledBadge": "MIGRATION ERFORDERLICH",
+ "nodes.humanInputMigration.disabledReason": "Migrieren Sie alte Knoten für menschliche Eingaben, bevor Sie einen neuen hinzufügen.",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} konnte nicht migriert werden: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Der Workflow wurde während der Migration geändert. Versuchen Sie es erneut. Ihre aktuellen Änderungen wurden beibehalten.",
+ "nodes.humanInputMigration.error.preflight": "Die Migration konnte nicht vorbereitet werden. Ihr Workflow wurde nicht geändert. Versuchen Sie es erneut.",
"nodes.humanInputMigration.error.sync": "Der migrierte Workflow konnte nicht gespeichert werden. Prüfen Sie den aktuellen Entwurf und versuchen Sie es erneut.",
+ "nodes.humanInputMigration.incompatibleVersions": "Alte und neue Human-Input-Knoten können nicht im selben Workflow verwendet werden.",
+ "nodes.humanInputMigration.oldVersion": "ALTE VERSION",
+ "nodes.humanInputMigration.preview.author": "Vom Dify-Team",
+ "nodes.humanInputMigration.preview.description": "Migrieren Sie alte Knoten für menschliche Eingaben, bevor Sie einen neuen hinzufügen.",
+ "nodes.humanInputMigration.success": "Knoten für menschliche Eingaben erfolgreich migriert",
+ "nodes.humanInputV2.card.configured": "{{count}} Empfänger konfiguriert",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} Kontakte",
+ "nodes.humanInputV2.card.empty": "Noch niemand kann diesen Schritt genehmigen",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Initiator und {{count}} Kontakte",
+ "nodes.humanInputV2.card.initiatorOnly": "Nur Initiator",
+ "nodes.humanInputV2.card.invalid": "Die Empfängerkonfiguration muss überprüft werden",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-Mail",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Debug-Modus konfigurieren",
"nodes.humanInputV2.debug.keepOneChannel": "Mindestens einen Kanal aktiviert lassen",
+ "nodes.humanInputV2.debug.sendVia": "Debug-Benachrichtigungen senden über",
+ "nodes.humanInputV2.debug.title": "Debug-Modus",
+ "nodes.humanInputV2.debug.toggle": "Debug-Modus aktivieren",
+ "nodes.humanInputV2.debug.unsupported": "Nicht unterstützte importierte Kanäle: {{channels}}. Entfernen oder aktualisieren Sie diese, bevor Sie diesen Workflow ausführen.",
"nodes.humanInputV2.disabled": "Human Input v2 ist nicht verfügbar, solange HITL IM deaktiviert ist.",
+ "nodes.humanInputV2.error.bodyRequired": "Nachrichtentext ist erforderlich",
+ "nodes.humanInputV2.error.debugChannelRequired": "Wählen Sie mindestens einen Kanal für den Debug-Modus",
+ "nodes.humanInputV2.error.recipientDuplicate": "Entfernen Sie doppelte Empfänger",
+ "nodes.humanInputV2.error.recipientInvalid": "Korrigieren Sie die ungültige Empfängerkonfiguration",
+ "nodes.humanInputV2.error.recipientRequired": "Fügen Sie mindestens einen Empfänger hinzu",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Kontaktempfänger konnten nicht überprüft werden",
"nodes.humanInputV2.error.requestURLDuplicate": "Der Nachrichtentext darf nur eine Anfrage-URL enthalten.",
"nodes.humanInputV2.error.requestURLRequired": "Fügen Sie eine Anfrage-URL in den Nachrichtentext ein.",
+ "nodes.humanInputV2.error.subjectRequired": "Nachrichtenbetreff ist erforderlich",
+ "nodes.humanInputV2.error.version": "Human Input v2 erfordert den Versionswert 2 als Zeichenfolge",
+ "nodes.humanInputV2.recipients.addContact": "Kontakt hinzufügen",
+ "nodes.humanInputV2.recipients.addEmail": "Hinzufügen",
+ "nodes.humanInputV2.recipients.addRecipient": "Empfänger hinzufügen",
+ "nodes.humanInputV2.recipients.added": "Hinzugefügt",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Alle Kontakte im Arbeitsbereich",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Alle Kontakte im Arbeitsbereich benachrichtigen; jeder von ihnen kann genehmigen",
+ "nodes.humanInputV2.recipients.cancel": "Abbrechen",
+ "nodes.humanInputV2.recipients.chooseVariable": "Variable auswählen",
+ "nodes.humanInputV2.recipients.confirm": "Bestätigen",
+ "nodes.humanInputV2.recipients.contactInfo": "Kontaktdetails für {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Alle",
+ "nodes.humanInputV2.recipients.contactSource.external": "Extern",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organisation",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Arbeitsbereich",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Kontaktquelle",
"nodes.humanInputV2.recipients.duplicateSource": "Bereits über {{name}} ({{source}}) hinzugefügt.",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} bearbeiten",
+ "nodes.humanInputV2.recipients.editRecipient": "Empfänger bearbeiten",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Jede E-Mail-Adresse kann nur einmal ausgewählt werden.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Geben Sie eine gültige E-Mail-Adresse ein, die noch nicht hinzugefügt wurde",
+ "nodes.humanInputV2.recipients.emailLabel": "Einmaliger E-Mail-Empfänger",
+ "nodes.humanInputV2.recipients.empty": "Keine Empfänger konfiguriert",
+ "nodes.humanInputV2.recipients.help": "Wählen Sie aus, wer auf diesen Schritt für menschliche Eingaben antworten kann.",
"nodes.humanInputV2.recipients.initiator": "Der Benutzer, der diesen Durchlauf über Web App oder CLI startet, kann genehmigen",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Die Person, die diesen Workflow-Lauf startet, kann antworten.",
"nodes.humanInputV2.recipients.inputHelp": "Geben Sie mehrere durch Kommas getrennte E-Mail-Adressen ein oder fügen Sie sie ein. Drücken Sie /, um eine Variable einzufügen.",
+ "nodes.humanInputV2.recipients.insertVariable": "Variable einfügen",
+ "nodes.humanInputV2.recipients.loadError": "Kontakte konnten nicht geladen werden. Gespeicherte Kontakt-IDs bleiben erhalten.",
+ "nodes.humanInputV2.recipients.loading": "Kontakte werden geladen…",
+ "nodes.humanInputV2.recipients.noResults": "Keine Kontakte gefunden",
+ "nodes.humanInputV2.recipients.placeholder": "Kontakte suchen oder E-Mail-Adressen hinzufügen",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} entfernen",
+ "nodes.humanInputV2.recipients.removeHint": "Zum Entfernen die Rücktaste oder Entf-Taste drücken.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} passende Empfänger",
+ "nodes.humanInputV2.recipients.search": "Kontakte suchen",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Nach Name oder E-Mail-Adresse suchen",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} Empfänger ausgewählt. Am Anfang der Eingabe die linke Pfeiltaste drücken, um sie zu fokussieren.",
+ "nodes.humanInputV2.recipients.title": "Empfänger",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Alle Kontakte im Arbeitsbereich",
+ "nodes.humanInputV2.recipients.type.contact": "Kontakt",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Dynamische E-Mail",
+ "nodes.humanInputV2.recipients.type.initiator": "Initiator",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Einmalige E-Mail",
+ "nodes.humanInputV2.recipients.typeLabel": "Empfängertyp",
"nodes.humanInputV2.recipients.useThisInstead": "Stattdessen diesen verwenden",
+ "nodes.humanInputV2.recipients.variableRequired": "Wählen Sie eine E-Mail-Variable",
+ "nodes.humanInputV2.template.body": "Nachrichtentext",
+ "nodes.humanInputV2.template.description": "Ersatztext für E-Mail und IM",
"nodes.humanInputV2.template.insertRequestURL": "Anfrage-URL einfügen",
+ "nodes.humanInputV2.template.insertVariable": "Variable einfügen",
+ "nodes.humanInputV2.template.notConfigured": "Nicht konfiguriert",
"nodes.humanInputV2.template.requestURLHint": "Empfänger öffnen das Genehmigungsformular über diesen Link. Fügen Sie genau eine Anfrage-URL ein.",
"nodes.humanInputV2.template.requestURLInserted": "Anfrage-URL eingefügt",
"nodes.humanInputV2.template.saveAndTest": "Speichern und testen",
+ "nodes.humanInputV2.template.subject": "Betreff",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Nachrichtenbetreff eingeben",
"nodes.humanInputV2.template.test": "Nachricht testen",
"nodes.humanInputV2.template.testChannel": "Testkanal",
"nodes.humanInputV2.template.testCompleted": "Die Testanfrage wurde abgeschlossen. Prüfen Sie den ausgewählten Kanal auf die Nachricht.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Geben Sie alle Werte der Testvariablen ein.",
"nodes.humanInputV2.template.testSaveFailed": "Der Workflow-Entwurf konnte nicht gespeichert werden. Der Test wurde nicht gesendet.",
"nodes.humanInputV2.template.testUnavailable": "Diese Umgebung unterstützt das Testen von Nachrichtenvorlagen noch nicht.",
+ "nodes.humanInputV2.template.title": "Nachrichtenvorlage",
"nodes.ifElse.operator": "Operator",
"nodes.iteration.currentIteration": "Aktuelle Iteration",
"nodes.iteration.deleteDesc": "Das Löschen des Iterationsknotens löscht alle untergeordneten Knoten",
diff --git a/web/i18n/locales/en-US/contacts.json b/web/i18n/locales/en-US/contacts.json
index 58ad0470ef4..02b39c8e3d8 100644
--- a/web/i18n/locales/en-US/contacts.json
+++ b/web/i18n/locales/en-US/contacts.json
@@ -42,7 +42,6 @@
"directory.externalEmptyDescription": "External contacts are people outside your organization. Think clients, partners, or vendors. They're reached by email only.",
"directory.externalEmptyTitle": "Add your first external contact",
"directory.filters": "Contact type filters",
- "directory.learnMore": "Learn more about Contacts",
"directory.loading": "Loading contacts",
"directory.noAccessDescription": "Only workspace owners and admins can browse the full Contacts directory.",
"directory.noAccessTitle": "You don't have access to Contacts",
@@ -50,10 +49,14 @@
"directory.noResultsTitle": "No matching contacts",
"directory.openDetails": "Open contact details for {{name}}",
"directory.pageError": "More contacts couldn't be loaded. Retry this page.",
+ "directory.removalCountTitle": "Remove contacts ({{count}})?",
"directory.removalDescription": "The selected contacts will be permanently removed from this workspace. This action cannot be undone.",
"directory.removalFailed": "The selected contacts couldn't be removed. Your selection has been kept.",
- "directory.removalTitle": "Remove contacts?",
+ "directory.removalSingleDescription": "{{name}} will be permanently removed from this workspace. This action cannot be undone.",
+ "directory.removalSingleFailed": "The contact couldn't be removed. Try again.",
+ "directory.removalSingleTitle": "Remove {{name}}?",
"directory.removeSelected": "Remove",
+ "directory.resultCount": "Results: {{count}}",
"directory.search": "Search name or email",
"directory.selectAll": "Select all removable contacts",
"directory.selectContact": "Select {{name}}",
@@ -62,7 +65,6 @@
"directory.viewOnly": "You can browse Contacts, but only workspace owners and admins can manage contacts.",
"external.add": "Add",
"external.adding": "Adding",
- "external.avatarFallback": "External contact",
"external.description": "Create a workspace-only contact that can be reached by email.",
"external.editDescription": "Update this external contact's name and email address.",
"external.editTitle": "Edit External Contact",
@@ -71,8 +73,6 @@
"external.namePlaceholder": "Full name",
"external.result.duplicate_external_contact": "An external contact with this email already exists.",
"external.result.failed": "The contact couldn't be added. Keep these details and try again.",
- "external.result.matches_platform_contact": "This email belongs to a Platform contact. Add it from Platform instead.",
- "external.result.matches_workspace_contact": "This person is already a workspace contact.",
"external.save": "Save",
"external.saving": "Saving",
"external.title": "Add External Contact",
@@ -119,15 +119,12 @@
"imBinding.select": "Select an IM contact",
"imBinding.title": "Bind IM identity",
"imBinding.workspaceMode": "Custom for this workspace",
- "imPlatform.action.authorize": "Authorize",
- "imPlatform.action.authorizing": "Authorizing",
"imPlatform.action.configure": "Configure",
"imPlatform.action.configureChannel": "Configure {{provider}}",
"imPlatform.action.connect": "Connect",
"imPlatform.action.copied": "Copied",
"imPlatform.action.copyCallback": "Copy callback URL",
"imPlatform.action.deleteChannel": "Delete {{provider}}",
- "imPlatform.action.disconnect": "Disconnect",
"imPlatform.action.loadMore": "Load more",
"imPlatform.action.replace": "Replace",
"imPlatform.action.retry": "Retry",
@@ -139,7 +136,6 @@
"imPlatform.action.testConnection": "Test connection",
"imPlatform.action.testing": "Testing",
"imPlatform.action.viewDetails": "View details",
- "imPlatform.bindingDialog.authorizationFailed": "Authorization couldn't be completed. Try again.",
"imPlatform.bindingDialog.back": "Back",
"imPlatform.bindingDialog.callback": "Callback URL",
"imPlatform.bindingDialog.callbackDescription": "Complete callback setup in {{provider}} to enable card actions.",
@@ -151,7 +147,6 @@
"imPlatform.bindingDialog.callbackInstruction.slack.path": "Interactivity & Shortcuts → Interactivity → Request URL",
"imPlatform.bindingDialog.callbackInstruction.teams.destination": "For card actions, paste this URL in the <console>Azure Bot configuration</console>:",
"imPlatform.bindingDialog.callbackInstruction.teams.path": "Settings → Configuration → Messaging endpoint",
- "imPlatform.bindingDialog.callbackPurpose": "This URL receives approval card interactions from {{provider}}. Use the exact URL shown for this channel.",
"imPlatform.bindingDialog.callbackStep": "Configure callbacks",
"imPlatform.bindingDialog.clearSavedCredential": "Clear saved value",
"imPlatform.bindingDialog.configureTitle": "Configure {{provider}}",
@@ -179,15 +174,14 @@
"imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Enter Verification Token, if configured",
"imPlatform.bindingDialog.finish": "Finish",
"imPlatform.bindingDialog.freshCredentials": "Saved secrets cannot be retrieved. Re-enter all required credentials to test or save this configuration.",
- "imPlatform.bindingDialog.openProviderConsole": "Open {{provider}} developer console",
"imPlatform.bindingDialog.openSetupGuide": "Open setup guide",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Replace tenant credentials for {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "These credentials belong to a different IM tenant and cannot be saved directly. Switching tenants requires replacing the current IM channel, which clears all automatic and manual IM bindings. Sync contacts again after replacement.",
"imPlatform.bindingDialog.required": "This field is required.",
"imPlatform.bindingDialog.saveAndContinue": "Save and continue",
"imPlatform.bindingDialog.saveFailed": "Configuration couldn't be saved. Check the fields and try again.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "The configuration was saved, but its details could not be loaded. Close this dialog and reopen it.",
"imPlatform.bindingDialog.secretConfigured": "A secret is already configured. Leave this field blank to keep it.",
- "imPlatform.bindingDialog.secretPlaceholder": "Enter a new secret",
"imPlatform.bindingDialog.step": "Step {{step}}",
"imPlatform.bindingDialog.testFailed": "The connection test failed. Check the configuration and try again.",
"imPlatform.bindingDialog.undoClearCredential": "Undo clear",
@@ -208,37 +202,20 @@
"imPlatform.details.downloadingReport": "Downloading report…",
"imPlatform.details.empty": "No results in this category.",
"imPlatform.details.filter.added": "Added",
- "imPlatform.details.filter.all": "All",
- "imPlatform.details.filter.created_binding": "Binding created",
"imPlatform.details.filter.failed": "Failed",
- "imPlatform.details.filter.matched": "Matched",
"imPlatform.details.filter.not_matched": "Not matched",
"imPlatform.details.filter.removed": "Removed",
"imPlatform.details.filter.skipped": "Skipped",
- "imPlatform.details.filter.unmatched": "Unmatched",
- "imPlatform.details.filter.updated_binding": "Binding updated",
"imPlatform.details.filters": "Sync result filters",
"imPlatform.details.latestMetadata": "{{status}} · {{date}}",
"imPlatform.details.loadError": "Sync details couldn't be loaded.",
- "imPlatform.details.loading": "Loading sync details",
- "imPlatform.details.metadata": "{{status}} · {{date}} by {{user}}",
"imPlatform.details.missing": "—",
"imPlatform.details.pageError": "More results couldn't be loaded. Retry this page.",
+ "imPlatform.details.removalReason.binding_invalidated": "Binding invalidated",
+ "imPlatform.details.removalReason.binding_replaced": "Binding replaced",
+ "imPlatform.details.removalReason.not_present_in_directory": "No longer in the directory",
"imPlatform.details.reportChanged": "The sync results changed. Reopen the latest sync details and try again.",
- "imPlatform.details.safeReason.contact_update_failed": "The Contact binding couldn't be updated.",
- "imPlatform.details.safeReason.duplicate_identity": "A duplicate platform identity was skipped.",
- "imPlatform.details.safeReason.missing_email": "The platform member has no Email address.",
- "imPlatform.details.safeReason.no_matching_contact": "No existing Contact matched this platform member.",
- "imPlatform.details.safeReason.provider_request_failed": "The provider request failed without exposing credentials.",
"imPlatform.details.title": "Sync details",
- "imPlatform.diagnostics.configured": "Configuration is saved. Test the connection before syncing Contacts.",
- "imPlatform.diagnostics.connected": "Directory access is ready.",
- "imPlatform.diagnostics.notConfigured": "Choose a provider to start the binding flow.",
- "imPlatform.diagnostics.title": "Connection diagnostics",
- "imPlatform.disconnect.confirm": "Disconnect",
- "imPlatform.disconnect.description": "Directory sync will stop and the current binding will be removed.",
- "imPlatform.disconnect.failed": "The provider couldn't be disconnected. Try again.",
- "imPlatform.disconnect.title": "Disconnect {{provider}}?",
"imPlatform.email.apiKey": "API Key",
"imPlatform.email.apiKeyConfigured": "For security reasons, the saved API Key cannot be viewed. Leave this field blank to keep it.",
"imPlatform.email.apiKeyDescription": "For security reasons, this API Key cannot be viewed once saved.",
@@ -252,51 +229,27 @@
"imPlatform.email.senderEmailDescription": "The email address shown as the sender. Its domain must be verified in Resend.",
"imPlatform.email.senderName": "Sender name",
"imPlatform.email.senderNameDescription": "Name displayed in the recipient's inbox.",
- "imPlatform.email.summary": "Resend · {{email}}",
"imPlatform.email.testSucceeded": "Connection test succeeded.",
"imPlatform.email.title": "Configure Email",
- "imPlatform.lastChecked": "Last checked {{date}}",
"imPlatform.learnMore": "Learn more",
"imPlatform.loadError.description": "Try again to read the current binding and permissions.",
"imPlatform.loadError.retry": "Try again",
"imPlatform.loadError.title": "Channels couldn't be loaded",
"imPlatform.loading": "Loading channels",
- "imPlatform.notChecked": "Connection hasn't been checked yet.",
- "imPlatform.permission.description": "Only workspace owners and admins can manage channels and directory sync.",
- "imPlatform.permission.title": "View only",
"imPlatform.provider.dingtalkDescription": "Connect a DingTalk application.",
"imPlatform.provider.emailDescription": "Configure the email service used to send approval requests from this workspace.",
"imPlatform.provider.feishuDescription": "Connect a Feishu application.",
"imPlatform.provider.larkDescription": "Connect a Lark application.",
"imPlatform.provider.msTeamsDescription": "Connect a Microsoft Teams application.",
"imPlatform.provider.slackDescription": "Sync people and their Slack identities.",
- "imPlatform.provider.unavailable": "Unavailable",
- "imPlatform.provider.unavailableReason.deployment_unsupported": "This provider isn't supported in the current deployment.",
- "imPlatform.provider.unavailableReason.not_released": "This provider isn't available yet.",
"imPlatform.provider.weComDescription": "Connect a WeCom application.",
"imPlatform.replacement.confirm": "Replace",
"imPlatform.replacement.description": "Replacing the active provider invalidates its IM bindings and workspace overrides. Sync the new provider directory again after replacement.",
"imPlatform.replacement.title": "Replace {{current}} with {{next}}?",
- "imPlatform.status.callback_error": "Callback error",
"imPlatform.status.configured": "Configured",
"imPlatform.status.connected": "Connected",
"imPlatform.status.connection_error": "Connection error",
- "imPlatform.status.not_configured": "Not configured",
"imPlatform.status.permission_issue": "Permission issue",
- "imPlatform.statusReason.callback_mismatch": "The provider callback URL doesn't match this workspace.",
- "imPlatform.statusReason.missing_directory_permission": "The provider app is missing directory read permission.",
- "imPlatform.statusReason.provider_request_failed": "The provider couldn't be reached. No credentials were exposed.",
- "imPlatform.sync.count.added": "Added",
- "imPlatform.sync.count.created_binding": "Binding created",
- "imPlatform.sync.count.failed": "Failed",
- "imPlatform.sync.count.matched": "Matched",
- "imPlatform.sync.count.not_matched": "Not matched",
- "imPlatform.sync.count.removed": "Removed",
- "imPlatform.sync.count.skipped": "Skipped",
- "imPlatform.sync.count.unmatched": "Unmatched",
- "imPlatform.sync.count.updated_binding": "Binding updated",
- "imPlatform.sync.description": "Sync is manual and reads the connected provider directory into Contacts matching results.",
- "imPlatform.sync.lastSynced": "Last synced {{date}} by {{user}}",
"imPlatform.sync.latestSynced": "Last synced {{date}}",
"imPlatform.sync.loading": "Checking for an active sync.",
"imPlatform.sync.noPermission": "Only workspace owners and admins can start directory sync.",
@@ -304,27 +257,13 @@
"imPlatform.sync.notConnected": "Connect and test a provider before starting directory sync.",
"imPlatform.sync.startFailed": "Directory sync couldn't be started or refreshed. Try again.",
"imPlatform.sync.status.failure": "Failed",
- "imPlatform.sync.status.partial_success": "Partial success",
"imPlatform.sync.status.queued": "Queued",
"imPlatform.sync.status.running": "Running",
"imPlatform.sync.status.success": "Success",
- "imPlatform.sync.title": "Directory sync",
- "imPlatform.sync.unsupported": "This provider doesn't support directory sync.",
"imPlatform.title": "Channels",
- "memberInviteUpgrade.confirm": "Add and upgrade",
- "memberInviteUpgrade.description_one": "This email is already used by an External Contact. Adding this member will convert the contact to a Workspace Contact. Existing workflow references and history will be preserved.",
- "memberInviteUpgrade.description_other": "{{count}} emails are already used by External Contacts. Adding these members will convert the contacts to Workspace Contacts. Existing workflow references and history will be preserved.",
- "memberInviteUpgrade.title_one": "Email already exists in Contacts",
- "memberInviteUpgrade.title_other": "Emails already exist in Contacts",
"memberRemoval.accessImpact": "{{memberName}} will immediately lose access to this workspace.",
"memberRemoval.contentImpact": "Apps and knowledge they created stay here. This action cannot be undone.",
- "memberRemoval.eeDescription": "Removing this member ends their workspace access. Choose whether to keep the same contact as a Platform contact.",
- "memberRemoval.failed": "The member couldn't be removed. Nothing has changed; try again.",
- "memberRemoval.keepPlatform": "Keep as Platform contact",
- "memberRemoval.keepPlatformDescription": "Keep this identity available in Contacts after workspace access is removed.",
"memberRemoval.remove": "Remove",
- "memberRemoval.removing": "Removing",
- "memberRemoval.standardDescription": "Removing this member also removes their workspace contact from the current Contacts directory.",
"memberRemoval.title": "Remove {{memberName}} from the workspace?",
"memberRemoval.workspaceTitle": "Remove {{memberName}} from {{workspaceName}}?",
"platformPicker.add": "Add contacts",
@@ -333,25 +272,14 @@
"platformPicker.addForbidden": "Only workspace administrators in an Enterprise deployment can add Platform contacts.",
"platformPicker.adding": "Adding",
"platformPicker.allMembers": "All Members",
- "platformPicker.backendTeam": "Backend Team",
"platformPicker.description": "Choose Platform contacts that are not already in this workspace Contacts directory.",
- "platformPicker.devTeam": "Dev Team",
"platformPicker.empty": "No available Platform contacts match this search.",
"platformPicker.error": "Platform contacts couldn't be loaded.",
- "platformPicker.externalUpgradeUnsupported": "External contacts cannot be upgraded through this action. No upgrade was performed.",
- "platformPicker.frontendTeam": "Frontend Team",
"platformPicker.loading": "Loading Platform contacts",
- "platformPicker.mobileDev": "Mobile Dev",
- "platformPicker.noExternalUpgrade": "Platform contacts are added separately. External contacts with the same email and their existing workflow references remain unchanged.",
"platformPicker.search": "Search Platform contacts",
"platformPicker.selectContact": "Select {{name}}",
"platformPicker.selected": "{{count}} selected",
"platformPicker.title": "Add from Platform",
- "platformPicker.upgrade.confirm": "Add and upgrade",
- "platformPicker.upgrade.description_one": "This email is already used by an External Contact. Adding this Platform Contact will upgrade the existing contact. Existing workflow references and history will be preserved.",
- "platformPicker.upgrade.description_other": "{{count}} emails are already used by External Contacts. Adding these Platform Contacts will upgrade the existing contacts. Existing workflow references and history will be preserved.",
- "platformPicker.upgrade.title_one": "Contact already exists",
- "platformPicker.upgrade.title_other": "Contacts already exist",
"type.external": "External",
"type.platform": "Platform",
"type.workspace": "Workspace"
diff --git a/web/i18n/locales/en-US/share.json b/web/i18n/locales/en-US/share.json
index 500ace5a8be..7d6d92f546b 100644
--- a/web/i18n/locales/en-US/share.json
+++ b/web/i18n/locales/en-US/share.json
@@ -79,7 +79,6 @@
"humanInputV2.otpPlaceholder": "Enter the 6-digit code",
"humanInputV2.requestingCode": "Sending a verification code…",
"humanInputV2.resendCode": "Resend code",
- "humanInputV2.resendIn": "Resend in {{seconds}}s",
"humanInputV2.retry": "Try again",
"humanInputV2.sendCode": "Send a new code",
"humanInputV2.unavailable": "This form is temporarily unavailable.",
diff --git a/web/i18n/locales/en-US/workflow.json b/web/i18n/locales/en-US/workflow.json
index 4d45327fd5e..607d74e74f6 100644
--- a/web/i18n/locales/en-US/workflow.json
+++ b/web/i18n/locales/en-US/workflow.json
@@ -395,6 +395,7 @@
"nodes.humanInputMigration.error.graphChanged": "The workflow changed during migration. Try again; your current edits have been kept.",
"nodes.humanInputMigration.error.preflight": "Migration could not be prepared. Your workflow was not changed. Please try again.",
"nodes.humanInputMigration.error.sync": "The migrated workflow could not be saved. Review the current draft and try again.",
+ "nodes.humanInputMigration.incompatibleVersions": "Old and new Human Input nodes cannot be used in the same workflow.",
"nodes.humanInputMigration.oldVersion": "OLD VERSION",
"nodes.humanInputMigration.preview.author": "By Dify Team",
"nodes.humanInputMigration.preview.description": "Migrate old Human Input nodes before adding a new one.",
@@ -424,6 +425,7 @@
"nodes.humanInputV2.error.recipientDuplicate": "Remove duplicate recipients",
"nodes.humanInputV2.error.recipientInvalid": "Repair invalid recipient configuration",
"nodes.humanInputV2.error.recipientRequired": "Add at least one recipient",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Couldn't verify contact recipients",
"nodes.humanInputV2.error.requestURLDuplicate": "The message body can contain only one Request URL.",
"nodes.humanInputV2.error.requestURLRequired": "Insert a Request URL in the message body.",
"nodes.humanInputV2.error.subjectRequired": "Message subject is required",
@@ -437,6 +439,7 @@
"nodes.humanInputV2.recipients.cancel": "Cancel",
"nodes.humanInputV2.recipients.chooseVariable": "Choose variable",
"nodes.humanInputV2.recipients.confirm": "Confirm",
+ "nodes.humanInputV2.recipients.contactInfo": "Contact details for {{name}}",
"nodes.humanInputV2.recipients.contactSource.all": "All",
"nodes.humanInputV2.recipients.contactSource.external": "External",
"nodes.humanInputV2.recipients.contactSource.organization": "Organization",
@@ -459,8 +462,11 @@
"nodes.humanInputV2.recipients.noResults": "No contacts found",
"nodes.humanInputV2.recipients.placeholder": "Search contacts or add emails",
"nodes.humanInputV2.recipients.remove": "Remove {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Press Backspace or Delete to remove.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} matching recipients",
"nodes.humanInputV2.recipients.search": "Search contacts",
"nodes.humanInputV2.recipients.searchPlaceholder": "Search by name or email",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} recipients selected. At the start of the input, press Left Arrow to focus them.",
"nodes.humanInputV2.recipients.title": "Recipients",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "All workspace contacts",
"nodes.humanInputV2.recipients.type.contact": "Contact",
diff --git a/web/i18n/locales/es-ES/contacts.json b/web/i18n/locales/es-ES/contacts.json
index 76fc09b2422..0c955c273da 100644
--- a/web/i18n/locales/es-ES/contacts.json
+++ b/web/i18n/locales/es-ES/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "¿Eliminar contactos ({{count}})?",
"directory.removalDescription": "Los contactos seleccionados se eliminarán permanentemente de este espacio de trabajo. Esta acción no se puede deshacer.",
- "directory.removalTitle": "¿Eliminar contactos?",
+ "directory.removalSingleDescription": "{{name}} se eliminará permanentemente de este espacio de trabajo. Esta acción no se puede deshacer.",
+ "directory.removalSingleFailed": "No se pudo eliminar el contacto. Inténtalo de nuevo.",
+ "directory.removalSingleTitle": "¿Eliminar a {{name}}?",
+ "directory.resultCount": "Resultados: {{count}}",
+ "imPlatform.action.configure": "Configurar",
+ "imPlatform.action.configureChannel": "Configurar {{provider}}",
+ "imPlatform.action.connect": "Conectar",
+ "imPlatform.action.copied": "Copiado",
+ "imPlatform.action.copyCallback": "Copiar URL de devolución de llamada",
+ "imPlatform.action.deleteChannel": "Eliminar {{provider}}",
+ "imPlatform.action.loadMore": "Cargar más",
+ "imPlatform.action.replace": "Reemplazar",
+ "imPlatform.action.retry": "Reintentar",
+ "imPlatform.action.save": "Guardar",
+ "imPlatform.action.saving": "Guardando",
+ "imPlatform.action.setupGuide": "Guía de configuración",
+ "imPlatform.action.syncNow": "Sincronizar ahora",
+ "imPlatform.action.syncing": "Sincronizando",
+ "imPlatform.action.testConnection": "Probar conexión",
+ "imPlatform.action.testing": "Probando",
+ "imPlatform.action.viewDetails": "Ver detalles",
+ "imPlatform.bindingDialog.back": "Atrás",
+ "imPlatform.bindingDialog.callback": "URL de retorno de llamada",
+ "imPlatform.bindingDialog.callbackDescription": "Completa la configuración de devoluciones de llamada en {{provider}} para habilitar las acciones de las tarjetas.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Para las acciones de las tarjetas, pega esta URL en la <console>consola de desarrolladores de Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Eventos y devoluciones de llamada → Configuración de devolución de llamada → URL de solicitud",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Para las acciones de las tarjetas, pega esta URL en la <console>consola de desarrolladores de Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Eventos y devoluciones de llamada → Configuración de devolución de llamada → URL de solicitud",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Para las acciones de las tarjetas, pega esta URL en la <console>consola de desarrolladores de Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interactividad y accesos directos → Interactividad → URL de solicitud",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Para las acciones de las tarjetas, pega esta URL en la <console>configuración de Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Ajustes → Configuración → Punto de conexión de mensajería",
+ "imPlatform.bindingDialog.callbackStep": "Configurar devoluciones de llamada",
"imPlatform.bindingDialog.clearSavedCredential": "Borrar valor guardado",
+ "imPlatform.bindingDialog.configureTitle": "Configurar {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Conectar {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Este valor guardado se borrará al guardar.",
+ "imPlatform.bindingDialog.credentialsDescription": "Primero conecta tu aplicación de {{provider}} y después configura su URL de devolución de llamada.",
+ "imPlatform.bindingDialog.credentialsStep": "Credenciales de la aplicación",
+ "imPlatform.bindingDialog.description": "Introduce las credenciales de la aplicación de este proveedor de mensajería instantánea.",
+ "imPlatform.bindingDialog.field.agentId": "ID del agente",
+ "imPlatform.bindingDialog.field.appId": "ID de la aplicación",
+ "imPlatform.bindingDialog.field.appToken": "Token de la aplicación (opcional)",
+ "imPlatform.bindingDialog.field.botToken": "Token del bot",
+ "imPlatform.bindingDialog.field.clientId": "ID del Cliente",
+ "imPlatform.bindingDialog.field.clientSecret": "Secreto del Cliente",
+ "imPlatform.bindingDialog.field.corpId": "ID de la empresa",
+ "imPlatform.bindingDialog.field.encryptKey": "Clave de cifrado (opcional)",
+ "imPlatform.bindingDialog.field.genericSecret": "Secreto",
+ "imPlatform.bindingDialog.field.secret": "Secreto de la aplicación",
+ "imPlatform.bindingDialog.field.signingSecret": "Secreto de firma",
+ "imPlatform.bindingDialog.field.tenantId": "ID del inquilino",
+ "imPlatform.bindingDialog.field.verificationToken": "Token de verificación (opcional)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Introduce la clave de cifrado, si está habilitada",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Introduce el secreto de la aplicación",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Introduce el token de verificación, si está configurado",
+ "imPlatform.bindingDialog.finish": "Finalizar",
+ "imPlatform.bindingDialog.freshCredentials": "Los secretos guardados no se pueden recuperar. Vuelve a introducir todas las credenciales necesarias para probar o guardar esta configuración.",
+ "imPlatform.bindingDialog.openSetupGuide": "Abrir guía de configuración",
+ "imPlatform.bindingDialog.replaceTenantTitle": "¿Reemplazar las credenciales del inquilino de {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Estas credenciales pertenecen a otro tenant de IM y no se pueden guardar directamente. Para cambiar de tenant, debes reemplazar el canal de IM actual, lo que elimina todas las vinculaciones de IM automáticas y manuales. Vuelve a sincronizar los contactos después del reemplazo.",
+ "imPlatform.bindingDialog.required": "Este campo es obligatorio.",
+ "imPlatform.bindingDialog.saveAndContinue": "Guardar y continuar",
+ "imPlatform.bindingDialog.saveFailed": "No se pudo guardar la configuración. Revisa los campos e inténtalo de nuevo.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "La configuración se ha guardado, pero no se han podido cargar sus detalles. Cierra este diálogo y vuelve a abrirlo.",
- "imPlatform.bindingDialog.undoClearCredential": "Deshacer borrado"
+ "imPlatform.bindingDialog.secretConfigured": "Ya hay un secreto configurado. Deja este campo vacío para conservarlo.",
+ "imPlatform.bindingDialog.step": "Paso {{step}}",
+ "imPlatform.bindingDialog.testFailed": "La prueba de conexión falló. Revisa la configuración e inténtalo de nuevo.",
+ "imPlatform.bindingDialog.undoClearCredential": "Deshacer borrado",
+ "imPlatform.bindingDialog.viewSetupGuide": "Ver guía de configuración",
+ "imPlatform.chooseProvider": "Elige un canal para conectar",
+ "imPlatform.configurationUpdated": "La configuración de este canal ha cambiado. Cierra este diálogo y actualiza la página antes de intentarlo de nuevo.",
+ "imPlatform.connectMore": "Conectar más canales",
+ "imPlatform.delete.confirm": "Eliminar",
+ "imPlatform.delete.description": "Al eliminar este canal se borra su configuración. Se detendrán las notificaciones de aprobación y la sincronización del directorio que lo utilicen.",
+ "imPlatform.delete.failed": "No se pudo eliminar el canal. No se ha cambiado nada; inténtalo de nuevo.",
+ "imPlatform.delete.title": "¿Eliminar el canal {{provider}}?",
+ "imPlatform.description": "Conecta los canales de tu empresa para que las solicitudes de aprobación lleguen a las personas donde trabajan.",
+ "imPlatform.details.column.contact": "Contactos",
+ "imPlatform.details.column.platform": "Plataforma de mensajería instantánea",
+ "imPlatform.details.description": "Consulta los resultados de solo lectura de la última sincronización.",
+ "imPlatform.details.downloadFailed": "No se pudo descargar el informe. Inténtalo de nuevo.",
+ "imPlatform.details.downloadReport": "Descargar informe",
+ "imPlatform.details.downloadingReport": "Descargando informe…",
+ "imPlatform.details.empty": "No hay resultados en esta categoría.",
+ "imPlatform.details.filter.added": "Agregado",
+ "imPlatform.details.filter.failed": "Fallida",
+ "imPlatform.details.filter.not_matched": "Sin coincidencia",
+ "imPlatform.details.filter.removed": "Eliminado",
+ "imPlatform.details.filter.skipped": "Omitido",
+ "imPlatform.details.filters": "Filtros de resultados de sincronización",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "No se pudieron cargar los detalles de sincronización.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "No se pudieron cargar más resultados. Vuelve a intentar cargar esta página.",
+ "imPlatform.details.removalReason.binding_invalidated": "Vínculo invalidado",
+ "imPlatform.details.removalReason.binding_replaced": "Vínculo reemplazado",
+ "imPlatform.details.removalReason.not_present_in_directory": "Ya no está en el directorio",
+ "imPlatform.details.reportChanged": "Los resultados de sincronización han cambiado. Vuelve a abrir los detalles de la última sincronización e inténtalo de nuevo.",
+ "imPlatform.details.title": "Detalles de sincronización",
+ "imPlatform.email.apiKey": "Clave de API",
+ "imPlatform.email.apiKeyConfigured": "Por motivos de seguridad, no se puede ver la clave API guardada. Deja este campo vacío para conservarla.",
+ "imPlatform.email.apiKeyDescription": "Por motivos de seguridad, esta clave API no se puede ver después de guardarla.",
+ "imPlatform.email.apiKeyPlaceholder": "Introduce tu clave API de Resend",
+ "imPlatform.email.description": "Esta configuración se aplica a todos los nodos de intervención humana de este espacio de trabajo que tengan activada la opción <emphasis>Enviar notificaciones de depuración por correo electrónico</emphasis>.",
+ "imPlatform.email.invalidEmail": "Introduce una dirección de correo electrónico válida.",
+ "imPlatform.email.provider": "Proveedor de correo electrónico",
+ "imPlatform.email.resendDescription": "Tu <apiKey>clave API de Resend</apiKey> se cifrará y no se podrá ver después de guardarla.<br/>Registra una cuenta de <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Configuración de Resend",
+ "imPlatform.email.senderEmail": "Dirección de correo del remitente",
+ "imPlatform.email.senderEmailDescription": "La dirección de correo que se muestra como remitente. Su dominio debe estar verificado en Resend.",
+ "imPlatform.email.senderName": "Nombre del remitente",
+ "imPlatform.email.senderNameDescription": "Nombre que aparece en la bandeja de entrada del destinatario.",
+ "imPlatform.email.testSucceeded": "Prueba de conexión completada correctamente.",
+ "imPlatform.email.title": "Configurar correo electrónico",
+ "imPlatform.learnMore": "Más información",
+ "imPlatform.loadError.description": "Inténtalo de nuevo para consultar la vinculación actual y los permisos.",
+ "imPlatform.loadError.retry": "Intentar de nuevo",
+ "imPlatform.loadError.title": "No se pudieron cargar los canales",
+ "imPlatform.loading": "Cargando canales",
+ "imPlatform.provider.dingtalkDescription": "Conecta una aplicación DingTalk.",
+ "imPlatform.provider.emailDescription": "Configura el servicio de correo utilizado para enviar solicitudes de aprobación desde este espacio de trabajo.",
+ "imPlatform.provider.feishuDescription": "Conecta una aplicación Feishu.",
+ "imPlatform.provider.larkDescription": "Conecta una aplicación Lark.",
+ "imPlatform.provider.msTeamsDescription": "Conecta una aplicación Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Sincroniza las personas y sus identidades de Slack.",
+ "imPlatform.provider.weComDescription": "Conecta una aplicación WeCom.",
+ "imPlatform.replacement.confirm": "Reemplazar",
+ "imPlatform.replacement.description": "Al reemplazar el proveedor activo, se invalidan sus vinculaciones de mensajería instantánea y las personalizaciones del espacio de trabajo. Después, vuelve a sincronizar el directorio del nuevo proveedor.",
+ "imPlatform.replacement.title": "¿Reemplazar {{current}} por {{next}}?",
+ "imPlatform.status.configured": "Configurado",
+ "imPlatform.status.connected": "Conectado",
+ "imPlatform.status.connection_error": "Error de conexión",
+ "imPlatform.status.permission_issue": "Problema de permisos",
+ "imPlatform.sync.latestSynced": "Última sincronización: {{date}}",
+ "imPlatform.sync.loading": "Buscando una sincronización activa.",
+ "imPlatform.sync.noPermission": "Solo los propietarios y administradores del espacio de trabajo pueden iniciar la sincronización del directorio.",
+ "imPlatform.sync.noRuns": "Todavía no se ha ejecutado ninguna sincronización del directorio.",
+ "imPlatform.sync.notConnected": "Conecta un proveedor y prueba la conexión antes de iniciar la sincronización del directorio.",
+ "imPlatform.sync.startFailed": "No se pudo iniciar o actualizar la sincronización del directorio. Inténtalo de nuevo.",
+ "imPlatform.sync.status.failure": "Fallida",
+ "imPlatform.sync.status.queued": "En cola",
+ "imPlatform.sync.status.running": "En ejecución",
+ "imPlatform.sync.status.success": "Correcto",
+ "imPlatform.title": "Canales"
}
diff --git a/web/i18n/locales/es-ES/share.json b/web/i18n/locales/es-ES/share.json
index 3d6268bc3bc..9f791774049 100644
--- a/web/i18n/locales/es-ES/share.json
+++ b/web/i18n/locales/es-ES/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "¡Gracias!",
"humanInput.unavailableDescription": "Es posible que el enlace no esté disponible o no corresponda a la cuenta con la que has iniciado sesión. Abre el formulario desde la notificación que recibiste o intenta cambiar de cuenta.",
"humanInput.unavailableTitle": "No se puede abrir este formulario",
+ "humanInputV2.accessRateLimited": "Se han solicitado demasiados correos de verificación. Inténtalo de nuevo más tarde.",
+ "humanInputV2.alreadySubmitted": "Esta solicitud ya se ha completado.",
+ "humanInputV2.challengeExpired": "Este código de verificación ha caducado. Solicita uno nuevo para continuar.",
+ "humanInputV2.challengeStale": "Este código de verificación se ha sustituido. Solicita uno nuevo para continuar.",
+ "humanInputV2.codeExpiresIn": "El código caduca en {{seconds}} s",
+ "humanInputV2.codeRequired": "Solicita un código de verificación para continuar.",
+ "humanInputV2.codeSent": "Se ha enviado un código de verificación a tu correo.",
+ "humanInputV2.deliveryFailed": "No se pudo enviar el correo de verificación. Inténtalo de nuevo.",
+ "humanInputV2.formExpired": "Esta solicitud ha caducado.",
+ "humanInputV2.formNotFound": "No se ha encontrado el formulario.",
+ "humanInputV2.formRateLimited": "Demasiadas solicitudes de formulario. Inténtalo de nuevo más tarde.",
+ "humanInputV2.invalidOtp": "El código de verificación es incorrecto. Compruébalo e inténtalo de nuevo.",
+ "humanInputV2.networkError": "No se pudo completar la solicitud. Comprueba tu conexión e inténtalo de nuevo.",
+ "humanInputV2.otpLabel": "Código de verificación por correo",
+ "humanInputV2.otpPlaceholder": "Introduce el código de 6 dígitos",
+ "humanInputV2.requestingCode": "Enviando un código de verificación…",
+ "humanInputV2.resendCode": "Reenviar código",
+ "humanInputV2.retry": "Intentar de nuevo",
+ "humanInputV2.sendCode": "Enviar un código nuevo",
+ "humanInputV2.unavailable": "Este formulario no está disponible temporalmente.",
+ "humanInputV2.unknownError": "Se ha producido un error. Inténtalo de nuevo.",
+ "humanInputV2.uploadFailed": "No se pudo subir el archivo. Inténtalo de nuevo.",
"login.backToHome": "Volver a Inicio"
}
diff --git a/web/i18n/locales/es-ES/workflow-human-input.json b/web/i18n/locales/es-ES/workflow-human-input.json
index cb3ac1e4f14..5fb3a128450 100644
--- a/web/i18n/locales/es-ES/workflow-human-input.json
+++ b/web/i18n/locales/es-ES/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Valor de la Acción",
"nodes.humanInput.userActions.buttonTextTooLong": "El texto del botón debe tener {{maxLength}} caracteres o menos",
"nodes.humanInput.userActions.chooseStyle": "Elija un estilo de botón",
+ "nodes.humanInput.userActions.defaultTitle": "Texto del botón {{index}}",
"nodes.humanInput.userActions.emptyTip": "Haga clic en el botón '+' para agregar acciones del usuario",
"nodes.humanInput.userActions.title": "Acciones del Usuario",
"nodes.humanInput.userActions.tooltip": "Defina botones en los que los usuarios puedan hacer clic para responder a este formulario. El ID de acción controla la ramificación. El Valor de la Acción se expone aguas abajo como la salida integrada seleccionada. El ID de acción debe comenzar con una letra o guiones bajos, seguido de letras, números o guiones bajos.",
diff --git a/web/i18n/locales/es-ES/workflow.json b/web/i18n/locales/es-ES/workflow.json
index 7f2303cb1cf..3caf00687fe 100644
--- a/web/i18n/locales/es-ES/workflow.json
+++ b/web/i18n/locales/es-ES/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Salida",
"blocks.http-request": "Solicitud HTTP",
"blocks.human-input": "Entrada Humana",
+ "blocks.human-input-v2": "Entrada Humana v2",
"blocks.if-else": "SI/SINO",
"blocks.iteration": "Iteración",
"blocks.iteration-start": "Inicio de iteración",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Define la salida y el tipo de resultado de un flujo de trabajo",
"blocksAbout.http-request": "Permite enviar solicitudes al servidor a través del protocolo HTTP",
"blocksAbout.human-input": "Solicitar confirmación humana antes de generar el siguiente paso",
+ "blocksAbout.human-input-v2": "Solicitar datos a los contactos configurados, destinatarios de correo o al iniciador del flujo de trabajo",
"blocksAbout.if-else": "Te permite dividir el flujo de trabajo en dos ramas basadas en condiciones SI/SINO",
"blocksAbout.iteration": "Realiza múltiples pasos en un objeto de lista hasta que se generen todos los resultados.",
"blocksAbout.iteration-start": "Nodo de inicio de iteración",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Agrega variables de múltiples ramas en una sola variable para configurar de manera unificada los nodos descendentes.",
"blocksAbout.variable-assigner": "Agrega variables de múltiples ramas en una sola variable para configurar de manera unificada los nodos descendentes.",
"changeHistory.edgeDelete": "Nodo desconectado",
+ "changeHistory.humanInputMigration": "Nodos de Entrada Humana migrados",
"changeHistory.nodeAdd": "Nodo añadido",
"changeHistory.nodeChange": "Nodo cambiado",
"changeHistory.nodeConnect": "Nodo conectado",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Active al menos un método de entrega",
"nodes.humanInput.errorMsg.noUserActions": "Agregue al menos una acción del usuario",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} está reservado para la rama de tiempo de espera. Elige otro ID de acción.",
+ "nodes.humanInput.output.actionId": "ID de la acción activada por el usuario",
+ "nodes.humanInput.output.actionValue": "Valor de la acción seleccionada",
+ "nodes.humanInput.output.formInput": "Valor introducido en el formulario",
+ "nodes.humanInput.output.renderedContent": "Contenido renderizado",
"nodes.humanInput.timeout.title": "Tiempo de Espera",
+ "nodes.humanInputMigration.action.migrate": "Migrar",
+ "nodes.humanInputMigration.action.migrateNow": "Migrar ahora",
+ "nodes.humanInputMigration.action.migrating": "Migrando...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Aviso de migración de Entrada Humana",
+ "nodes.humanInputMigration.banner.description": "Este flujo de trabajo usa el nodo antiguo de Entrada Humana. Migra todos los nodos antiguos antes de añadir nuevos.",
+ "nodes.humanInputMigration.banner.learnMore": "Más información",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "un método de entrega desactivado todavía contiene configuración",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "los métodos de correo activados usan plantillas incompatibles entre sí",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Valor predeterminado no válido",
+ "nodes.humanInputMigration.blocker.invalidEmail": "el correo de un destinatario no es válido",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "un método de correo activado está incompleto",
+ "nodes.humanInputMigration.blocker.missingRecipients": "el nodo no tiene destinatarios compatibles",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "no se puede asociar un miembro del espacio de trabajo con un contacto o un correo verificado",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "Human Input v2 no admite un método de entrega activado",
"nodes.humanInputMigration.blocker.unsupportedInputType": "El campo {{field}} aún no se puede migrar. Puedes seguir utilizando los nodos de entrada humana antiguos.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "el nodo tiene un valor de versión no compatible",
+ "nodes.humanInputMigration.dialog.description": "Se conservarán tus destinatarios, el formulario y las acciones.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Solo cambia este borrador. Las versiones publicadas seguirán ejecutándose hasta que vuelvas a publicar.",
+ "nodes.humanInputMigration.dialog.review": "Revisa los nodos y publica cuando esté todo listo.",
+ "nodes.humanInputMigration.dialog.title": "Migrar {{count}} nodos de Entrada Humana",
+ "nodes.humanInputMigration.disabledBadge": "MIGRACIÓN NECESARIA",
+ "nodes.humanInputMigration.disabledReason": "Migra los nodos antiguos de Entrada Humana antes de añadir uno nuevo.",
+ "nodes.humanInputMigration.error.blocked": "No se pudo migrar {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "El flujo de trabajo cambió durante la migración. Inténtalo de nuevo; se han conservado tus cambios actuales.",
+ "nodes.humanInputMigration.error.preflight": "No se pudo preparar la migración. Tu flujo de trabajo no ha cambiado. Inténtalo de nuevo.",
"nodes.humanInputMigration.error.sync": "No se pudo guardar el flujo de trabajo migrado. Revisa el borrador actual e inténtalo de nuevo.",
+ "nodes.humanInputMigration.incompatibleVersions": "Los nodos de entrada humana antiguos y nuevos no pueden usarse en el mismo flujo de trabajo.",
+ "nodes.humanInputMigration.oldVersion": "VERSIÓN ANTIGUA",
+ "nodes.humanInputMigration.preview.author": "Por el equipo de Dify",
+ "nodes.humanInputMigration.preview.description": "Migra los nodos antiguos de Entrada Humana antes de añadir uno nuevo.",
+ "nodes.humanInputMigration.success": "Nodos de Entrada Humana migrados correctamente",
+ "nodes.humanInputV2.card.configured": "{{count}} destinatarios configurados",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} contactos",
+ "nodes.humanInputV2.card.empty": "Todavía nadie puede aprobar este paso",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Iniciador y {{count}} contactos",
+ "nodes.humanInputV2.card.initiatorOnly": "Solo el iniciador",
+ "nodes.humanInputV2.card.invalid": "Revisa la configuración de destinatarios",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "Correo electrónico",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Configurar el modo de depuración",
"nodes.humanInputV2.debug.keepOneChannel": "Mantén al menos un canal activado",
+ "nodes.humanInputV2.debug.sendVia": "Enviar notificaciones de depuración a través de",
+ "nodes.humanInputV2.debug.title": "Modo de depuración",
+ "nodes.humanInputV2.debug.toggle": "Activar el modo de depuración",
+ "nodes.humanInputV2.debug.unsupported": "Canales importados no compatibles: {{channels}}. Elimínalos o actualízalos antes de ejecutar este flujo de trabajo.",
"nodes.humanInputV2.disabled": "Human Input v2 no está disponible mientras HITL IM esté desactivado.",
+ "nodes.humanInputV2.error.bodyRequired": "El cuerpo del mensaje es obligatorio",
+ "nodes.humanInputV2.error.debugChannelRequired": "Selecciona al menos un canal del modo de depuración",
+ "nodes.humanInputV2.error.recipientDuplicate": "Elimina los destinatarios duplicados",
+ "nodes.humanInputV2.error.recipientInvalid": "Corrige la configuración de destinatarios no válida",
+ "nodes.humanInputV2.error.recipientRequired": "Añade al menos un destinatario",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "No se pudieron verificar los destinatarios de contactos",
"nodes.humanInputV2.error.requestURLDuplicate": "El cuerpo del mensaje solo puede contener una URL de solicitud.",
"nodes.humanInputV2.error.requestURLRequired": "Inserte una URL de solicitud en el cuerpo del mensaje.",
+ "nodes.humanInputV2.error.subjectRequired": "El asunto del mensaje es obligatorio",
+ "nodes.humanInputV2.error.version": "Human Input v2 requiere el valor de versión 2 como cadena de texto",
+ "nodes.humanInputV2.recipients.addContact": "Añadir contacto",
+ "nodes.humanInputV2.recipients.addEmail": "Añadir",
+ "nodes.humanInputV2.recipients.addRecipient": "Añadir destinatario",
+ "nodes.humanInputV2.recipients.added": "Añadido",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Todos los contactos del espacio de trabajo",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Notificar a todos los contactos del espacio de trabajo; cualquiera de ellos puede aprobar",
+ "nodes.humanInputV2.recipients.cancel": "Cancelar",
+ "nodes.humanInputV2.recipients.chooseVariable": "Elegir variable",
+ "nodes.humanInputV2.recipients.confirm": "Confirmar",
+ "nodes.humanInputV2.recipients.contactInfo": "Datos de contacto de {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Todos",
+ "nodes.humanInputV2.recipients.contactSource.external": "Externo",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organización",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Espacio de trabajo",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Origen del contacto",
"nodes.humanInputV2.recipients.duplicateSource": "Ya se ha añadido a través de {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Editar {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Editar destinatario",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Cada dirección de correo solo se puede seleccionar una vez.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Introduce un correo válido que no se haya añadido ya",
+ "nodes.humanInputV2.recipients.emailLabel": "Destinatario de correo de un solo uso",
+ "nodes.humanInputV2.recipients.empty": "No hay destinatarios configurados",
+ "nodes.humanInputV2.recipients.help": "Elige quién puede responder a este paso de Entrada Humana.",
"nodes.humanInputV2.recipients.initiator": "El usuario que inicia esta ejecución a través de Web App o CLI puede aprobar",
+ "nodes.humanInputV2.recipients.initiatorDescription": "La persona que inicia esta ejecución del flujo de trabajo puede responder.",
"nodes.humanInputV2.recipients.inputHelp": "Escribe o pega varias direcciones de correo separadas por comas. Pulsa / para insertar una variable.",
+ "nodes.humanInputV2.recipients.insertVariable": "Insertar variable",
+ "nodes.humanInputV2.recipients.loadError": "No se pudieron cargar los contactos. Se conservan los ID de contacto guardados.",
+ "nodes.humanInputV2.recipients.loading": "Cargando contactos…",
+ "nodes.humanInputV2.recipients.noResults": "No se encontraron contactos",
+ "nodes.humanInputV2.recipients.placeholder": "Buscar contactos o añadir correos",
+ "nodes.humanInputV2.recipients.remove": "Eliminar {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Pulsa Retroceso o Supr para eliminar.",
+ "nodes.humanInputV2.recipients.resultCount": "Destinatarios coincidentes: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Buscar contactos",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Buscar por nombre o correo",
+ "nodes.humanInputV2.recipients.selectionHint": "Destinatarios seleccionados: {{count}}. Al inicio del campo, pulsa la flecha izquierda para enfocarlos.",
+ "nodes.humanInputV2.recipients.title": "Destinatarios",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Todos los contactos del espacio de trabajo",
+ "nodes.humanInputV2.recipients.type.contact": "Contacto",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Correo dinámico",
+ "nodes.humanInputV2.recipients.type.initiator": "Iniciador",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Correo de un solo uso",
+ "nodes.humanInputV2.recipients.typeLabel": "Tipo de destinatario",
"nodes.humanInputV2.recipients.useThisInstead": "Usar este en su lugar",
+ "nodes.humanInputV2.recipients.variableRequired": "Elige una variable de correo",
+ "nodes.humanInputV2.template.body": "Cuerpo",
+ "nodes.humanInputV2.template.description": "Texto alternativo para correo y mensajería instantánea",
"nodes.humanInputV2.template.insertRequestURL": "Insertar URL de solicitud",
+ "nodes.humanInputV2.template.insertVariable": "Insertar variable",
+ "nodes.humanInputV2.template.notConfigured": "Sin configurar",
"nodes.humanInputV2.template.requestURLHint": "Los destinatarios usan este enlace para abrir el formulario de aprobación. Incluya exactamente una URL de solicitud.",
"nodes.humanInputV2.template.requestURLInserted": "URL de solicitud insertada",
"nodes.humanInputV2.template.saveAndTest": "Guardar y probar",
+ "nodes.humanInputV2.template.subject": "Asunto",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Introduce el asunto del mensaje",
"nodes.humanInputV2.template.test": "Probar mensaje",
"nodes.humanInputV2.template.testChannel": "Canal de prueba",
"nodes.humanInputV2.template.testCompleted": "La solicitud de prueba se ha completado. Revisa el canal seleccionado para ver el mensaje.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Introduce todos los valores de las variables de prueba.",
"nodes.humanInputV2.template.testSaveFailed": "No se pudo guardar el borrador del flujo de trabajo. La prueba no se ha enviado.",
"nodes.humanInputV2.template.testUnavailable": "Este entorno aún no admite pruebas de plantillas de mensajes.",
+ "nodes.humanInputV2.template.title": "Plantilla del mensaje",
"nodes.ifElse.operator": "Operador",
"nodes.iteration.currentIteration": "Iteración actual",
"nodes.iteration.deleteDesc": "Eliminar el nodo de iteración eliminará todos los nodos secundarios",
diff --git a/web/i18n/locales/fa-IR/contacts.json b/web/i18n/locales/fa-IR/contacts.json
index d3e320d6a21..c3429c56d7f 100644
--- a/web/i18n/locales/fa-IR/contacts.json
+++ b/web/i18n/locales/fa-IR/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "مخاطبین حذف شوند ({{count}})؟",
"directory.removalDescription": "مخاطبان انتخاب‌شده برای همیشه از این فضای کاری حذف می‌شوند. این عمل قابل بازگشت نیست.",
- "directory.removalTitle": "مخاطبان حذف شوند؟",
+ "directory.removalSingleDescription": "{{name}} برای همیشه از این فضای کاری حذف خواهد شد. این اقدام قابل بازگشت نیست.",
+ "directory.removalSingleFailed": "مخاطب حذف نشد. دوباره تلاش کنید.",
+ "directory.removalSingleTitle": "{{name}} حذف شود؟",
+ "directory.resultCount": "نتایج: {{count}}",
+ "imPlatform.action.configure": "پیکربندی",
+ "imPlatform.action.configureChannel": "{{provider}} را پیکربندی کنید",
+ "imPlatform.action.connect": "اتصال",
+ "imPlatform.action.copied": "کپی",
+ "imPlatform.action.copyCallback": "کپی نشانی فراخوان بازگشتی",
+ "imPlatform.action.deleteChannel": "حذف {{provider}}",
+ "imPlatform.action.loadMore": "بارگذاری بیشتر",
+ "imPlatform.action.replace": "جایگزین کنید",
+ "imPlatform.action.retry": "تلاش مجدد",
+ "imPlatform.action.save": "ذخیره کنید",
+ "imPlatform.action.saving": "در حال ذخیره",
+ "imPlatform.action.setupGuide": "راهنمای راه‌اندازی",
+ "imPlatform.action.syncNow": "اکنون همگام سازی کنید",
+ "imPlatform.action.syncing": "در حال همگام‌سازی",
+ "imPlatform.action.testConnection": "آزمایش اتصال",
+ "imPlatform.action.testing": "در حال آزمایش",
+ "imPlatform.action.viewDetails": "مشاهده جزئیات",
+ "imPlatform.bindingDialog.back": "بازگشت",
+ "imPlatform.bindingDialog.callback": "آدرس بازگشت تماس",
+ "imPlatform.bindingDialog.callbackDescription": "برای فعال‌سازی عملکردهای کارت، راه‌اندازی فراخوان بازگشتی را در {{provider}} تکمیل کنید.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "برای عملکردهای کارت، این نشانی را در <console>کنسول توسعه‌دهندگان Feishu</console> جای‌گذاری کنید:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "رویدادها و فراخوان‌های بازگشتی → پیکربندی فراخوان بازگشتی → نشانی درخواست",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "برای عملکردهای کارت، این نشانی را در <console>کنسول توسعه‌دهندگان Lark</console> جای‌گذاری کنید:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "رویدادها و فراخوان‌های بازگشتی → پیکربندی فراخوان بازگشتی → نشانی درخواست",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "برای عملکردهای کارت، این نشانی را در <console>کنسول توسعه‌دهندگان Slack</console> جای‌گذاری کنید:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "تعامل و میان‌برها → تعامل → نشانی درخواست",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "برای عملکردهای کارت، این نشانی را در <console>پیکربندی Azure Bot</console> جای‌گذاری کنید:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "تنظیمات → پیکربندی → نقطه پایانی پیام‌رسانی",
+ "imPlatform.bindingDialog.callbackStep": "پیکربندی فراخوان‌های بازگشتی",
"imPlatform.bindingDialog.clearSavedCredential": "پاک کردن مقدار ذخیره‌شده",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} را پیکربندی کنید",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}} را وصل کنید",
"imPlatform.bindingDialog.credentialWillBeCleared": "این مقدار ذخیره‌شده هنگام ذخیره پاک خواهد شد.",
+ "imPlatform.bindingDialog.credentialsDescription": "ابتدا برنامه {{provider}} را متصل کنید، سپس نشانی فراخوان بازگشتی آن را پیکربندی کنید.",
+ "imPlatform.bindingDialog.credentialsStep": "اطلاعات احراز هویت برنامه",
+ "imPlatform.bindingDialog.description": "اطلاعات احراز هویت برنامه این ارائه‌دهنده پیام‌رسانی را وارد کنید.",
+ "imPlatform.bindingDialog.field.agentId": "شناسه عامل",
+ "imPlatform.bindingDialog.field.appId": "شناسه برنامه",
+ "imPlatform.bindingDialog.field.appToken": "توکن برنامه (اختیاری)",
+ "imPlatform.bindingDialog.field.botToken": "توکن ربات",
+ "imPlatform.bindingDialog.field.clientId": "شناسه مشتری",
+ "imPlatform.bindingDialog.field.clientSecret": "رمز مشتری",
+ "imPlatform.bindingDialog.field.corpId": "شناسه شرکت",
+ "imPlatform.bindingDialog.field.encryptKey": "کلید رمزنگاری (اختیاری)",
+ "imPlatform.bindingDialog.field.genericSecret": "محرمانه",
+ "imPlatform.bindingDialog.field.secret": "رمز برنامه",
+ "imPlatform.bindingDialog.field.signingSecret": "رمز امضا",
+ "imPlatform.bindingDialog.field.tenantId": "شناسه مستأجر",
+ "imPlatform.bindingDialog.field.verificationToken": "توکن تأیید (اختیاری)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "اگر فعال است، کلید رمزنگاری را وارد کنید",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "رمز برنامه را وارد کنید",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "اگر پیکربندی شده است، توکن تأیید را وارد کنید",
+ "imPlatform.bindingDialog.finish": "پایان",
+ "imPlatform.bindingDialog.freshCredentials": "رمزهای ذخیره‌شده قابل بازیابی نیستند. برای آزمایش یا ذخیره این پیکربندی، تمام اطلاعات احراز هویت ضروری را دوباره وارد کنید.",
+ "imPlatform.bindingDialog.openSetupGuide": "باز کردن راهنمای راه‌اندازی",
+ "imPlatform.bindingDialog.replaceTenantTitle": "اطلاعات ورود مستأجر برای {{identity}} جایگزین شود؟",
"imPlatform.bindingDialog.replacementRequired": "این اطلاعات ورود به یک مستأجر IM دیگر تعلق دارد و نمی‌توان آن را مستقیماً ذخیره کرد. برای تغییر مستأجر باید کانال IM فعلی جایگزین شود؛ این کار همهٔ پیوندهای خودکار و دستی IM را پاک می‌کند. پس از جایگزینی، مخاطبان را دوباره همگام‌سازی کنید.",
+ "imPlatform.bindingDialog.required": "این فیلد الزامی است.",
+ "imPlatform.bindingDialog.saveAndContinue": "ذخیره و ادامه",
+ "imPlatform.bindingDialog.saveFailed": "پیکربندی ذخیره نشد. فیلدها را بررسی کرده و دوباره تلاش کنید.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "پیکربندی ذخیره شد، اما جزئیات آن بارگیری نشد. این پنجره را ببندید و دوباره باز کنید.",
- "imPlatform.bindingDialog.undoClearCredential": "لغو پاک کردن"
+ "imPlatform.bindingDialog.secretConfigured": "رمزی از قبل پیکربندی شده است. برای حفظ آن، این فیلد را خالی بگذارید.",
+ "imPlatform.bindingDialog.step": "مرحله {{step}}",
+ "imPlatform.bindingDialog.testFailed": "آزمایش اتصال ناموفق بود. پیکربندی را بررسی کرده و دوباره تلاش کنید.",
+ "imPlatform.bindingDialog.undoClearCredential": "لغو پاک کردن",
+ "imPlatform.bindingDialog.viewSetupGuide": "مشاهده راهنمای راه‌اندازی",
+ "imPlatform.chooseProvider": "یک کانال برای اتصال انتخاب کنید",
+ "imPlatform.configurationUpdated": "پیکربندی این کانال تغییر کرده است. پیش از تلاش دوباره، این پنجره را ببندید و صفحه را تازه‌سازی کنید.",
+ "imPlatform.connectMore": "اتصال کانال‌های بیشتر",
+ "imPlatform.delete.confirm": "حذف کنید",
+ "imPlatform.delete.description": "حذف این کانال، پیکربندی آن را پاک می‌کند. اعلان‌های تأیید و همگام‌سازی فهرست مخاطبانی که از آن استفاده می‌کنند متوقف می‌شوند.",
+ "imPlatform.delete.failed": "کانال حذف نشد. چیزی تغییر نکرده است؛ دوباره تلاش کنید.",
+ "imPlatform.delete.title": "کانال {{provider}} حذف شود؟",
+ "imPlatform.description": "کانال‌های شرکت را متصل کنید تا درخواست‌های تأیید در محل کار افراد به آن‌ها برسد.",
+ "imPlatform.details.column.contact": "مخاطبین",
+ "imPlatform.details.column.platform": "پلتفرم پیام‌رسانی",
+ "imPlatform.details.description": "نتایج فقط‌خواندنی آخرین همگام‌سازی را مشاهده کنید.",
+ "imPlatform.details.downloadFailed": "گزارش دانلود نشد. دوباره تلاش کنید.",
+ "imPlatform.details.downloadReport": "دانلود گزارش",
+ "imPlatform.details.downloadingReport": "در حال دانلود گزارش…",
+ "imPlatform.details.empty": "نتیجه‌ای در این دسته وجود ندارد.",
+ "imPlatform.details.filter.added": "اضافه شد",
+ "imPlatform.details.filter.failed": "ناموفق",
+ "imPlatform.details.filter.not_matched": "بدون تطبیق",
+ "imPlatform.details.filter.removed": "حذف شد",
+ "imPlatform.details.filter.skipped": "رد شده",
+ "imPlatform.details.filters": "فیلترهای نتایج همگام‌سازی",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "جزئیات همگام‌سازی بارگیری نشد.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "نتایج بیشتری بارگیری نشد. این صفحه را دوباره امتحان کنید.",
+ "imPlatform.details.removalReason.binding_invalidated": "پیوند نامعتبر شد",
+ "imPlatform.details.removalReason.binding_replaced": "پیوند جایگزین شد",
+ "imPlatform.details.removalReason.not_present_in_directory": "دیگر در فهرست نیست",
+ "imPlatform.details.reportChanged": "نتایج همگام‌سازی تغییر کرده‌اند. جزئیات آخرین همگام‌سازی را دوباره باز کرده و تلاش کنید.",
+ "imPlatform.details.title": "جزئیات همگام‌سازی",
+ "imPlatform.email.apiKey": "کلید API",
+ "imPlatform.email.apiKeyConfigured": "به دلایل امنیتی، کلید API ذخیره‌شده قابل مشاهده نیست. برای حفظ آن، این فیلد را خالی بگذارید.",
+ "imPlatform.email.apiKeyDescription": "به دلایل امنیتی، این کلید API پس از ذخیره قابل مشاهده نیست.",
+ "imPlatform.email.apiKeyPlaceholder": "کلید API مربوط به Resend را وارد کنید",
+ "imPlatform.email.description": "این پیکربندی برای تمام گره‌های ورودی انسانی این فضای کاری که گزینه <emphasis>ارسال اعلان‌های اشکال‌زدایی از طریق ایمیل</emphasis> در آن‌ها فعال است، اعمال می‌شود.",
+ "imPlatform.email.invalidEmail": "یک نشانی ایمیل معتبر وارد کنید.",
+ "imPlatform.email.provider": "ارائه‌دهنده ایمیل",
+ "imPlatform.email.resendDescription": "<apiKey>کلید API مربوط به Resend</apiKey> رمزنگاری می‌شود و پس از ذخیره قابل مشاهده نخواهد بود.<br/>یک حساب <resend>Resend</resend> بسازید.",
+ "imPlatform.email.resendSettings": "تنظیمات Resend",
+ "imPlatform.email.senderEmail": "نشانی ایمیل فرستنده",
+ "imPlatform.email.senderEmailDescription": "نشانی ایمیلی که به عنوان فرستنده نمایش داده می‌شود. دامنه آن باید در Resend تأیید شده باشد.",
+ "imPlatform.email.senderName": "نام فرستنده",
+ "imPlatform.email.senderNameDescription": "نامی که در صندوق ورودی گیرنده نمایش داده می‌شود.",
+ "imPlatform.email.testSucceeded": "آزمایش اتصال موفق بود.",
+ "imPlatform.email.title": "پیکربندی ایمیل",
+ "imPlatform.learnMore": "بیشتر بدانید",
+ "imPlatform.loadError.description": "برای خواندن اتصال فعلی و مجوزها دوباره تلاش کنید.",
+ "imPlatform.loadError.retry": "تلاش مجدد",
+ "imPlatform.loadError.title": "کانال‌ها بارگیری نشدند",
+ "imPlatform.loading": "در حال بارگیری کانال‌ها",
+ "imPlatform.provider.dingtalkDescription": "یک برنامه DingTalk متصل کنید.",
+ "imPlatform.provider.emailDescription": "سرویس ایمیل مورد استفاده برای ارسال درخواست‌های تأیید این فضای کاری را پیکربندی کنید.",
+ "imPlatform.provider.feishuDescription": "یک برنامه Feishu متصل کنید.",
+ "imPlatform.provider.larkDescription": "یک برنامه Lark متصل کنید.",
+ "imPlatform.provider.msTeamsDescription": "یک برنامه Microsoft Teams متصل کنید.",
+ "imPlatform.provider.slackDescription": "افراد و هویت‌های Slack آن‌ها را همگام‌سازی کنید.",
+ "imPlatform.provider.weComDescription": "یک برنامه WeCom متصل کنید.",
+ "imPlatform.replacement.confirm": "جایگزین کنید",
+ "imPlatform.replacement.description": "جایگزینی ارائه‌دهنده فعال، اتصال‌های پیام‌رسانی و تنظیمات اختصاصی فضای کاری آن را نامعتبر می‌کند. پس از جایگزینی، فهرست مخاطبان ارائه‌دهنده جدید را دوباره همگام‌سازی کنید.",
+ "imPlatform.replacement.title": "{{current}} با {{next}} جایگزین شود؟",
+ "imPlatform.status.configured": "پیکربندی شده",
+ "imPlatform.status.connected": "متصل شده",
+ "imPlatform.status.connection_error": "خطای اتصال",
+ "imPlatform.status.permission_issue": "مشکل مجوز",
+ "imPlatform.sync.latestSynced": "آخرین همگام‌سازی: {{date}}",
+ "imPlatform.sync.loading": "در حال بررسی همگام‌سازی فعال.",
+ "imPlatform.sync.noPermission": "فقط مالکان و مدیران فضای کاری می‌توانند همگام‌سازی فهرست مخاطبان را آغاز کنند.",
+ "imPlatform.sync.noRuns": "هنوز همگام‌سازی فهرست مخاطبان اجرا نشده است.",
+ "imPlatform.sync.notConnected": "پیش از شروع همگام‌سازی فهرست مخاطبان، یک ارائه‌دهنده متصل کنید و اتصال را آزمایش کنید.",
+ "imPlatform.sync.startFailed": "همگام‌سازی فهرست مخاطبان آغاز یا تازه‌سازی نشد. دوباره تلاش کنید.",
+ "imPlatform.sync.status.failure": "ناموفق",
+ "imPlatform.sync.status.queued": "در صف",
+ "imPlatform.sync.status.running": "در حال اجرا",
+ "imPlatform.sync.status.success": "موفق",
+ "imPlatform.title": "کانال‌ها"
}
diff --git a/web/i18n/locales/fa-IR/share.json b/web/i18n/locales/fa-IR/share.json
index 45ef0e17653..06306aafc4f 100644
--- a/web/i18n/locales/fa-IR/share.json
+++ b/web/i18n/locales/fa-IR/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "متشکریم!",
"humanInput.unavailableDescription": "ممکن است پیوند در دسترس نباشد یا با حسابی که با آن وارد شده‌اید مطابقت نداشته باشد. فرم را از اعلان دریافتی باز کنید یا حساب را تغییر دهید.",
"humanInput.unavailableTitle": "امکان باز کردن این فرم وجود ندارد",
+ "humanInputV2.accessRateLimited": "تعداد درخواست‌های ایمیل تأیید بیش از حد مجاز است. لطفاً بعداً دوباره تلاش کنید.",
+ "humanInputV2.alreadySubmitted": "این درخواست قبلاً تکمیل شده است.",
+ "humanInputV2.challengeExpired": "این کد تأیید منقضی شده است. برای ادامه، کد جدید درخواست کنید.",
+ "humanInputV2.challengeStale": "این کد تأیید جایگزین شده است. برای ادامه، کد جدید درخواست کنید.",
+ "humanInputV2.codeExpiresIn": "کد تا {{seconds}} ثانیه دیگر منقضی می‌شود",
+ "humanInputV2.codeRequired": "برای ادامه، کد تأیید درخواست کنید.",
+ "humanInputV2.codeSent": "یک کد تأیید به ایمیل شما ارسال شد.",
+ "humanInputV2.deliveryFailed": "ارسال ایمیل تأیید ممکن نبود. لطفاً دوباره تلاش کنید.",
+ "humanInputV2.formExpired": "این درخواست منقضی شده است.",
+ "humanInputV2.formNotFound": "فرم یافت نشد.",
+ "humanInputV2.formRateLimited": "تعداد درخواست‌های فرم بیش از حد مجاز است. لطفاً بعداً دوباره تلاش کنید.",
+ "humanInputV2.invalidOtp": "کد تأیید نادرست است. کد را بررسی کرده و دوباره تلاش کنید.",
+ "humanInputV2.networkError": "تکمیل درخواست ممکن نبود. اتصال خود را بررسی کرده و دوباره تلاش کنید.",
+ "humanInputV2.otpLabel": "کد تأیید ایمیل",
+ "humanInputV2.otpPlaceholder": "کد ۶ رقمی را وارد کنید",
+ "humanInputV2.requestingCode": "در حال ارسال کد تأیید…",
+ "humanInputV2.resendCode": "ارسال دوباره کد",
+ "humanInputV2.retry": "تلاش دوباره",
+ "humanInputV2.sendCode": "ارسال کد جدید",
+ "humanInputV2.unavailable": "این فرم موقتاً در دسترس نیست.",
+ "humanInputV2.unknownError": "مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
+ "humanInputV2.uploadFailed": "بارگذاری فایل ممکن نبود. لطفاً دوباره تلاش کنید.",
"login.backToHome": "بازگشت به خانه"
}
diff --git a/web/i18n/locales/fa-IR/workflow-human-input.json b/web/i18n/locales/fa-IR/workflow-human-input.json
index 3cb8ac534db..b3d1c4c32b2 100644
--- a/web/i18n/locales/fa-IR/workflow-human-input.json
+++ b/web/i18n/locales/fa-IR/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "مقدار عملیات",
"nodes.humanInput.userActions.buttonTextTooLong": "متن دکمه باید {{maxLength}} کاراکتر یا کمتر باشد",
"nodes.humanInput.userActions.chooseStyle": "انتخاب سبک دکمه",
+ "nodes.humanInput.userActions.defaultTitle": "متن دکمه {{index}}",
"nodes.humanInput.userActions.emptyTip": "برای افزودن عملیات کاربر روی '+' کلیک کنید",
"nodes.humanInput.userActions.title": "عملیات کاربر",
"nodes.humanInput.userActions.tooltip": "دکمه‌هایی تعریف کنید که کاربر برای پاسخ به فرم روی آن‌ها کلیک کند. شناسه عملیات انشعاب را کنترل می‌کند. مقدار عملیات به عنوان خروجی داخلی انتخاب‌شده در مرحله پایین‌تر نمایش داده می‌شود. شناسه عملیات باید با حرف یا زیرخط شروع شود، و سپس حروف، اعداد یا زیرخط بیاید.",
diff --git a/web/i18n/locales/fa-IR/workflow.json b/web/i18n/locales/fa-IR/workflow.json
index 01565982aa1..5c05dcf0c69 100644
--- a/web/i18n/locales/fa-IR/workflow.json
+++ b/web/i18n/locales/fa-IR/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "پایان",
"blocks.http-request": "درخواست HTTP",
"blocks.human-input": "ورودی انسانی",
+ "blocks.human-input-v2": "ورودی انسانی v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "تکرار",
"blocks.iteration-start": "شروع تکرار",
@@ -45,6 +46,7 @@
"blocksAbout.end": "تعریف خروجی و نوع نتیجه گردش کار",
"blocksAbout.http-request": "ارسال درخواست به سرور از طریق پروتکل HTTP",
"blocksAbout.human-input": "درخواست تأیید انسانی پیش از ادامه به مرحله بعد",
+ "blocksAbout.human-input-v2": "از مخاطبان پیکربندی‌شده، گیرندگان ایمیل یا آغازکننده گردش کار درخواست ورودی کنید",
"blocksAbout.if-else": "تقسیم گردش کار به دو شاخه بر اساس شرط if/else",
"blocksAbout.iteration": "اجرای چندین مرحله روی آیتم‌های یک لیست تا تمام نتایج خروجی داده شوند",
"blocksAbout.iteration-start": "گره شروع تکرار",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "تجمیع متغیرهای چند شاخه در یک متغیر واحد برای پیکربندی یکپارچه گره‌های پایین‌دستی",
"blocksAbout.variable-assigner": "تجمیع متغیرهای چند شاخه در یک متغیر واحد برای پیکربندی یکپارچه گره‌های پایین‌دستی",
"changeHistory.edgeDelete": "اتصال حذف شد",
+ "changeHistory.humanInputMigration": "گره‌های ورودی انسانی مهاجرت داده شدند",
"changeHistory.nodeAdd": "گره اضافه شد",
"changeHistory.nodeChange": "گره تغییر کرد",
"changeHistory.nodeConnect": "گره متصل شد",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "لطفاً حداقل یک روش ارسال را فعال کنید",
"nodes.humanInput.errorMsg.noUserActions": "لطفاً حداقل یک عملیات کاربر اضافه کنید",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} برای شاخه پایان مهلت رزرو شده است. شناسه دیگری برای اقدام انتخاب کنید.",
+ "nodes.humanInput.output.actionId": "شناسه اقدامی که کاربر اجرا کرده است",
+ "nodes.humanInput.output.actionValue": "مقدار اقدام انتخاب‌شده",
+ "nodes.humanInput.output.formInput": "مقدار ورودی فرم",
+ "nodes.humanInput.output.renderedContent": "محتوای رندرشده",
"nodes.humanInput.timeout.title": "مهلت زمانی",
+ "nodes.humanInputMigration.action.migrate": "مهاجرت",
+ "nodes.humanInputMigration.action.migrateNow": "همین حالا مهاجرت دهید",
+ "nodes.humanInputMigration.action.migrating": "در حال مهاجرت...",
+ "nodes.humanInputMigration.banner.ariaLabel": "اعلان مهاجرت ورودی انسانی",
+ "nodes.humanInputMigration.banner.description": "این گردش کار از گره ورودی انسانی قدیمی استفاده می‌کند. پیش از افزودن گره‌های جدید، همه گره‌های قدیمی را مهاجرت دهید.",
+ "nodes.humanInputMigration.banner.learnMore": "بیشتر بدانید",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "یک روش ارسال غیرفعال هنوز دارای پیکربندی است",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "روش‌های ایمیل فعال از الگوهای ناسازگار استفاده می‌کنند",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "مقدار پیش‌فرض نامعتبر است",
+ "nodes.humanInputMigration.blocker.invalidEmail": "نشانی ایمیل یک گیرنده نامعتبر است",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "پیکربندی یک روش ایمیل فعال ناقص است",
+ "nodes.humanInputMigration.blocker.missingRecipients": "این گره هیچ گیرنده پشتیبانی‌شده‌ای ندارد",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "یکی از اعضای فضای کاری را نمی‌توان به مخاطب یا ایمیل تأییدشده مرتبط کرد",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "یک روش ارسال فعال در ورودی انسانی v2 پشتیبانی نمی‌شود",
"nodes.humanInputMigration.blocker.unsupportedInputType": "فیلد {{field}} هنوز قابل مهاجرت نیست. می‌توانید به استفاده از گره‌های قدیمی ورودی انسانی ادامه دهید.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "مقدار نسخه این گره پشتیبانی نمی‌شود",
+ "nodes.humanInputMigration.dialog.description": "گیرندگان، فرم و اقدام‌های شما حفظ می‌شوند.",
+ "nodes.humanInputMigration.dialog.draftNotice": "فقط این پیش‌نویس تغییر می‌کند. نسخه‌های منتشرشده تا زمان انتشار دوباره به کار خود ادامه می‌دهند.",
+ "nodes.humanInputMigration.dialog.review": "گره‌ها را بررسی کنید و هر زمان آماده بودید منتشر کنید.",
+ "nodes.humanInputMigration.dialog.title": "مهاجرت {{count}} گره ورودی انسانی",
+ "nodes.humanInputMigration.disabledBadge": "مهاجرت لازم است",
+ "nodes.humanInputMigration.disabledReason": "پیش از افزودن گره جدید، گره‌های ورودی انسانی قدیمی را مهاجرت دهید.",
+ "nodes.humanInputMigration.error.blocked": "مهاجرت {{nodeTitle}} ممکن نبود: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "گردش کار در هنگام انتقال تغییر کرد. دوباره تلاش کنید؛ ویرایش‌های فعلی شما حفظ شده‌اند.",
+ "nodes.humanInputMigration.error.preflight": "آماده‌سازی مهاجرت ممکن نبود. گردش کار شما تغییری نکرده است. دوباره تلاش کنید.",
"nodes.humanInputMigration.error.sync": "گردش کار منتقل‌شده ذخیره نشد. پیش‌نویس فعلی را بررسی کنید و دوباره تلاش کنید.",
+ "nodes.humanInputMigration.incompatibleVersions": "گره‌های قدیمی و جدید ورودی انسانی را نمی‌توان در یک گردش کار استفاده کرد.",
+ "nodes.humanInputMigration.oldVersion": "نسخه قدیمی",
+ "nodes.humanInputMigration.preview.author": "ساخته تیم Dify",
+ "nodes.humanInputMigration.preview.description": "پیش از افزودن گره جدید، گره‌های ورودی انسانی قدیمی را مهاجرت دهید.",
+ "nodes.humanInputMigration.success": "گره‌های ورودی انسانی با موفقیت مهاجرت داده شدند",
+ "nodes.humanInputV2.card.configured": "{{count}} گیرنده پیکربندی شده است",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} مخاطب",
+ "nodes.humanInputV2.card.empty": "هنوز کسی نمی‌تواند این مرحله را تأیید کند",
+ "nodes.humanInputV2.card.initiatorAndContacts": "آغازکننده و {{count}} مخاطب",
+ "nodes.humanInputV2.card.initiatorOnly": "فقط آغازکننده",
+ "nodes.humanInputV2.card.invalid": "پیکربندی گیرندگان نیاز به بررسی دارد",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "ایمیل",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "پیکربندی حالت اشکال‌زدایی",
"nodes.humanInputV2.debug.keepOneChannel": "حداقل یک کانال را روشن نگه دارید",
+ "nodes.humanInputV2.debug.sendVia": "ارسال اعلان‌های اشکال‌زدایی از طریق",
+ "nodes.humanInputV2.debug.title": "حالت اشکال‌زدایی",
+ "nodes.humanInputV2.debug.toggle": "فعال‌سازی حالت اشکال‌زدایی",
+ "nodes.humanInputV2.debug.unsupported": "کانال‌های واردشده پشتیبانی نمی‌شوند: {{channels}}. پیش از اجرای این گردش کار، آن‌ها را حذف یا به‌روزرسانی کنید.",
"nodes.humanInputV2.disabled": "هنگامی که HITL IM غیرفعال است، Human Input v2 در دسترس نیست.",
+ "nodes.humanInputV2.error.bodyRequired": "متن پیام الزامی است",
+ "nodes.humanInputV2.error.debugChannelRequired": "حداقل یک کانال حالت اشکال‌زدایی انتخاب کنید",
+ "nodes.humanInputV2.error.recipientDuplicate": "گیرندگان تکراری را حذف کنید",
+ "nodes.humanInputV2.error.recipientInvalid": "پیکربندی نامعتبر گیرندگان را اصلاح کنید",
+ "nodes.humanInputV2.error.recipientRequired": "حداقل یک گیرنده اضافه کنید",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "تأیید گیرندگان از مخاطبان ممکن نشد",
"nodes.humanInputV2.error.requestURLDuplicate": "متن پیام فقط می‌تواند شامل یک نشانی درخواست باشد.",
"nodes.humanInputV2.error.requestURLRequired": "یک نشانی درخواست در متن پیام درج کنید.",
+ "nodes.humanInputV2.error.subjectRequired": "موضوع پیام الزامی است",
+ "nodes.humanInputV2.error.version": "ورودی انسانی v2 به مقدار نسخه 2 از نوع رشته نیاز دارد",
+ "nodes.humanInputV2.recipients.addContact": "افزودن مخاطب",
+ "nodes.humanInputV2.recipients.addEmail": "افزودن",
+ "nodes.humanInputV2.recipients.addRecipient": "افزودن گیرنده",
+ "nodes.humanInputV2.recipients.added": "اضافه شد",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "همه مخاطبان فضای کاری",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "به همه مخاطبان فضای کاری اعلان ارسال کنید؛ هر یک از آن‌ها می‌تواند تأیید کند",
+ "nodes.humanInputV2.recipients.cancel": "لغو",
+ "nodes.humanInputV2.recipients.chooseVariable": "انتخاب متغیر",
+ "nodes.humanInputV2.recipients.confirm": "تأیید",
+ "nodes.humanInputV2.recipients.contactInfo": "جزئیات مخاطب {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "همه",
+ "nodes.humanInputV2.recipients.contactSource.external": "خارجی",
+ "nodes.humanInputV2.recipients.contactSource.organization": "سازمان",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "فضای کاری",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "منبع مخاطبان",
"nodes.humanInputV2.recipients.duplicateSource": "قبلاً از طریق {{name}} ({{source}}) اضافه شده است.",
+ "nodes.humanInputV2.recipients.edit": "ویرایش {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "ویرایش گیرنده",
"nodes.humanInputV2.recipients.emailAlreadySelected": "هر ایمیل را فقط یک بار می‌توان انتخاب کرد.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "یک نشانی ایمیل معتبر وارد کنید که قبلاً اضافه نشده باشد",
+ "nodes.humanInputV2.recipients.emailLabel": "گیرنده ایمیل یک‌باره",
+ "nodes.humanInputV2.recipients.empty": "هیچ گیرنده‌ای پیکربندی نشده است",
+ "nodes.humanInputV2.recipients.help": "انتخاب کنید چه کسی می‌تواند به این مرحله ورودی انسانی پاسخ دهد.",
"nodes.humanInputV2.recipients.initiator": "کاربری که این اجرا را از طریق Web App یا CLI آغاز می‌کند، می‌تواند تأیید کند",
+ "nodes.humanInputV2.recipients.initiatorDescription": "فردی که این اجرای گردش کار را آغاز می‌کند می‌تواند پاسخ دهد.",
"nodes.humanInputV2.recipients.inputHelp": "چند نشانی ایمیل را با جداکنندهٔ ویرگول تایپ یا جای‌گذاری کنید. برای درج متغیر، / را فشار دهید.",
+ "nodes.humanInputV2.recipients.insertVariable": "درج متغیر",
+ "nodes.humanInputV2.recipients.loadError": "بارگذاری مخاطبان ممکن نبود. شناسه‌های ذخیره‌شده مخاطبان حفظ شده‌اند.",
+ "nodes.humanInputV2.recipients.loading": "در حال بارگذاری مخاطبان…",
+ "nodes.humanInputV2.recipients.noResults": "مخاطبی یافت نشد",
+ "nodes.humanInputV2.recipients.placeholder": "جستجوی مخاطبان یا افزودن ایمیل",
+ "nodes.humanInputV2.recipients.remove": "حذف {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "برای حذف، کلید Backspace یا Delete را فشار دهید.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} گیرنده منطبق",
+ "nodes.humanInputV2.recipients.search": "جستجوی مخاطبان",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "جستجو بر اساس نام یا ایمیل",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} گیرنده انتخاب شده است. در ابتدای کادر ورودی، کلید پیکان راست را فشار دهید تا روی آن‌ها تمرکز کنید.",
+ "nodes.humanInputV2.recipients.title": "گیرندگان",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "همه مخاطبان فضای کاری",
+ "nodes.humanInputV2.recipients.type.contact": "مخاطب",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "ایمیل پویا",
+ "nodes.humanInputV2.recipients.type.initiator": "آغازکننده",
+ "nodes.humanInputV2.recipients.type.onetime_email": "ایمیل یک‌باره",
+ "nodes.humanInputV2.recipients.typeLabel": "نوع گیرنده",
"nodes.humanInputV2.recipients.useThisInstead": "به‌جای آن از این استفاده کنید",
+ "nodes.humanInputV2.recipients.variableRequired": "یک متغیر ایمیل انتخاب کنید",
+ "nodes.humanInputV2.template.body": "متن",
+ "nodes.humanInputV2.template.description": "متن جایگزین برای ایمیل و پیام‌رسانی فوری",
"nodes.humanInputV2.template.insertRequestURL": "درج نشانی درخواست",
+ "nodes.humanInputV2.template.insertVariable": "درج متغیر",
+ "nodes.humanInputV2.template.notConfigured": "پیکربندی نشده",
"nodes.humanInputV2.template.requestURLHint": "گیرندگان با این پیوند فرم تأیید را باز می‌کنند. دقیقاً یک نشانی درخواست درج کنید.",
"nodes.humanInputV2.template.requestURLInserted": "نشانی درخواست درج شد",
"nodes.humanInputV2.template.saveAndTest": "ذخیره و آزمایش",
+ "nodes.humanInputV2.template.subject": "موضوع",
+ "nodes.humanInputV2.template.subjectPlaceholder": "موضوع پیام را وارد کنید",
"nodes.humanInputV2.template.test": "آزمایش پیام",
"nodes.humanInputV2.template.testChannel": "کانال آزمایش",
"nodes.humanInputV2.template.testCompleted": "درخواست آزمایش انجام شد. پیام را در کانال انتخاب‌شده بررسی کنید.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "مقادیر تمام متغیرهای آزمایش را وارد کنید.",
"nodes.humanInputV2.template.testSaveFailed": "پیش‌نویس گردش کار ذخیره نشد. آزمایش ارسال نشد.",
"nodes.humanInputV2.template.testUnavailable": "این محیط هنوز از آزمایش قالب پیام پشتیبانی نمی‌کند.",
+ "nodes.humanInputV2.template.title": "الگوی پیام",
"nodes.ifElse.operator": "عملگر",
"nodes.iteration.currentIteration": "تکرار فعلی",
"nodes.iteration.deleteDesc": "حذف گره تکرار باعث حذف تمام گره‌های فرزند می‌شود",
diff --git a/web/i18n/locales/fr-FR/contacts.json b/web/i18n/locales/fr-FR/contacts.json
index 3a90c4fee1d..90db784167f 100644
--- a/web/i18n/locales/fr-FR/contacts.json
+++ b/web/i18n/locales/fr-FR/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Supprimer les contacts ({{count}}) ?",
"directory.removalDescription": "Les contacts sélectionnés seront définitivement supprimés de cet espace de travail. Cette action est irréversible.",
- "directory.removalTitle": "Supprimer les contacts ?",
+ "directory.removalSingleDescription": "{{name}} sera définitivement supprimé de cet espace de travail. Cette action est irréversible.",
+ "directory.removalSingleFailed": "Impossible de supprimer ce contact. Réessayez.",
+ "directory.removalSingleTitle": "Supprimer {{name}} ?",
+ "directory.resultCount": "Résultats : {{count}}",
+ "imPlatform.action.configure": "Configurer",
+ "imPlatform.action.configureChannel": "Configurer {{provider}}",
+ "imPlatform.action.connect": "Connecter",
+ "imPlatform.action.copied": "Copié",
+ "imPlatform.action.copyCallback": "Copier l’URL de rappel",
+ "imPlatform.action.deleteChannel": "Supprimer {{provider}}",
+ "imPlatform.action.loadMore": "Charger plus",
+ "imPlatform.action.replace": "Remplacer",
+ "imPlatform.action.retry": "Réessayer",
+ "imPlatform.action.save": "Enregistrer",
+ "imPlatform.action.saving": "Enregistrement",
+ "imPlatform.action.setupGuide": "Guide de configuration",
+ "imPlatform.action.syncNow": "Synchroniser maintenant",
+ "imPlatform.action.syncing": "Synchronisation en cours",
+ "imPlatform.action.testConnection": "Tester la connexion",
+ "imPlatform.action.testing": "Test en cours",
+ "imPlatform.action.viewDetails": "Voir les détails",
+ "imPlatform.bindingDialog.back": "Retour",
+ "imPlatform.bindingDialog.callback": "URL de rappel",
+ "imPlatform.bindingDialog.callbackDescription": "Terminez la configuration des rappels dans {{provider}} pour activer les actions des cartes.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Pour les actions des cartes, collez cette URL dans la <console>console développeur Feishu</console> :",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Événements et rappels → Configuration des rappels → URL de requête",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Pour les actions des cartes, collez cette URL dans la <console>console développeur Lark</console> :",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Événements et rappels → Configuration des rappels → URL de requête",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Pour les actions des cartes, collez cette URL dans la <console>console développeur Slack</console> :",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interactivité et raccourcis → Interactivité → URL de requête",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Pour les actions des cartes, collez cette URL dans la <console>configuration Azure Bot</console> :",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Paramètres → Configuration → Point de terminaison de messagerie",
+ "imPlatform.bindingDialog.callbackStep": "Configurer les rappels",
"imPlatform.bindingDialog.clearSavedCredential": "Effacer la valeur enregistrée",
+ "imPlatform.bindingDialog.configureTitle": "Configurer {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Connecter {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Cette valeur enregistrée sera effacée lors de la sauvegarde.",
+ "imPlatform.bindingDialog.credentialsDescription": "Connectez d’abord votre application {{provider}}, puis configurez son URL de rappel.",
+ "imPlatform.bindingDialog.credentialsStep": "Identifiants de l’application",
+ "imPlatform.bindingDialog.description": "Saisissez les identifiants de l’application de ce fournisseur de messagerie instantanée.",
+ "imPlatform.bindingDialog.field.agentId": "Identifiant de l’agent",
+ "imPlatform.bindingDialog.field.appId": "Identifiant de l’application",
+ "imPlatform.bindingDialog.field.appToken": "Jeton de l’application (facultatif)",
+ "imPlatform.bindingDialog.field.botToken": "Jeton du bot",
+ "imPlatform.bindingDialog.field.clientId": "ID client",
+ "imPlatform.bindingDialog.field.clientSecret": "Secret client",
+ "imPlatform.bindingDialog.field.corpId": "Identifiant de l’entreprise",
+ "imPlatform.bindingDialog.field.encryptKey": "Clé de chiffrement (facultative)",
+ "imPlatform.bindingDialog.field.genericSecret": "Clé secrète",
+ "imPlatform.bindingDialog.field.secret": "Secret de l’application",
+ "imPlatform.bindingDialog.field.signingSecret": "Secret de signature",
+ "imPlatform.bindingDialog.field.tenantId": "Identifiant du locataire",
+ "imPlatform.bindingDialog.field.verificationToken": "Jeton de vérification (facultatif)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Saisissez la clé de chiffrement, si elle est activée",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Saisissez le secret de l’application",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Saisissez le jeton de vérification, s’il est configuré",
+ "imPlatform.bindingDialog.finish": "Terminer",
+ "imPlatform.bindingDialog.freshCredentials": "Les secrets enregistrés ne peuvent pas être récupérés. Saisissez à nouveau tous les identifiants requis pour tester ou enregistrer cette configuration.",
+ "imPlatform.bindingDialog.openSetupGuide": "Ouvrir le guide de configuration",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Remplacer les identifiants du locataire pour {{identity}} ?",
"imPlatform.bindingDialog.replacementRequired": "Ces identifiants appartiennent à un autre locataire IM et ne peuvent pas être enregistrés directement. Pour changer de locataire, vous devez remplacer le canal IM actuel, ce qui supprime toutes les associations IM automatiques et manuelles. Synchronisez à nouveau les contacts après le remplacement.",
+ "imPlatform.bindingDialog.required": "Ce champ est obligatoire.",
+ "imPlatform.bindingDialog.saveAndContinue": "Enregistrer et continuer",
+ "imPlatform.bindingDialog.saveFailed": "Impossible d’enregistrer la configuration. Vérifiez les champs et réessayez.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "La configuration a été enregistrée, mais ses détails n’ont pas pu être chargés. Fermez cette boîte de dialogue et rouvrez-la.",
- "imPlatform.bindingDialog.undoClearCredential": "Annuler l’effacement"
+ "imPlatform.bindingDialog.secretConfigured": "Un secret est déjà configuré. Laissez ce champ vide pour le conserver.",
+ "imPlatform.bindingDialog.step": "Étape {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Le test de connexion a échoué. Vérifiez la configuration et réessayez.",
+ "imPlatform.bindingDialog.undoClearCredential": "Annuler l’effacement",
+ "imPlatform.bindingDialog.viewSetupGuide": "Consulter le guide de configuration",
+ "imPlatform.chooseProvider": "Choisissez un canal à connecter",
+ "imPlatform.configurationUpdated": "La configuration de ce canal a changé. Fermez cette boîte de dialogue et actualisez avant de réessayer.",
+ "imPlatform.connectMore": "Connecter d’autres canaux",
+ "imPlatform.delete.confirm": "Supprimer",
+ "imPlatform.delete.description": "La suppression de ce canal efface sa configuration. L’envoi des demandes d’approbation et la synchronisation de l’annuaire qui l’utilisent s’arrêteront.",
+ "imPlatform.delete.failed": "Impossible de supprimer ce canal. Rien n’a changé ; réessayez.",
+ "imPlatform.delete.title": "Supprimer le canal {{provider}} ?",
+ "imPlatform.description": "Connectez les canaux de votre entreprise pour envoyer les demandes d’approbation là où les personnes travaillent.",
+ "imPlatform.details.column.contact": "Contacts",
+ "imPlatform.details.column.platform": "Plateforme de messagerie instantanée",
+ "imPlatform.details.description": "Consultez les résultats en lecture seule de la dernière synchronisation.",
+ "imPlatform.details.downloadFailed": "Impossible de télécharger le rapport. Réessayez.",
+ "imPlatform.details.downloadReport": "Télécharger le rapport",
+ "imPlatform.details.downloadingReport": "Téléchargement du rapport…",
+ "imPlatform.details.empty": "Aucun résultat dans cette catégorie.",
+ "imPlatform.details.filter.added": "Ajouté",
+ "imPlatform.details.filter.failed": "Échec",
+ "imPlatform.details.filter.not_matched": "Sans correspondance",
+ "imPlatform.details.filter.removed": "Supprimé",
+ "imPlatform.details.filter.skipped": "Ignoré",
+ "imPlatform.details.filters": "Filtres des résultats de synchronisation",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Impossible de charger les détails de synchronisation.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Impossible de charger d’autres résultats. Réessayez cette page.",
+ "imPlatform.details.removalReason.binding_invalidated": "Liaison invalidée",
+ "imPlatform.details.removalReason.binding_replaced": "Liaison remplacée",
+ "imPlatform.details.removalReason.not_present_in_directory": "Absent de l’annuaire",
+ "imPlatform.details.reportChanged": "Les résultats de synchronisation ont changé. Rouvrez les détails de la dernière synchronisation et réessayez.",
+ "imPlatform.details.title": "Détails de synchronisation",
+ "imPlatform.email.apiKey": "Clé API",
+ "imPlatform.email.apiKeyConfigured": "Pour des raisons de sécurité, la clé API enregistrée ne peut pas être consultée. Laissez ce champ vide pour la conserver.",
+ "imPlatform.email.apiKeyDescription": "Pour des raisons de sécurité, cette clé API ne peut plus être consultée après son enregistrement.",
+ "imPlatform.email.apiKeyPlaceholder": "Saisissez votre clé API Resend",
+ "imPlatform.email.description": "Cette configuration s’applique à tous les nœuds d’intervention humaine de cet espace de travail pour lesquels l’option <emphasis>Envoyer les notifications de débogage par e-mail</emphasis> est activée.",
+ "imPlatform.email.invalidEmail": "Saisissez une adresse e-mail valide.",
+ "imPlatform.email.provider": "Fournisseur de messagerie",
+ "imPlatform.email.resendDescription": "Votre <apiKey>clé API Resend</apiKey> sera chiffrée et ne pourra plus être consultée après son enregistrement.<br/>Créez un compte <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Paramètres Resend",
+ "imPlatform.email.senderEmail": "Adresse e-mail de l’expéditeur",
+ "imPlatform.email.senderEmailDescription": "L’adresse e-mail affichée comme expéditeur. Son domaine doit être vérifié dans Resend.",
+ "imPlatform.email.senderName": "Nom de l’expéditeur",
+ "imPlatform.email.senderNameDescription": "Nom affiché dans la boîte de réception du destinataire.",
+ "imPlatform.email.testSucceeded": "Test de connexion réussi.",
+ "imPlatform.email.title": "Configurer l’e-mail",
+ "imPlatform.learnMore": "En savoir plus",
+ "imPlatform.loadError.description": "Réessayez de charger la liaison actuelle et les autorisations.",
+ "imPlatform.loadError.retry": "Réessayer",
+ "imPlatform.loadError.title": "Impossible de charger les canaux",
+ "imPlatform.loading": "Chargement des canaux",
+ "imPlatform.provider.dingtalkDescription": "Connectez une application DingTalk.",
+ "imPlatform.provider.emailDescription": "Configurez le service de messagerie utilisé pour envoyer les demandes d’approbation de cet espace de travail.",
+ "imPlatform.provider.feishuDescription": "Connectez une application Feishu.",
+ "imPlatform.provider.larkDescription": "Connectez une application Lark.",
+ "imPlatform.provider.msTeamsDescription": "Connectez une application Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Synchronisez les personnes et leurs identités Slack.",
+ "imPlatform.provider.weComDescription": "Connectez une application WeCom.",
+ "imPlatform.replacement.confirm": "Remplacer",
+ "imPlatform.replacement.description": "Le remplacement du fournisseur actif invalide ses liaisons de messagerie instantanée et les personnalisations de l’espace de travail. Synchronisez à nouveau l’annuaire du nouveau fournisseur après le remplacement.",
+ "imPlatform.replacement.title": "Remplacer {{current}} par {{next}} ?",
+ "imPlatform.status.configured": "Configuré",
+ "imPlatform.status.connected": "Connecté",
+ "imPlatform.status.connection_error": "Erreur de connexion",
+ "imPlatform.status.permission_issue": "Problème d’autorisation",
+ "imPlatform.sync.latestSynced": "Dernière synchronisation le {{date}}",
+ "imPlatform.sync.loading": "Vérification d’une synchronisation en cours.",
+ "imPlatform.sync.noPermission": "Seuls les propriétaires et les administrateurs de l’espace de travail peuvent lancer la synchronisation de l’annuaire.",
+ "imPlatform.sync.noRuns": "Aucune synchronisation de l’annuaire n’a encore été exécutée.",
+ "imPlatform.sync.notConnected": "Connectez un fournisseur et testez la connexion avant de lancer la synchronisation de l’annuaire.",
+ "imPlatform.sync.startFailed": "Impossible de lancer ou d’actualiser la synchronisation de l’annuaire. Réessayez.",
+ "imPlatform.sync.status.failure": "Échec",
+ "imPlatform.sync.status.queued": "En attente",
+ "imPlatform.sync.status.running": "En cours",
+ "imPlatform.sync.status.success": "Réussi",
+ "imPlatform.title": "Canaux"
}
diff --git a/web/i18n/locales/fr-FR/share.json b/web/i18n/locales/fr-FR/share.json
index 6cbb89a5ef0..86d3ea346ca 100644
--- a/web/i18n/locales/fr-FR/share.json
+++ b/web/i18n/locales/fr-FR/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Merci !",
"humanInput.unavailableDescription": "Le lien est peut-être indisponible ou ne correspond pas au compte avec lequel vous êtes connecté. Ouvrez le formulaire depuis la notification que vous avez reçue ou essayez de changer de compte.",
"humanInput.unavailableTitle": "Impossible d’ouvrir ce formulaire",
+ "humanInputV2.accessRateLimited": "Trop d’e-mails de vérification ont été demandés. Réessayez plus tard.",
+ "humanInputV2.alreadySubmitted": "Cette demande a déjà été traitée.",
+ "humanInputV2.challengeExpired": "Ce code de vérification a expiré. Demandez un nouveau code pour continuer.",
+ "humanInputV2.challengeStale": "Ce code de vérification a été remplacé. Demandez un nouveau code pour continuer.",
+ "humanInputV2.codeExpiresIn": "Le code expire dans {{seconds}} s",
+ "humanInputV2.codeRequired": "Demandez un code de vérification pour continuer.",
+ "humanInputV2.codeSent": "Un code de vérification a été envoyé à votre adresse e-mail.",
+ "humanInputV2.deliveryFailed": "Impossible d’envoyer l’e-mail de vérification. Réessayez.",
+ "humanInputV2.formExpired": "Cette demande a expiré.",
+ "humanInputV2.formNotFound": "Formulaire introuvable.",
+ "humanInputV2.formRateLimited": "Trop de demandes de formulaire. Réessayez plus tard.",
+ "humanInputV2.invalidOtp": "Le code de vérification est incorrect. Vérifiez-le et réessayez.",
+ "humanInputV2.networkError": "Impossible de traiter la demande. Vérifiez votre connexion et réessayez.",
+ "humanInputV2.otpLabel": "Code de vérification par e-mail",
+ "humanInputV2.otpPlaceholder": "Saisissez le code à 6 chiffres",
+ "humanInputV2.requestingCode": "Envoi d’un code de vérification…",
+ "humanInputV2.resendCode": "Renvoyer le code",
+ "humanInputV2.retry": "Réessayer",
+ "humanInputV2.sendCode": "Envoyer un nouveau code",
+ "humanInputV2.unavailable": "Ce formulaire est temporairement indisponible.",
+ "humanInputV2.unknownError": "Une erreur s’est produite. Réessayez.",
+ "humanInputV2.uploadFailed": "Impossible d’importer le fichier. Réessayez.",
"login.backToHome": "Retour à l'accueil"
}
diff --git a/web/i18n/locales/fr-FR/workflow-human-input.json b/web/i18n/locales/fr-FR/workflow-human-input.json
index f2c6bf4e3f5..58221645ebc 100644
--- a/web/i18n/locales/fr-FR/workflow-human-input.json
+++ b/web/i18n/locales/fr-FR/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Valeur de l'action",
"nodes.humanInput.userActions.buttonTextTooLong": "Le texte du bouton doit comporter {{maxLength}} caractères ou moins",
"nodes.humanInput.userActions.chooseStyle": "Choisissez un style de bouton",
+ "nodes.humanInput.userActions.defaultTitle": "Texte du bouton {{index}}",
"nodes.humanInput.userActions.emptyTip": "Cliquez sur le bouton '+' pour ajouter des actions utilisateur",
"nodes.humanInput.userActions.title": "Actions Utilisateur",
"nodes.humanInput.userActions.tooltip": "Définissez les boutons sur lesquels les utilisateurs peuvent cliquer pour répondre à ce formulaire. L'ID d'action contrôle la ramification. La Valeur de l'action est exposée en aval comme la sortie intégrée sélectionnée. L'ID d'action doit commencer par une lettre ou des traits de soulignement, suivi de lettres, de chiffres ou de traits de soulignement.",
diff --git a/web/i18n/locales/fr-FR/workflow.json b/web/i18n/locales/fr-FR/workflow.json
index aaff4e2223d..f761a38d82f 100644
--- a/web/i18n/locales/fr-FR/workflow.json
+++ b/web/i18n/locales/fr-FR/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Sortie",
"blocks.http-request": "Requête HTTP",
"blocks.human-input": "Saisie Humaine",
+ "blocks.human-input-v2": "Saisie Humaine v2",
"blocks.if-else": "SI/SINON",
"blocks.iteration": "Itération",
"blocks.iteration-start": "Début d'itération",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Définir la sortie et le type de résultat d'un flux de travail",
"blocksAbout.http-request": "Permettre l'envoi de requêtes serveur via le protocole HTTP",
"blocksAbout.human-input": "Demander une confirmation humaine avant de générer l'étape suivante",
+ "blocksAbout.human-input-v2": "Demander une saisie aux contacts configurés, aux destinataires par e-mail ou à la personne à l’origine du workflow",
"blocksAbout.if-else": "Permet de diviser le flux de travail en deux branches basées sur des conditions if/else",
"blocksAbout.iteration": "Effectuer plusieurs étapes sur un objet de liste jusqu'à ce que tous les résultats soient produits.",
"blocksAbout.iteration-start": "Nœud de début d'itération",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Agrégation de variables de plusieurs branches en une seule variable pour la configuration unifiée des nœuds en aval.",
"blocksAbout.variable-assigner": "Agrégation de variables de plusieurs branches en une seule variable pour la configuration unifiée des nœuds en aval.",
"changeHistory.edgeDelete": "Nœud déconnecté",
+ "changeHistory.humanInputMigration": "Nœuds de saisie humaine migrés",
"changeHistory.nodeAdd": "Nœud ajouté",
"changeHistory.nodeChange": "Nœud changé",
"changeHistory.nodeConnect": "Node connecté",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Veuillez activer au moins une méthode de livraison",
"nodes.humanInput.errorMsg.noUserActions": "Veuillez ajouter au moins une action utilisateur",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} est réservé à la branche d’expiration du délai. Choisissez un autre identifiant d’action.",
+ "nodes.humanInput.output.actionId": "ID de l’action déclenchée par l’utilisateur",
+ "nodes.humanInput.output.actionValue": "Valeur de l’action sélectionnée",
+ "nodes.humanInput.output.formInput": "Valeur saisie dans le formulaire",
+ "nodes.humanInput.output.renderedContent": "Contenu rendu",
"nodes.humanInput.timeout.title": "Délai d'expiration",
+ "nodes.humanInputMigration.action.migrate": "Migrer",
+ "nodes.humanInputMigration.action.migrateNow": "Migrer maintenant",
+ "nodes.humanInputMigration.action.migrating": "Migration en cours...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Avis de migration de la saisie humaine",
+ "nodes.humanInputMigration.banner.description": "Ce workflow utilise l’ancien nœud de saisie humaine. Migrez tous les anciens nœuds avant d’en ajouter de nouveaux.",
+ "nodes.humanInputMigration.banner.learnMore": "En savoir plus",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "une méthode de transmission désactivée contient encore une configuration",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "les méthodes d’e-mail activées utilisent des modèles incompatibles entre eux",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Valeur par défaut invalide",
+ "nodes.humanInputMigration.blocker.invalidEmail": "l’adresse e-mail d’un destinataire est invalide",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "une méthode d’e-mail activée est incomplète",
+ "nodes.humanInputMigration.blocker.missingRecipients": "le nœud ne comporte aucun destinataire pris en charge",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "un membre de l’espace de travail ne peut être associé à un contact ou à une adresse e-mail vérifiée",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "une méthode de transmission activée n’est pas prise en charge par Human Input v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Le champ {{field}} ne peut pas encore être migré. Vous pouvez continuer à utiliser les anciens nœuds de saisie humaine.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "la valeur de version du nœud n’est pas prise en charge",
+ "nodes.humanInputMigration.dialog.description": "Vos destinataires, votre formulaire et vos actions sont conservés.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Seul ce brouillon est modifié. Les versions publiées continuent de fonctionner jusqu’à la prochaine publication.",
+ "nodes.humanInputMigration.dialog.review": "Vérifiez les nœuds et publiez lorsque tout est prêt.",
+ "nodes.humanInputMigration.dialog.title": "Migrer {{count}} nœuds de saisie humaine",
+ "nodes.humanInputMigration.disabledBadge": "MIGRATION REQUISE",
+ "nodes.humanInputMigration.disabledReason": "Migrez les anciens nœuds de saisie humaine avant d’en ajouter un nouveau.",
+ "nodes.humanInputMigration.error.blocked": "Impossible de migrer {{nodeTitle}} : {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Le workflow a été modifié pendant la migration. Réessayez ; vos modifications actuelles ont été conservées.",
+ "nodes.humanInputMigration.error.preflight": "Impossible de préparer la migration. Votre workflow n’a pas été modifié. Réessayez.",
"nodes.humanInputMigration.error.sync": "Le workflow migré n’a pas pu être enregistré. Vérifiez le brouillon actuel et réessayez.",
+ "nodes.humanInputMigration.incompatibleVersions": "Les anciens et les nouveaux nœuds de saisie humaine ne peuvent pas être utilisés dans le même workflow.",
+ "nodes.humanInputMigration.oldVersion": "ANCIENNE VERSION",
+ "nodes.humanInputMigration.preview.author": "Par l’équipe Dify",
+ "nodes.humanInputMigration.preview.description": "Migrez les anciens nœuds de saisie humaine avant d’en ajouter un nouveau.",
+ "nodes.humanInputMigration.success": "Nœuds de saisie humaine migrés avec succès",
+ "nodes.humanInputV2.card.configured": "{{count}} destinataires configurés",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} contacts",
+ "nodes.humanInputV2.card.empty": "Personne ne peut encore approuver cette étape",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Initiateur et {{count}} contacts",
+ "nodes.humanInputV2.card.initiatorOnly": "Initiateur uniquement",
+ "nodes.humanInputV2.card.invalid": "La configuration des destinataires doit être vérifiée",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-mail",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Configurer le mode débogage",
"nodes.humanInputV2.debug.keepOneChannel": "Gardez au moins un canal activé",
+ "nodes.humanInputV2.debug.sendVia": "Envoyer les notifications de débogage via",
+ "nodes.humanInputV2.debug.title": "Mode débogage",
+ "nodes.humanInputV2.debug.toggle": "Activer le mode débogage",
+ "nodes.humanInputV2.debug.unsupported": "Canaux importés non pris en charge : {{channels}}. Supprimez-les ou mettez-les à jour avant d’exécuter ce workflow.",
"nodes.humanInputV2.disabled": "Human Input v2 est indisponible lorsque HITL IM est désactivé.",
+ "nodes.humanInputV2.error.bodyRequired": "Le corps du message est requis",
+ "nodes.humanInputV2.error.debugChannelRequired": "Sélectionnez au moins un canal du mode débogage",
+ "nodes.humanInputV2.error.recipientDuplicate": "Supprimez les destinataires en double",
+ "nodes.humanInputV2.error.recipientInvalid": "Corrigez la configuration invalide des destinataires",
+ "nodes.humanInputV2.error.recipientRequired": "Ajoutez au moins un destinataire",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Impossible de vérifier les destinataires issus des contacts",
"nodes.humanInputV2.error.requestURLDuplicate": "Le corps du message ne peut contenir qu’une seule URL de demande.",
"nodes.humanInputV2.error.requestURLRequired": "Insérez une URL de demande dans le corps du message.",
+ "nodes.humanInputV2.error.subjectRequired": "L’objet du message est requis",
+ "nodes.humanInputV2.error.version": "Human Input v2 exige la valeur de version 2 sous forme de chaîne de caractères",
+ "nodes.humanInputV2.recipients.addContact": "Ajouter un contact",
+ "nodes.humanInputV2.recipients.addEmail": "Ajouter",
+ "nodes.humanInputV2.recipients.addRecipient": "Ajouter un destinataire",
+ "nodes.humanInputV2.recipients.added": "Ajouté",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Tous les contacts de l’espace de travail",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Notifier tous les contacts de l’espace de travail ; chacun d’entre eux peut approuver",
+ "nodes.humanInputV2.recipients.cancel": "Annuler",
+ "nodes.humanInputV2.recipients.chooseVariable": "Choisir une variable",
+ "nodes.humanInputV2.recipients.confirm": "Confirmer",
+ "nodes.humanInputV2.recipients.contactInfo": "Coordonnées de {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Tous",
+ "nodes.humanInputV2.recipients.contactSource.external": "Externe",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organisation",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Espace de travail",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Source du contact",
"nodes.humanInputV2.recipients.duplicateSource": "Déjà ajouté via {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Modifier {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Modifier le destinataire",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Chaque adresse e-mail ne peut être sélectionnée qu’une seule fois.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Saisissez une adresse e-mail valide qui n’a pas déjà été ajoutée",
+ "nodes.humanInputV2.recipients.emailLabel": "Destinataire par e-mail ponctuel",
+ "nodes.humanInputV2.recipients.empty": "Aucun destinataire configuré",
+ "nodes.humanInputV2.recipients.help": "Choisissez qui peut répondre à cette étape de saisie humaine.",
"nodes.humanInputV2.recipients.initiator": "L’utilisateur qui lance cette exécution via Web App ou CLI peut approuver",
+ "nodes.humanInputV2.recipients.initiatorDescription": "La personne qui lance cette exécution du workflow peut répondre.",
"nodes.humanInputV2.recipients.inputHelp": "Saisissez ou collez plusieurs adresses e-mail séparées par des virgules. Appuyez sur / pour insérer une variable.",
+ "nodes.humanInputV2.recipients.insertVariable": "Insérer une variable",
+ "nodes.humanInputV2.recipients.loadError": "Impossible de charger les contacts. Les ID de contact enregistrés sont conservés.",
+ "nodes.humanInputV2.recipients.loading": "Chargement des contacts…",
+ "nodes.humanInputV2.recipients.noResults": "Aucun contact trouvé",
+ "nodes.humanInputV2.recipients.placeholder": "Rechercher des contacts ou ajouter des adresses e-mail",
+ "nodes.humanInputV2.recipients.remove": "Supprimer {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Appuyez sur Retour arrière ou Suppr pour supprimer.",
+ "nodes.humanInputV2.recipients.resultCount": "Destinataires correspondants : {{count}}",
+ "nodes.humanInputV2.recipients.search": "Rechercher des contacts",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Rechercher par nom ou par adresse e-mail",
+ "nodes.humanInputV2.recipients.selectionHint": "Destinataires sélectionnés : {{count}}. Au début du champ, appuyez sur la flèche gauche pour les sélectionner.",
+ "nodes.humanInputV2.recipients.title": "Destinataires",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Tous les contacts de l’espace de travail",
+ "nodes.humanInputV2.recipients.type.contact": "Contact",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "E-mail dynamique",
+ "nodes.humanInputV2.recipients.type.initiator": "Initiateur",
+ "nodes.humanInputV2.recipients.type.onetime_email": "E-mail ponctuel",
+ "nodes.humanInputV2.recipients.typeLabel": "Type de destinataire",
"nodes.humanInputV2.recipients.useThisInstead": "Utiliser celui-ci à la place",
+ "nodes.humanInputV2.recipients.variableRequired": "Choisissez une variable d’e-mail",
+ "nodes.humanInputV2.template.body": "Corps",
+ "nodes.humanInputV2.template.description": "Texte de repli pour les e-mails et la messagerie instantanée",
"nodes.humanInputV2.template.insertRequestURL": "Insérer l’URL de la demande",
+ "nodes.humanInputV2.template.insertVariable": "Insérer une variable",
+ "nodes.humanInputV2.template.notConfigured": "Non configuré",
"nodes.humanInputV2.template.requestURLHint": "Les destinataires ouvrent le formulaire d’approbation avec ce lien. Insérez exactement une URL de demande.",
"nodes.humanInputV2.template.requestURLInserted": "URL de la demande insérée",
"nodes.humanInputV2.template.saveAndTest": "Enregistrer et tester",
+ "nodes.humanInputV2.template.subject": "Objet",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Saisissez l’objet du message",
"nodes.humanInputV2.template.test": "Tester le message",
"nodes.humanInputV2.template.testChannel": "Canal de test",
"nodes.humanInputV2.template.testCompleted": "La demande de test est terminée. Consultez le canal sélectionné pour voir le message.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Renseignez toutes les valeurs des variables de test.",
"nodes.humanInputV2.template.testSaveFailed": "Impossible d’enregistrer le brouillon du workflow. Le test n’a pas été envoyé.",
"nodes.humanInputV2.template.testUnavailable": "Cet environnement ne prend pas encore en charge le test des modèles de message.",
+ "nodes.humanInputV2.template.title": "Modèle de message",
"nodes.ifElse.operator": "Opérateur",
"nodes.iteration.currentIteration": "Itération actuelle",
"nodes.iteration.deleteDesc": "La suppression du nœud d'itération supprimera tous les nœuds enfants",
diff --git a/web/i18n/locales/hi-IN/contacts.json b/web/i18n/locales/hi-IN/contacts.json
index 5cc14b8c21a..598412cdc80 100644
--- a/web/i18n/locales/hi-IN/contacts.json
+++ b/web/i18n/locales/hi-IN/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "संपर्क हटाएँ ({{count}})?",
"directory.removalDescription": "चुने गए संपर्क इस कार्यक्षेत्र से स्थायी रूप से हटा दिए जाएँगे। इस कार्रवाई को पूर्ववत नहीं किया जा सकता।",
- "directory.removalTitle": "संपर्क हटाएँ?",
+ "directory.removalSingleDescription": "{{name}} को इस कार्यक्षेत्र से स्थायी रूप से हटा दिया जाएगा। इस कार्रवाई को वापस नहीं लिया जा सकता।",
+ "directory.removalSingleFailed": "संपर्क हटाया नहीं जा सका। फिर से प्रयास करें।",
+ "directory.removalSingleTitle": "{{name}} को हटाएँ?",
+ "directory.resultCount": "परिणाम: {{count}}",
+ "imPlatform.action.configure": "कॉन्फ़िगर करें",
+ "imPlatform.action.configureChannel": "{{provider}} कॉन्फ़िगर करें",
+ "imPlatform.action.connect": "कनेक्ट करें",
+ "imPlatform.action.copied": "कॉपी किया गया",
+ "imPlatform.action.copyCallback": "कॉलबैक URL कॉपी करें",
+ "imPlatform.action.deleteChannel": "{{provider}} हटाएँ",
+ "imPlatform.action.loadMore": "और लोड करें",
+ "imPlatform.action.replace": "प्रतिस्थापित करें",
+ "imPlatform.action.retry": "पुनर्प्रयास",
+ "imPlatform.action.save": "सहेजें",
+ "imPlatform.action.saving": "सहेजा जा रहा है",
+ "imPlatform.action.setupGuide": "सेटअप गाइड",
+ "imPlatform.action.syncNow": "अभी सिंक करें",
+ "imPlatform.action.syncing": "सिंक हो रहा है",
+ "imPlatform.action.testConnection": "कनेक्शन जाँचें",
+ "imPlatform.action.testing": "जाँच हो रही है",
+ "imPlatform.action.viewDetails": "विवरण देखें",
+ "imPlatform.bindingDialog.back": "वापस",
+ "imPlatform.bindingDialog.callback": "कॉलबैक URL",
+ "imPlatform.bindingDialog.callbackDescription": "कार्ड की कार्रवाइयाँ चालू करने के लिए {{provider}} में कॉलबैक सेटअप पूरा करें।",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "कार्ड की कार्रवाइयों के लिए इस URL को <console>Feishu डेवलपर कंसोल</console> में पेस्ट करें:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "इवेंट और कॉलबैक → कॉलबैक कॉन्फ़िगरेशन → अनुरोध URL",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "कार्ड की कार्रवाइयों के लिए इस URL को <console>Lark डेवलपर कंसोल</console> में पेस्ट करें:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "इवेंट और कॉलबैक → कॉलबैक कॉन्फ़िगरेशन → अनुरोध URL",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "कार्ड की कार्रवाइयों के लिए इस URL को <console>Slack डेवलपर कंसोल</console> में पेस्ट करें:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "इंटरैक्टिविटी और शॉर्टकट → इंटरैक्टिविटी → अनुरोध URL",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "कार्ड की कार्रवाइयों के लिए इस URL को <console>Azure Bot कॉन्फ़िगरेशन</console> में पेस्ट करें:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "सेटिंग्स → कॉन्फ़िगरेशन → मैसेजिंग एंडपॉइंट",
+ "imPlatform.bindingDialog.callbackStep": "कॉलबैक कॉन्फ़िगर करें",
"imPlatform.bindingDialog.clearSavedCredential": "सहेजा गया मान साफ़ करें",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} कॉन्फ़िगर करें",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}} कनेक्ट करें",
"imPlatform.bindingDialog.credentialWillBeCleared": "सहेजने पर यह सहेजा गया मान साफ़ हो जाएगा।",
+ "imPlatform.bindingDialog.credentialsDescription": "पहले अपना {{provider}} ऐप कनेक्ट करें, फिर उसका कॉलबैक URL कॉन्फ़िगर करें।",
+ "imPlatform.bindingDialog.credentialsStep": "ऐप क्रेडेंशियल",
+ "imPlatform.bindingDialog.description": "इस मैसेजिंग प्लेटफ़ॉर्म के ऐप क्रेडेंशियल दर्ज करें।",
+ "imPlatform.bindingDialog.field.agentId": "एजेंट ID",
+ "imPlatform.bindingDialog.field.appId": "ऐप ID",
+ "imPlatform.bindingDialog.field.appToken": "ऐप टोकन (वैकल्पिक)",
+ "imPlatform.bindingDialog.field.botToken": "बॉट टोकन",
+ "imPlatform.bindingDialog.field.clientId": "क्लाइंट आईडी",
+ "imPlatform.bindingDialog.field.clientSecret": "क्लाइंट सीक्रेट",
+ "imPlatform.bindingDialog.field.corpId": "संगठन ID",
+ "imPlatform.bindingDialog.field.encryptKey": "एन्क्रिप्शन कुंजी (वैकल्पिक)",
+ "imPlatform.bindingDialog.field.genericSecret": "गुप्त",
+ "imPlatform.bindingDialog.field.secret": "ऐप सीक्रेट",
+ "imPlatform.bindingDialog.field.signingSecret": "साइनिंग सीक्रेट",
+ "imPlatform.bindingDialog.field.tenantId": "टेनेंट ID",
+ "imPlatform.bindingDialog.field.verificationToken": "सत्यापन टोकन (वैकल्पिक)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "यदि चालू हो, तो एन्क्रिप्शन कुंजी दर्ज करें",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "ऐप सीक्रेट दर्ज करें",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "यदि कॉन्फ़िगर किया गया हो, तो सत्यापन टोकन दर्ज करें",
+ "imPlatform.bindingDialog.finish": "समाप्त करें",
+ "imPlatform.bindingDialog.freshCredentials": "सहेजे गए सीक्रेट दोबारा प्राप्त नहीं किए जा सकते। इस कॉन्फ़िगरेशन को जाँचने या सहेजने के लिए सभी आवश्यक क्रेडेंशियल फिर से दर्ज करें।",
+ "imPlatform.bindingDialog.openSetupGuide": "सेटअप गाइड खोलें",
+ "imPlatform.bindingDialog.replaceTenantTitle": "{{identity}} के टेनेंट क्रेडेंशियल बदलें?",
"imPlatform.bindingDialog.replacementRequired": "ये क्रेडेंशियल किसी दूसरे IM टेनेंट के हैं और इन्हें सीधे सहेजा नहीं जा सकता। टेनेंट बदलने के लिए मौजूदा IM चैनल को बदलना होगा, जिससे सभी स्वचालित और मैन्युअल IM बाइंडिंग मिट जाएँगी। चैनल बदलने के बाद संपर्कों को फिर से सिंक करें।",
+ "imPlatform.bindingDialog.required": "यह फ़ील्ड आवश्यक है।",
+ "imPlatform.bindingDialog.saveAndContinue": "सहेजें और जारी रखें",
+ "imPlatform.bindingDialog.saveFailed": "कॉन्फ़िगरेशन सहेजा नहीं जा सका। फ़ील्ड जाँचें और फिर से कोशिश करें।",
"imPlatform.bindingDialog.savedDetailsUnavailable": "कॉन्फ़िगरेशन सहेज लिया गया है, लेकिन उसका विवरण लोड नहीं हो सका। यह संवाद बंद करके फिर खोलें।",
- "imPlatform.bindingDialog.undoClearCredential": "साफ़ करना पूर्ववत करें"
+ "imPlatform.bindingDialog.secretConfigured": "सीक्रेट पहले से कॉन्फ़िगर है। उसे बनाए रखने के लिए यह फ़ील्ड खाली छोड़ें।",
+ "imPlatform.bindingDialog.step": "चरण {{step}}",
+ "imPlatform.bindingDialog.testFailed": "कनेक्शन की जाँच विफल हुई। कॉन्फ़िगरेशन जाँचें और फिर से कोशिश करें।",
+ "imPlatform.bindingDialog.undoClearCredential": "साफ़ करना पूर्ववत करें",
+ "imPlatform.bindingDialog.viewSetupGuide": "सेटअप गाइड देखें",
+ "imPlatform.chooseProvider": "कनेक्ट करने के लिए कोई चैनल चुनें",
+ "imPlatform.configurationUpdated": "इस चैनल का कॉन्फ़िगरेशन बदल गया है। फिर से कोशिश करने से पहले यह डायलॉग बंद करके पेज रीफ़्रेश करें।",
+ "imPlatform.connectMore": "और चैनल कनेक्ट करें",
+ "imPlatform.delete.confirm": "हटाएँ",
+ "imPlatform.delete.description": "इस चैनल को हटाने पर उसका कॉन्फ़िगरेशन मिट जाएगा। इस चैनल का उपयोग करने वाले अनुमोदन संदेश और डायरेक्टरी सिंक बंद हो जाएँगे।",
+ "imPlatform.delete.failed": "चैनल हटाया नहीं जा सका। कोई बदलाव नहीं हुआ; फिर से कोशिश करें।",
+ "imPlatform.delete.title": "{{provider}} चैनल हटाएँ?",
+ "imPlatform.description": "अपनी कंपनी के चैनल कनेक्ट करें, ताकि अनुमोदन अनुरोध लोगों तक उनके कार्यस्थल पर पहुँचें।",
+ "imPlatform.details.column.contact": "संपर्क",
+ "imPlatform.details.column.platform": "मैसेजिंग प्लेटफ़ॉर्म",
+ "imPlatform.details.description": "नवीनतम सिंक के परिणाम केवल पढ़ने के लिए देखें।",
+ "imPlatform.details.downloadFailed": "रिपोर्ट डाउनलोड नहीं हो सकी। फिर से कोशिश करें।",
+ "imPlatform.details.downloadReport": "रिपोर्ट डाउनलोड करें",
+ "imPlatform.details.downloadingReport": "रिपोर्ट डाउनलोड हो रही है…",
+ "imPlatform.details.empty": "इस श्रेणी में कोई परिणाम नहीं है।",
+ "imPlatform.details.filter.added": "जोड़ा गया",
+ "imPlatform.details.filter.failed": "असफल",
+ "imPlatform.details.filter.not_matched": "मेल नहीं मिला",
+ "imPlatform.details.filter.removed": "हटाया गया",
+ "imPlatform.details.filter.skipped": "छोड़े गए",
+ "imPlatform.details.filters": "सिंक परिणामों के फ़िल्टर",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "सिंक की जानकारी लोड नहीं हो सकी।",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "और परिणाम लोड नहीं हो सके। इस पेज को फिर से लोड करें।",
+ "imPlatform.details.removalReason.binding_invalidated": "बाइंडिंग अमान्य कर दी गई",
+ "imPlatform.details.removalReason.binding_replaced": "बाइंडिंग बदल दी गई",
+ "imPlatform.details.removalReason.not_present_in_directory": "अब निर्देशिका में नहीं है",
+ "imPlatform.details.reportChanged": "सिंक के परिणाम बदल गए हैं। नवीनतम सिंक की जानकारी फिर से खोलकर कोशिश करें।",
+ "imPlatform.details.title": "सिंक की जानकारी",
+ "imPlatform.email.apiKey": "एपीआई कुंजी",
+ "imPlatform.email.apiKeyConfigured": "सुरक्षा कारणों से सहेजी गई API कुंजी नहीं देखी जा सकती। उसे बनाए रखने के लिए यह फ़ील्ड खाली छोड़ें।",
+ "imPlatform.email.apiKeyDescription": "सुरक्षा कारणों से यह API कुंजी सहेजने के बाद नहीं देखी जा सकती।",
+ "imPlatform.email.apiKeyPlaceholder": "अपनी Resend API कुंजी दर्ज करें",
+ "imPlatform.email.description": "यह कॉन्फ़िगरेशन इस वर्कस्पेस के उन सभी Human Input नोड पर लागू होता है जिनमें <emphasis>ईमेल से डीबग सूचनाएँ भेजें</emphasis> चालू है।",
+ "imPlatform.email.invalidEmail": "मान्य ईमेल पता दर्ज करें।",
+ "imPlatform.email.provider": "ईमेल प्रदाता",
+ "imPlatform.email.resendDescription": "आपकी <apiKey>Resend API कुंजी</apiKey> एन्क्रिप्ट की जाएगी और सहेजने के बाद नहीं देखी जा सकेगी।<br/><resend>Resend</resend> खाता बनाएँ।",
+ "imPlatform.email.resendSettings": "Resend सेटिंग्स",
+ "imPlatform.email.senderEmail": "प्रेषक का ईमेल पता",
+ "imPlatform.email.senderEmailDescription": "प्रेषक के रूप में दिखाई देने वाला ईमेल पता। उसका डोमेन Resend में सत्यापित होना चाहिए।",
+ "imPlatform.email.senderName": "प्रेषक का नाम",
+ "imPlatform.email.senderNameDescription": "प्राप्तकर्ता के इनबॉक्स में दिखाई देने वाला नाम।",
+ "imPlatform.email.testSucceeded": "कनेक्शन की जाँच सफल रही।",
+ "imPlatform.email.title": "ईमेल कॉन्फ़िगर करें",
+ "imPlatform.learnMore": "और जानें",
+ "imPlatform.loadError.description": "वर्तमान बाइंडिंग और अनुमतियाँ पढ़ने के लिए फिर से कोशिश करें।",
+ "imPlatform.loadError.retry": "फिर से कोशिश करें",
+ "imPlatform.loadError.title": "चैनल लोड नहीं हो सके",
+ "imPlatform.loading": "चैनल लोड हो रहे हैं",
+ "imPlatform.provider.dingtalkDescription": "DingTalk ऐप कनेक्ट करें।",
+ "imPlatform.provider.emailDescription": "इस वर्कस्पेस से अनुमोदन अनुरोध भेजने के लिए ईमेल सेवा कॉन्फ़िगर करें।",
+ "imPlatform.provider.feishuDescription": "Feishu ऐप कनेक्ट करें।",
+ "imPlatform.provider.larkDescription": "Lark ऐप कनेक्ट करें।",
+ "imPlatform.provider.msTeamsDescription": "Microsoft Teams ऐप कनेक्ट करें।",
+ "imPlatform.provider.slackDescription": "लोगों और उनकी Slack पहचानों को सिंक करें।",
+ "imPlatform.provider.weComDescription": "WeCom ऐप कनेक्ट करें।",
+ "imPlatform.replacement.confirm": "प्रतिस्थापित करें",
+ "imPlatform.replacement.description": "सक्रिय प्रदाता को बदलने से उसकी मैसेजिंग बाइंडिंग और वर्कस्पेस ओवरराइड अमान्य हो जाएँगे। बदलने के बाद नए प्रदाता की डायरेक्टरी फिर से सिंक करें।",
+ "imPlatform.replacement.title": "{{current}} को {{next}} से बदलें?",
+ "imPlatform.status.configured": "कॉन्फ़िगर किया गया",
+ "imPlatform.status.connected": "कनेक्टेड",
+ "imPlatform.status.connection_error": "कनेक्शन में त्रुटि",
+ "imPlatform.status.permission_issue": "अनुमति में समस्या",
+ "imPlatform.sync.latestSynced": "पिछला सिंक: {{date}}",
+ "imPlatform.sync.loading": "सक्रिय सिंक की जाँच हो रही है।",
+ "imPlatform.sync.noPermission": "केवल वर्कस्पेस के मालिक और व्यवस्थापक डायरेक्टरी सिंक शुरू कर सकते हैं।",
+ "imPlatform.sync.noRuns": "अभी तक कोई डायरेक्टरी सिंक नहीं चला है।",
+ "imPlatform.sync.notConnected": "डायरेक्टरी सिंक शुरू करने से पहले किसी प्रदाता को कनेक्ट करके जाँचें।",
+ "imPlatform.sync.startFailed": "डायरेक्टरी सिंक शुरू या रीफ़्रेश नहीं हो सका। फिर से कोशिश करें।",
+ "imPlatform.sync.status.failure": "असफल",
+ "imPlatform.sync.status.queued": "कतार में",
+ "imPlatform.sync.status.running": "चल रहा है",
+ "imPlatform.sync.status.success": "सफल",
+ "imPlatform.title": "चैनल"
}
diff --git a/web/i18n/locales/hi-IN/share.json b/web/i18n/locales/hi-IN/share.json
index bfade2e42fb..d337f5d535f 100644
--- a/web/i18n/locales/hi-IN/share.json
+++ b/web/i18n/locales/hi-IN/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "धन्यवाद!",
"humanInput.unavailableDescription": "हो सकता है कि लिंक उपलब्ध न हो या उस खाते से मेल न खाता हो जिससे आपने साइन इन किया है। मिले हुए नोटिफ़िकेशन से फ़ॉर्म खोलें या खाता बदलकर देखें।",
"humanInput.unavailableTitle": "यह फ़ॉर्म नहीं खोला जा सकता",
+ "humanInputV2.accessRateLimited": "सत्यापन ईमेल के लिए बहुत अधिक अनुरोध किए गए हैं। कृपया बाद में फिर से कोशिश करें।",
+ "humanInputV2.alreadySubmitted": "यह अनुरोध पहले ही पूरा हो चुका है।",
+ "humanInputV2.challengeExpired": "इस सत्यापन कोड की समय-सीमा समाप्त हो गई है। जारी रखने के लिए नया कोड माँगें।",
+ "humanInputV2.challengeStale": "यह सत्यापन कोड बदल दिया गया है। जारी रखने के लिए नया कोड माँगें।",
+ "humanInputV2.codeExpiresIn": "कोड की समय-सीमा {{seconds}} सेकंड में समाप्त होगी",
+ "humanInputV2.codeRequired": "जारी रखने के लिए सत्यापन कोड माँगें।",
+ "humanInputV2.codeSent": "आपके ईमेल पर सत्यापन कोड भेज दिया गया है।",
+ "humanInputV2.deliveryFailed": "सत्यापन ईमेल नहीं भेजा जा सका। कृपया फिर से कोशिश करें।",
+ "humanInputV2.formExpired": "इस अनुरोध की समय-सीमा समाप्त हो गई है।",
+ "humanInputV2.formNotFound": "फ़ॉर्म नहीं मिला।",
+ "humanInputV2.formRateLimited": "फ़ॉर्म के लिए बहुत अधिक अनुरोध किए गए हैं। कृपया बाद में फिर से कोशिश करें।",
+ "humanInputV2.invalidOtp": "सत्यापन कोड गलत है। कोड जाँचें और फिर से कोशिश करें।",
+ "humanInputV2.networkError": "अनुरोध पूरा नहीं किया जा सका। अपना कनेक्शन जाँचें और फिर से कोशिश करें।",
+ "humanInputV2.otpLabel": "ईमेल सत्यापन कोड",
+ "humanInputV2.otpPlaceholder": "6 अंकों का कोड दर्ज करें",
+ "humanInputV2.requestingCode": "सत्यापन कोड भेजा जा रहा है…",
+ "humanInputV2.resendCode": "कोड फिर से भेजें",
+ "humanInputV2.retry": "फिर से कोशिश करें",
+ "humanInputV2.sendCode": "नया कोड भेजें",
+ "humanInputV2.unavailable": "यह फ़ॉर्म अस्थायी रूप से उपलब्ध नहीं है।",
+ "humanInputV2.unknownError": "कुछ गड़बड़ी हुई। कृपया फिर से कोशिश करें।",
+ "humanInputV2.uploadFailed": "फ़ाइल अपलोड नहीं की जा सकी। कृपया फिर से कोशिश करें।",
"login.backToHome": "होम पर वापस"
}
diff --git a/web/i18n/locales/hi-IN/workflow-human-input.json b/web/i18n/locales/hi-IN/workflow-human-input.json
index 26f21bc669c..372dd5f411e 100644
--- a/web/i18n/locales/hi-IN/workflow-human-input.json
+++ b/web/i18n/locales/hi-IN/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "क्रिया मूल्य",
"nodes.humanInput.userActions.buttonTextTooLong": "बटन पाठ {{maxLength}} वर्ण या उससे कम होना चाहिए",
"nodes.humanInput.userActions.chooseStyle": "बटन शैली चुनें",
+ "nodes.humanInput.userActions.defaultTitle": "बटन टेक्स्ट {{index}}",
"nodes.humanInput.userActions.emptyTip": "उपयोगकर्ता कार्रवाइयां जोड़ने के लिए '+' बटन पर क्लिक करें",
"nodes.humanInput.userActions.title": "उपयोगकर्ता कार्रवाइयां",
"nodes.humanInput.userActions.tooltip": "उन बटन को परिभाषित करें जिन पर उपयोगकर्ता इस फॉर्म का जवाब देने के लिए क्लिक कर सकते हैं। कार्रवाई आईडी शाखाओं को नियंत्रित करती है। क्रिया मूल्य डाउनस्ट्रीम में चयनित बिल्ट-इन आउटपुट के रूप में उजागर होता है। कार्रवाई आईडी एक अक्षर या अंडरस्कोर से शुरू होनी चाहिए, उसके बाद अक्षर, संख्याएं या अंडरस्कोर हो सकते हैं।",
diff --git a/web/i18n/locales/hi-IN/workflow.json b/web/i18n/locales/hi-IN/workflow.json
index 903ff5e72b4..f651e48fd00 100644
--- a/web/i18n/locales/hi-IN/workflow.json
+++ b/web/i18n/locales/hi-IN/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "आउटपुट",
"blocks.http-request": "एचटीटीपी अनुरोध",
"blocks.human-input": "मानव इनपुट",
+ "blocks.human-input-v2": "मानव इनपुट v2",
"blocks.if-else": "यदि/अन्यथा",
"blocks.iteration": "पुनरावृत्ति",
"blocks.iteration-start": "पुनरावृत्ति प्रारंभ",
@@ -45,6 +46,7 @@
"blocksAbout.end": "वर्कफ़्लो का आउटपुट और परिणाम प्रकार परिभाषित करें",
"blocksAbout.http-request": "HTTP प्रोटोकॉल पर सर्वर अनुरोधों को भेजने की अनुमति दें",
"blocksAbout.human-input": "अगला कदम उत्पन्न करने से पहले मानव से पुष्टि मांगें",
+ "blocksAbout.human-input-v2": "कॉन्फ़िगर किए गए संपर्कों, ईमेल प्राप्तकर्ताओं या वर्कफ़्लो आरंभकर्ता से इनपुट माँगें",
"blocksAbout.if-else": "if/else शर्तों के आधार पर वर्कफ़्लो को दो शाखाओं में विभाजित करने की अनुमति देता है",
"blocksAbout.iteration": "एक सूची वस्तु पर तब तक कई कदम करें जब तक सभी परिणाम आउटपुट न हो जाएं।",
"blocksAbout.iteration-start": "पुनरावृत्ति प्रारंभ नोड",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "डाउनस्ट्रीम नोड्स की एकीकृत कॉन्फ़िगरेशन के लिए बहु-शाखा चर को एकल चर में संकलित करें।",
"blocksAbout.variable-assigner": "डाउनस्ट्रीम नोड्स की एकीकृत कॉन्फ़िगरेशन के लिए बहु-शाखा चर को एकल चर में संकलित करें।",
"changeHistory.edgeDelete": "नोड डिस्कनेक्ट हो गया",
+ "changeHistory.humanInputMigration": "मानव इनपुट नोड माइग्रेट किए गए",
"changeHistory.nodeAdd": "नोड जोड़ा गया",
"changeHistory.nodeChange": "नोड बदला गया",
"changeHistory.nodeConnect": "नोड कनेक्टेड",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "कृपया कम से कम एक डिलीवरी विधि सक्षम करें",
"nodes.humanInput.errorMsg.noUserActions": "कृपया कम से कम एक उपयोगकर्ता कार्रवाई जोड़ें",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} टाइमआउट शाखा के लिए आरक्षित है। कोई अन्य कार्रवाई ID चुनें।",
+ "nodes.humanInput.output.actionId": "उपयोगकर्ता द्वारा शुरू की गई कार्रवाई का ID",
+ "nodes.humanInput.output.actionValue": "चुनी गई कार्रवाई का मान",
+ "nodes.humanInput.output.formInput": "फ़ॉर्म इनपुट का मान",
+ "nodes.humanInput.output.renderedContent": "रेंडर की गई सामग्री",
"nodes.humanInput.timeout.title": "टाइमआउट",
+ "nodes.humanInputMigration.action.migrate": "माइग्रेट करें",
+ "nodes.humanInputMigration.action.migrateNow": "अभी माइग्रेट करें",
+ "nodes.humanInputMigration.action.migrating": "माइग्रेट हो रहा है...",
+ "nodes.humanInputMigration.banner.ariaLabel": "मानव इनपुट माइग्रेशन सूचना",
+ "nodes.humanInputMigration.banner.description": "यह वर्कफ़्लो पुराने मानव इनपुट नोड का उपयोग करता है। नए नोड जोड़ने से पहले सभी पुराने नोड माइग्रेट करें।",
+ "nodes.humanInputMigration.banner.learnMore": "और जानें",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "अक्षम वितरण विधि में अभी भी कॉन्फ़िगरेशन मौजूद है",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "सक्षम ईमेल विधियाँ परस्पर विरोधी टेम्पलेट का उपयोग करती हैं",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "अमान्य डिफ़ॉल्ट मान",
+ "nodes.humanInputMigration.blocker.invalidEmail": "प्राप्तकर्ता का ईमेल अमान्य है",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "सक्षम ईमेल विधि का कॉन्फ़िगरेशन अधूरा है",
+ "nodes.humanInputMigration.blocker.missingRecipients": "नोड में कोई समर्थित प्राप्तकर्ता नहीं है",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "कार्यस्थान के किसी सदस्य को संपर्क या सत्यापित ईमेल से नहीं जोड़ा जा सका",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "सक्षम वितरण विधि मानव इनपुट v2 में समर्थित नहीं है",
"nodes.humanInputMigration.blocker.unsupportedInputType": "फ़ील्ड {{field}} को अभी माइग्रेट नहीं किया जा सकता। आप पुराने मानव इनपुट नोड का उपयोग जारी रख सकते हैं।",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "नोड का संस्करण मान समर्थित नहीं है",
+ "nodes.humanInputMigration.dialog.description": "आपके प्राप्तकर्ता, फ़ॉर्म और कार्रवाइयाँ बनी रहेंगी।",
+ "nodes.humanInputMigration.dialog.draftNotice": "केवल यह ड्राफ़्ट बदलेगा। दोबारा प्रकाशित करने तक प्रकाशित संस्करण चलते रहेंगे।",
+ "nodes.humanInputMigration.dialog.review": "नोड की समीक्षा करें और तैयार होने पर प्रकाशित करें।",
+ "nodes.humanInputMigration.dialog.title": "{{count}} मानव इनपुट नोड माइग्रेट करें",
+ "nodes.humanInputMigration.disabledBadge": "माइग्रेशन आवश्यक है",
+ "nodes.humanInputMigration.disabledReason": "नया नोड जोड़ने से पहले पुराने मानव इनपुट नोड माइग्रेट करें।",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} माइग्रेट नहीं किया जा सका: {{reason}}।",
"nodes.humanInputMigration.error.graphChanged": "माइग्रेशन के दौरान वर्कफ़्लो बदल गया। फिर से कोशिश करें; आपके वर्तमान संपादन सुरक्षित हैं।",
+ "nodes.humanInputMigration.error.preflight": "माइग्रेशन की तैयारी नहीं हो सकी। आपके वर्कफ़्लो में कोई बदलाव नहीं किया गया। कृपया फिर से कोशिश करें।",
"nodes.humanInputMigration.error.sync": "माइग्रेट किए गए वर्कफ़्लो को सहेजा नहीं जा सका। वर्तमान ड्राफ़्ट की जाँच करें और फिर से कोशिश करें।",
+ "nodes.humanInputMigration.incompatibleVersions": "एक ही वर्कफ़्लो में पुराने और नए मानव इनपुट नोड का एक साथ उपयोग नहीं किया जा सकता।",
+ "nodes.humanInputMigration.oldVersion": "पुराना संस्करण",
+ "nodes.humanInputMigration.preview.author": "Dify टीम द्वारा",
+ "nodes.humanInputMigration.preview.description": "नया नोड जोड़ने से पहले पुराने मानव इनपुट नोड माइग्रेट करें।",
+ "nodes.humanInputMigration.success": "मानव इनपुट नोड सफलतापूर्वक माइग्रेट किए गए",
+ "nodes.humanInputV2.card.configured": "{{count}} प्राप्तकर्ता कॉन्फ़िगर किए गए",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} संपर्क",
+ "nodes.humanInputV2.card.empty": "अभी इस चरण को कोई स्वीकृति नहीं दे सकता",
+ "nodes.humanInputV2.card.initiatorAndContacts": "आरंभकर्ता और {{count}} संपर्क",
+ "nodes.humanInputV2.card.initiatorOnly": "केवल आरंभकर्ता",
+ "nodes.humanInputV2.card.invalid": "प्राप्तकर्ता कॉन्फ़िगरेशन पर ध्यान देने की आवश्यकता है",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "ईमेल",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "डीबग मोड कॉन्फ़िगर करें",
"nodes.humanInputV2.debug.keepOneChannel": "कम से कम एक चैनल चालू रखें",
+ "nodes.humanInputV2.debug.sendVia": "डीबग सूचनाएँ भेजने का माध्यम",
+ "nodes.humanInputV2.debug.title": "डीबग मोड",
+ "nodes.humanInputV2.debug.toggle": "डीबग मोड सक्षम करें",
+ "nodes.humanInputV2.debug.unsupported": "आयात किए गए असमर्थित चैनल: {{channels}}। इस वर्कफ़्लो को चलाने से पहले उन्हें हटाएँ या अपडेट करें।",
"nodes.humanInputV2.disabled": "HITL IM अक्षम होने पर Human Input v2 उपलब्ध नहीं है।",
+ "nodes.humanInputV2.error.bodyRequired": "संदेश का मुख्य भाग आवश्यक है",
+ "nodes.humanInputV2.error.debugChannelRequired": "डीबग मोड का कम से कम एक चैनल चुनें",
+ "nodes.humanInputV2.error.recipientDuplicate": "डुप्लिकेट प्राप्तकर्ता हटाएँ",
+ "nodes.humanInputV2.error.recipientInvalid": "अमान्य प्राप्तकर्ता कॉन्फ़िगरेशन ठीक करें",
+ "nodes.humanInputV2.error.recipientRequired": "कम से कम एक प्राप्तकर्ता जोड़ें",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "संपर्क प्राप्तकर्ताओं को सत्यापित नहीं किया जा सका",
"nodes.humanInputV2.error.requestURLDuplicate": "संदेश के मुख्य भाग में केवल एक अनुरोध URL हो सकता है।",
"nodes.humanInputV2.error.requestURLRequired": "संदेश के मुख्य भाग में अनुरोध URL डालें।",
+ "nodes.humanInputV2.error.subjectRequired": "संदेश का विषय आवश्यक है",
+ "nodes.humanInputV2.error.version": "मानव इनपुट v2 के लिए संस्करण का मान स्ट्रिंग 2 होना चाहिए",
+ "nodes.humanInputV2.recipients.addContact": "संपर्क जोड़ें",
+ "nodes.humanInputV2.recipients.addEmail": "जोड़ें",
+ "nodes.humanInputV2.recipients.addRecipient": "प्राप्तकर्ता जोड़ें",
+ "nodes.humanInputV2.recipients.added": "जोड़ा गया",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "कार्यस्थान के सभी संपर्क",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "कार्यस्थान के सभी संपर्कों को सूचना भेजें; उनमें से कोई भी अनुमोदन कर सकता है",
+ "nodes.humanInputV2.recipients.cancel": "रद्द करें",
+ "nodes.humanInputV2.recipients.chooseVariable": "वेरिएबल चुनें",
+ "nodes.humanInputV2.recipients.confirm": "पुष्टि करें",
+ "nodes.humanInputV2.recipients.contactInfo": "{{name}} के संपर्क का विवरण",
+ "nodes.humanInputV2.recipients.contactSource.all": "सभी",
+ "nodes.humanInputV2.recipients.contactSource.external": "बाहरी",
+ "nodes.humanInputV2.recipients.contactSource.organization": "संगठन",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "कार्यस्थान",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "संपर्क का स्रोत",
"nodes.humanInputV2.recipients.duplicateSource": "{{name}} ({{source}}) के ज़रिए पहले ही जोड़ा जा चुका है।",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} संपादित करें",
+ "nodes.humanInputV2.recipients.editRecipient": "प्राप्तकर्ता संपादित करें",
"nodes.humanInputV2.recipients.emailAlreadySelected": "हर ईमेल केवल एक बार चुना जा सकता है।",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "ऐसा मान्य ईमेल दर्ज करें जो पहले से जोड़ा न गया हो",
+ "nodes.humanInputV2.recipients.emailLabel": "एक बार के लिए ईमेल प्राप्तकर्ता",
+ "nodes.humanInputV2.recipients.empty": "कोई प्राप्तकर्ता कॉन्फ़िगर नहीं किया गया",
+ "nodes.humanInputV2.recipients.help": "चुनें कि मानव इनपुट के इस चरण का उत्तर कौन दे सकता है।",
"nodes.humanInputV2.recipients.initiator": "Web App या CLI के ज़रिए यह रन शुरू करने वाला उपयोगकर्ता अनुमोदन कर सकता है",
+ "nodes.humanInputV2.recipients.initiatorDescription": "इस वर्कफ़्लो को शुरू करने वाला व्यक्ति उत्तर दे सकता है।",
"nodes.humanInputV2.recipients.inputHelp": "अल्पविराम से अलग किए गए कई ईमेल टाइप या पेस्ट करें। वेरिएबल डालने के लिए / दबाएँ।",
+ "nodes.humanInputV2.recipients.insertVariable": "वेरिएबल डालें",
+ "nodes.humanInputV2.recipients.loadError": "संपर्क लोड नहीं किए जा सके। सहेजी गई संपर्क ID सुरक्षित हैं।",
+ "nodes.humanInputV2.recipients.loading": "संपर्क लोड हो रहे हैं…",
+ "nodes.humanInputV2.recipients.noResults": "कोई संपर्क नहीं मिला",
+ "nodes.humanInputV2.recipients.placeholder": "संपर्क खोजें या ईमेल जोड़ें",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} हटाएँ",
+ "nodes.humanInputV2.recipients.removeHint": "हटाने के लिए Backspace या Delete दबाएँ।",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} मेल खाने वाले प्राप्तकर्ता",
+ "nodes.humanInputV2.recipients.search": "संपर्क खोजें",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "नाम या ईमेल से खोजें",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} प्राप्तकर्ता चुने गए हैं। उन पर फ़ोकस करने के लिए इनपुट की शुरुआत में बायाँ तीर दबाएँ।",
+ "nodes.humanInputV2.recipients.title": "प्राप्तकर्ता",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "कार्यस्थान के सभी संपर्क",
+ "nodes.humanInputV2.recipients.type.contact": "संपर्क",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "डायनेमिक ईमेल",
+ "nodes.humanInputV2.recipients.type.initiator": "आरंभकर्ता",
+ "nodes.humanInputV2.recipients.type.onetime_email": "एक बार के लिए ईमेल",
+ "nodes.humanInputV2.recipients.typeLabel": "प्राप्तकर्ता का प्रकार",
"nodes.humanInputV2.recipients.useThisInstead": "इसके बजाय इसका उपयोग करें",
+ "nodes.humanInputV2.recipients.variableRequired": "ईमेल वेरिएबल चुनें",
+ "nodes.humanInputV2.template.body": "मुख्य भाग",
+ "nodes.humanInputV2.template.description": "ईमेल और IM के लिए फ़ॉलबैक पाठ",
"nodes.humanInputV2.template.insertRequestURL": "अनुरोध URL डालें",
+ "nodes.humanInputV2.template.insertVariable": "वेरिएबल डालें",
+ "nodes.humanInputV2.template.notConfigured": "कॉन्फ़िगर नहीं किया गया",
"nodes.humanInputV2.template.requestURLHint": "प्राप्तकर्ता इस लिंक से अनुमोदन फ़ॉर्म खोलते हैं। ठीक एक अनुरोध URL शामिल करें।",
"nodes.humanInputV2.template.requestURLInserted": "अनुरोध URL डाला गया",
"nodes.humanInputV2.template.saveAndTest": "सहेजें और परीक्षण करें",
+ "nodes.humanInputV2.template.subject": "विषय",
+ "nodes.humanInputV2.template.subjectPlaceholder": "संदेश का विषय दर्ज करें",
"nodes.humanInputV2.template.test": "संदेश का परीक्षण करें",
"nodes.humanInputV2.template.testChannel": "परीक्षण चैनल",
"nodes.humanInputV2.template.testCompleted": "परीक्षण अनुरोध पूरा हो गया। संदेश देखने के लिए चुना गया चैनल देखें।",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "सभी परीक्षण वेरिएबल के मान भरें।",
"nodes.humanInputV2.template.testSaveFailed": "वर्कफ़्लो का ड्राफ़्ट सहेजा नहीं जा सका। परीक्षण नहीं भेजा गया।",
"nodes.humanInputV2.template.testUnavailable": "यह परिवेश अभी संदेश टेम्पलेट के परीक्षण का समर्थन नहीं करता है।",
+ "nodes.humanInputV2.template.title": "संदेश टेम्पलेट",
"nodes.ifElse.operator": "ऑपरेटर",
"nodes.iteration.currentIteration": "वर्तमान इटरेशन",
"nodes.iteration.deleteDesc": "इटरेशन नोड हटाने से सभी चाइल्ड नोड्स हट जाएंगे",
diff --git a/web/i18n/locales/id-ID/contacts.json b/web/i18n/locales/id-ID/contacts.json
index 608e765c3b2..02aa79aa4af 100644
--- a/web/i18n/locales/id-ID/contacts.json
+++ b/web/i18n/locales/id-ID/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Hapus kontak ({{count}})?",
"directory.removalDescription": "Kontak yang dipilih akan dihapus secara permanen dari ruang kerja ini. Tindakan ini tidak dapat dibatalkan.",
- "directory.removalTitle": "Hapus kontak?",
+ "directory.removalSingleDescription": "{{name}} akan dihapus secara permanen dari ruang kerja ini. Tindakan ini tidak dapat dibatalkan.",
+ "directory.removalSingleFailed": "Kontak tidak dapat dihapus. Coba lagi.",
+ "directory.removalSingleTitle": "Hapus {{name}}?",
+ "directory.resultCount": "Hasil: {{count}}",
+ "imPlatform.action.configure": "Konfigurasikan",
+ "imPlatform.action.configureChannel": "Konfigurasikan {{provider}}",
+ "imPlatform.action.connect": "Sambung",
+ "imPlatform.action.copied": "Disalin",
+ "imPlatform.action.copyCallback": "Salin URL callback",
+ "imPlatform.action.deleteChannel": "Hapus {{provider}}",
+ "imPlatform.action.loadMore": "Muat lebih banyak",
+ "imPlatform.action.replace": "Mengganti",
+ "imPlatform.action.retry": "Pengulangan",
+ "imPlatform.action.save": "Simpan",
+ "imPlatform.action.saving": "Menyimpan",
+ "imPlatform.action.setupGuide": "Panduan penyiapan",
+ "imPlatform.action.syncNow": "Sinkronkan sekarang",
+ "imPlatform.action.syncing": "Sedang disinkronkan",
+ "imPlatform.action.testConnection": "Uji koneksi",
+ "imPlatform.action.testing": "Menguji",
+ "imPlatform.action.viewDetails": "Lihat detail",
+ "imPlatform.bindingDialog.back": "Belakang",
+ "imPlatform.bindingDialog.callback": "URL Panggilan Balik",
+ "imPlatform.bindingDialog.callbackDescription": "Selesaikan penyiapan callback di {{provider}} untuk mengaktifkan tindakan kartu.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Untuk tindakan kartu, tempel URL ini di <console>Konsol Pengembang Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Peristiwa & Callback → Konfigurasi callback → URL Permintaan",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Untuk tindakan kartu, tempel URL ini di <console>Konsol Pengembang Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Peristiwa & Callback → Konfigurasi callback → URL Permintaan",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Untuk tindakan kartu, tempel URL ini di <console>Konsol Pengembang Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interaktivitas & Pintasan → Interaktivitas → URL Permintaan",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Untuk tindakan kartu, tempel URL ini di <console>konfigurasi Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Pengaturan → Konfigurasi → Endpoint pesan",
+ "imPlatform.bindingDialog.callbackStep": "Konfigurasi callback",
"imPlatform.bindingDialog.clearSavedCredential": "Hapus nilai tersimpan",
+ "imPlatform.bindingDialog.configureTitle": "Konfigurasikan {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Hubungkan {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Nilai tersimpan ini akan dihapus saat Anda menyimpan.",
+ "imPlatform.bindingDialog.credentialsDescription": "Hubungkan aplikasi {{provider}} terlebih dahulu, lalu konfigurasikan URL callback-nya.",
+ "imPlatform.bindingDialog.credentialsStep": "Kredensial aplikasi",
+ "imPlatform.bindingDialog.description": "Masukkan kredensial aplikasi untuk penyedia IM ini.",
+ "imPlatform.bindingDialog.field.agentId": "ID Agen",
+ "imPlatform.bindingDialog.field.appId": "ID Aplikasi",
+ "imPlatform.bindingDialog.field.appToken": "Token Aplikasi (opsional)",
+ "imPlatform.bindingDialog.field.botToken": "Token Bot",
+ "imPlatform.bindingDialog.field.clientId": "ID Klien",
+ "imPlatform.bindingDialog.field.clientSecret": "Rahasia Klien",
+ "imPlatform.bindingDialog.field.corpId": "ID Perusahaan",
+ "imPlatform.bindingDialog.field.encryptKey": "Kunci Enkripsi (opsional)",
+ "imPlatform.bindingDialog.field.genericSecret": "Rahasia",
+ "imPlatform.bindingDialog.field.secret": "Rahasia Aplikasi",
+ "imPlatform.bindingDialog.field.signingSecret": "Rahasia Penandatanganan",
+ "imPlatform.bindingDialog.field.tenantId": "ID Tenant",
+ "imPlatform.bindingDialog.field.verificationToken": "Token Verifikasi (opsional)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Masukkan Kunci Enkripsi jika diaktifkan",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Masukkan Rahasia Aplikasi",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Masukkan Token Verifikasi jika dikonfigurasi",
+ "imPlatform.bindingDialog.finish": "Selesai",
+ "imPlatform.bindingDialog.freshCredentials": "Rahasia yang disimpan tidak dapat diambil kembali. Masukkan ulang semua kredensial wajib untuk menguji atau menyimpan konfigurasi ini.",
+ "imPlatform.bindingDialog.openSetupGuide": "Buka panduan penyiapan",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Ganti kredensial tenant untuk {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Kredensial ini milik tenant IM lain dan tidak dapat disimpan langsung. Untuk beralih tenant, Anda harus mengganti kanal IM saat ini, yang akan menghapus semua pengikatan IM otomatis dan manual. Sinkronkan ulang kontak setelah penggantian.",
+ "imPlatform.bindingDialog.required": "Kolom ini wajib diisi.",
+ "imPlatform.bindingDialog.saveAndContinue": "Simpan dan lanjutkan",
+ "imPlatform.bindingDialog.saveFailed": "Konfigurasi tidak dapat disimpan. Periksa kolom dan coba lagi.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Konfigurasi telah disimpan, tetapi detailnya tidak dapat dimuat. Tutup dialog ini lalu buka kembali.",
- "imPlatform.bindingDialog.undoClearCredential": "Urungkan penghapusan"
+ "imPlatform.bindingDialog.secretConfigured": "Rahasia sudah dikonfigurasi. Biarkan kolom ini kosong untuk mempertahankannya.",
+ "imPlatform.bindingDialog.step": "Langkah {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Uji koneksi gagal. Periksa konfigurasi dan coba lagi.",
+ "imPlatform.bindingDialog.undoClearCredential": "Urungkan penghapusan",
+ "imPlatform.bindingDialog.viewSetupGuide": "Lihat panduan penyiapan",
+ "imPlatform.chooseProvider": "Pilih saluran untuk dihubungkan",
+ "imPlatform.configurationUpdated": "Konfigurasi saluran ini telah berubah. Tutup dialog ini dan muat ulang sebelum mencoba lagi.",
+ "imPlatform.connectMore": "Hubungkan saluran lainnya",
+ "imPlatform.delete.confirm": "Hapus",
+ "imPlatform.delete.description": "Menghapus saluran ini akan menghapus konfigurasinya. Pengiriman persetujuan atau sinkronisasi direktori yang menggunakannya akan berhenti.",
+ "imPlatform.delete.failed": "Saluran tidak dapat dihapus. Tidak ada perubahan; coba lagi.",
+ "imPlatform.delete.title": "Hapus saluran {{provider}}?",
+ "imPlatform.description": "Hubungkan saluran perusahaan agar permintaan persetujuan sampai kepada pengguna di tempat mereka bekerja.",
+ "imPlatform.details.column.contact": "Kontak",
+ "imPlatform.details.column.platform": "Platform IM",
+ "imPlatform.details.description": "Lihat hasil hanya baca dari proses sinkronisasi terbaru.",
+ "imPlatform.details.downloadFailed": "Laporan tidak dapat diunduh. Coba lagi.",
+ "imPlatform.details.downloadReport": "Unduh laporan",
+ "imPlatform.details.downloadingReport": "Mengunduh laporan…",
+ "imPlatform.details.empty": "Tidak ada hasil dalam kategori ini.",
+ "imPlatform.details.filter.added": "Ditambahkan",
+ "imPlatform.details.filter.failed": "Gagal",
+ "imPlatform.details.filter.not_matched": "Tidak cocok",
+ "imPlatform.details.filter.removed": "Dihapus",
+ "imPlatform.details.filter.skipped": "Dilewati",
+ "imPlatform.details.filters": "Filter hasil sinkronisasi",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Detail sinkronisasi tidak dapat dimuat.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Hasil lainnya tidak dapat dimuat. Coba lagi halaman ini.",
+ "imPlatform.details.removalReason.binding_invalidated": "Pengikatan dibatalkan",
+ "imPlatform.details.removalReason.binding_replaced": "Pengikatan diganti",
+ "imPlatform.details.removalReason.not_present_in_directory": "Tidak lagi ada dalam direktori",
+ "imPlatform.details.reportChanged": "Hasil sinkronisasi telah berubah. Buka kembali detail sinkronisasi terbaru dan coba lagi.",
+ "imPlatform.details.title": "Detail sinkronisasi",
+ "imPlatform.email.apiKey": "Kunci API",
+ "imPlatform.email.apiKeyConfigured": "Demi keamanan, Kunci API yang disimpan tidak dapat dilihat. Biarkan kolom ini kosong untuk mempertahankannya.",
+ "imPlatform.email.apiKeyDescription": "Demi keamanan, Kunci API ini tidak dapat dilihat setelah disimpan.",
+ "imPlatform.email.apiKeyPlaceholder": "Masukkan Kunci API Resend Anda",
+ "imPlatform.email.description": "Konfigurasi ini berlaku untuk semua node Human Input di ruang kerja ini yang mengaktifkan <emphasis>Kirim notifikasi debug melalui Email</emphasis>.",
+ "imPlatform.email.invalidEmail": "Masukkan alamat email yang valid.",
+ "imPlatform.email.provider": "Penyedia Email",
+ "imPlatform.email.resendDescription": "<apiKey>Kunci API Resend</apiKey> Anda akan dienkripsi dan tidak dapat dilihat setelah disimpan.<br/>Daftar akun <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Pengaturan Resend",
+ "imPlatform.email.senderEmail": "Alamat email pengirim",
+ "imPlatform.email.senderEmailDescription": "Alamat email yang ditampilkan sebagai pengirim. Domainnya harus diverifikasi di Resend.",
+ "imPlatform.email.senderName": "Nama pengirim",
+ "imPlatform.email.senderNameDescription": "Nama yang ditampilkan di kotak masuk penerima.",
+ "imPlatform.email.testSucceeded": "Uji koneksi berhasil.",
+ "imPlatform.email.title": "Konfigurasi Email",
+ "imPlatform.learnMore": "Pelajari lebih lanjut",
+ "imPlatform.loadError.description": "Coba lagi untuk membaca pengikatan dan izin saat ini.",
+ "imPlatform.loadError.retry": "Coba lagi",
+ "imPlatform.loadError.title": "Saluran tidak dapat dimuat",
+ "imPlatform.loading": "Memuat saluran",
+ "imPlatform.provider.dingtalkDescription": "Hubungkan aplikasi DingTalk.",
+ "imPlatform.provider.emailDescription": "Konfigurasikan layanan email untuk mengirim permintaan persetujuan dari ruang kerja ini.",
+ "imPlatform.provider.feishuDescription": "Hubungkan aplikasi Feishu.",
+ "imPlatform.provider.larkDescription": "Hubungkan aplikasi Lark.",
+ "imPlatform.provider.msTeamsDescription": "Hubungkan aplikasi Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Sinkronkan pengguna dan identitas Slack mereka.",
+ "imPlatform.provider.weComDescription": "Hubungkan aplikasi WeCom.",
+ "imPlatform.replacement.confirm": "Mengganti",
+ "imPlatform.replacement.description": "Mengganti penyedia aktif akan membatalkan pengikatan IM dan penggantian pengaturan ruang kerja miliknya. Setelah penggantian, sinkronkan kembali direktori penyedia baru.",
+ "imPlatform.replacement.title": "Ganti {{current}} dengan {{next}}?",
+ "imPlatform.status.configured": "Dikonfigurasi",
+ "imPlatform.status.connected": "Terhubung",
+ "imPlatform.status.connection_error": "Kesalahan koneksi",
+ "imPlatform.status.permission_issue": "Masalah izin",
+ "imPlatform.sync.latestSynced": "Terakhir disinkronkan {{date}}",
+ "imPlatform.sync.loading": "Memeriksa sinkronisasi yang sedang aktif.",
+ "imPlatform.sync.noPermission": "Hanya pemilik dan admin ruang kerja yang dapat memulai sinkronisasi direktori.",
+ "imPlatform.sync.noRuns": "Belum ada sinkronisasi direktori yang dijalankan.",
+ "imPlatform.sync.notConnected": "Hubungkan dan uji penyedia sebelum memulai sinkronisasi direktori.",
+ "imPlatform.sync.startFailed": "Sinkronisasi direktori tidak dapat dimulai atau dimuat ulang. Coba lagi.",
+ "imPlatform.sync.status.failure": "Gagal",
+ "imPlatform.sync.status.queued": "Dalam antrean",
+ "imPlatform.sync.status.running": "Berjalan",
+ "imPlatform.sync.status.success": "Berhasil",
+ "imPlatform.title": "Saluran"
}
diff --git a/web/i18n/locales/id-ID/share.json b/web/i18n/locales/id-ID/share.json
index eed3c502c87..503fa9d7c20 100644
--- a/web/i18n/locales/id-ID/share.json
+++ b/web/i18n/locales/id-ID/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Terima kasih!",
"humanInput.unavailableDescription": "Tautan mungkin tidak tersedia atau tidak sesuai dengan akun yang Anda gunakan untuk masuk. Buka formulir dari notifikasi yang Anda terima, atau coba ganti akun.",
"humanInput.unavailableTitle": "Formulir ini tidak dapat dibuka",
+ "humanInputV2.accessRateLimited": "Terlalu banyak permintaan email verifikasi. Silakan coba lagi nanti.",
+ "humanInputV2.alreadySubmitted": "Permintaan ini sudah diselesaikan.",
+ "humanInputV2.challengeExpired": "Kode verifikasi ini telah kedaluwarsa. Minta kode baru untuk melanjutkan.",
+ "humanInputV2.challengeStale": "Kode verifikasi ini telah diganti. Minta kode baru untuk melanjutkan.",
+ "humanInputV2.codeExpiresIn": "Kode kedaluwarsa dalam {{seconds}} detik",
+ "humanInputV2.codeRequired": "Minta kode verifikasi untuk melanjutkan.",
+ "humanInputV2.codeSent": "Kode verifikasi telah dikirim ke email Anda.",
+ "humanInputV2.deliveryFailed": "Email verifikasi tidak dapat dikirim. Silakan coba lagi.",
+ "humanInputV2.formExpired": "Permintaan ini telah kedaluwarsa.",
+ "humanInputV2.formNotFound": "Formulir tidak ditemukan.",
+ "humanInputV2.formRateLimited": "Terlalu banyak permintaan formulir. Silakan coba lagi nanti.",
+ "humanInputV2.invalidOtp": "Kode verifikasi salah. Periksa kode dan coba lagi.",
+ "humanInputV2.networkError": "Permintaan tidak dapat diselesaikan. Periksa koneksi Anda dan coba lagi.",
+ "humanInputV2.otpLabel": "Kode verifikasi email",
+ "humanInputV2.otpPlaceholder": "Masukkan kode 6 digit",
+ "humanInputV2.requestingCode": "Mengirim kode verifikasi…",
+ "humanInputV2.resendCode": "Kirim ulang kode",
+ "humanInputV2.retry": "Coba lagi",
+ "humanInputV2.sendCode": "Kirim kode baru",
+ "humanInputV2.unavailable": "Formulir ini sementara tidak tersedia.",
+ "humanInputV2.unknownError": "Terjadi kesalahan. Silakan coba lagi.",
+ "humanInputV2.uploadFailed": "File tidak dapat diunggah. Silakan coba lagi.",
"login.backToHome": "Kembali ke Beranda"
}
diff --git a/web/i18n/locales/id-ID/workflow-human-input.json b/web/i18n/locales/id-ID/workflow-human-input.json
index 7dafafb4bb8..5a5bcb022a6 100644
--- a/web/i18n/locales/id-ID/workflow-human-input.json
+++ b/web/i18n/locales/id-ID/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Nilai Tindakan",
"nodes.humanInput.userActions.buttonTextTooLong": "Teks tombol harus {{maxLength}} karakter atau kurang",
"nodes.humanInput.userActions.chooseStyle": "Pilih gaya tombol",
+ "nodes.humanInput.userActions.defaultTitle": "Teks Tombol {{index}}",
"nodes.humanInput.userActions.emptyTip": "Klik tombol '+' untuk menambahkan tindakan pengguna",
"nodes.humanInput.userActions.title": "Tindakan Pengguna",
"nodes.humanInput.userActions.tooltip": "Tentukan tombol yang dapat diklik pengguna untuk merespons formulir ini. ID tindakan mengontrol percabangan. Nilai Tindakan diekspos ke hilir sebagai output bawaan yang dipilih. ID tindakan harus dimulai dengan huruf atau garis bawah, diikuti dengan huruf, angka, atau garis bawah.",
diff --git a/web/i18n/locales/id-ID/workflow.json b/web/i18n/locales/id-ID/workflow.json
index 58f2f6b2aea..a9a0f9e68fb 100644
--- a/web/i18n/locales/id-ID/workflow.json
+++ b/web/i18n/locales/id-ID/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Keluaran",
"blocks.http-request": "Permintaan HTTP",
"blocks.human-input": "Input Manusia",
+ "blocks.human-input-v2": "Input Manusia v2",
"blocks.if-else": "JIKA/LAIN",
"blocks.iteration": "Iterasi",
"blocks.iteration-start": "Iterasi Mulai",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Menentukan output dan jenis hasil alur kerja",
"blocksAbout.http-request": "Izinkan permintaan server dikirim melalui protokol HTTP",
"blocksAbout.human-input": "Minta konfirmasi manusia sebelum menghasilkan langkah berikutnya",
+ "blocksAbout.human-input-v2": "Minta input dari kontak yang dikonfigurasi, penerima email, atau pemulai alur kerja",
"blocksAbout.if-else": "Memungkinkan Anda membagi alur kerja menjadi dua cabang berdasarkan kondisi if/else",
"blocksAbout.iteration": "Lakukan beberapa langkah pada objek daftar hingga semua hasil dikeluarkan.",
"blocksAbout.iteration-start": "Node Mulai Iterasi",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Agregatkan variabel multi-cabang menjadi satu variabel untuk konfigurasi terpadu simpul hilir.",
"blocksAbout.variable-assigner": "Agregatkan variabel multi-cabang menjadi satu variabel untuk konfigurasi terpadu simpul hilir.",
"changeHistory.edgeDelete": "Node terputus",
+ "changeHistory.humanInputMigration": "Node Input Manusia telah dimigrasikan",
"changeHistory.nodeAdd": "Node ditambahkan",
"changeHistory.nodeChange": "Node diubah",
"changeHistory.nodeConnect": "Node terhubung",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Silakan aktifkan setidaknya satu metode pengiriman",
"nodes.humanInput.errorMsg.noUserActions": "Silakan tambahkan setidaknya satu tindakan pengguna",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} dicadangkan untuk cabang batas waktu. Pilih ID tindakan lain.",
+ "nodes.humanInput.output.actionId": "ID tindakan yang dijalankan pengguna",
+ "nodes.humanInput.output.actionValue": "Nilai tindakan yang dipilih",
+ "nodes.humanInput.output.formInput": "Nilai input formulir",
+ "nodes.humanInput.output.renderedContent": "Konten yang dirender",
"nodes.humanInput.timeout.title": "Batas waktu",
+ "nodes.humanInputMigration.action.migrate": "Migrasikan",
+ "nodes.humanInputMigration.action.migrateNow": "Migrasikan sekarang",
+ "nodes.humanInputMigration.action.migrating": "Memigrasikan...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Pemberitahuan migrasi Input Manusia",
+ "nodes.humanInputMigration.banner.description": "Alur kerja ini menggunakan node Input Manusia versi lama. Migrasikan semua node lama sebelum menambahkan yang baru.",
+ "nodes.humanInputMigration.banner.learnMore": "Pelajari lebih lanjut",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "metode pengiriman yang dinonaktifkan masih memiliki konfigurasi",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "metode email yang diaktifkan menggunakan templat yang saling bertentangan",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Nilai default tidak valid",
+ "nodes.humanInputMigration.blocker.invalidEmail": "alamat email penerima tidak valid",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "konfigurasi metode email yang diaktifkan belum lengkap",
+ "nodes.humanInputMigration.blocker.missingRecipients": "node tidak memiliki penerima yang didukung",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "anggota ruang kerja tidak dapat dipetakan ke kontak atau email terverifikasi",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "metode pengiriman yang diaktifkan tidak didukung oleh Input Manusia v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Kolom {{field}} belum dapat dimigrasikan. Anda dapat terus menggunakan node Input Manusia versi lama.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "node memiliki nilai versi yang tidak didukung",
+ "nodes.humanInputMigration.dialog.description": "Penerima, formulir, dan tindakan Anda akan tetap dipertahankan.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Hanya draf ini yang berubah. Versi yang dipublikasikan tetap berjalan hingga Anda memublikasikan ulang.",
+ "nodes.humanInputMigration.dialog.review": "Tinjau node dan publikasikan setelah siap.",
+ "nodes.humanInputMigration.dialog.title": "Migrasikan {{count}} node Input Manusia",
+ "nodes.humanInputMigration.disabledBadge": "PERLU MIGRASI",
+ "nodes.humanInputMigration.disabledReason": "Migrasikan node Input Manusia lama sebelum menambahkan yang baru.",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} tidak dapat dimigrasikan: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Alur kerja berubah selama migrasi. Coba lagi; perubahan Anda saat ini telah dipertahankan.",
+ "nodes.humanInputMigration.error.preflight": "Migrasi tidak dapat disiapkan. Alur kerja Anda tidak diubah. Silakan coba lagi.",
"nodes.humanInputMigration.error.sync": "Alur kerja yang dimigrasikan tidak dapat disimpan. Periksa draf saat ini dan coba lagi.",
+ "nodes.humanInputMigration.incompatibleVersions": "Node Input Manusia versi lama dan baru tidak dapat digunakan dalam alur kerja yang sama.",
+ "nodes.humanInputMigration.oldVersion": "VERSI LAMA",
+ "nodes.humanInputMigration.preview.author": "Oleh Tim Dify",
+ "nodes.humanInputMigration.preview.description": "Migrasikan node Input Manusia lama sebelum menambahkan yang baru.",
+ "nodes.humanInputMigration.success": "Node Input Manusia berhasil dimigrasikan",
+ "nodes.humanInputV2.card.configured": "{{count}} penerima dikonfigurasi",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} kontak",
+ "nodes.humanInputV2.card.empty": "Belum ada yang dapat menyetujui langkah ini",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Pemulai dan {{count}} kontak",
+ "nodes.humanInputV2.card.initiatorOnly": "Hanya pemulai",
+ "nodes.humanInputV2.card.invalid": "Konfigurasi penerima perlu diperiksa",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "Email",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Konfigurasikan Mode Debug",
"nodes.humanInputV2.debug.keepOneChannel": "Biarkan setidaknya satu saluran tetap aktif",
+ "nodes.humanInputV2.debug.sendVia": "Kirim notifikasi debug melalui",
+ "nodes.humanInputV2.debug.title": "Mode Debug",
+ "nodes.humanInputV2.debug.toggle": "Aktifkan Mode Debug",
+ "nodes.humanInputV2.debug.unsupported": "Saluran yang diimpor tidak didukung: {{channels}}. Hapus atau perbarui saluran tersebut sebelum menjalankan alur kerja ini.",
"nodes.humanInputV2.disabled": "Human Input v2 tidak tersedia saat HITL IM dinonaktifkan.",
+ "nodes.humanInputV2.error.bodyRequired": "Isi pesan wajib diisi",
+ "nodes.humanInputV2.error.debugChannelRequired": "Pilih setidaknya satu saluran Mode Debug",
+ "nodes.humanInputV2.error.recipientDuplicate": "Hapus penerima duplikat",
+ "nodes.humanInputV2.error.recipientInvalid": "Perbaiki konfigurasi penerima yang tidak valid",
+ "nodes.humanInputV2.error.recipientRequired": "Tambahkan setidaknya satu penerima",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Tidak dapat memverifikasi penerima kontak",
"nodes.humanInputV2.error.requestURLDuplicate": "Isi pesan hanya boleh memuat satu URL permintaan.",
"nodes.humanInputV2.error.requestURLRequired": "Sisipkan URL permintaan di isi pesan.",
+ "nodes.humanInputV2.error.subjectRequired": "Subjek pesan wajib diisi",
+ "nodes.humanInputV2.error.version": "Input Manusia v2 memerlukan versi berupa string 2",
+ "nodes.humanInputV2.recipients.addContact": "Tambah kontak",
+ "nodes.humanInputV2.recipients.addEmail": "Tambah",
+ "nodes.humanInputV2.recipients.addRecipient": "Tambah penerima",
+ "nodes.humanInputV2.recipients.added": "Ditambahkan",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Semua kontak ruang kerja",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Kirim notifikasi ke semua kontak di ruang kerja; siapa pun dari mereka dapat menyetujui",
+ "nodes.humanInputV2.recipients.cancel": "Batal",
+ "nodes.humanInputV2.recipients.chooseVariable": "Pilih variabel",
+ "nodes.humanInputV2.recipients.confirm": "Konfirmasi",
+ "nodes.humanInputV2.recipients.contactInfo": "Detail kontak {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Semua",
+ "nodes.humanInputV2.recipients.contactSource.external": "Eksternal",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organisasi",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Ruang kerja",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Sumber kontak",
"nodes.humanInputV2.recipients.duplicateSource": "Sudah ditambahkan melalui {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Sunting {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Sunting penerima",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Setiap email hanya dapat dipilih sekali.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Masukkan alamat email yang valid dan belum ditambahkan",
+ "nodes.humanInputV2.recipients.emailLabel": "Penerima email sekali pakai",
+ "nodes.humanInputV2.recipients.empty": "Belum ada penerima yang dikonfigurasi",
+ "nodes.humanInputV2.recipients.help": "Pilih siapa yang dapat merespons langkah Input Manusia ini.",
"nodes.humanInputV2.recipients.initiator": "Pengguna yang memulai proses ini melalui Web App atau CLI dapat menyetujui",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Orang yang memulai eksekusi alur kerja ini dapat merespons.",
"nodes.humanInputV2.recipients.inputHelp": "Ketik atau tempel beberapa alamat email yang dipisahkan dengan koma. Tekan / untuk menyisipkan variabel.",
+ "nodes.humanInputV2.recipients.insertVariable": "Sisipkan variabel",
+ "nodes.humanInputV2.recipients.loadError": "Kontak tidak dapat dimuat. ID kontak yang tersimpan tetap dipertahankan.",
+ "nodes.humanInputV2.recipients.loading": "Memuat kontak…",
+ "nodes.humanInputV2.recipients.noResults": "Kontak tidak ditemukan",
+ "nodes.humanInputV2.recipients.placeholder": "Cari kontak atau tambahkan email",
+ "nodes.humanInputV2.recipients.remove": "Hapus {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Tekan Backspace atau Delete untuk menghapus.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} penerima yang cocok",
+ "nodes.humanInputV2.recipients.search": "Cari kontak",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Cari berdasarkan nama atau email",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} penerima dipilih. Di awal kolom input, tekan panah kiri untuk memfokuskan penerima.",
+ "nodes.humanInputV2.recipients.title": "Penerima",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Semua kontak ruang kerja",
+ "nodes.humanInputV2.recipients.type.contact": "Kontak",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Email dinamis",
+ "nodes.humanInputV2.recipients.type.initiator": "Pemulai",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Email sekali pakai",
+ "nodes.humanInputV2.recipients.typeLabel": "Jenis penerima",
"nodes.humanInputV2.recipients.useThisInstead": "Gunakan ini sebagai gantinya",
+ "nodes.humanInputV2.recipients.variableRequired": "Pilih variabel email",
+ "nodes.humanInputV2.template.body": "Isi",
+ "nodes.humanInputV2.template.description": "Teks cadangan untuk email dan IM",
"nodes.humanInputV2.template.insertRequestURL": "Sisipkan URL permintaan",
+ "nodes.humanInputV2.template.insertVariable": "Sisipkan variabel",
+ "nodes.humanInputV2.template.notConfigured": "Belum dikonfigurasi",
"nodes.humanInputV2.template.requestURLHint": "Penerima menggunakan tautan ini untuk membuka formulir persetujuan. Sertakan tepat satu URL permintaan.",
"nodes.humanInputV2.template.requestURLInserted": "URL permintaan disisipkan",
"nodes.humanInputV2.template.saveAndTest": "Simpan dan uji",
+ "nodes.humanInputV2.template.subject": "Subjek",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Masukkan subjek pesan",
"nodes.humanInputV2.template.test": "Uji pesan",
"nodes.humanInputV2.template.testChannel": "Saluran uji",
"nodes.humanInputV2.template.testCompleted": "Permintaan uji selesai. Periksa pesan di saluran yang dipilih.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Isi semua nilai variabel uji.",
"nodes.humanInputV2.template.testSaveFailed": "Draf alur kerja tidak dapat disimpan. Pengujian tidak dikirim.",
"nodes.humanInputV2.template.testUnavailable": "Lingkungan ini belum mendukung pengujian templat pesan.",
+ "nodes.humanInputV2.template.title": "Templat pesan",
"nodes.ifElse.operator": "Operator",
"nodes.iteration.currentIteration": "Iterasi Saat Ini",
"nodes.iteration.deleteDesc": "Menghapus simpul iterasi akan menghapus semua simpul turunan",
diff --git a/web/i18n/locales/it-IT/contacts.json b/web/i18n/locales/it-IT/contacts.json
index 06209286ecb..a6a3d5f679d 100644
--- a/web/i18n/locales/it-IT/contacts.json
+++ b/web/i18n/locales/it-IT/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Rimuovere i contatti ({{count}})?",
"directory.removalDescription": "I contatti selezionati verranno rimossi definitivamente da questo spazio di lavoro. Questa azione non può essere annullata.",
- "directory.removalTitle": "Rimuovere i contatti?",
+ "directory.removalSingleDescription": "{{name}} verrà rimosso definitivamente da questo spazio di lavoro. Questa azione non può essere annullata.",
+ "directory.removalSingleFailed": "Impossibile rimuovere il contatto. Riprova.",
+ "directory.removalSingleTitle": "Rimuovere {{name}}?",
+ "directory.resultCount": "Risultati: {{count}}",
+ "imPlatform.action.configure": "Configura",
+ "imPlatform.action.configureChannel": "Configura {{provider}}",
+ "imPlatform.action.connect": "Connetti",
+ "imPlatform.action.copied": "Copiato",
+ "imPlatform.action.copyCallback": "Copia URL di callback",
+ "imPlatform.action.deleteChannel": "Elimina {{provider}}",
+ "imPlatform.action.loadMore": "Carica altro",
+ "imPlatform.action.replace": "Sostituire",
+ "imPlatform.action.retry": "Ripetere",
+ "imPlatform.action.save": "Salva",
+ "imPlatform.action.saving": "Salvataggio",
+ "imPlatform.action.setupGuide": "Guida alla configurazione",
+ "imPlatform.action.syncNow": "Sincronizza ora",
+ "imPlatform.action.syncing": "Sincronizzazione in corso",
+ "imPlatform.action.testConnection": "Prova connessione",
+ "imPlatform.action.testing": "Test in corso",
+ "imPlatform.action.viewDetails": "Mostra dettagli",
+ "imPlatform.bindingDialog.back": "Indietro",
+ "imPlatform.bindingDialog.callback": "URL di richiamata",
+ "imPlatform.bindingDialog.callbackDescription": "Completa la configurazione dei callback in {{provider}} per abilitare le azioni delle schede.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Per le azioni delle schede, incolla questo URL nella <console>console per sviluppatori Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Eventi e callback → Configurazione callback → URL della richiesta",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Per le azioni delle schede, incolla questo URL nella <console>console per sviluppatori Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Eventi e callback → Configurazione callback → URL della richiesta",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Per le azioni delle schede, incolla questo URL nella <console>console per sviluppatori Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interattività e scorciatoie → Interattività → URL della richiesta",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Per le azioni delle schede, incolla questo URL nella <console>configurazione di Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Impostazioni → Configurazione → Endpoint di messaggistica",
+ "imPlatform.bindingDialog.callbackStep": "Configura callback",
"imPlatform.bindingDialog.clearSavedCredential": "Cancella il valore salvato",
+ "imPlatform.bindingDialog.configureTitle": "Configura {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Connetti {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Questo valore salvato verrà cancellato al salvataggio.",
+ "imPlatform.bindingDialog.credentialsDescription": "Collega prima la tua applicazione {{provider}}, quindi configura il suo URL di callback.",
+ "imPlatform.bindingDialog.credentialsStep": "Credenziali dell’applicazione",
+ "imPlatform.bindingDialog.description": "Inserisci le credenziali dell’applicazione di questo fornitore di messaggistica istantanea.",
+ "imPlatform.bindingDialog.field.agentId": "ID agente",
+ "imPlatform.bindingDialog.field.appId": "ID applicazione",
+ "imPlatform.bindingDialog.field.appToken": "Token applicazione (facoltativo)",
+ "imPlatform.bindingDialog.field.botToken": "Token del bot",
+ "imPlatform.bindingDialog.field.clientId": "ID cliente",
+ "imPlatform.bindingDialog.field.clientSecret": "Segreto del Cliente",
+ "imPlatform.bindingDialog.field.corpId": "ID azienda",
+ "imPlatform.bindingDialog.field.encryptKey": "Chiave di crittografia (facoltativa)",
+ "imPlatform.bindingDialog.field.genericSecret": "Segreto",
+ "imPlatform.bindingDialog.field.secret": "Segreto applicazione",
+ "imPlatform.bindingDialog.field.signingSecret": "Segreto di firma",
+ "imPlatform.bindingDialog.field.tenantId": "ID tenant",
+ "imPlatform.bindingDialog.field.verificationToken": "Token di verifica (facoltativo)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Inserisci la chiave di crittografia, se abilitata",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Inserisci il segreto dell’applicazione",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Inserisci il token di verifica, se configurato",
+ "imPlatform.bindingDialog.finish": "Completa",
+ "imPlatform.bindingDialog.freshCredentials": "I segreti salvati non possono essere recuperati. Inserisci nuovamente tutte le credenziali richieste per testare o salvare questa configurazione.",
+ "imPlatform.bindingDialog.openSetupGuide": "Apri guida alla configurazione",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Sostituire le credenziali del tenant per {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Queste credenziali appartengono a un altro tenant IM e non possono essere salvate direttamente. Per cambiare tenant è necessario sostituire il canale IM attuale, eliminando tutte le associazioni IM automatiche e manuali. Sincronizza nuovamente i contatti dopo la sostituzione.",
+ "imPlatform.bindingDialog.required": "Questo campo è obbligatorio.",
+ "imPlatform.bindingDialog.saveAndContinue": "Salva e continua",
+ "imPlatform.bindingDialog.saveFailed": "Impossibile salvare la configurazione. Controlla i campi e riprova.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "La configurazione è stata salvata, ma non è stato possibile caricarne i dettagli. Chiudi questa finestra e riaprila.",
- "imPlatform.bindingDialog.undoClearCredential": "Annulla cancellazione"
+ "imPlatform.bindingDialog.secretConfigured": "Un segreto è già configurato. Lascia vuoto questo campo per mantenerlo.",
+ "imPlatform.bindingDialog.step": "Passaggio {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Il test della connessione non è riuscito. Controlla la configurazione e riprova.",
+ "imPlatform.bindingDialog.undoClearCredential": "Annulla cancellazione",
+ "imPlatform.bindingDialog.viewSetupGuide": "Visualizza guida alla configurazione",
+ "imPlatform.chooseProvider": "Scegli un canale da collegare",
+ "imPlatform.configurationUpdated": "La configurazione di questo canale è cambiata. Chiudi questa finestra e aggiorna la pagina prima di riprovare.",
+ "imPlatform.connectMore": "Collega altri canali",
+ "imPlatform.delete.confirm": "Elimina",
+ "imPlatform.delete.description": "L’eliminazione di questo canale rimuove la sua configurazione. Le notifiche di approvazione e la sincronizzazione della directory che lo utilizzano verranno interrotte.",
+ "imPlatform.delete.failed": "Impossibile eliminare il canale. Nulla è cambiato; riprova.",
+ "imPlatform.delete.title": "Eliminare il canale {{provider}}?",
+ "imPlatform.description": "Collega i canali aziendali affinché le richieste di approvazione raggiungano le persone dove lavorano.",
+ "imPlatform.details.column.contact": "Contatti",
+ "imPlatform.details.column.platform": "Piattaforma di messaggistica istantanea",
+ "imPlatform.details.description": "Visualizza i risultati di sola lettura dell’ultima sincronizzazione.",
+ "imPlatform.details.downloadFailed": "Impossibile scaricare il rapporto. Riprova.",
+ "imPlatform.details.downloadReport": "Scarica rapporto",
+ "imPlatform.details.downloadingReport": "Download del rapporto…",
+ "imPlatform.details.empty": "Nessun risultato in questa categoria.",
+ "imPlatform.details.filter.added": "Aggiunto",
+ "imPlatform.details.filter.failed": "Non riuscita",
+ "imPlatform.details.filter.not_matched": "Nessuna corrispondenza",
+ "imPlatform.details.filter.removed": "Rimosso",
+ "imPlatform.details.filter.skipped": "Ignorato",
+ "imPlatform.details.filters": "Filtri dei risultati di sincronizzazione",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Impossibile caricare i dettagli della sincronizzazione.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Impossibile caricare altri risultati. Riprova a caricare questa pagina.",
+ "imPlatform.details.removalReason.binding_invalidated": "Associazione invalidata",
+ "imPlatform.details.removalReason.binding_replaced": "Associazione sostituita",
+ "imPlatform.details.removalReason.not_present_in_directory": "Non più presente nella directory",
+ "imPlatform.details.reportChanged": "I risultati della sincronizzazione sono cambiati. Riapri i dettagli dell’ultima sincronizzazione e riprova.",
+ "imPlatform.details.title": "Dettagli sincronizzazione",
+ "imPlatform.email.apiKey": "Chiave API",
+ "imPlatform.email.apiKeyConfigured": "Per motivi di sicurezza, la chiave API salvata non può essere visualizzata. Lascia vuoto questo campo per mantenerla.",
+ "imPlatform.email.apiKeyDescription": "Per motivi di sicurezza, questa chiave API non può essere visualizzata dopo il salvataggio.",
+ "imPlatform.email.apiKeyPlaceholder": "Inserisci la tua chiave API Resend",
+ "imPlatform.email.description": "Questa configurazione si applica a tutti i nodi di intervento umano di questo spazio di lavoro con l’opzione <emphasis>Invia notifiche di debug via e-mail</emphasis> abilitata.",
+ "imPlatform.email.invalidEmail": "Inserisci un indirizzo e-mail valido.",
+ "imPlatform.email.provider": "Fornitore e-mail",
+ "imPlatform.email.resendDescription": "La tua <apiKey>chiave API Resend</apiKey> verrà crittografata e non potrà essere visualizzata dopo il salvataggio.<br/>Registra un account <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Impostazioni Resend",
+ "imPlatform.email.senderEmail": "Indirizzo e-mail del mittente",
+ "imPlatform.email.senderEmailDescription": "L’indirizzo e-mail mostrato come mittente. Il dominio deve essere verificato in Resend.",
+ "imPlatform.email.senderName": "Nome del mittente",
+ "imPlatform.email.senderNameDescription": "Nome visualizzato nella posta in arrivo del destinatario.",
+ "imPlatform.email.testSucceeded": "Test della connessione riuscito.",
+ "imPlatform.email.title": "Configura e-mail",
+ "imPlatform.learnMore": "Scopri di più",
+ "imPlatform.loadError.description": "Riprova a leggere il collegamento attuale e le autorizzazioni.",
+ "imPlatform.loadError.retry": "Riprova",
+ "imPlatform.loadError.title": "Impossibile caricare i canali",
+ "imPlatform.loading": "Caricamento dei canali",
+ "imPlatform.provider.dingtalkDescription": "Collega un’applicazione DingTalk.",
+ "imPlatform.provider.emailDescription": "Configura il servizio e-mail utilizzato per inviare richieste di approvazione da questo spazio di lavoro.",
+ "imPlatform.provider.feishuDescription": "Collega un’applicazione Feishu.",
+ "imPlatform.provider.larkDescription": "Collega un’applicazione Lark.",
+ "imPlatform.provider.msTeamsDescription": "Collega un’applicazione Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Sincronizza le persone e le loro identità Slack.",
+ "imPlatform.provider.weComDescription": "Collega un’applicazione WeCom.",
+ "imPlatform.replacement.confirm": "Sostituire",
+ "imPlatform.replacement.description": "La sostituzione del fornitore attivo invalida i relativi collegamenti di messaggistica e le personalizzazioni dello spazio di lavoro. Dopo la sostituzione, sincronizza nuovamente la directory del nuovo fornitore.",
+ "imPlatform.replacement.title": "Sostituire {{current}} con {{next}}?",
+ "imPlatform.status.configured": "Configurato",
+ "imPlatform.status.connected": "Connesso",
+ "imPlatform.status.connection_error": "Errore di connessione",
+ "imPlatform.status.permission_issue": "Problema di autorizzazione",
+ "imPlatform.sync.latestSynced": "Ultima sincronizzazione: {{date}}",
+ "imPlatform.sync.loading": "Verifica di una sincronizzazione attiva.",
+ "imPlatform.sync.noPermission": "Solo i proprietari e gli amministratori dello spazio di lavoro possono avviare la sincronizzazione della directory.",
+ "imPlatform.sync.noRuns": "Non è stata ancora eseguita alcuna sincronizzazione della directory.",
+ "imPlatform.sync.notConnected": "Collega un fornitore e prova la connessione prima di avviare la sincronizzazione della directory.",
+ "imPlatform.sync.startFailed": "Impossibile avviare o aggiornare la sincronizzazione della directory. Riprova.",
+ "imPlatform.sync.status.failure": "Non riuscita",
+ "imPlatform.sync.status.queued": "In coda",
+ "imPlatform.sync.status.running": "In esecuzione",
+ "imPlatform.sync.status.success": "Riuscito",
+ "imPlatform.title": "Canali"
}
diff --git a/web/i18n/locales/it-IT/share.json b/web/i18n/locales/it-IT/share.json
index 95ca91a7736..8c4f82e1b00 100644
--- a/web/i18n/locales/it-IT/share.json
+++ b/web/i18n/locales/it-IT/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Grazie!",
"humanInput.unavailableDescription": "Il link potrebbe non essere disponibile o non corrispondere all’account con cui hai effettuato l’accesso. Apri il modulo dalla notifica che hai ricevuto oppure prova a cambiare account.",
"humanInput.unavailableTitle": "Impossibile aprire questo modulo",
+ "humanInputV2.accessRateLimited": "Sono state richieste troppe email di verifica. Riprova più tardi.",
+ "humanInputV2.alreadySubmitted": "Questa richiesta è già stata completata.",
+ "humanInputV2.challengeExpired": "Questo codice di verifica è scaduto. Richiedi un nuovo codice per continuare.",
+ "humanInputV2.challengeStale": "Questo codice di verifica è stato sostituito. Richiedi un nuovo codice per continuare.",
+ "humanInputV2.codeExpiresIn": "Il codice scade tra {{seconds}} s",
+ "humanInputV2.codeRequired": "Richiedi un codice di verifica per continuare.",
+ "humanInputV2.codeSent": "Un codice di verifica è stato inviato al tuo indirizzo email.",
+ "humanInputV2.deliveryFailed": "Impossibile inviare l’email di verifica. Riprova.",
+ "humanInputV2.formExpired": "Questa richiesta è scaduta.",
+ "humanInputV2.formNotFound": "Modulo non trovato.",
+ "humanInputV2.formRateLimited": "Troppe richieste di modulo. Riprova più tardi.",
+ "humanInputV2.invalidOtp": "Il codice di verifica non è corretto. Controlla il codice e riprova.",
+ "humanInputV2.networkError": "Impossibile completare la richiesta. Controlla la connessione e riprova.",
+ "humanInputV2.otpLabel": "Codice di verifica email",
+ "humanInputV2.otpPlaceholder": "Inserisci il codice di 6 cifre",
+ "humanInputV2.requestingCode": "Invio di un codice di verifica…",
+ "humanInputV2.resendCode": "Invia di nuovo il codice",
+ "humanInputV2.retry": "Riprova",
+ "humanInputV2.sendCode": "Invia un nuovo codice",
+ "humanInputV2.unavailable": "Questo modulo non è temporaneamente disponibile.",
+ "humanInputV2.unknownError": "Si è verificato un errore. Riprova.",
+ "humanInputV2.uploadFailed": "Impossibile caricare il file. Riprova.",
"login.backToHome": "Torna alla home"
}
diff --git a/web/i18n/locales/it-IT/workflow-human-input.json b/web/i18n/locales/it-IT/workflow-human-input.json
index 7acbcd542d6..36851a04f1d 100644
--- a/web/i18n/locales/it-IT/workflow-human-input.json
+++ b/web/i18n/locales/it-IT/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Valore dell'azione",
"nodes.humanInput.userActions.buttonTextTooLong": "Il testo del pulsante deve essere di {{maxLength}} caratteri o meno",
"nodes.humanInput.userActions.chooseStyle": "Scegli uno stile del pulsante",
+ "nodes.humanInput.userActions.defaultTitle": "Testo del pulsante {{index}}",
"nodes.humanInput.userActions.emptyTip": "Clicca il pulsante '+' per aggiungere azioni utente",
"nodes.humanInput.userActions.title": "Azioni Utente",
"nodes.humanInput.userActions.tooltip": "Definisci i pulsanti su cui gli utenti possono cliccare per rispondere a questo modulo. L'ID azione controlla la ramificazione. Il Valore dell'azione viene esposto a valle come output integrato selezionato. L'ID azione deve iniziare con una lettera o underscore, seguito da lettere, numeri o underscore.",
diff --git a/web/i18n/locales/it-IT/workflow.json b/web/i18n/locales/it-IT/workflow.json
index 8500a1a647f..2a4851a8a0c 100644
--- a/web/i18n/locales/it-IT/workflow.json
+++ b/web/i18n/locales/it-IT/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Uscita",
"blocks.http-request": "Richiesta HTTP",
"blocks.human-input": "Input Umano",
+ "blocks.human-input-v2": "Input Umano v2",
"blocks.if-else": "SE/ALTRIMENTI",
"blocks.iteration": "Iterazione",
"blocks.iteration-start": "Inizio Iterazione",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Definisci l'uscita e il tipo di risultato di un flusso di lavoro",
"blocksAbout.http-request": "Consenti l'invio di richieste server tramite il protocollo HTTP",
"blocksAbout.human-input": "Chiedi conferma umana prima di generare il prossimo passo",
+ "blocksAbout.human-input-v2": "Richiedi dati ai contatti configurati, ai destinatari email o a chi avvia il flusso di lavoro",
"blocksAbout.if-else": "Ti consente di dividere il flusso di lavoro in due rami basati su condizioni se/altrimenti",
"blocksAbout.iteration": "Esegui più passaggi su un oggetto lista fino a quando tutti i risultati non sono stati prodotti.",
"blocksAbout.iteration-start": "Nodo iniziale dell'iterazione",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Aggrega variabili multi-ramo in una singola variabile per la configurazione unificata dei nodi a valle.",
"blocksAbout.variable-assigner": "Aggrega variabili multi-ramo in una singola variabile per la configurazione unificata dei nodi a valle.",
"changeHistory.edgeDelete": "Nodo disconnesso",
+ "changeHistory.humanInputMigration": "Nodi di input umano migrati",
"changeHistory.nodeAdd": "Nodo aggiunto",
"changeHistory.nodeChange": "Nodo cambiato",
"changeHistory.nodeConnect": "Nodo connesso",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Abilita almeno un metodo di consegna",
"nodes.humanInput.errorMsg.noUserActions": "Aggiungi almeno un'azione utente",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} è riservato al ramo di timeout. Scegli un altro ID azione.",
+ "nodes.humanInput.output.actionId": "ID dell’azione attivata dall’utente",
+ "nodes.humanInput.output.actionValue": "Valore dell’azione selezionata",
+ "nodes.humanInput.output.formInput": "Valore inserito nel modulo",
+ "nodes.humanInput.output.renderedContent": "Contenuto renderizzato",
"nodes.humanInput.timeout.title": "Timeout",
+ "nodes.humanInputMigration.action.migrate": "Migra",
+ "nodes.humanInputMigration.action.migrateNow": "Migra ora",
+ "nodes.humanInputMigration.action.migrating": "Migrazione in corso...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Avviso di migrazione dell’input umano",
+ "nodes.humanInputMigration.banner.description": "Questo flusso di lavoro usa il vecchio nodo di input umano. Migra tutti i vecchi nodi prima di aggiungerne di nuovi.",
+ "nodes.humanInputMigration.banner.learnMore": "Scopri di più",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "un metodo di consegna disattivato contiene ancora una configurazione",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "i metodi email attivati usano modelli in conflitto",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Valore predefinito non valido",
+ "nodes.humanInputMigration.blocker.invalidEmail": "l’indirizzo email di un destinatario non è valido",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "un metodo email attivato è incompleto",
+ "nodes.humanInputMigration.blocker.missingRecipients": "il nodo non ha destinatari supportati",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "non è possibile associare un membro dello spazio di lavoro a un contatto o a un indirizzo email verificato",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "un metodo di consegna attivato non è supportato da Human Input v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Il campo {{field}} non può ancora essere migrato. Puoi continuare a utilizzare i nodi di input umano precedenti.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "il nodo ha un valore di versione non supportato",
+ "nodes.humanInputMigration.dialog.description": "I destinatari, il modulo e le azioni vengono mantenuti.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Viene modificata solo questa bozza. Le versioni pubblicate continueranno a funzionare fino alla prossima pubblicazione.",
+ "nodes.humanInputMigration.dialog.review": "Controlla i nodi e pubblica quando è tutto pronto.",
+ "nodes.humanInputMigration.dialog.title": "Migra {{count}} nodi di input umano",
+ "nodes.humanInputMigration.disabledBadge": "MIGRAZIONE NECESSARIA",
+ "nodes.humanInputMigration.disabledReason": "Migra i vecchi nodi di input umano prima di aggiungerne uno nuovo.",
+ "nodes.humanInputMigration.error.blocked": "Impossibile migrare {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Il flusso di lavoro è cambiato durante la migrazione. Riprova; le modifiche attuali sono state mantenute.",
+ "nodes.humanInputMigration.error.preflight": "Impossibile preparare la migrazione. Il flusso di lavoro non è stato modificato. Riprova.",
"nodes.humanInputMigration.error.sync": "Impossibile salvare il flusso di lavoro migrato. Controlla la bozza attuale e riprova.",
+ "nodes.humanInputMigration.incompatibleVersions": "I nodi di input umano vecchi e nuovi non possono essere usati nello stesso flusso di lavoro.",
+ "nodes.humanInputMigration.oldVersion": "VECCHIA VERSIONE",
+ "nodes.humanInputMigration.preview.author": "Dal team Dify",
+ "nodes.humanInputMigration.preview.description": "Migra i vecchi nodi di input umano prima di aggiungerne uno nuovo.",
+ "nodes.humanInputMigration.success": "Nodi di input umano migrati correttamente",
+ "nodes.humanInputV2.card.configured": "{{count}} destinatari configurati",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} contatti",
+ "nodes.humanInputV2.card.empty": "Nessuno può ancora approvare questo passaggio",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Iniziatore e {{count}} contatti",
+ "nodes.humanInputV2.card.initiatorOnly": "Solo l’iniziatore",
+ "nodes.humanInputV2.card.invalid": "La configurazione dei destinatari richiede attenzione",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "Email",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Configura la modalità debug",
"nodes.humanInputV2.debug.keepOneChannel": "Mantieni attivo almeno un canale",
+ "nodes.humanInputV2.debug.sendVia": "Invia notifiche di debug tramite",
+ "nodes.humanInputV2.debug.title": "Modalità debug",
+ "nodes.humanInputV2.debug.toggle": "Attiva la modalità debug",
+ "nodes.humanInputV2.debug.unsupported": "Canali importati non supportati: {{channels}}. Rimuovili o aggiornali prima di eseguire questo flusso di lavoro.",
"nodes.humanInputV2.disabled": "Human Input v2 non è disponibile quando HITL IM è disattivato.",
+ "nodes.humanInputV2.error.bodyRequired": "Il corpo del messaggio è obbligatorio",
+ "nodes.humanInputV2.error.debugChannelRequired": "Seleziona almeno un canale della modalità debug",
+ "nodes.humanInputV2.error.recipientDuplicate": "Rimuovi i destinatari duplicati",
+ "nodes.humanInputV2.error.recipientInvalid": "Correggi la configurazione non valida dei destinatari",
+ "nodes.humanInputV2.error.recipientRequired": "Aggiungi almeno un destinatario",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Impossibile verificare i destinatari dai contatti",
"nodes.humanInputV2.error.requestURLDuplicate": "Il corpo del messaggio può contenere un solo URL della richiesta.",
"nodes.humanInputV2.error.requestURLRequired": "Inserisci un URL della richiesta nel corpo del messaggio.",
+ "nodes.humanInputV2.error.subjectRequired": "L’oggetto del messaggio è obbligatorio",
+ "nodes.humanInputV2.error.version": "Human Input v2 richiede il valore di versione 2 come stringa",
+ "nodes.humanInputV2.recipients.addContact": "Aggiungi contatto",
+ "nodes.humanInputV2.recipients.addEmail": "Aggiungi",
+ "nodes.humanInputV2.recipients.addRecipient": "Aggiungi destinatario",
+ "nodes.humanInputV2.recipients.added": "Aggiunto",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Tutti i contatti dell’area di lavoro",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Invia una notifica a tutti i contatti dell’area di lavoro; chiunque di loro può approvare",
+ "nodes.humanInputV2.recipients.cancel": "Annulla",
+ "nodes.humanInputV2.recipients.chooseVariable": "Scegli variabile",
+ "nodes.humanInputV2.recipients.confirm": "Conferma",
+ "nodes.humanInputV2.recipients.contactInfo": "Dettagli del contatto {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Tutti",
+ "nodes.humanInputV2.recipients.contactSource.external": "Esterno",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organizzazione",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Spazio di lavoro",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Origine del contatto",
"nodes.humanInputV2.recipients.duplicateSource": "Già aggiunto tramite {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Modifica {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Modifica destinatario",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Ogni indirizzo email può essere selezionato una sola volta.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Inserisci un indirizzo email valido che non sia già stato aggiunto",
+ "nodes.humanInputV2.recipients.emailLabel": "Destinatario email occasionale",
+ "nodes.humanInputV2.recipients.empty": "Nessun destinatario configurato",
+ "nodes.humanInputV2.recipients.help": "Scegli chi può rispondere a questo passaggio di input umano.",
"nodes.humanInputV2.recipients.initiator": "L’utente che avvia questa esecuzione tramite Web App o CLI può approvare",
+ "nodes.humanInputV2.recipients.initiatorDescription": "La persona che avvia questa esecuzione del flusso di lavoro può rispondere.",
"nodes.humanInputV2.recipients.inputHelp": "Digita o incolla più indirizzi email separati da virgole. Premi / per inserire una variabile.",
+ "nodes.humanInputV2.recipients.insertVariable": "Inserisci variabile",
+ "nodes.humanInputV2.recipients.loadError": "Impossibile caricare i contatti. Gli ID dei contatti salvati vengono mantenuti.",
+ "nodes.humanInputV2.recipients.loading": "Caricamento dei contatti…",
+ "nodes.humanInputV2.recipients.noResults": "Nessun contatto trovato",
+ "nodes.humanInputV2.recipients.placeholder": "Cerca contatti o aggiungi indirizzi email",
+ "nodes.humanInputV2.recipients.remove": "Rimuovi {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Premi Backspace o Canc per rimuovere.",
+ "nodes.humanInputV2.recipients.resultCount": "Destinatari corrispondenti: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Cerca contatti",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Cerca per nome o email",
+ "nodes.humanInputV2.recipients.selectionHint": "Destinatari selezionati: {{count}}. All’inizio del campo, premi la freccia sinistra per spostare il focus sui destinatari.",
+ "nodes.humanInputV2.recipients.title": "Destinatari",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Tutti i contatti dell’area di lavoro",
+ "nodes.humanInputV2.recipients.type.contact": "Contatto",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Email dinamica",
+ "nodes.humanInputV2.recipients.type.initiator": "Iniziatore",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Email occasionale",
+ "nodes.humanInputV2.recipients.typeLabel": "Tipo di destinatario",
"nodes.humanInputV2.recipients.useThisInstead": "Usa questo al suo posto",
+ "nodes.humanInputV2.recipients.variableRequired": "Scegli una variabile email",
+ "nodes.humanInputV2.template.body": "Corpo",
+ "nodes.humanInputV2.template.description": "Testo alternativo per email e messaggistica istantanea",
"nodes.humanInputV2.template.insertRequestURL": "Inserisci URL della richiesta",
+ "nodes.humanInputV2.template.insertVariable": "Inserisci variabile",
+ "nodes.humanInputV2.template.notConfigured": "Non configurato",
"nodes.humanInputV2.template.requestURLHint": "I destinatari usano questo link per aprire il modulo di approvazione. Includi esattamente un URL della richiesta.",
"nodes.humanInputV2.template.requestURLInserted": "URL della richiesta inserito",
"nodes.humanInputV2.template.saveAndTest": "Salva e testa",
+ "nodes.humanInputV2.template.subject": "Oggetto",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Inserisci l’oggetto del messaggio",
"nodes.humanInputV2.template.test": "Testa messaggio",
"nodes.humanInputV2.template.testChannel": "Canale di prova",
"nodes.humanInputV2.template.testCompleted": "La richiesta di test è stata completata. Controlla il canale selezionato per vedere il messaggio.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Inserisci tutti i valori delle variabili di test.",
"nodes.humanInputV2.template.testSaveFailed": "Impossibile salvare la bozza del flusso di lavoro. Il test non è stato inviato.",
"nodes.humanInputV2.template.testUnavailable": "Questo ambiente non supporta ancora i test dei modelli di messaggio.",
+ "nodes.humanInputV2.template.title": "Modello del messaggio",
"nodes.ifElse.operator": "Operatore",
"nodes.iteration.currentIteration": "Iterazione Corrente",
"nodes.iteration.deleteDesc": "Eliminando il nodo iterazione verranno eliminati tutti i nodi figlio",
diff --git a/web/i18n/locales/ja-JP/contacts.json b/web/i18n/locales/ja-JP/contacts.json
index cfe451d128b..53047d9dce3 100644
--- a/web/i18n/locales/ja-JP/contacts.json
+++ b/web/i18n/locales/ja-JP/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "連絡先({{count}})を削除しますか?",
"directory.removalDescription": "選択した連絡先はこのワークスペースから完全に削除されます。この操作は取り消せません。",
- "directory.removalTitle": "連絡先を削除しますか?",
+ "directory.removalSingleDescription": "{{name}} はこのワークスペースから完全に削除されます。この操作は取り消せません。",
+ "directory.removalSingleFailed": "連絡先を削除できませんでした。再試行してください。",
+ "directory.removalSingleTitle": "{{name}} を削除しますか?",
+ "directory.resultCount": "検索結果:{{count}}",
+ "imPlatform.action.configure": "設定",
+ "imPlatform.action.configureChannel": "{{provider}} を構成する",
+ "imPlatform.action.connect": "接続",
+ "imPlatform.action.copied": "コピーしました",
+ "imPlatform.action.copyCallback": "コールバック URL をコピー",
+ "imPlatform.action.deleteChannel": "{{provider}} を削除",
+ "imPlatform.action.loadMore": "さらに読み込む",
+ "imPlatform.action.replace": "交換する",
+ "imPlatform.action.retry": "再試行",
+ "imPlatform.action.save": "保存",
+ "imPlatform.action.saving": "保存中",
+ "imPlatform.action.setupGuide": "設定ガイド",
+ "imPlatform.action.syncNow": "今すぐ同期",
+ "imPlatform.action.syncing": "同期中",
+ "imPlatform.action.testConnection": "接続をテスト",
+ "imPlatform.action.testing": "テスト中",
+ "imPlatform.action.viewDetails": "詳細を見る",
+ "imPlatform.bindingDialog.back": "戻る",
+ "imPlatform.bindingDialog.callback": "コールバック URL",
+ "imPlatform.bindingDialog.callbackDescription": "カード操作を有効にするには、{{provider}} でコールバックの設定を完了してください。",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "カード操作を受け取るには、<console>Feishu 開発者コンソール</console>の次の場所にこの URL を貼り付けてください:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "イベントとコールバック → コールバック設定 → リクエスト URL",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "カード操作を受け取るには、<console>Lark 開発者コンソール</console>の次の場所にこの URL を貼り付けてください:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "イベントとコールバック → コールバック設定 → リクエスト URL",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "カード操作を受け取るには、<console>Slack 開発者コンソール</console>の次の場所にこの URL を貼り付けてください:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "インタラクティビティとショートカット → インタラクティビティ → リクエスト URL",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "カード操作を受け取るには、<console>Azure Bot の構成</console>の次の場所にこの URL を貼り付けてください:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "設定 → 構成 → メッセージング エンドポイント",
+ "imPlatform.bindingDialog.callbackStep": "コールバックを設定",
"imPlatform.bindingDialog.clearSavedCredential": "保存済みの値をクリア",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} を構成する",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}} を接続する",
"imPlatform.bindingDialog.credentialWillBeCleared": "保存すると、この保存済みの値がクリアされます。",
+ "imPlatform.bindingDialog.credentialsDescription": "まず {{provider}} アプリを接続し、その後コールバック URL を設定してください。",
+ "imPlatform.bindingDialog.credentialsStep": "アプリの認証情報",
+ "imPlatform.bindingDialog.description": "この IM プロバイダーのアプリ認証情報を入力してください。",
+ "imPlatform.bindingDialog.field.agentId": "エージェント ID",
+ "imPlatform.bindingDialog.field.appId": "アプリ ID",
+ "imPlatform.bindingDialog.field.appToken": "アプリトークン(任意)",
+ "imPlatform.bindingDialog.field.botToken": "ボットトークン",
+ "imPlatform.bindingDialog.field.clientId": "クライアントID",
+ "imPlatform.bindingDialog.field.clientSecret": "クライアントシークレット",
+ "imPlatform.bindingDialog.field.corpId": "企業 ID",
+ "imPlatform.bindingDialog.field.encryptKey": "暗号化キー(任意)",
+ "imPlatform.bindingDialog.field.genericSecret": "シークレット",
+ "imPlatform.bindingDialog.field.secret": "アプリシークレット",
+ "imPlatform.bindingDialog.field.signingSecret": "署名シークレット",
+ "imPlatform.bindingDialog.field.tenantId": "テナント ID",
+ "imPlatform.bindingDialog.field.verificationToken": "検証トークン(任意)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "暗号化を有効にした場合は、暗号化キーを入力してください",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "アプリシークレットを入力",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "検証トークンを設定した場合は、入力してください",
+ "imPlatform.bindingDialog.finish": "完了",
+ "imPlatform.bindingDialog.freshCredentials": "保存済みのシークレットは取得できません。この設定をテストまたは保存するには、必要な認証情報をすべて入力し直してください。",
+ "imPlatform.bindingDialog.openSetupGuide": "設定ガイドを開く",
+ "imPlatform.bindingDialog.replaceTenantTitle": "{{identity}} のテナント認証情報を置き換えますか?",
"imPlatform.bindingDialog.replacementRequired": "この認証情報は別の IM テナントに属するため、そのまま保存できません。テナントを切り替えるには、現在の IM チャネルを置き換える必要があり、自動および手動で設定されたすべての IM バインディングが削除されます。置き換え後に連絡先を再同期してください。",
+ "imPlatform.bindingDialog.required": "この項目は必須です。",
+ "imPlatform.bindingDialog.saveAndContinue": "保存して続行",
+ "imPlatform.bindingDialog.saveFailed": "設定を保存できませんでした。入力内容を確認して、もう一度お試しください。",
"imPlatform.bindingDialog.savedDetailsUnavailable": "設定は保存されましたが、詳細を読み込めませんでした。このダイアログを閉じて、再度開いてください。",
- "imPlatform.bindingDialog.undoClearCredential": "クリアを取り消す"
+ "imPlatform.bindingDialog.secretConfigured": "シークレットは設定済みです。変更しない場合は空欄にしてください。",
+ "imPlatform.bindingDialog.step": "ステップ {{step}}",
+ "imPlatform.bindingDialog.testFailed": "接続テストに失敗しました。設定を確認して、もう一度お試しください。",
+ "imPlatform.bindingDialog.undoClearCredential": "クリアを取り消す",
+ "imPlatform.bindingDialog.viewSetupGuide": "設定ガイドを見る",
+ "imPlatform.chooseProvider": "接続するチャネルを選択",
+ "imPlatform.configurationUpdated": "このチャネルの設定が変更されました。ダイアログを閉じて更新し、もう一度お試しください。",
+ "imPlatform.connectMore": "他のチャネルを接続",
+ "imPlatform.delete.confirm": "削除",
+ "imPlatform.delete.description": "このチャネルを削除すると設定が消去され、このチャネルを使用する承認通知の送信とディレクトリ同期が停止します。",
+ "imPlatform.delete.failed": "チャネルを削除できませんでした。変更は行われていません。もう一度お試しください。",
+ "imPlatform.delete.title": "{{provider}} チャネルを削除しますか?",
+ "imPlatform.description": "社内のチャネルを接続して、普段の業務環境に承認リクエストを届けます。",
+ "imPlatform.details.column.contact": "連絡先",
+ "imPlatform.details.column.platform": "IM プラットフォーム",
+ "imPlatform.details.description": "最新の同期処理の結果を読み取り専用で表示します。",
+ "imPlatform.details.downloadFailed": "レポートをダウンロードできませんでした。もう一度お試しください。",
+ "imPlatform.details.downloadReport": "レポートをダウンロード",
+ "imPlatform.details.downloadingReport": "レポートをダウンロード中…",
+ "imPlatform.details.empty": "このカテゴリに結果はありません。",
+ "imPlatform.details.filter.added": "追加済み",
+ "imPlatform.details.filter.failed": "失敗",
+ "imPlatform.details.filter.not_matched": "一致なし",
+ "imPlatform.details.filter.removed": "削除済み",
+ "imPlatform.details.filter.skipped": "スキップ",
+ "imPlatform.details.filters": "同期結果のフィルター",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "同期の詳細を読み込めませんでした。",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "追加の結果を読み込めませんでした。このページを再試行してください。",
+ "imPlatform.details.removalReason.binding_invalidated": "バインドが無効になりました",
+ "imPlatform.details.removalReason.binding_replaced": "バインドが置き換えられました",
+ "imPlatform.details.removalReason.not_present_in_directory": "ディレクトリに存在しません",
+ "imPlatform.details.reportChanged": "同期結果が変更されました。最新の同期詳細を開き直して、もう一度お試しください。",
+ "imPlatform.details.title": "同期の詳細",
+ "imPlatform.email.apiKey": "API キー",
+ "imPlatform.email.apiKeyConfigured": "セキュリティ上、保存済みの API キーは表示できません。変更しない場合は空欄にしてください。",
+ "imPlatform.email.apiKeyDescription": "セキュリティ上、この API キーは保存後に表示できません。",
+ "imPlatform.email.apiKeyPlaceholder": "Resend API キーを入力",
+ "imPlatform.email.description": "この設定は、このワークスペースで<emphasis>メールによるデバッグ通知の送信</emphasis>を有効にしたすべての Human Input ノードに適用されます。",
+ "imPlatform.email.invalidEmail": "有効なメールアドレスを入力してください。",
+ "imPlatform.email.provider": "メールプロバイダー",
+ "imPlatform.email.resendDescription": "<apiKey>Resend API キー</apiKey>は暗号化され、保存後は表示できません。<br/><resend>Resend</resend> アカウントを作成してください。",
+ "imPlatform.email.resendSettings": "Resend の設定",
+ "imPlatform.email.senderEmail": "送信元メールアドレス",
+ "imPlatform.email.senderEmailDescription": "送信元として表示するメールアドレスです。ドメインを Resend で認証する必要があります。",
+ "imPlatform.email.senderName": "送信者名",
+ "imPlatform.email.senderNameDescription": "受信者の受信トレイに表示する名前です。",
+ "imPlatform.email.testSucceeded": "接続テストに成功しました。",
+ "imPlatform.email.title": "メールを設定",
+ "imPlatform.learnMore": "詳細を見る",
+ "imPlatform.loadError.description": "現在の接続設定と権限を取得するには、もう一度お試しください。",
+ "imPlatform.loadError.retry": "再試行",
+ "imPlatform.loadError.title": "チャネルを読み込めませんでした",
+ "imPlatform.loading": "チャネルを読み込み中",
+ "imPlatform.provider.dingtalkDescription": "DingTalk アプリを接続します。",
+ "imPlatform.provider.emailDescription": "このワークスペースから承認リクエストを送信するメールサービスを設定します。",
+ "imPlatform.provider.feishuDescription": "Feishu アプリを接続します。",
+ "imPlatform.provider.larkDescription": "Lark アプリを接続します。",
+ "imPlatform.provider.msTeamsDescription": "Microsoft Teams アプリを接続します。",
+ "imPlatform.provider.slackDescription": "ユーザーと Slack の ID を同期します。",
+ "imPlatform.provider.weComDescription": "WeCom アプリを接続します。",
+ "imPlatform.replacement.confirm": "交換する",
+ "imPlatform.replacement.description": "現在のプロバイダーを置き換えると、その IM バインドとワークスペースの上書き設定が無効になります。置き換え後、新しいプロバイダーのディレクトリを再同期してください。",
+ "imPlatform.replacement.title": "{{current}} を {{next}} に置き換えますか?",
+ "imPlatform.status.configured": "設定しました",
+ "imPlatform.status.connected": "接続済み",
+ "imPlatform.status.connection_error": "接続エラー",
+ "imPlatform.status.permission_issue": "権限の問題",
+ "imPlatform.sync.latestSynced": "最終同期:{{date}}",
+ "imPlatform.sync.loading": "実行中の同期を確認しています。",
+ "imPlatform.sync.noPermission": "ディレクトリ同期を開始できるのは、ワークスペースの所有者と管理者のみです。",
+ "imPlatform.sync.noRuns": "ディレクトリ同期はまだ実行されていません。",
+ "imPlatform.sync.notConnected": "ディレクトリ同期を開始する前に、プロバイダーを接続してテストしてください。",
+ "imPlatform.sync.startFailed": "ディレクトリ同期を開始または更新できませんでした。もう一度お試しください。",
+ "imPlatform.sync.status.failure": "失敗",
+ "imPlatform.sync.status.queued": "待機中",
+ "imPlatform.sync.status.running": "実行中",
+ "imPlatform.sync.status.success": "成功",
+ "imPlatform.title": "チャネル"
}
diff --git a/web/i18n/locales/ja-JP/share.json b/web/i18n/locales/ja-JP/share.json
index 187277a08f0..9063b1e5588 100644
--- a/web/i18n/locales/ja-JP/share.json
+++ b/web/i18n/locales/ja-JP/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "ありがとうございます!",
"humanInput.unavailableDescription": "リンクが利用できないか、ログイン中のアカウントに対応していない可能性があります。受信した通知からフォームを開くか、アカウントを切り替えてください。",
"humanInput.unavailableTitle": "このフォームを開けません",
+ "humanInputV2.accessRateLimited": "確認メールのリクエストが多すぎます。しばらくしてからもう一度お試しください。",
+ "humanInputV2.alreadySubmitted": "このリクエストはすでに完了しています。",
+ "humanInputV2.challengeExpired": "この確認コードは有効期限が切れています。続行するには新しいコードをリクエストしてください。",
+ "humanInputV2.challengeStale": "この確認コードは新しいコードに置き換えられました。続行するには新しいコードをリクエストしてください。",
+ "humanInputV2.codeExpiresIn": "コードの有効期限まで {{seconds}} 秒",
+ "humanInputV2.codeRequired": "続行するには確認コードをリクエストしてください。",
+ "humanInputV2.codeSent": "メールアドレスに確認コードを送信しました。",
+ "humanInputV2.deliveryFailed": "確認メールを送信できませんでした。もう一度お試しください。",
+ "humanInputV2.formExpired": "このリクエストは有効期限が切れています。",
+ "humanInputV2.formNotFound": "フォームが見つかりません。",
+ "humanInputV2.formRateLimited": "フォームへのリクエストが多すぎます。しばらくしてからもう一度お試しください。",
+ "humanInputV2.invalidOtp": "確認コードが正しくありません。コードを確認してもう一度お試しください。",
+ "humanInputV2.networkError": "リクエストを完了できませんでした。接続を確認してもう一度お試しください。",
+ "humanInputV2.otpLabel": "メール確認コード",
+ "humanInputV2.otpPlaceholder": "6 桁のコードを入力",
+ "humanInputV2.requestingCode": "確認コードを送信中…",
+ "humanInputV2.resendCode": "コードを再送信",
+ "humanInputV2.retry": "再試行",
+ "humanInputV2.sendCode": "新しいコードを送信",
+ "humanInputV2.unavailable": "このフォームは一時的に利用できません。",
+ "humanInputV2.unknownError": "問題が発生しました。もう一度お試しください。",
+ "humanInputV2.uploadFailed": "ファイルをアップロードできませんでした。もう一度お試しください。",
"login.backToHome": "ホームに戻る"
}
diff --git a/web/i18n/locales/ja-JP/workflow-human-input.json b/web/i18n/locales/ja-JP/workflow-human-input.json
index 6b77b17d26d..b8a02e5368b 100644
--- a/web/i18n/locales/ja-JP/workflow-human-input.json
+++ b/web/i18n/locales/ja-JP/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "アクション値",
"nodes.humanInput.userActions.buttonTextTooLong": "ボタンテキストは{{maxLength}}文字以下である必要があります",
"nodes.humanInput.userActions.chooseStyle": "ボタンスタイルを選択",
+ "nodes.humanInput.userActions.defaultTitle": "ボタンのテキスト {{index}}",
"nodes.humanInput.userActions.emptyTip": "'+'ボタンをクリックしてユーザーアクションを追加",
"nodes.humanInput.userActions.title": "ユーザーアクション",
"nodes.humanInput.userActions.tooltip": "ユーザーがこのフォームに応答するためにクリックできるボタンを定義します。アクションIDは分岐を制御します。アクション値は選択された組み込み出力として下流に公開されます。アクションIDは文字またはアンダースコアで始まり、その後に文字、数字、またはアンダースコアが続く必要があります。",
diff --git a/web/i18n/locales/ja-JP/workflow.json b/web/i18n/locales/ja-JP/workflow.json
index 5c680d2dfe5..16b29095f29 100644
--- a/web/i18n/locales/ja-JP/workflow.json
+++ b/web/i18n/locales/ja-JP/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "出力",
"blocks.http-request": "HTTP リクエスト",
"blocks.human-input": "人間の入力",
+ "blocks.human-input-v2": "人間の入力 v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "イテレーション",
"blocks.iteration-start": "イテレーション開始",
@@ -45,6 +46,7 @@
"blocksAbout.end": "ワークフローの出力と結果のタイプを定義します",
"blocksAbout.http-request": "HTTP リクエストを送信できます。",
"blocksAbout.human-input": "次のステップを生成する前に人間の確認を求める",
+ "blocksAbout.human-input-v2": "設定済みの連絡先、メールの受信者、またはワークフローの開始者に入力をリクエストします",
"blocksAbout.if-else": "if/else 条件でワークフローを 2 つの分岐に分割します。",
"blocksAbout.iteration": "リスト要素に対して反復処理を実行し全結果を出力します。",
"blocksAbout.iteration-start": "反復開始ノード",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "複数分岐の変数を集約し、下流ノードの設定を統一します。",
"blocksAbout.variable-assigner": "複数分岐の変数を集約し、下流ノードの設定を統一します。",
"changeHistory.edgeDelete": "ブロックの接続が解除されました",
+ "changeHistory.humanInputMigration": "人間の入力ノードを移行しました",
"changeHistory.nodeAdd": "ブロックが追加されました",
"changeHistory.nodeChange": "ブロックが変更されました",
"changeHistory.nodeConnect": "ブロックが接続されました",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "少なくとも1つの配信方法を有効にしてください",
"nodes.humanInput.errorMsg.noUserActions": "少なくとも1つのユーザーアクションを追加してください",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} はタイムアウト分岐用に予約されています。別のアクション ID を指定してください。",
+ "nodes.humanInput.output.actionId": "ユーザーが実行したアクションの ID",
+ "nodes.humanInput.output.actionValue": "選択されたアクションの値",
+ "nodes.humanInput.output.formInput": "フォームの入力値",
+ "nodes.humanInput.output.renderedContent": "レンダリングされたコンテンツ",
"nodes.humanInput.timeout.title": "タイムアウト",
+ "nodes.humanInputMigration.action.migrate": "移行",
+ "nodes.humanInputMigration.action.migrateNow": "今すぐ移行",
+ "nodes.humanInputMigration.action.migrating": "移行中...",
+ "nodes.humanInputMigration.banner.ariaLabel": "人間の入力ノードの移行に関するお知らせ",
+ "nodes.humanInputMigration.banner.description": "このワークフローでは旧バージョンの人間の入力ノードが使われています。新しいノードを追加する前に、すべての旧ノードを移行してください。",
+ "nodes.humanInputMigration.banner.learnMore": "詳細を見る",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "無効な配信方法に設定が残っています",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "有効なメール配信方法で競合するテンプレートが使われています",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "デフォルト値が無効です",
+ "nodes.humanInputMigration.blocker.invalidEmail": "受信者のメールアドレスが無効です",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "有効なメール配信方法の設定が不完全です",
+ "nodes.humanInputMigration.blocker.missingRecipients": "このノードには対応している受信者がいません",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "ワークスペースのメンバーを連絡先または確認済みメールアドレスに対応付けられません",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "有効な配信方法が人間の入力 v2 でサポートされていません",
"nodes.humanInputMigration.blocker.unsupportedInputType": "フィールド {{field}} はまだ移行できません。従来のヒューマン入力ノードを引き続き使用できます。",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "このノードのバージョン値はサポートされていません",
+ "nodes.humanInputMigration.dialog.description": "受信者、フォーム、アクションは引き継がれます。",
+ "nodes.humanInputMigration.dialog.draftNotice": "変更されるのはこの下書きのみです。公開済みのバージョンは、再公開するまで引き続き実行されます。",
+ "nodes.humanInputMigration.dialog.review": "ノードを確認し、準備ができたら公開してください。",
+ "nodes.humanInputMigration.dialog.title": "{{count}} 個の人間の入力ノードを移行",
+ "nodes.humanInputMigration.disabledBadge": "移行が必要",
+ "nodes.humanInputMigration.disabledReason": "新しいノードを追加する前に、旧バージョンの人間の入力ノードを移行してください。",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} を移行できませんでした:{{reason}}。",
"nodes.humanInputMigration.error.graphChanged": "移行中にワークフローが変更されました。再試行してください。現在の編集内容は保持されています。",
+ "nodes.humanInputMigration.error.preflight": "移行の準備ができませんでした。ワークフローは変更されていません。もう一度お試しください。",
"nodes.humanInputMigration.error.sync": "移行後のワークフローを保存できませんでした。現在の下書きを確認して、再試行してください。",
+ "nodes.humanInputMigration.incompatibleVersions": "同じワークフローで旧版と新版のユーザー入力ノードを併用することはできません。",
+ "nodes.humanInputMigration.oldVersion": "旧バージョン",
+ "nodes.humanInputMigration.preview.author": "Dify チーム作成",
+ "nodes.humanInputMigration.preview.description": "新しいノードを追加する前に、旧バージョンの人間の入力ノードを移行してください。",
+ "nodes.humanInputMigration.success": "人間の入力ノードを正常に移行しました",
+ "nodes.humanInputV2.card.configured": "{{count}} 件の受信者を設定済み",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} 件の連絡先",
+ "nodes.humanInputV2.card.empty": "このステップを承認できる人はまだいません",
+ "nodes.humanInputV2.card.initiatorAndContacts": "開始者と {{count}} 件の連絡先",
+ "nodes.humanInputV2.card.initiatorOnly": "開始者のみ",
+ "nodes.humanInputV2.card.invalid": "受信者の設定を確認してください",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "メール",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "デバッグモードを設定",
"nodes.humanInputV2.debug.keepOneChannel": "少なくとも1つのチャンネルを有効にしてください",
+ "nodes.humanInputV2.debug.sendVia": "デバッグ通知の送信先",
+ "nodes.humanInputV2.debug.title": "デバッグモード",
+ "nodes.humanInputV2.debug.toggle": "デバッグモードを有効にする",
+ "nodes.humanInputV2.debug.unsupported": "インポートされたチャンネルはサポートされていません:{{channels}}。このワークフローを実行する前に削除または更新してください。",
"nodes.humanInputV2.disabled": "HITL IM が無効の間、Human Input v2 は利用できません。",
+ "nodes.humanInputV2.error.bodyRequired": "メッセージ本文は必須です",
+ "nodes.humanInputV2.error.debugChannelRequired": "デバッグモードのチャンネルを少なくとも1つ選択してください",
+ "nodes.humanInputV2.error.recipientDuplicate": "重複する受信者を削除してください",
+ "nodes.humanInputV2.error.recipientInvalid": "無効な受信者の設定を修正してください",
+ "nodes.humanInputV2.error.recipientRequired": "受信者を少なくとも1件追加してください",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "連絡先の受信者を確認できませんでした",
"nodes.humanInputV2.error.requestURLDuplicate": "本文に含められるリクエスト URL は 1 つだけです。",
"nodes.humanInputV2.error.requestURLRequired": "本文にリクエスト URL を挿入してください。",
+ "nodes.humanInputV2.error.subjectRequired": "メッセージの件名は必須です",
+ "nodes.humanInputV2.error.version": "人間の入力 v2 では、バージョンを文字列の 2 にする必要があります",
+ "nodes.humanInputV2.recipients.addContact": "連絡先を追加",
+ "nodes.humanInputV2.recipients.addEmail": "追加",
+ "nodes.humanInputV2.recipients.addRecipient": "受信者を追加",
+ "nodes.humanInputV2.recipients.added": "追加済み",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "ワークスペースのすべての連絡先",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "ワークスペース内のすべての連絡先に通知を送信し、いずれかのユーザーが承認できます",
+ "nodes.humanInputV2.recipients.cancel": "キャンセル",
+ "nodes.humanInputV2.recipients.chooseVariable": "変数を選択",
+ "nodes.humanInputV2.recipients.confirm": "確認",
+ "nodes.humanInputV2.recipients.contactInfo": "{{name}} の連絡先の詳細",
+ "nodes.humanInputV2.recipients.contactSource.all": "すべて",
+ "nodes.humanInputV2.recipients.contactSource.external": "外部",
+ "nodes.humanInputV2.recipients.contactSource.organization": "組織",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "ワークスペース",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "連絡先の取得元",
"nodes.humanInputV2.recipients.duplicateSource": "{{name}}({{source}})経由ですでに追加されています。",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} を編集",
+ "nodes.humanInputV2.recipients.editRecipient": "受信者を編集",
"nodes.humanInputV2.recipients.emailAlreadySelected": "各メールアドレスは一度だけ選択できます。",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "まだ追加されていない有効なメールアドレスを入力してください",
+ "nodes.humanInputV2.recipients.emailLabel": "今回のみのメール受信者",
+ "nodes.humanInputV2.recipients.empty": "受信者が設定されていません",
+ "nodes.humanInputV2.recipients.help": "この人間の入力ステップに回答できる人を選択します。",
"nodes.humanInputV2.recipients.initiator": "Web App または CLI から今回の実行を開始したユーザーが承認できます",
+ "nodes.humanInputV2.recipients.initiatorDescription": "このワークフローの実行を開始した人が回答できます。",
"nodes.humanInputV2.recipients.inputHelp": "複数のメールアドレスをカンマで区切って入力または貼り付けます。/ を押すと変数を挿入できます。",
+ "nodes.humanInputV2.recipients.insertVariable": "変数を挿入",
+ "nodes.humanInputV2.recipients.loadError": "連絡先を読み込めませんでした。保存済みの連絡先 ID は保持されています。",
+ "nodes.humanInputV2.recipients.loading": "連絡先を読み込み中…",
+ "nodes.humanInputV2.recipients.noResults": "連絡先が見つかりません",
+ "nodes.humanInputV2.recipients.placeholder": "連絡先を検索するかメールアドレスを追加",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} を削除",
+ "nodes.humanInputV2.recipients.removeHint": "Backspace または Delete キーで削除します。",
+ "nodes.humanInputV2.recipients.resultCount": "一致する宛先は {{count}} 件です",
+ "nodes.humanInputV2.recipients.search": "連絡先を検索",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "名前またはメールアドレスで検索",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} 件の宛先を選択中。入力欄の先頭で左矢印キーを押すと宛先にフォーカスします。",
+ "nodes.humanInputV2.recipients.title": "受信者",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "ワークスペースのすべての連絡先",
+ "nodes.humanInputV2.recipients.type.contact": "連絡先",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "動的メールアドレス",
+ "nodes.humanInputV2.recipients.type.initiator": "開始者",
+ "nodes.humanInputV2.recipients.type.onetime_email": "今回のみのメールアドレス",
+ "nodes.humanInputV2.recipients.typeLabel": "受信者の種類",
"nodes.humanInputV2.recipients.useThisInstead": "代わりにこちらを使用",
+ "nodes.humanInputV2.recipients.variableRequired": "メールアドレスの変数を選択してください",
+ "nodes.humanInputV2.template.body": "本文",
+ "nodes.humanInputV2.template.description": "メールおよび IM のフォールバック文面",
"nodes.humanInputV2.template.insertRequestURL": "リクエスト URL を挿入",
+ "nodes.humanInputV2.template.insertVariable": "変数を挿入",
+ "nodes.humanInputV2.template.notConfigured": "未設定",
"nodes.humanInputV2.template.requestURLHint": "受信者はこのリンクから承認フォームを開きます。本文にはリクエスト URL を必ず 1 つ含めてください。",
"nodes.humanInputV2.template.requestURLInserted": "リクエスト URL を挿入済み",
"nodes.humanInputV2.template.saveAndTest": "保存してテスト",
+ "nodes.humanInputV2.template.subject": "件名",
+ "nodes.humanInputV2.template.subjectPlaceholder": "メッセージの件名を入力",
"nodes.humanInputV2.template.test": "メッセージをテスト",
"nodes.humanInputV2.template.testChannel": "テストチャネル",
"nodes.humanInputV2.template.testCompleted": "テストリクエストが完了しました。選択したチャネルでメッセージを確認してください。",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "すべてのテスト変数の値を入力してください。",
"nodes.humanInputV2.template.testSaveFailed": "ワークフローの下書きを保存できませんでした。テストは送信されていません。",
"nodes.humanInputV2.template.testUnavailable": "この環境はまだメッセージテンプレートのテストに対応していません。",
+ "nodes.humanInputV2.template.title": "メッセージテンプレート",
"nodes.ifElse.operator": "演算子",
"nodes.iteration.currentIteration": "現在のイテレーション",
"nodes.iteration.deleteDesc": "イテレーションノードを削除すると、すべての子ノードが削除されます",
diff --git a/web/i18n/locales/ko-KR/contacts.json b/web/i18n/locales/ko-KR/contacts.json
index 364457079c9..c9a60e83a0d 100644
--- a/web/i18n/locales/ko-KR/contacts.json
+++ b/web/i18n/locales/ko-KR/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "연락처({{count}})를 삭제하시겠습니까?",
"directory.removalDescription": "선택한 연락처가 이 워크스페이스에서 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.",
- "directory.removalTitle": "연락처를 삭제하시겠습니까?",
+ "directory.removalSingleDescription": "{{name}} 님이 이 작업 공간에서 영구적으로 삭제됩니다. 이 작업은 취소할 수 없습니다.",
+ "directory.removalSingleFailed": "연락처를 삭제하지 못했습니다. 다시 시도하세요.",
+ "directory.removalSingleTitle": "{{name}} 님을 삭제하시겠습니까?",
+ "directory.resultCount": "결과: {{count}}",
+ "imPlatform.action.configure": "구성",
+ "imPlatform.action.configureChannel": "{{provider}} 구성",
+ "imPlatform.action.connect": "연결",
+ "imPlatform.action.copied": "복사",
+ "imPlatform.action.copyCallback": "콜백 URL 복사",
+ "imPlatform.action.deleteChannel": "{{provider}} 삭제",
+ "imPlatform.action.loadMore": "더 보기",
+ "imPlatform.action.replace": "바꾸다",
+ "imPlatform.action.retry": "재시도",
+ "imPlatform.action.save": "저장",
+ "imPlatform.action.saving": "저장 중",
+ "imPlatform.action.setupGuide": "설정 가이드",
+ "imPlatform.action.syncNow": "지금 동기화",
+ "imPlatform.action.syncing": "동기화 중",
+ "imPlatform.action.testConnection": "연결 테스트",
+ "imPlatform.action.testing": "테스트 중",
+ "imPlatform.action.viewDetails": "세부 정보보기",
+ "imPlatform.bindingDialog.back": "뒤로",
+ "imPlatform.bindingDialog.callback": "콜백 URL",
+ "imPlatform.bindingDialog.callbackDescription": "카드 작업을 활성화하려면 {{provider}}에서 콜백 설정을 완료하세요.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "카드 작업을 받으려면 <console>Feishu 개발자 콘솔</console>의 다음 위치에 이 URL을 붙여넣으세요:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "이벤트 및 콜백 → 콜백 구성 → 요청 URL",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "카드 작업을 받으려면 <console>Lark 개발자 콘솔</console>의 다음 위치에 이 URL을 붙여넣으세요:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "이벤트 및 콜백 → 콜백 구성 → 요청 URL",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "카드 작업을 받으려면 <console>Slack 개발자 콘솔</console>의 다음 위치에 이 URL을 붙여넣으세요:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "상호작용 및 바로가기 → 상호작용 → 요청 URL",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "카드 작업을 받으려면 <console>Azure Bot 구성</console>의 다음 위치에 이 URL을 붙여넣으세요:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "설정 → 구성 → 메시징 엔드포인트",
+ "imPlatform.bindingDialog.callbackStep": "콜백 구성",
"imPlatform.bindingDialog.clearSavedCredential": "저장된 값 지우기",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} 구성",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}} 연결",
"imPlatform.bindingDialog.credentialWillBeCleared": "저장하면 이 저장된 값이 지워집니다.",
+ "imPlatform.bindingDialog.credentialsDescription": "먼저 {{provider}} 앱을 연결한 다음 콜백 URL을 구성하세요.",
+ "imPlatform.bindingDialog.credentialsStep": "앱 자격 증명",
+ "imPlatform.bindingDialog.description": "이 IM 제공자의 앱 자격 증명을 입력하세요.",
+ "imPlatform.bindingDialog.field.agentId": "에이전트 ID",
+ "imPlatform.bindingDialog.field.appId": "앱 ID",
+ "imPlatform.bindingDialog.field.appToken": "앱 토큰(선택 사항)",
+ "imPlatform.bindingDialog.field.botToken": "봇 토큰",
+ "imPlatform.bindingDialog.field.clientId": "클라이언트 ID",
+ "imPlatform.bindingDialog.field.clientSecret": "클라이언트 시크릿",
+ "imPlatform.bindingDialog.field.corpId": "기업 ID",
+ "imPlatform.bindingDialog.field.encryptKey": "암호화 키(선택 사항)",
+ "imPlatform.bindingDialog.field.genericSecret": "비밀",
+ "imPlatform.bindingDialog.field.secret": "앱 시크릿",
+ "imPlatform.bindingDialog.field.signingSecret": "서명 시크릿",
+ "imPlatform.bindingDialog.field.tenantId": "테넌트 ID",
+ "imPlatform.bindingDialog.field.verificationToken": "검증 토큰(선택 사항)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "암호화가 활성화된 경우 암호화 키를 입력하세요",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "앱 시크릿 입력",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "검증 토큰이 구성된 경우 입력하세요",
+ "imPlatform.bindingDialog.finish": "완료",
+ "imPlatform.bindingDialog.freshCredentials": "저장된 시크릿은 조회할 수 없습니다. 이 구성을 테스트하거나 저장하려면 필수 자격 증명을 모두 다시 입력하세요.",
+ "imPlatform.bindingDialog.openSetupGuide": "설정 가이드 열기",
+ "imPlatform.bindingDialog.replaceTenantTitle": "{{identity}}의 테넌트 자격 증명을 교체할까요?",
"imPlatform.bindingDialog.replacementRequired": "이 인증 정보는 다른 IM 테넌트에 속하므로 바로 저장할 수 없습니다. 테넌트를 전환하려면 현재 IM 채널을 교체해야 하며, 이 과정에서 모든 자동 및 수동 IM 바인딩이 삭제됩니다. 교체 후 연락처를 다시 동기화하세요.",
+ "imPlatform.bindingDialog.required": "필수 항목입니다.",
+ "imPlatform.bindingDialog.saveAndContinue": "저장 후 계속",
+ "imPlatform.bindingDialog.saveFailed": "구성을 저장할 수 없습니다. 입력 내용을 확인한 후 다시 시도하세요.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "설정은 저장되었지만 세부 정보를 불러올 수 없습니다. 이 대화 상자를 닫았다가 다시 여세요.",
- "imPlatform.bindingDialog.undoClearCredential": "지우기 취소"
+ "imPlatform.bindingDialog.secretConfigured": "시크릿이 이미 구성되어 있습니다. 유지하려면 이 필드를 비워 두세요.",
+ "imPlatform.bindingDialog.step": "{{step}}단계",
+ "imPlatform.bindingDialog.testFailed": "연결 테스트에 실패했습니다. 구성을 확인한 후 다시 시도하세요.",
+ "imPlatform.bindingDialog.undoClearCredential": "지우기 취소",
+ "imPlatform.bindingDialog.viewSetupGuide": "설정 가이드 보기",
+ "imPlatform.chooseProvider": "연결할 채널 선택",
+ "imPlatform.configurationUpdated": "이 채널의 구성이 변경되었습니다. 이 대화 상자를 닫고 새로고침한 후 다시 시도하세요.",
+ "imPlatform.connectMore": "추가 채널 연결",
+ "imPlatform.delete.confirm": "삭 ",
+ "imPlatform.delete.description": "이 채널을 삭제하면 구성이 제거됩니다. 이 채널을 사용하는 승인 알림 전송과 디렉터리 동기화가 중지됩니다.",
+ "imPlatform.delete.failed": "채널을 삭제할 수 없습니다. 변경된 사항은 없습니다. 다시 시도하세요.",
+ "imPlatform.delete.title": "{{provider}} 채널을 삭제할까요?",
+ "imPlatform.description": "회사 채널을 연결하여 구성원이 일하는 곳으로 승인 요청을 보내세요.",
+ "imPlatform.details.column.contact": "연락처",
+ "imPlatform.details.column.platform": "IM 플랫폼",
+ "imPlatform.details.description": "최근 동기화 실행 결과를 읽기 전용으로 확인합니다.",
+ "imPlatform.details.downloadFailed": "보고서를 다운로드할 수 없습니다. 다시 시도하세요.",
+ "imPlatform.details.downloadReport": "보고서 다운로드",
+ "imPlatform.details.downloadingReport": "보고서 다운로드 중…",
+ "imPlatform.details.empty": "이 범주에는 결과가 없습니다.",
+ "imPlatform.details.filter.added": "추가됨",
+ "imPlatform.details.filter.failed": "실패",
+ "imPlatform.details.filter.not_matched": "일치하지 않음",
+ "imPlatform.details.filter.removed": "삭제됨",
+ "imPlatform.details.filter.skipped": "건너뜀",
+ "imPlatform.details.filters": "동기화 결과 필터",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "동기화 세부 정보를 불러올 수 없습니다.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "추가 결과를 불러올 수 없습니다. 이 페이지를 다시 시도하세요.",
+ "imPlatform.details.removalReason.binding_invalidated": "바인딩 무효화됨",
+ "imPlatform.details.removalReason.binding_replaced": "바인딩 교체됨",
+ "imPlatform.details.removalReason.not_present_in_directory": "디렉터리에 더 이상 없음",
+ "imPlatform.details.reportChanged": "동기화 결과가 변경되었습니다. 최근 동기화 세부 정보를 다시 열고 시도하세요.",
+ "imPlatform.details.title": "동기화 세부 정보",
+ "imPlatform.email.apiKey": "API 키",
+ "imPlatform.email.apiKeyConfigured": "보안상의 이유로 저장된 API 키를 볼 수 없습니다. 유지하려면 이 필드를 비워 두세요.",
+ "imPlatform.email.apiKeyDescription": "보안상의 이유로 이 API 키는 저장 후 볼 수 없습니다.",
+ "imPlatform.email.apiKeyPlaceholder": "Resend API 키 입력",
+ "imPlatform.email.description": "이 구성은 이 워크스페이스에서 <emphasis>이메일로 디버그 알림 전송</emphasis>이 활성화된 모든 Human Input 노드에 적용됩니다.",
+ "imPlatform.email.invalidEmail": "올바른 이메일 주소를 입력하세요.",
+ "imPlatform.email.provider": "이메일 제공자",
+ "imPlatform.email.resendDescription": "<apiKey>Resend API 키</apiKey>는 암호화되며 저장 후에는 볼 수 없습니다.<br/><resend>Resend</resend> 계정을 만드세요.",
+ "imPlatform.email.resendSettings": "Resend 설정",
+ "imPlatform.email.senderEmail": "발신자 이메일 주소",
+ "imPlatform.email.senderEmailDescription": "발신자로 표시되는 이메일 주소입니다. Resend에서 해당 도메인을 인증해야 합니다.",
+ "imPlatform.email.senderName": "발신자 이름",
+ "imPlatform.email.senderNameDescription": "수신자의 받은편지함에 표시되는 이름입니다.",
+ "imPlatform.email.testSucceeded": "연결 테스트에 성공했습니다.",
+ "imPlatform.email.title": "이메일 구성",
+ "imPlatform.learnMore": "자세히 알아보기",
+ "imPlatform.loadError.description": "현재 바인딩과 권한을 불러오려면 다시 시도하세요.",
+ "imPlatform.loadError.retry": "다시 시도",
+ "imPlatform.loadError.title": "채널을 불러올 수 없습니다",
+ "imPlatform.loading": "채널 불러오는 중",
+ "imPlatform.provider.dingtalkDescription": "DingTalk 앱을 연결합니다.",
+ "imPlatform.provider.emailDescription": "이 워크스페이스에서 승인 요청을 보낼 이메일 서비스를 구성합니다.",
+ "imPlatform.provider.feishuDescription": "Feishu 앱을 연결합니다.",
+ "imPlatform.provider.larkDescription": "Lark 앱을 연결합니다.",
+ "imPlatform.provider.msTeamsDescription": "Microsoft Teams 앱을 연결합니다.",
+ "imPlatform.provider.slackDescription": "사용자와 해당 Slack ID를 동기화합니다.",
+ "imPlatform.provider.weComDescription": "WeCom 앱을 연결합니다.",
+ "imPlatform.replacement.confirm": "바꾸다",
+ "imPlatform.replacement.description": "현재 제공자를 교체하면 IM 바인딩과 워크스페이스 재정의가 무효화됩니다. 교체 후 새 제공자의 디렉터리를 다시 동기화하세요.",
+ "imPlatform.replacement.title": "{{current}}을(를) {{next}}(으)로 교체할까요?",
+ "imPlatform.status.configured": "구성됨",
+ "imPlatform.status.connected": "연결됨",
+ "imPlatform.status.connection_error": "연결 오류",
+ "imPlatform.status.permission_issue": "권한 문제",
+ "imPlatform.sync.latestSynced": "마지막 동기화: {{date}}",
+ "imPlatform.sync.loading": "진행 중인 동기화를 확인하고 있습니다.",
+ "imPlatform.sync.noPermission": "워크스페이스 소유자와 관리자만 디렉터리 동기화를 시작할 수 있습니다.",
+ "imPlatform.sync.noRuns": "아직 디렉터리 동기화를 실행하지 않았습니다.",
+ "imPlatform.sync.notConnected": "디렉터리 동기화를 시작하기 전에 제공자를 연결하고 테스트하세요.",
+ "imPlatform.sync.startFailed": "디렉터리 동기화를 시작하거나 새로고침할 수 없습니다. 다시 시도하세요.",
+ "imPlatform.sync.status.failure": "실패",
+ "imPlatform.sync.status.queued": "대기 중",
+ "imPlatform.sync.status.running": "실행 중",
+ "imPlatform.sync.status.success": "성공",
+ "imPlatform.title": "채널"
}
diff --git a/web/i18n/locales/ko-KR/share.json b/web/i18n/locales/ko-KR/share.json
index 1743ae79aa1..863e948acf7 100644
--- a/web/i18n/locales/ko-KR/share.json
+++ b/web/i18n/locales/ko-KR/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "감사합니다!",
"humanInput.unavailableDescription": "링크를 사용할 수 없거나 현재 로그인한 계정과 일치하지 않을 수 있습니다. 받은 알림에서 양식을 열거나 계정을 전환해 보세요.",
"humanInput.unavailableTitle": "이 양식을 열 수 없습니다",
+ "humanInputV2.accessRateLimited": "인증 이메일 요청이 너무 많습니다. 나중에 다시 시도하세요.",
+ "humanInputV2.alreadySubmitted": "이 요청은 이미 완료되었습니다.",
+ "humanInputV2.challengeExpired": "이 인증 코드는 만료되었습니다. 계속하려면 새 코드를 요청하세요.",
+ "humanInputV2.challengeStale": "이 인증 코드는 새 코드로 대체되었습니다. 계속하려면 새 코드를 요청하세요.",
+ "humanInputV2.codeExpiresIn": "코드 만료까지 {{seconds}}초",
+ "humanInputV2.codeRequired": "계속하려면 인증 코드를 요청하세요.",
+ "humanInputV2.codeSent": "이메일로 인증 코드를 보냈습니다.",
+ "humanInputV2.deliveryFailed": "인증 이메일을 보낼 수 없습니다. 다시 시도하세요.",
+ "humanInputV2.formExpired": "이 요청은 만료되었습니다.",
+ "humanInputV2.formNotFound": "양식을 찾을 수 없습니다.",
+ "humanInputV2.formRateLimited": "양식 요청이 너무 많습니다. 나중에 다시 시도하세요.",
+ "humanInputV2.invalidOtp": "인증 코드가 올바르지 않습니다. 코드를 확인하고 다시 시도하세요.",
+ "humanInputV2.networkError": "요청을 완료할 수 없습니다. 연결을 확인하고 다시 시도하세요.",
+ "humanInputV2.otpLabel": "이메일 인증 코드",
+ "humanInputV2.otpPlaceholder": "6자리 코드 입력",
+ "humanInputV2.requestingCode": "인증 코드 보내는 중…",
+ "humanInputV2.resendCode": "코드 다시 보내기",
+ "humanInputV2.retry": "다시 시도",
+ "humanInputV2.sendCode": "새 코드 보내기",
+ "humanInputV2.unavailable": "이 양식은 일시적으로 사용할 수 없습니다.",
+ "humanInputV2.unknownError": "문제가 발생했습니다. 다시 시도하세요.",
+ "humanInputV2.uploadFailed": "파일을 업로드할 수 없습니다. 다시 시도하세요.",
"login.backToHome": "홈으로 돌아가기"
}
diff --git a/web/i18n/locales/ko-KR/workflow-human-input.json b/web/i18n/locales/ko-KR/workflow-human-input.json
index 6ed322b307e..7fc15e92a67 100644
--- a/web/i18n/locales/ko-KR/workflow-human-input.json
+++ b/web/i18n/locales/ko-KR/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "액션 값",
"nodes.humanInput.userActions.buttonTextTooLong": "버튼 텍스트는 {{maxLength}}자 이하여야 합니다",
"nodes.humanInput.userActions.chooseStyle": "버튼 스타일 선택",
+ "nodes.humanInput.userActions.defaultTitle": "버튼 텍스트 {{index}}",
"nodes.humanInput.userActions.emptyTip": "'+' 버튼을 클릭하여 사용자 작업 추가",
"nodes.humanInput.userActions.title": "사용자 작업",
"nodes.humanInput.userActions.tooltip": "사용자가 이 양식에 응답하기 위해 클릭할 수 있는 버튼을 정의합니다. 작업 ID는 분기를 제어합니다. 액션 값은 선택된 내장 출력으로 다운스트림에 노출됩니다. 작업 ID는 문자 또는 밑줄로 시작하고 그 뒤에 문자, 숫자 또는 밑줄이 와야 합니다.",
diff --git a/web/i18n/locales/ko-KR/workflow.json b/web/i18n/locales/ko-KR/workflow.json
index 807a5ac8374..19a082dd6b2 100644
--- a/web/i18n/locales/ko-KR/workflow.json
+++ b/web/i18n/locales/ko-KR/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "출력",
"blocks.http-request": "HTTP 요청",
"blocks.human-input": "사람 입력",
+ "blocks.human-input-v2": "사람 입력 v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "반복",
"blocks.iteration-start": "반복 시작",
@@ -45,6 +46,7 @@
"blocksAbout.end": "워크플로의 출력 및 결과 유형을 정의합니다",
"blocksAbout.http-request": "HTTP 프로토콜을 통해 서버 요청을 보낼 수 있습니다",
"blocksAbout.human-input": "다음 단계를 생성하기 전에 사람의 확인 요청",
+ "blocksAbout.human-input-v2": "설정된 연락처, 이메일 수신자 또는 워크플로 시작자에게 입력을 요청합니다",
"blocksAbout.if-else": "if/else 조건을 기반으로 워크플로우를 두 가지 분기로 나눌 수 있습니다",
"blocksAbout.iteration": "목록 객체에서 여러 단계를 수행하여 모든 결과가 출력될 때까지 반복합니다.",
"blocksAbout.iteration-start": "반복 시작 노드",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "다중 분기 변수들을 하나의 변수로 집계하여 다운스트림 노드의 통합 구성을 가능하게 합니다.",
"blocksAbout.variable-assigner": "다중 분기 변수들을 하나의 변수로 집계하여 다운스트림 노드의 통합 구성을 가능하게 합니다.",
"changeHistory.edgeDelete": "노드가 연결이 끊어졌습니다.",
+ "changeHistory.humanInputMigration": "사람 입력 노드 마이그레이션 완료",
"changeHistory.nodeAdd": "노드가 추가되었습니다.",
"changeHistory.nodeChange": "노드가 변경되었습니다.",
"changeHistory.nodeConnect": "노드가 연결되었습니다.",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "최소 하나의 전달 방법을 활성화하세요",
"nodes.humanInput.errorMsg.noUserActions": "최소 하나의 사용자 작업을 추가하세요",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}}는 시간 초과 분기용으로 예약되어 있습니다. 다른 작업 ID를 선택하세요.",
+ "nodes.humanInput.output.actionId": "사용자가 실행한 작업 ID",
+ "nodes.humanInput.output.actionValue": "선택한 작업 값",
+ "nodes.humanInput.output.formInput": "양식 입력 값",
+ "nodes.humanInput.output.renderedContent": "렌더링된 콘텐츠",
"nodes.humanInput.timeout.title": "시간 초과",
+ "nodes.humanInputMigration.action.migrate": "마이그레이션",
+ "nodes.humanInputMigration.action.migrateNow": "지금 마이그레이션",
+ "nodes.humanInputMigration.action.migrating": "마이그레이션 중...",
+ "nodes.humanInputMigration.banner.ariaLabel": "사람 입력 마이그레이션 안내",
+ "nodes.humanInputMigration.banner.description": "이 워크플로는 이전 사람 입력 노드를 사용합니다. 새 노드를 추가하기 전에 모든 이전 노드를 마이그레이션하세요.",
+ "nodes.humanInputMigration.banner.learnMore": "자세히 알아보기",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "비활성화된 전달 방법에 설정이 남아 있습니다",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "활성화된 이메일 전달 방법에서 서로 충돌하는 템플릿을 사용합니다",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "기본값이 유효하지 않습니다",
+ "nodes.humanInputMigration.blocker.invalidEmail": "수신자 이메일 주소가 유효하지 않습니다",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "활성화된 이메일 전달 방법의 설정이 불완전합니다",
+ "nodes.humanInputMigration.blocker.missingRecipients": "노드에 지원되는 수신자가 없습니다",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "워크스페이스 멤버를 연락처 또는 확인된 이메일 주소로 연결할 수 없습니다",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "활성화된 전달 방법이 사람 입력 v2에서 지원되지 않습니다",
"nodes.humanInputMigration.blocker.unsupportedInputType": "{{field}} 필드는 아직 마이그레이션할 수 없습니다. 기존 사용자 입력 노드를 계속 사용할 수 있습니다.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "노드의 버전 값이 지원되지 않습니다",
+ "nodes.humanInputMigration.dialog.description": "수신자, 양식 및 작업이 그대로 유지됩니다.",
+ "nodes.humanInputMigration.dialog.draftNotice": "이 초안만 변경됩니다. 게시된 버전은 다시 게시할 때까지 계속 실행됩니다.",
+ "nodes.humanInputMigration.dialog.review": "노드를 검토하고 준비가 되면 게시하세요.",
+ "nodes.humanInputMigration.dialog.title": "사람 입력 노드 {{count}}개 마이그레이션",
+ "nodes.humanInputMigration.disabledBadge": "마이그레이션 필요",
+ "nodes.humanInputMigration.disabledReason": "새 노드를 추가하기 전에 이전 사람 입력 노드를 마이그레이션하세요.",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}}을(를) 마이그레이션할 수 없습니다: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "마이그레이션 중 워크플로가 변경되었습니다. 다시 시도하세요. 현재 편집 내용은 유지됩니다.",
+ "nodes.humanInputMigration.error.preflight": "마이그레이션을 준비할 수 없습니다. 워크플로는 변경되지 않았습니다. 다시 시도하세요.",
"nodes.humanInputMigration.error.sync": "마이그레이션된 워크플로를 저장할 수 없습니다. 현재 초안을 확인하고 다시 시도하세요.",
+ "nodes.humanInputMigration.incompatibleVersions": "같은 워크플로우에서 이전 버전과 새 버전의 사용자 입력 노드를 함께 사용할 수 없습니다.",
+ "nodes.humanInputMigration.oldVersion": "이전 버전",
+ "nodes.humanInputMigration.preview.author": "Dify 팀 제작",
+ "nodes.humanInputMigration.preview.description": "새 노드를 추가하기 전에 이전 사람 입력 노드를 마이그레이션하세요.",
+ "nodes.humanInputMigration.success": "사람 입력 노드를 마이그레이션했습니다",
+ "nodes.humanInputV2.card.configured": "수신자 {{count}}명 설정됨",
+ "nodes.humanInputV2.card.contactsOnly": "연락처 {{count}}개",
+ "nodes.humanInputV2.card.empty": "아직 이 단계를 승인할 수 있는 사람이 없습니다",
+ "nodes.humanInputV2.card.initiatorAndContacts": "시작자 및 연락처 {{count}}개",
+ "nodes.humanInputV2.card.initiatorOnly": "시작자만",
+ "nodes.humanInputV2.card.invalid": "수신자 설정을 확인해야 합니다",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "이메일",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "디버그 모드 설정",
"nodes.humanInputV2.debug.keepOneChannel": "최소 하나의 채널을 켜 두세요",
+ "nodes.humanInputV2.debug.sendVia": "디버그 알림을 보낼 채널",
+ "nodes.humanInputV2.debug.title": "디버그 모드",
+ "nodes.humanInputV2.debug.toggle": "디버그 모드 활성화",
+ "nodes.humanInputV2.debug.unsupported": "가져온 채널 중 지원되지 않는 채널이 있습니다: {{channels}}. 이 워크플로를 실행하기 전에 삭제하거나 업데이트하세요.",
"nodes.humanInputV2.disabled": "HITL IM이 비활성화된 동안에는 Human Input v2를 사용할 수 없습니다.",
+ "nodes.humanInputV2.error.bodyRequired": "메시지 본문은 필수입니다",
+ "nodes.humanInputV2.error.debugChannelRequired": "디버그 모드 채널을 하나 이상 선택하세요",
+ "nodes.humanInputV2.error.recipientDuplicate": "중복된 수신자를 삭제하세요",
+ "nodes.humanInputV2.error.recipientInvalid": "유효하지 않은 수신자 설정을 수정하세요",
+ "nodes.humanInputV2.error.recipientRequired": "수신자를 한 명 이상 추가하세요",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "연락처 수신자를 확인할 수 없습니다",
"nodes.humanInputV2.error.requestURLDuplicate": "메시지 본문에는 요청 URL을 하나만 포함할 수 있습니다.",
"nodes.humanInputV2.error.requestURLRequired": "메시지 본문에 요청 URL을 삽입하세요.",
+ "nodes.humanInputV2.error.subjectRequired": "메시지 제목은 필수입니다",
+ "nodes.humanInputV2.error.version": "사람 입력 v2의 버전은 문자열 2여야 합니다",
+ "nodes.humanInputV2.recipients.addContact": "연락처 추가",
+ "nodes.humanInputV2.recipients.addEmail": "추가",
+ "nodes.humanInputV2.recipients.addRecipient": "수신자 추가",
+ "nodes.humanInputV2.recipients.added": "추가됨",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "워크스페이스의 모든 연락처",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "워크스페이스의 모든 연락처에 알림을 보내며, 누구나 승인할 수 있습니다",
+ "nodes.humanInputV2.recipients.cancel": "취소",
+ "nodes.humanInputV2.recipients.chooseVariable": "변수 선택",
+ "nodes.humanInputV2.recipients.confirm": "확인",
+ "nodes.humanInputV2.recipients.contactInfo": "{{name}}의 연락처 세부 정보",
+ "nodes.humanInputV2.recipients.contactSource.all": "모두",
+ "nodes.humanInputV2.recipients.contactSource.external": "외부",
+ "nodes.humanInputV2.recipients.contactSource.organization": "조직",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "워크스페이스",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "연락처 출처",
"nodes.humanInputV2.recipients.duplicateSource": "{{name}}({{source}})을(를) 통해 이미 추가되었습니다.",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} 편집",
+ "nodes.humanInputV2.recipients.editRecipient": "수신자 편집",
"nodes.humanInputV2.recipients.emailAlreadySelected": "각 이메일 주소는 한 번만 선택할 수 있습니다.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "아직 추가되지 않은 유효한 이메일 주소를 입력하세요",
+ "nodes.humanInputV2.recipients.emailLabel": "일회성 이메일 수신자",
+ "nodes.humanInputV2.recipients.empty": "설정된 수신자가 없습니다",
+ "nodes.humanInputV2.recipients.help": "이 사람 입력 단계에 응답할 수 있는 사람을 선택하세요.",
"nodes.humanInputV2.recipients.initiator": "Web App 또는 CLI를 통해 이번 실행을 시작한 사용자가 승인할 수 있습니다",
+ "nodes.humanInputV2.recipients.initiatorDescription": "이 워크플로 실행을 시작한 사람이 응답할 수 있습니다.",
"nodes.humanInputV2.recipients.inputHelp": "여러 이메일 주소를 쉼표로 구분하여 입력하거나 붙여넣으세요. /를 눌러 변수를 삽입하세요.",
+ "nodes.humanInputV2.recipients.insertVariable": "변수 삽입",
+ "nodes.humanInputV2.recipients.loadError": "연락처를 불러올 수 없습니다. 저장된 연락처 ID는 유지됩니다.",
+ "nodes.humanInputV2.recipients.loading": "연락처 불러오는 중…",
+ "nodes.humanInputV2.recipients.noResults": "연락처를 찾을 수 없습니다",
+ "nodes.humanInputV2.recipients.placeholder": "연락처 검색 또는 이메일 추가",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} 삭제",
+ "nodes.humanInputV2.recipients.removeHint": "Backspace 또는 Delete 키를 눌러 삭제하세요.",
+ "nodes.humanInputV2.recipients.resultCount": "일치하는 수신자 {{count}}명",
+ "nodes.humanInputV2.recipients.search": "연락처 검색",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "이름 또는 이메일로 검색",
+ "nodes.humanInputV2.recipients.selectionHint": "수신자 {{count}}명 선택됨. 입력란의 시작에서 왼쪽 화살표 키를 누르면 수신자로 포커스가 이동합니다.",
+ "nodes.humanInputV2.recipients.title": "수신자",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "워크스페이스의 모든 연락처",
+ "nodes.humanInputV2.recipients.type.contact": "연락처",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "동적 이메일",
+ "nodes.humanInputV2.recipients.type.initiator": "시작자",
+ "nodes.humanInputV2.recipients.type.onetime_email": "일회성 이메일",
+ "nodes.humanInputV2.recipients.typeLabel": "수신자 유형",
"nodes.humanInputV2.recipients.useThisInstead": "대신 이 항목 사용",
+ "nodes.humanInputV2.recipients.variableRequired": "이메일 변수를 선택하세요",
+ "nodes.humanInputV2.template.body": "본문",
+ "nodes.humanInputV2.template.description": "이메일 및 IM 대체 문구",
"nodes.humanInputV2.template.insertRequestURL": "요청 URL 삽입",
+ "nodes.humanInputV2.template.insertVariable": "변수 삽입",
+ "nodes.humanInputV2.template.notConfigured": "설정되지 않음",
"nodes.humanInputV2.template.requestURLHint": "수신자는 이 링크로 승인 양식을 엽니다. 본문에는 요청 URL이 정확히 하나 있어야 합니다.",
"nodes.humanInputV2.template.requestURLInserted": "요청 URL 삽입됨",
"nodes.humanInputV2.template.saveAndTest": "저장 후 테스트",
+ "nodes.humanInputV2.template.subject": "제목",
+ "nodes.humanInputV2.template.subjectPlaceholder": "메시지 제목 입력",
"nodes.humanInputV2.template.test": "메시지 테스트",
"nodes.humanInputV2.template.testChannel": "테스트 채널",
"nodes.humanInputV2.template.testCompleted": "테스트 요청이 완료되었습니다. 선택한 채널에서 메시지를 확인하세요.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "모든 테스트 변수의 값을 입력하세요.",
"nodes.humanInputV2.template.testSaveFailed": "워크플로 초안을 저장하지 못했습니다. 테스트는 전송되지 않았습니다.",
"nodes.humanInputV2.template.testUnavailable": "이 환경은 아직 메시지 템플릿 테스트를 지원하지 않습니다.",
+ "nodes.humanInputV2.template.title": "메시지 템플릿",
"nodes.ifElse.operator": "연산자",
"nodes.iteration.currentIteration": "현재 반복",
"nodes.iteration.deleteDesc": "반복 노드를 삭제하면 모든 하위 노드가 삭제됩니다",
diff --git a/web/i18n/locales/lo-LA/contacts.json b/web/i18n/locales/lo-LA/contacts.json
index b1e75a92c59..7e8f3cc5126 100644
--- a/web/i18n/locales/lo-LA/contacts.json
+++ b/web/i18n/locales/lo-LA/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "ລຶບຜູ້ຕິດຕໍ່ ({{count}}) ຫຼືບໍ່?",
"directory.removalDescription": "ຜູ້ຕິດຕໍ່ທີ່ເລືອກຈະຖືກລຶບອອກຈາກພື້ນທີ່ເຮັດວຽກນີ້ຢ່າງຖາວອນ. ບໍ່ສາມາດຍົກເລີກການດຳເນີນການນີ້ໄດ້.",
- "directory.removalTitle": "ລຶບຜູ້ຕິດຕໍ່ບໍ?",
+ "directory.removalSingleDescription": "{{name}} ຈະຖືກລຶບອອກຈາກພື້ນທີ່ເຮັດວຽກນີ້ຢ່າງຖາວອນ. ບໍ່ສາມາດຍົກເລີກການກະທຳນີ້ໄດ້.",
+ "directory.removalSingleFailed": "ບໍ່ສາມາດລຶບຜູ້ຕິດຕໍ່ໄດ້. ກະລຸນາລອງໃໝ່.",
+ "directory.removalSingleTitle": "ລຶບ {{name}} ຫຼືບໍ່?",
+ "directory.resultCount": "ຜົນລັບ: {{count}}",
+ "imPlatform.action.configure": "ຕັ້ງຄ່າ",
+ "imPlatform.action.configureChannel": "ຕັ້ງຄ່າ {{provider}}",
+ "imPlatform.action.connect": "ເຊື່ອມຕໍ່",
+ "imPlatform.action.copied": "ຄັດລອກແລ້ວ",
+ "imPlatform.action.copyCallback": "ຄັດລອກ URL ຄອລແບັກ",
+ "imPlatform.action.deleteChannel": "ລຶບ {{provider}}",
+ "imPlatform.action.loadMore": "ໂຫຼດເພີ່ມເຕີມ",
+ "imPlatform.action.replace": "ແທນທີ່",
+ "imPlatform.action.retry": "ລອງໃໝ່",
+ "imPlatform.action.save": "ບັນທຶກ",
+ "imPlatform.action.saving": "ກຳລັງບັນທຶກ",
+ "imPlatform.action.setupGuide": "ຄູ່ມືການຕັ້ງຄ່າ",
+ "imPlatform.action.syncNow": "ຊິ້ງຂໍ້ມູນດຽວນີ້",
+ "imPlatform.action.syncing": "ກຳລັງຊິງຄ໌",
+ "imPlatform.action.testConnection": "ທົດສອບການເຊື່ອມຕໍ່",
+ "imPlatform.action.testing": "ກຳລັງທົດສອບ",
+ "imPlatform.action.viewDetails": "ເບິ່ງລາຍລະອຽດ View details",
+ "imPlatform.bindingDialog.back": "ກັບຄືນ",
+ "imPlatform.bindingDialog.callback": "URL ຄອລແບັກ",
+ "imPlatform.bindingDialog.callbackDescription": "ຕັ້ງຄ່າຄອລແບັກໃນ {{provider}} ໃຫ້ສຳເລັດ ເພື່ອເປີດໃຊ້ການດຳເນີນການໃນບັດ.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "ເພື່ອຮັບການດຳເນີນການໃນບັດ, ວາງ URL ນີ້ໃນ <console>ຄອນໂຊນນັກພັດທະນາ Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "ເຫດການ ແລະ ຄອລແບັກ → ການຕັ້ງຄ່າຄອລແບັກ → URL ຄຳຮ້ອງຂໍ",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "ເພື່ອຮັບການດຳເນີນການໃນບັດ, ວາງ URL ນີ້ໃນ <console>ຄອນໂຊນນັກພັດທະນາ Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "ເຫດການ ແລະ ຄອລແບັກ → ການຕັ້ງຄ່າຄອລແບັກ → URL ຄຳຮ້ອງຂໍ",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "ເພື່ອຮັບການດຳເນີນການໃນບັດ, ວາງ URL ນີ້ໃນ <console>ຄອນໂຊນນັກພັດທະນາ Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "ການໂຕ້ຕອບ ແລະ ທາງລັດ → ການໂຕ້ຕອບ → URL ຄຳຮ້ອງຂໍ",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "ເພື່ອຮັບການດຳເນີນການໃນບັດ, ວາງ URL ນີ້ໃນ <console>ການຕັ້ງຄ່າ Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "ການຕັ້ງຄ່າ → ການກຳນົດຄ່າ → ຈຸດປາຍການສົ່ງຂໍ້ຄວາມ",
+ "imPlatform.bindingDialog.callbackStep": "ຕັ້ງຄ່າຄອລແບັກ",
"imPlatform.bindingDialog.clearSavedCredential": "ລ້າງຄ່າທີ່ບັນທຶກໄວ້",
+ "imPlatform.bindingDialog.configureTitle": "ຕັ້ງຄ່າ {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "ເຊື່ອມຕໍ່ {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "ຄ່າທີ່ບັນທຶກໄວ້ນີ້ຈະຖືກລ້າງເມື່ອທ່ານບັນທຶກ.",
+ "imPlatform.bindingDialog.credentialsDescription": "ເຊື່ອມຕໍ່ແອັບ {{provider}} ກ່ອນ ແລ້ວຈຶ່ງຕັ້ງຄ່າ URL ຄອລແບັກ.",
+ "imPlatform.bindingDialog.credentialsStep": "ຂໍ້ມູນຢືນຢັນຕົວຕົນຂອງແອັບ",
+ "imPlatform.bindingDialog.description": "ປ້ອນຂໍ້ມູນຢືນຢັນຕົວຕົນແອັບສຳລັບຜູ້ໃຫ້ບໍລິການ IM ນີ້.",
+ "imPlatform.bindingDialog.field.agentId": "ID ຕົວແທນ",
+ "imPlatform.bindingDialog.field.appId": "ID ແອັບ",
+ "imPlatform.bindingDialog.field.appToken": "ໂທເຄັນແອັບ (ບໍ່ບັງຄັບ)",
+ "imPlatform.bindingDialog.field.botToken": "ໂທເຄັນບອດ",
+ "imPlatform.bindingDialog.field.clientId": "ID ໄຄລເອັນ",
+ "imPlatform.bindingDialog.field.clientSecret": "ຂໍ້ມູນລັບຂອງໄຄລເອັນ",
+ "imPlatform.bindingDialog.field.corpId": "ID ບໍລິສັດ",
+ "imPlatform.bindingDialog.field.encryptKey": "ກະແຈເຂົ້າລະຫັດ (ບໍ່ບັງຄັບ)",
+ "imPlatform.bindingDialog.field.genericSecret": "ຄວາມລັບ (Secret)",
+ "imPlatform.bindingDialog.field.secret": "ຂໍ້ມູນລັບຂອງແອັບ",
+ "imPlatform.bindingDialog.field.signingSecret": "ຂໍ້ມູນລັບສຳລັບການເຊັນ",
+ "imPlatform.bindingDialog.field.tenantId": "ID ຜູ້ເຊົ່າ",
+ "imPlatform.bindingDialog.field.verificationToken": "ໂທເຄັນຢືນຢັນ (ບໍ່ບັງຄັບ)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "ປ້ອນກະແຈເຂົ້າລະຫັດ ຖ້າເປີດໃຊ້",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "ປ້ອນຂໍ້ມູນລັບຂອງແອັບ",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "ປ້ອນໂທເຄັນຢືນຢັນ ຖ້າຕັ້ງຄ່າໄວ້",
+ "imPlatform.bindingDialog.finish": "ສຳເລັດ",
+ "imPlatform.bindingDialog.freshCredentials": "ບໍ່ສາມາດດຶງຂໍ້ມູນລັບທີ່ບັນທຶກໄວ້ໄດ້. ປ້ອນຂໍ້ມູນຢືນຢັນທີ່ຈຳເປັນທັງໝົດຄືນ ເພື່ອທົດສອບ ຫຼື ບັນທຶກການຕັ້ງຄ່ານີ້.",
+ "imPlatform.bindingDialog.openSetupGuide": "ເປີດຄູ່ມືການຕັ້ງຄ່າ",
+ "imPlatform.bindingDialog.replaceTenantTitle": "ປ່ຽນຂໍ້ມູນຢືນຢັນຕົວຕົນຜູ້ເຊົ່າສຳລັບ {{identity}} ບໍ?",
"imPlatform.bindingDialog.replacementRequired": "ຂໍ້ມູນຢັ້ງຢືນເຫຼົ່ານີ້ເປັນຂອງບັນຊີອົງກອນ IM (tenant) ອື່ນ ແລະ ບໍ່ສາມາດບັນທຶກໂດຍກົງໄດ້. ການປ່ຽນ tenant ຈຳເປັນຕ້ອງແທນທີ່ຊ່ອງທາງ IM ປັດຈຸບັນ ເຊິ່ງຈະລຶບການເຊື່ອມໂຍງ IM ທັງໝົດ ທັງແບບອັດຕະໂນມັດ ແລະ ແບບກຳນົດເອງ. ຫຼັງຈາກແທນທີ່ແລ້ວ ໃຫ້ຊິງຄ໌ລາຍຊື່ຜູ້ຕິດຕໍ່ອີກຄັ້ງ.",
+ "imPlatform.bindingDialog.required": "ຕ້ອງປ້ອນຂໍ້ມູນຊ່ອງນີ້.",
+ "imPlatform.bindingDialog.saveAndContinue": "ບັນທຶກ ແລະ ດຳເນີນການຕໍ່",
+ "imPlatform.bindingDialog.saveFailed": "ບັນທຶກການຕັ້ງຄ່າບໍ່ໄດ້. ກວດສອບຊ່ອງຂໍ້ມູນ ແລ້ວລອງໃໝ່.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "ບັນທຶກການຕັ້ງຄ່າແລ້ວ ແຕ່ບໍ່ສາມາດໂຫຼດລາຍລະອຽດໄດ້. ກະລຸນາປິດກ່ອງໂຕ້ຕອບນີ້ ແລ້ວເປີດຄືນ.",
- "imPlatform.bindingDialog.undoClearCredential": "ຍົກເລີກການລ້າງ"
+ "imPlatform.bindingDialog.secretConfigured": "ຕັ້ງຄ່າຂໍ້ມູນລັບແລ້ວ. ປະໄວ້ຫວ່າງເພື່ອເກັບຄ່າເດີມ.",
+ "imPlatform.bindingDialog.step": "ຂັ້ນຕອນ {{step}}",
+ "imPlatform.bindingDialog.testFailed": "ການທົດສອບການເຊື່ອມຕໍ່ລົ້ມເຫຼວ. ກວດສອບການຕັ້ງຄ່າ ແລ້ວລອງໃໝ່.",
+ "imPlatform.bindingDialog.undoClearCredential": "ຍົກເລີກການລ້າງ",
+ "imPlatform.bindingDialog.viewSetupGuide": "ເບິ່ງຄູ່ມືການຕັ້ງຄ່າ",
+ "imPlatform.chooseProvider": "ເລືອກຊ່ອງທາງທີ່ຈະເຊື່ອມຕໍ່",
+ "imPlatform.configurationUpdated": "ການຕັ້ງຄ່າຊ່ອງທາງນີ້ປ່ຽນໄປແລ້ວ. ປິດກ່ອງໂຕ້ຕອບ ແລະ ໂຫຼດໃໝ່ກ່ອນລອງອີກຄັ້ງ.",
+ "imPlatform.connectMore": "ເຊື່ອມຕໍ່ຊ່ອງທາງເພີ່ມເຕີມ",
+ "imPlatform.delete.confirm": "ລຶບ",
+ "imPlatform.delete.description": "ການລຶບຊ່ອງທາງນີ້ຈະລຶບການຕັ້ງຄ່າຂອງມັນ. ການສົ່ງຄຳຂໍອະນຸມັດ ຫຼື ການຊິງຄ໌ລາຍຊື່ທີ່ໃຊ້ຊ່ອງທາງນີ້ຈະຢຸດ.",
+ "imPlatform.delete.failed": "ລຶບຊ່ອງທາງບໍ່ໄດ້. ບໍ່ມີຫຍັງປ່ຽນແປງ; ລອງໃໝ່.",
+ "imPlatform.delete.title": "ລຶບຊ່ອງທາງ {{provider}} ບໍ?",
+ "imPlatform.description": "ເຊື່ອມຕໍ່ຊ່ອງທາງບໍລິສັດ ເພື່ອໃຫ້ຄຳຂໍອະນຸມັດໄປເຖິງຜູ້ໃຊ້ໃນບ່ອນເຮັດວຽກ.",
+ "imPlatform.details.column.contact": "ຜູ້ຕິດຕໍ່",
+ "imPlatform.details.column.platform": "ແພລດຟອມ IM",
+ "imPlatform.details.description": "ເບິ່ງຜົນແບບອ່ານຢ່າງດຽວຂອງການຊິງຄ໌ຄັ້ງຫຼ້າສຸດ.",
+ "imPlatform.details.downloadFailed": "ດາວໂຫຼດລາຍງານບໍ່ໄດ້. ລອງໃໝ່.",
+ "imPlatform.details.downloadReport": "ດາວໂຫຼດລາຍງານ",
+ "imPlatform.details.downloadingReport": "ກຳລັງດາວໂຫຼດລາຍງານ…",
+ "imPlatform.details.empty": "ບໍ່ມີຜົນໃນໝວດນີ້.",
+ "imPlatform.details.filter.added": "ເພີ່ມແລ້ວ",
+ "imPlatform.details.filter.failed": "ລົ້ມເຫຼວ",
+ "imPlatform.details.filter.not_matched": "ບໍ່ກົງກັນ",
+ "imPlatform.details.filter.removed": "ລຶບອອກແລ້ວ",
+ "imPlatform.details.filter.skipped": "ຂ້າມແລ້ວ",
+ "imPlatform.details.filters": "ຕົວກອງຜົນການຊິງຄ໌",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "ໂຫຼດລາຍລະອຽດການຊິງຄ໌ບໍ່ໄດ້.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "ໂຫຼດຜົນເພີ່ມເຕີມບໍ່ໄດ້. ລອງໂຫຼດໜ້ານີ້ອີກຄັ້ງ.",
+ "imPlatform.details.removalReason.binding_invalidated": "ການຜູກບໍ່ມີຜົນແລ້ວ",
+ "imPlatform.details.removalReason.binding_replaced": "ປ່ຽນການຜູກແລ້ວ",
+ "imPlatform.details.removalReason.not_present_in_directory": "ບໍ່ມີຢູ່ໃນລາຍຊື່ອີກແລ້ວ",
+ "imPlatform.details.reportChanged": "ຜົນການຊິງຄ໌ປ່ຽນໄປແລ້ວ. ເປີດລາຍລະອຽດການຊິງຄ໌ຫຼ້າສຸດຄືນ ແລ້ວລອງໃໝ່.",
+ "imPlatform.details.title": "ລາຍລະອຽດການຊິງຄ໌",
+ "imPlatform.email.apiKey": "ຄີ API",
+ "imPlatform.email.apiKeyConfigured": "ເພື່ອຄວາມປອດໄພ, ບໍ່ສາມາດເບິ່ງກະແຈ API ທີ່ບັນທຶກແລ້ວໄດ້. ປະໄວ້ຫວ່າງເພື່ອເກັບຄ່າເດີມ.",
+ "imPlatform.email.apiKeyDescription": "ເພື່ອຄວາມປອດໄພ, ກະແຈ API ນີ້ຈະເບິ່ງບໍ່ໄດ້ຫຼັງບັນທຶກ.",
+ "imPlatform.email.apiKeyPlaceholder": "ປ້ອນກະແຈ API ຂອງ Resend",
+ "imPlatform.email.description": "ການຕັ້ງຄ່ານີ້ໃຊ້ກັບໂນດ Human Input ທັງໝົດໃນພື້ນທີ່ເຮັດວຽກນີ້ທີ່ເປີດໃຊ້ <emphasis>ສົ່ງແຈ້ງເຕືອນດີບັກຜ່ານອີເມວ</emphasis>.",
+ "imPlatform.email.invalidEmail": "ປ້ອນທີ່ຢູ່ອີເມວທີ່ຖືກຕ້ອງ.",
+ "imPlatform.email.provider": "ຜູ້ໃຫ້ບໍລິການອີເມວ",
+ "imPlatform.email.resendDescription": "<apiKey>ກະແຈ API ຂອງ Resend</apiKey> ຈະຖືກເຂົ້າລະຫັດ ແລະ ເບິ່ງບໍ່ໄດ້ຫຼັງບັນທຶກ.<br/>ລົງທະບຽນບັນຊີ <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "ການຕັ້ງຄ່າ Resend",
+ "imPlatform.email.senderEmail": "ທີ່ຢູ່ອີເມວຜູ້ສົ່ງ",
+ "imPlatform.email.senderEmailDescription": "ທີ່ຢູ່ອີເມວທີ່ສະແດງເປັນຜູ້ສົ່ງ. ໂດເມນຕ້ອງຢືນຢັນໃນ Resend.",
+ "imPlatform.email.senderName": "ຊື່ຜູ້ສົ່ງ",
+ "imPlatform.email.senderNameDescription": "ຊື່ທີ່ສະແດງໃນກ່ອງຈົດໝາຍຂອງຜູ້ຮັບ.",
+ "imPlatform.email.testSucceeded": "ທົດສອບການເຊື່ອມຕໍ່ສຳເລັດ.",
+ "imPlatform.email.title": "ຕັ້ງຄ່າອີເມວ",
+ "imPlatform.learnMore": "ຮຽນຮູ້ເພີ່ມເຕີມ",
+ "imPlatform.loadError.description": "ລອງໃໝ່ເພື່ອອ່ານການຜູກ ແລະ ສິດປັດຈຸບັນ.",
+ "imPlatform.loadError.retry": "ລອງໃໝ່",
+ "imPlatform.loadError.title": "ໂຫຼດຊ່ອງທາງບໍ່ໄດ້",
+ "imPlatform.loading": "ກຳລັງໂຫຼດຊ່ອງທາງ",
+ "imPlatform.provider.dingtalkDescription": "ເຊື່ອມຕໍ່ແອັບ DingTalk.",
+ "imPlatform.provider.emailDescription": "ຕັ້ງຄ່າບໍລິການອີເມວສຳລັບສົ່ງຄຳຂໍອະນຸມັດຈາກພື້ນທີ່ເຮັດວຽກນີ້.",
+ "imPlatform.provider.feishuDescription": "ເຊື່ອມຕໍ່ແອັບ Feishu.",
+ "imPlatform.provider.larkDescription": "ເຊື່ອມຕໍ່ແອັບ Lark.",
+ "imPlatform.provider.msTeamsDescription": "ເຊື່ອມຕໍ່ແອັບ Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "ຊິງຄ໌ຜູ້ໃຊ້ ແລະ ຕົວຕົນ Slack ຂອງພວກເຂົາ.",
+ "imPlatform.provider.weComDescription": "ເຊື່ອມຕໍ່ແອັບ WeCom.",
+ "imPlatform.replacement.confirm": "ແທນທີ່",
+ "imPlatform.replacement.description": "ການແທນຜູ້ໃຫ້ບໍລິການປັດຈຸບັນຈະເຮັດໃຫ້ການຜູກ IM ແລະ ຄ່າທັບຂອງພື້ນທີ່ເຮັດວຽກໃຊ້ບໍ່ໄດ້. ຫຼັງແທນແລ້ວ, ຊິງຄ໌ລາຍຊື່ຂອງຜູ້ໃຫ້ບໍລິການໃໝ່ອີກຄັ້ງ.",
+ "imPlatform.replacement.title": "ແທນ {{current}} ດ້ວຍ {{next}} ບໍ?",
+ "imPlatform.status.configured": "ຕັ້ງຄ່າແລ້ວ",
+ "imPlatform.status.connected": "ເຊື່ອມຕໍ່ແລ້ວ",
+ "imPlatform.status.connection_error": "ຂໍ້ຜິດພາດການເຊື່ອມຕໍ່",
+ "imPlatform.status.permission_issue": "ບັນຫາສິດ",
+ "imPlatform.sync.latestSynced": "ຊິງຄ໌ຄັ້ງຫຼ້າສຸດ {{date}}",
+ "imPlatform.sync.loading": "ກຳລັງກວດສອບການຊິງຄ໌ທີ່ກຳລັງເຮັດວຽກ.",
+ "imPlatform.sync.noPermission": "ມີພຽງເຈົ້າຂອງ ແລະ ຜູ້ດູແລພື້ນທີ່ເຮັດວຽກທີ່ເລີ່ມຊິງຄ໌ລາຍຊື່ໄດ້.",
+ "imPlatform.sync.noRuns": "ຍັງບໍ່ເຄີຍຊິງຄ໌ລາຍຊື່.",
+ "imPlatform.sync.notConnected": "ເຊື່ອມຕໍ່ ແລະ ທົດສອບຜູ້ໃຫ້ບໍລິການກ່ອນເລີ່ມຊິງຄ໌ລາຍຊື່.",
+ "imPlatform.sync.startFailed": "ເລີ່ມ ຫຼື ໂຫຼດການຊິງຄ໌ລາຍຊື່ໃໝ່ບໍ່ໄດ້. ລອງໃໝ່.",
+ "imPlatform.sync.status.failure": "ລົ້ມເຫຼວ",
+ "imPlatform.sync.status.queued": "ຢູ່ໃນຄິວ",
+ "imPlatform.sync.status.running": "ກຳລັງດຳເນີນ",
+ "imPlatform.sync.status.success": "ສຳເລັດ",
+ "imPlatform.title": "ຊ່ອງທາງ"
}
diff --git a/web/i18n/locales/lo-LA/share.json b/web/i18n/locales/lo-LA/share.json
index a663bc04edd..44662d29238 100644
--- a/web/i18n/locales/lo-LA/share.json
+++ b/web/i18n/locales/lo-LA/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "ຂອບໃຈ!",
"humanInput.unavailableDescription": "ລິ້ງອາດບໍ່ພ້ອມໃຊ້ງານ ຫຼື ບໍ່ກົງກັບບັນຊີທີ່ທ່ານກຳລັງເຂົ້າລະບົບ. ກະລຸນາເປີດແບບຟອມຈາກການແຈ້ງເຕືອນທີ່ທ່ານໄດ້ຮັບ ຫຼື ລອງປ່ຽນບັນຊີ.",
"humanInput.unavailableTitle": "ບໍ່ສາມາດເປີດແບບຟອມນີ້ໄດ້",
+ "humanInputV2.accessRateLimited": "ມີການຮ້ອງຂໍອີເມວຢືນຢັນຫຼາຍເກີນໄປ. ກະລຸນາລອງໃໝ່ພາຍຫຼັງ.",
+ "humanInputV2.alreadySubmitted": "ຄຳຮ້ອງຂໍນີ້ສຳເລັດແລ້ວ.",
+ "humanInputV2.challengeExpired": "ລະຫັດຢືນຢັນນີ້ໝົດອາຍຸແລ້ວ. ຮ້ອງຂໍລະຫັດໃໝ່ເພື່ອສືບຕໍ່.",
+ "humanInputV2.challengeStale": "ລະຫັດຢືນຢັນນີ້ຖືກແທນທີ່ແລ້ວ. ຮ້ອງຂໍລະຫັດໃໝ່ເພື່ອສືບຕໍ່.",
+ "humanInputV2.codeExpiresIn": "ລະຫັດຈະໝົດອາຍຸໃນ {{seconds}} ວິນາທີ",
+ "humanInputV2.codeRequired": "ຮ້ອງຂໍລະຫັດຢືນຢັນເພື່ອສືບຕໍ່.",
+ "humanInputV2.codeSent": "ສົ່ງລະຫັດຢືນຢັນໄປຫາອີເມວຂອງທ່ານແລ້ວ.",
+ "humanInputV2.deliveryFailed": "ບໍ່ສາມາດສົ່ງອີເມວຢືນຢັນໄດ້. ກະລຸນາລອງອີກຄັ້ງ.",
+ "humanInputV2.formExpired": "ຄຳຮ້ອງຂໍນີ້ໝົດອາຍຸແລ້ວ.",
+ "humanInputV2.formNotFound": "ບໍ່ພົບແບບຟອມ.",
+ "humanInputV2.formRateLimited": "ມີຄຳຮ້ອງຂໍແບບຟອມຫຼາຍເກີນໄປ. ກະລຸນາລອງໃໝ່ພາຍຫຼັງ.",
+ "humanInputV2.invalidOtp": "ລະຫັດຢືນຢັນບໍ່ຖືກຕ້ອງ. ກວດສອບລະຫັດ ແລະ ລອງອີກຄັ້ງ.",
+ "humanInputV2.networkError": "ບໍ່ສາມາດດຳເນີນຄຳຮ້ອງຂໍໃຫ້ສຳເລັດໄດ້. ກວດສອບການເຊື່ອມຕໍ່ ແລະ ລອງອີກຄັ້ງ.",
+ "humanInputV2.otpLabel": "ລະຫັດຢືນຢັນອີເມວ",
+ "humanInputV2.otpPlaceholder": "ປ້ອນລະຫັດ 6 ຕົວເລກ",
+ "humanInputV2.requestingCode": "ກຳລັງສົ່ງລະຫັດຢືນຢັນ…",
+ "humanInputV2.resendCode": "ສົ່ງລະຫັດອີກຄັ້ງ",
+ "humanInputV2.retry": "ລອງອີກຄັ້ງ",
+ "humanInputV2.sendCode": "ສົ່ງລະຫັດໃໝ່",
+ "humanInputV2.unavailable": "ແບບຟອມນີ້ບໍ່ສາມາດໃຊ້ງານໄດ້ຊົ່ວຄາວ.",
+ "humanInputV2.unknownError": "ເກີດຂໍ້ຜິດພາດ. ກະລຸນາລອງອີກຄັ້ງ.",
+ "humanInputV2.uploadFailed": "ບໍ່ສາມາດອັບໂຫຼດໄຟລ໌ໄດ້. ກະລຸນາລອງອີກຄັ້ງ.",
"login.backToHome": "ກັບຄືນສູ່ໜ້າຫຼັກ"
}
diff --git a/web/i18n/locales/lo-LA/workflow-human-input.json b/web/i18n/locales/lo-LA/workflow-human-input.json
index ff7e4bead8b..19b4d87dd7d 100644
--- a/web/i18n/locales/lo-LA/workflow-human-input.json
+++ b/web/i18n/locales/lo-LA/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "ຄ່າການດຳເນີນການ",
"nodes.humanInput.userActions.buttonTextTooLong": "ຂໍ້ຄວາມປຸ່ມຕ້ອງບໍ່ເກີນ {{maxLength}} ຕົວອັກສອນ",
"nodes.humanInput.userActions.chooseStyle": "ເລືອກຮູບແບບປຸ່ມ",
+ "nodes.humanInput.userActions.defaultTitle": "ຂໍ້ຄວາມປຸ່ມ {{index}}",
"nodes.humanInput.userActions.emptyTip": "ຄລິກປຸ່ມ '+' ເພື່ອເພີ່ມການດຳເນີນການຜູ້ໃຊ້",
"nodes.humanInput.userActions.title": "ການດຳເນີນການຜູ້ໃຊ້",
"nodes.humanInput.userActions.tooltip": "ກຳນົດປຸ່ມທີ່ຜູ້ໃຊ້ສາມາດຄລິກເພື່ອຕອບກັບຟອມນີ້. ໄອດີການດຳເນີນການຈະຄວບຄຸມການແຍກສາຂາ. ຄ່າການດຳເນີນການຈະຖືກສົ່ງໄປຫາຂັ້ນຕອນຖັດໄປ.",
diff --git a/web/i18n/locales/lo-LA/workflow.json b/web/i18n/locales/lo-LA/workflow.json
index 9334a5fc500..755f3ed38a9 100644
--- a/web/i18n/locales/lo-LA/workflow.json
+++ b/web/i18n/locales/lo-LA/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "ຜົນອອກ (Output)",
"blocks.http-request": "ຄຳຂໍ HTTP",
"blocks.human-input": "ການປ້ອນຂໍ້ມູນໂດຍມະນຸດ",
+ "blocks.human-input-v2": "ການປ້ອນຂໍ້ມູນໂດຍມະນຸດ v2",
"blocks.if-else": "ຖ້າ/ຫຼື (IF/ELSE)",
"blocks.iteration": "ການເຮັດຊ້ຳ (Iteration)",
"blocks.iteration-start": "ເລີ່ມຕົ້ນການເຮັດຊ້ຳ",
@@ -45,6 +46,7 @@
"blocksAbout.end": "ກຳນົດຜົນອອກ ແລະ ປະເພດຜົນລັບຂອງ Workflow",
"blocksAbout.http-request": "ອະນຸຍາດໃຫ້ສົ່ງຄຳຂໍເຊີເວີຜ່ານໂປຣໂຕຄໍ HTTP",
"blocksAbout.human-input": "ໃຫ້ມະນຸດຢືນຢັນກ່ອນທີ່ຈະສ້າງຂັ້ນຕອນຕໍ່ໄປ",
+ "blocksAbout.human-input-v2": "ຮ້ອງຂໍຂໍ້ມູນຈາກຜູ້ຕິດຕໍ່ທີ່ຕັ້ງຄ່າໄວ້, ຜູ້ຮັບອີເມວ ຫຼື ຜູ້ເລີ່ມ Workflow",
"blocksAbout.if-else": "ອະນຸຍາດໃຫ້ແຍກ Workflow ອອກເປັນສອງທາງເລືອກຕາມເງື່ອນໄຂ If/Else",
"blocksAbout.iteration": "ດຳເນີນການຫຼາຍຂັ້ນຕອນໃນລາຍການຈົນກວ່າຜົນລັບທັງໝົດຈະຖືກສົ່ງອອກ.",
"blocksAbout.iteration-start": "ໂນດເລີ່ມຕົ້ນການເຮັດຊ້ຳ",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "ລວມຕົວປ່ຽນຈາກຫຼາຍສາຂາເຂົ້າເປັນຕົວປ່ຽນດຽວເພື່ອການຕັ້ງຄ່າທີ່ເປັນເອກະພາບ.",
"blocksAbout.variable-assigner": "ລວມຕົວປ່ຽນຈາກຫຼາຍສາຂາເຂົ້າເປັນຕົວປ່ຽນດຽວເພື່ອການຕັ້ງຄ່າທີ່ເປັນເອກະພາບ.",
"changeHistory.edgeDelete": "ຕັດການເຊື່ອມຕໍ່ໂນດ",
+ "changeHistory.humanInputMigration": "ຍ້າຍໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດແລ້ວ",
"changeHistory.nodeAdd": "ເພີ່ມໂນດແລ້ວ",
"changeHistory.nodeChange": "ປ່ຽນແປງໂນດແລ້ວ",
"changeHistory.nodeConnect": "ເຊື່ອມຕໍ່ໂນດແລ້ວ",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "ກະລຸນາເປີດໃຊ້ຢ່າງໜ້ອຍໜຶ່ງວິທີການສົ່ງ",
"nodes.humanInput.errorMsg.noUserActions": "ກະລຸນາເພີ່ມຢ່າງໜ້ອຍໜຶ່ງການດຳເນີນການຜູ້ໃຊ້",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} ຖືກສະຫງວນໄວ້ສຳລັບສາຂາໝົດເວລາ. ກະລຸນາເລືອກ ID ການດຳເນີນການອື່ນ.",
+ "nodes.humanInput.output.actionId": "ID ຂອງການດຳເນີນການທີ່ຜູ້ໃຊ້ສັ່ງ",
+ "nodes.humanInput.output.actionValue": "ຄ່າຂອງການດຳເນີນການທີ່ເລືອກ",
+ "nodes.humanInput.output.formInput": "ຄ່າທີ່ປ້ອນໃນແບບຟອມ",
+ "nodes.humanInput.output.renderedContent": "ເນື້ອຫາທີ່ສະແດງແລ້ວ",
"nodes.humanInput.timeout.title": "Timeout",
+ "nodes.humanInputMigration.action.migrate": "ຍ້າຍ",
+ "nodes.humanInputMigration.action.migrateNow": "ຍ້າຍດຽວນີ້",
+ "nodes.humanInputMigration.action.migrating": "ກຳລັງຍ້າຍ...",
+ "nodes.humanInputMigration.banner.ariaLabel": "ແຈ້ງການຍ້າຍການປ້ອນຂໍ້ມູນໂດຍມະນຸດ",
+ "nodes.humanInputMigration.banner.description": "Workflow ນີ້ໃຊ້ໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດລຸ້ນເກົ່າ. ກະລຸນາຍ້າຍໂນດເກົ່າທັງໝົດກ່ອນເພີ່ມໂນດໃໝ່.",
+ "nodes.humanInputMigration.banner.learnMore": "ຮຽນຮູ້ເພີ່ມເຕີມ",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "ວິທີການສົ່ງທີ່ປິດໃຊ້ງານຍັງມີການຕັ້ງຄ່າຢູ່",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "ວິທີການສົ່ງອີເມວທີ່ເປີດໃຊ້ງານໃຊ້ແມ່ແບບທີ່ຂັດແຍ້ງກັນ",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "ຄ່າເລີ່ມຕົ້ນບໍ່ຖືກຕ້ອງ",
+ "nodes.humanInputMigration.blocker.invalidEmail": "ອີເມວຂອງຜູ້ຮັບບໍ່ຖືກຕ້ອງ",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "ການຕັ້ງຄ່າວິທີການສົ່ງອີເມວທີ່ເປີດໃຊ້ງານຍັງບໍ່ຄົບຖ້ວນ",
+ "nodes.humanInputMigration.blocker.missingRecipients": "ໂນດນີ້ບໍ່ມີຜູ້ຮັບທີ່ຮອງຮັບ",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "ບໍ່ສາມາດເຊື່ອມໂຍງສະມາຊິກໃນພື້ນທີ່ເຮັດວຽກກັບຜູ້ຕິດຕໍ່ ຫຼື ອີເມວທີ່ຢືນຢັນແລ້ວ",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "ການປ້ອນຂໍ້ມູນໂດຍມະນຸດ v2 ບໍ່ຮອງຮັບວິທີການສົ່ງທີ່ເປີດໃຊ້ງານນີ້",
"nodes.humanInputMigration.blocker.unsupportedInputType": "ຍັງບໍ່ສາມາດຍ້າຍຟິວ {{field}} ໄດ້. ທ່ານສາມາດໃຊ້ໂນດຮັບຂໍ້ມູນຈາກຄົນລຸ້ນເກົ່າຕໍ່ໄປໄດ້.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "ໂນດນີ້ມີຄ່າລຸ້ນທີ່ບໍ່ຮອງຮັບ",
+ "nodes.humanInputMigration.dialog.description": "ຜູ້ຮັບ, ແບບຟອມ ແລະ ການດຳເນີນການຂອງທ່ານຈະຖືກຮັກສາໄວ້.",
+ "nodes.humanInputMigration.dialog.draftNotice": "ມີພຽງສະບັບຮ່າງນີ້ທີ່ປ່ຽນແປງ. ລຸ້ນທີ່ເຜີຍແຜ່ແລ້ວຈະເຮັດວຽກຕໍ່ໄປຈົນກວ່າທ່ານຈະເຜີຍແຜ່ອີກຄັ້ງ.",
+ "nodes.humanInputMigration.dialog.review": "ກວດສອບໂນດ ແລະ ເຜີຍແຜ່ເມື່ອພ້ອມ.",
+ "nodes.humanInputMigration.dialog.title": "ຍ້າຍໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດ {{count}} ໂນດ",
+ "nodes.humanInputMigration.disabledBadge": "ຈຳເປັນຕ້ອງຍ້າຍ",
+ "nodes.humanInputMigration.disabledReason": "ກະລຸນາຍ້າຍໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດລຸ້ນເກົ່າກ່ອນເພີ່ມໂນດໃໝ່.",
+ "nodes.humanInputMigration.error.blocked": "ບໍ່ສາມາດຍ້າຍ {{nodeTitle}} ໄດ້: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "ຂັ້ນຕອນການເຮັດວຽກປ່ຽນແປງໃນລະຫວ່າງການຍ້າຍ. ກະລຸນາລອງໃໝ່; ການແກ້ໄຂປັດຈຸບັນຂອງທ່ານຍັງຖືກເກັບໄວ້.",
+ "nodes.humanInputMigration.error.preflight": "ບໍ່ສາມາດກະກຽມການຍ້າຍໄດ້. Workflow ຂອງທ່ານບໍ່ໄດ້ຖືກປ່ຽນແປງ. ກະລຸນາລອງອີກຄັ້ງ.",
"nodes.humanInputMigration.error.sync": "ບໍ່ສາມາດບັນທຶກຂັ້ນຕອນການເຮັດວຽກທີ່ຍ້າຍແລ້ວໄດ້. ກະລຸນາກວດເບິ່ງສະບັບຮ່າງປັດຈຸບັນ ແລະ ລອງໃໝ່.",
+ "nodes.humanInputMigration.incompatibleVersions": "ບໍ່ສາມາດໃຊ້ໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດລຸ້ນເກົ່າ ແລະ ລຸ້ນໃໝ່ຮ່ວມກັນໃນຂະບວນວຽກດຽວໄດ້.",
+ "nodes.humanInputMigration.oldVersion": "ລຸ້ນເກົ່າ",
+ "nodes.humanInputMigration.preview.author": "ໂດຍທີມ Dify",
+ "nodes.humanInputMigration.preview.description": "ກະລຸນາຍ້າຍໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດລຸ້ນເກົ່າກ່ອນເພີ່ມໂນດໃໝ່.",
+ "nodes.humanInputMigration.success": "ຍ້າຍໂນດການປ້ອນຂໍ້ມູນໂດຍມະນຸດສຳເລັດແລ້ວ",
+ "nodes.humanInputV2.card.configured": "ຕັ້ງຄ່າຜູ້ຮັບ {{count}} ຄົນແລ້ວ",
+ "nodes.humanInputV2.card.contactsOnly": "ຜູ້ຕິດຕໍ່ {{count}} ຄົນ",
+ "nodes.humanInputV2.card.empty": "ຍັງບໍ່ມີໃຜສາມາດອະນຸມັດຂັ້ນຕອນນີ້ໄດ້",
+ "nodes.humanInputV2.card.initiatorAndContacts": "ຜູ້ເລີ່ມ ແລະ ຜູ້ຕິດຕໍ່ {{count}} ຄົນ",
+ "nodes.humanInputV2.card.initiatorOnly": "ຜູ້ເລີ່ມເທົ່ານັ້ນ",
+ "nodes.humanInputV2.card.invalid": "ຕ້ອງກວດສອບການຕັ້ງຄ່າຜູ້ຮັບ",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "ອີເມວ",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "ຕັ້ງຄ່າໂໝດ Debug",
"nodes.humanInputV2.debug.keepOneChannel": "ເປີດໃຊ້ງານຢ່າງໜ້ອຍໜຶ່ງຊ່ອງທາງໄວ້",
+ "nodes.humanInputV2.debug.sendVia": "ສົ່ງການແຈ້ງເຕືອນ Debug ຜ່ານ",
+ "nodes.humanInputV2.debug.title": "ໂໝດ Debug",
+ "nodes.humanInputV2.debug.toggle": "ເປີດໃຊ້ໂໝດ Debug",
+ "nodes.humanInputV2.debug.unsupported": "ຊ່ອງທາງທີ່ນຳເຂົ້າບໍ່ຮອງຮັບ: {{channels}}. ກະລຸນາລຶບ ຫຼື ອັບເດດຊ່ອງທາງເຫຼົ່ານີ້ກ່ອນເປີດໃຊ້ Workflow ນີ້.",
"nodes.humanInputV2.disabled": "ບໍ່ສາມາດໃຊ້ Human Input v2 ໄດ້ເມື່ອປິດໃຊ້ HITL IM.",
+ "nodes.humanInputV2.error.bodyRequired": "ຈຳເປັນຕ້ອງມີເນື້ອຫາຂໍ້ຄວາມ",
+ "nodes.humanInputV2.error.debugChannelRequired": "ເລືອກຊ່ອງທາງໂໝດ Debug ຢ່າງໜ້ອຍໜຶ່ງຊ່ອງທາງ",
+ "nodes.humanInputV2.error.recipientDuplicate": "ລຶບຜູ້ຮັບທີ່ຊ້ຳກັນ",
+ "nodes.humanInputV2.error.recipientInvalid": "ແກ້ໄຂການຕັ້ງຄ່າຜູ້ຮັບທີ່ບໍ່ຖືກຕ້ອງ",
+ "nodes.humanInputV2.error.recipientRequired": "ເພີ່ມຜູ້ຮັບຢ່າງໜ້ອຍໜຶ່ງຄົນ",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "ບໍ່ສາມາດກວດສອບຜູ້ຮັບຈາກລາຍຊື່ຕິດຕໍ່ໄດ້",
"nodes.humanInputV2.error.requestURLDuplicate": "ເນື້ອຫາຂໍ້ຄວາມສາມາດມີ URL ຄຳຮ້ອງຂໍໄດ້ພຽງໜຶ່ງລາຍການເທົ່ານັ້ນ.",
"nodes.humanInputV2.error.requestURLRequired": "ກະລຸນາແຊກ URL ຄຳຮ້ອງຂໍໃນເນື້ອຫາຂໍ້ຄວາມ.",
+ "nodes.humanInputV2.error.subjectRequired": "ຈຳເປັນຕ້ອງມີຫົວຂໍ້ຂໍ້ຄວາມ",
+ "nodes.humanInputV2.error.version": "ການປ້ອນຂໍ້ມູນໂດຍມະນຸດ v2 ຕ້ອງໃຊ້ຄ່າລຸ້ນເປັນສະຕຣິງ 2",
+ "nodes.humanInputV2.recipients.addContact": "ເພີ່ມຜູ້ຕິດຕໍ່",
+ "nodes.humanInputV2.recipients.addEmail": "ເພີ່ມ",
+ "nodes.humanInputV2.recipients.addRecipient": "ເພີ່ມຜູ້ຮັບ",
+ "nodes.humanInputV2.recipients.added": "ເພີ່ມແລ້ວ",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "ຜູ້ຕິດຕໍ່ທັງໝົດໃນພື້ນທີ່ເຮັດວຽກ",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "ສົ່ງການແຈ້ງເຕືອນໄປຫາຜູ້ຕິດຕໍ່ທັງໝົດໃນພື້ນທີ່ເຮັດວຽກ; ຜູ້ໃດກໍສາມາດອະນຸມັດໄດ້",
+ "nodes.humanInputV2.recipients.cancel": "ຍົກເລີກ",
+ "nodes.humanInputV2.recipients.chooseVariable": "ເລືອກຕົວແປ",
+ "nodes.humanInputV2.recipients.confirm": "ຢືນຢັນ",
+ "nodes.humanInputV2.recipients.contactInfo": "ລາຍລະອຽດຜູ້ຕິດຕໍ່ {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "ທັງໝົດ",
+ "nodes.humanInputV2.recipients.contactSource.external": "ພາຍນອກ",
+ "nodes.humanInputV2.recipients.contactSource.organization": "ອົງກອນ",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "ພື້ນທີ່ເຮັດວຽກ",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "ແຫຼ່ງຜູ້ຕິດຕໍ່",
"nodes.humanInputV2.recipients.duplicateSource": "ເພີ່ມຜ່ານ {{name}} ({{source}}) ແລ້ວ.",
+ "nodes.humanInputV2.recipients.edit": "ແກ້ໄຂ {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "ແກ້ໄຂຜູ້ຮັບ",
"nodes.humanInputV2.recipients.emailAlreadySelected": "ແຕ່ລະອີເມວສາມາດເລືອກໄດ້ພຽງຄັ້ງດຽວ.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "ປ້ອນອີເມວທີ່ຖືກຕ້ອງ ແລະ ຍັງບໍ່ໄດ້ເພີ່ມ",
+ "nodes.humanInputV2.recipients.emailLabel": "ຜູ້ຮັບອີເມວສຳລັບຄັ້ງດຽວ",
+ "nodes.humanInputV2.recipients.empty": "ຍັງບໍ່ໄດ້ຕັ້ງຄ່າຜູ້ຮັບ",
+ "nodes.humanInputV2.recipients.help": "ເລືອກຜູ້ທີ່ສາມາດຕອບຂັ້ນຕອນການປ້ອນຂໍ້ມູນໂດຍມະນຸດນີ້ໄດ້.",
"nodes.humanInputV2.recipients.initiator": "ຜູ້ໃຊ້ທີ່ເລີ່ມການເຮັດວຽກຄັ້ງນີ້ຜ່ານ Web App ຫຼື CLI ສາມາດອະນຸມັດໄດ້",
+ "nodes.humanInputV2.recipients.initiatorDescription": "ຜູ້ທີ່ເລີ່ມການເຮັດວຽກຂອງ Workflow ຄັ້ງນີ້ສາມາດຕອບໄດ້.",
"nodes.humanInputV2.recipients.inputHelp": "ພິມ ຫຼື ວາງຫຼາຍອີເມວໂດຍໃຊ້ , ຄັ່ນແຕ່ລະອີເມວ. ກົດ / ເພື່ອແຊກຕົວແປ.",
+ "nodes.humanInputV2.recipients.insertVariable": "ແຊກຕົວແປ",
+ "nodes.humanInputV2.recipients.loadError": "ບໍ່ສາມາດໂຫຼດຜູ້ຕິດຕໍ່ໄດ້. ID ຜູ້ຕິດຕໍ່ທີ່ບັນທຶກໄວ້ຍັງຖືກຮັກສາໄວ້.",
+ "nodes.humanInputV2.recipients.loading": "ກຳລັງໂຫຼດຜູ້ຕິດຕໍ່…",
+ "nodes.humanInputV2.recipients.noResults": "ບໍ່ພົບຜູ້ຕິດຕໍ່",
+ "nodes.humanInputV2.recipients.placeholder": "ຄົ້ນຫາຜູ້ຕິດຕໍ່ ຫຼື ເພີ່ມອີເມວ",
+ "nodes.humanInputV2.recipients.remove": "ລຶບ {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "ກົດ Backspace ຫຼື Delete ເພື່ອລຶບ.",
+ "nodes.humanInputV2.recipients.resultCount": "ພົບຜູ້ຮັບທີ່ກົງກັນ {{count}} ຄົນ",
+ "nodes.humanInputV2.recipients.search": "ຄົ້ນຫາຜູ້ຕິດຕໍ່",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "ຄົ້ນຫາດ້ວຍຊື່ ຫຼື ອີເມວ",
+ "nodes.humanInputV2.recipients.selectionHint": "ເລືອກຜູ້ຮັບ {{count}} ຄົນແລ້ວ. ຢູ່ຕົ້ນຊ່ອງປ້ອນຂໍ້ມູນ ໃຫ້ກົດລູກສອນຊ້າຍເພື່ອເລືອກຜູ້ຮັບ.",
+ "nodes.humanInputV2.recipients.title": "ຜູ້ຮັບ",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "ຜູ້ຕິດຕໍ່ທັງໝົດໃນພື້ນທີ່ເຮັດວຽກ",
+ "nodes.humanInputV2.recipients.type.contact": "ຜູ້ຕິດຕໍ່",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "ອີເມວແບບໄດນາມິກ",
+ "nodes.humanInputV2.recipients.type.initiator": "ຜູ້ເລີ່ມ",
+ "nodes.humanInputV2.recipients.type.onetime_email": "ອີເມວສຳລັບຄັ້ງດຽວ",
+ "nodes.humanInputV2.recipients.typeLabel": "ປະເພດຜູ້ຮັບ",
"nodes.humanInputV2.recipients.useThisInstead": "ໃຊ້ອັນນີ້ແທນ",
+ "nodes.humanInputV2.recipients.variableRequired": "ເລືອກຕົວແປອີເມວ",
+ "nodes.humanInputV2.template.body": "ເນື້ອຫາ",
+ "nodes.humanInputV2.template.description": "ຂໍ້ຄວາມສຳຮອງສຳລັບອີເມວ ແລະ ຂໍ້ຄວາມດ່ວນ",
"nodes.humanInputV2.template.insertRequestURL": "ແຊກ URL ຄຳຮ້ອງຂໍ",
+ "nodes.humanInputV2.template.insertVariable": "ແຊກຕົວແປ",
+ "nodes.humanInputV2.template.notConfigured": "ຍັງບໍ່ໄດ້ຕັ້ງຄ່າ",
"nodes.humanInputV2.template.requestURLHint": "ຜູ້ຮັບໃຊ້ລິ້ງນີ້ເພື່ອເປີດແບບຟອມອະນຸມັດ. ເນື້ອຫາຕ້ອງມີ URL ຄຳຮ້ອງຂໍພຽງໜຶ່ງລາຍການ.",
"nodes.humanInputV2.template.requestURLInserted": "ແຊກ URL ຄຳຮ້ອງຂໍແລ້ວ",
"nodes.humanInputV2.template.saveAndTest": "ບັນທຶກ ແລະ ທົດສອບ",
+ "nodes.humanInputV2.template.subject": "ຫົວຂໍ້",
+ "nodes.humanInputV2.template.subjectPlaceholder": "ປ້ອນຫົວຂໍ້ຂໍ້ຄວາມ",
"nodes.humanInputV2.template.test": "ທົດສອບຂໍ້ຄວາມ",
"nodes.humanInputV2.template.testChannel": "ຊ່ອງທາງທົດສອບ",
"nodes.humanInputV2.template.testCompleted": "ຄຳຮ້ອງຂໍທົດສອບສຳເລັດແລ້ວ. ກະລຸນາກວດເບິ່ງຂໍ້ຄວາມໃນຊ່ອງທາງທີ່ເລືອກ.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "ກະລຸນາປ້ອນຄ່າຕົວແປທົດສອບທັງໝົດ.",
"nodes.humanInputV2.template.testSaveFailed": "ບໍ່ສາມາດບັນທຶກຮ່າງເວີກໂຟລໄດ້. ຍັງບໍ່ໄດ້ສົ່ງການທົດສອບ.",
"nodes.humanInputV2.template.testUnavailable": "ສະພາບແວດລ້ອມນີ້ຍັງບໍ່ຮອງຮັບການທົດສອບແມ່ແບບຂໍ້ຄວາມ.",
+ "nodes.humanInputV2.template.title": "ແມ່ແບບຂໍ້ຄວາມ",
"nodes.ifElse.operator": "ຕົວດຳເນີນການ",
"nodes.iteration.currentIteration": "ການເຮັດຊ້ຳປັດຈຸບັນ",
"nodes.iteration.deleteDesc": "ການລຶບໂນດການເຮັດຊ້ຳຈະລຶບໂນດຍ່ອຍທັງໝົດ",
diff --git a/web/i18n/locales/nl-NL/contacts.json b/web/i18n/locales/nl-NL/contacts.json
index 0a01c90d5a6..9f37ddd1925 100644
--- a/web/i18n/locales/nl-NL/contacts.json
+++ b/web/i18n/locales/nl-NL/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Contacten verwijderen ({{count}})?",
"directory.removalDescription": "De geselecteerde contacten worden permanent uit deze werkruimte verwijderd. Deze actie kan niet ongedaan worden gemaakt.",
- "directory.removalTitle": "Contacten verwijderen?",
+ "directory.removalSingleDescription": "{{name}} wordt definitief uit deze werkruimte verwijderd. Deze actie kan niet ongedaan worden gemaakt.",
+ "directory.removalSingleFailed": "Het contact kon niet worden verwijderd. Probeer het opnieuw.",
+ "directory.removalSingleTitle": "{{name}} verwijderen?",
+ "directory.resultCount": "Resultaten: {{count}}",
+ "imPlatform.action.configure": "Config",
+ "imPlatform.action.configureChannel": "{{provider}} configureren",
+ "imPlatform.action.connect": "Verbinden",
+ "imPlatform.action.copied": "Gekopieerd",
+ "imPlatform.action.copyCallback": "Callback-URL kopiëren",
+ "imPlatform.action.deleteChannel": "{{provider}} verwijderen",
+ "imPlatform.action.loadMore": "Meer laden",
+ "imPlatform.action.replace": "Vervangen",
+ "imPlatform.action.retry": "Opnieuw proberen",
+ "imPlatform.action.save": "Opslaan",
+ "imPlatform.action.saving": "Opslaan",
+ "imPlatform.action.setupGuide": "Installatiehandleiding",
+ "imPlatform.action.syncNow": "Synchroniseer nu",
+ "imPlatform.action.syncing": "Wordt gesynchroniseerd",
+ "imPlatform.action.testConnection": "Verbinding testen",
+ "imPlatform.action.testing": "Bezig met testen",
+ "imPlatform.action.viewDetails": "Details bekijken",
+ "imPlatform.bindingDialog.back": "Terug",
+ "imPlatform.bindingDialog.callback": "Callback-URL",
+ "imPlatform.bindingDialog.callbackDescription": "Voltooi de callbackconfiguratie in {{provider}} om kaartacties in te schakelen.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Plak deze URL voor kaartacties in de <console>Feishu-ontwikkelaarsconsole</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Gebeurtenissen en callbacks → Callbackconfiguratie → Aanvraag-URL",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Plak deze URL voor kaartacties in de <console>Lark-ontwikkelaarsconsole</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Gebeurtenissen en callbacks → Callbackconfiguratie → Aanvraag-URL",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Plak deze URL voor kaartacties in de <console>Slack-ontwikkelaarsconsole</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interactiviteit en snelkoppelingen → Interactiviteit → Aanvraag-URL",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Plak deze URL voor kaartacties in de <console>Azure Bot-configuratie</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Instellingen → Configuratie → Berichtenendpoint",
+ "imPlatform.bindingDialog.callbackStep": "Callbacks configureren",
"imPlatform.bindingDialog.clearSavedCredential": "Opgeslagen waarde wissen",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}} configureren",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}} verbinden",
"imPlatform.bindingDialog.credentialWillBeCleared": "Deze opgeslagen waarde wordt gewist wanneer je opslaat.",
+ "imPlatform.bindingDialog.credentialsDescription": "Verbind eerst je {{provider}}-app en configureer vervolgens de callback-URL.",
+ "imPlatform.bindingDialog.credentialsStep": "App-inloggegevens",
+ "imPlatform.bindingDialog.description": "Voer de app-inloggegevens voor deze chatprovider in.",
+ "imPlatform.bindingDialog.field.agentId": "Agent-ID",
+ "imPlatform.bindingDialog.field.appId": "App-ID",
+ "imPlatform.bindingDialog.field.appToken": "App-token (optioneel)",
+ "imPlatform.bindingDialog.field.botToken": "Bot-token",
+ "imPlatform.bindingDialog.field.clientId": "Client-ID",
+ "imPlatform.bindingDialog.field.clientSecret": "Clientgeheim",
+ "imPlatform.bindingDialog.field.corpId": "Bedrijfs-ID",
+ "imPlatform.bindingDialog.field.encryptKey": "Versleutelingssleutel (optioneel)",
+ "imPlatform.bindingDialog.field.genericSecret": "Geheim",
+ "imPlatform.bindingDialog.field.secret": "App-geheim",
+ "imPlatform.bindingDialog.field.signingSecret": "Ondertekeningsgeheim",
+ "imPlatform.bindingDialog.field.tenantId": "Tenant-ID",
+ "imPlatform.bindingDialog.field.verificationToken": "Verificatietoken (optioneel)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Voer de versleutelingssleutel in, indien ingeschakeld",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Voer het app-geheim in",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Voer het verificatietoken in, indien geconfigureerd",
+ "imPlatform.bindingDialog.finish": "Voltooien",
+ "imPlatform.bindingDialog.freshCredentials": "Opgeslagen geheimen kunnen niet worden opgehaald. Voer alle vereiste inloggegevens opnieuw in om deze configuratie te testen of op te slaan.",
+ "imPlatform.bindingDialog.openSetupGuide": "Installatiehandleiding openen",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Tenantreferenties voor {{identity}} vervangen?",
"imPlatform.bindingDialog.replacementRequired": "Deze inloggegevens horen bij een andere IM-tenant en kunnen niet rechtstreeks worden opgeslagen. Om van tenant te wisselen, moet je het huidige IM-kanaal vervangen. Daarbij worden alle automatische en handmatige IM-koppelingen verwijderd. Synchroniseer de contacten opnieuw na de vervanging.",
+ "imPlatform.bindingDialog.required": "Dit veld is verplicht.",
+ "imPlatform.bindingDialog.saveAndContinue": "Opslaan en doorgaan",
+ "imPlatform.bindingDialog.saveFailed": "De configuratie kon niet worden opgeslagen. Controleer de velden en probeer het opnieuw.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "De configuratie is opgeslagen, maar de details konden niet worden geladen. Sluit dit dialoogvenster en open het opnieuw.",
- "imPlatform.bindingDialog.undoClearCredential": "Wissen ongedaan maken"
+ "imPlatform.bindingDialog.secretConfigured": "Er is al een geheim geconfigureerd. Laat dit veld leeg om het te behouden.",
+ "imPlatform.bindingDialog.step": "Stap {{step}}",
+ "imPlatform.bindingDialog.testFailed": "De verbindingstest is mislukt. Controleer de configuratie en probeer het opnieuw.",
+ "imPlatform.bindingDialog.undoClearCredential": "Wissen ongedaan maken",
+ "imPlatform.bindingDialog.viewSetupGuide": "Installatiehandleiding bekijken",
+ "imPlatform.chooseProvider": "Kies een kanaal om te verbinden",
+ "imPlatform.configurationUpdated": "Deze kanaalconfiguratie is gewijzigd. Sluit dit venster en vernieuw de pagina voordat je het opnieuw probeert.",
+ "imPlatform.connectMore": "Meer kanalen verbinden",
+ "imPlatform.delete.confirm": "Verwijderen",
+ "imPlatform.delete.description": "Als je dit kanaal verwijdert, wordt de configuratie verwijderd. Goedkeuringsmeldingen en adresboeksynchronisaties die dit kanaal gebruiken, stoppen.",
+ "imPlatform.delete.failed": "Het kanaal kon niet worden verwijderd. Er is niets gewijzigd; probeer het opnieuw.",
+ "imPlatform.delete.title": "Kanaal {{provider}} verwijderen?",
+ "imPlatform.description": "Verbind je bedrijfskanalen zodat goedkeuringsverzoeken mensen bereiken waar ze werken.",
+ "imPlatform.details.column.contact": "Contacten",
+ "imPlatform.details.column.platform": "Chatplatform",
+ "imPlatform.details.description": "Bekijk de alleen-lezenresultaten van de laatste synchronisatie.",
+ "imPlatform.details.downloadFailed": "Het rapport kon niet worden gedownload. Probeer het opnieuw.",
+ "imPlatform.details.downloadReport": "Rapport downloaden",
+ "imPlatform.details.downloadingReport": "Rapport wordt gedownload…",
+ "imPlatform.details.empty": "Geen resultaten in deze categorie.",
+ "imPlatform.details.filter.added": "Toegevoegd",
+ "imPlatform.details.filter.failed": "Mislukt",
+ "imPlatform.details.filter.not_matched": "Geen overeenkomst",
+ "imPlatform.details.filter.removed": "Verwijderd",
+ "imPlatform.details.filter.skipped": "Overgeslagen",
+ "imPlatform.details.filters": "Filters voor synchronisatieresultaten",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "De synchronisatiedetails konden niet worden geladen.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Meer resultaten konden niet worden geladen. Probeer deze pagina opnieuw.",
+ "imPlatform.details.removalReason.binding_invalidated": "Koppeling ongeldig gemaakt",
+ "imPlatform.details.removalReason.binding_replaced": "Koppeling vervangen",
+ "imPlatform.details.removalReason.not_present_in_directory": "Niet meer in de adreslijst",
+ "imPlatform.details.reportChanged": "De synchronisatieresultaten zijn gewijzigd. Open de details van de laatste synchronisatie opnieuw en probeer het nogmaals.",
+ "imPlatform.details.title": "Synchronisatiedetails",
+ "imPlatform.email.apiKey": "API-sleutel",
+ "imPlatform.email.apiKeyConfigured": "Om veiligheidsredenen kan de opgeslagen API-sleutel niet worden bekeken. Laat dit veld leeg om deze te behouden.",
+ "imPlatform.email.apiKeyDescription": "Om veiligheidsredenen kan deze API-sleutel na het opslaan niet meer worden bekeken.",
+ "imPlatform.email.apiKeyPlaceholder": "Voer je Resend-API-sleutel in",
+ "imPlatform.email.description": "Deze configuratie geldt voor alle knooppunten voor menselijke invoer in deze werkruimte waarvoor <emphasis>Foutopsporingsmeldingen via e-mail verzenden</emphasis> is ingeschakeld.",
+ "imPlatform.email.invalidEmail": "Voer een geldig e-mailadres in.",
+ "imPlatform.email.provider": "E-mailprovider",
+ "imPlatform.email.resendDescription": "Je <apiKey>Resend-API-sleutel</apiKey> wordt versleuteld en kan na het opslaan niet meer worden bekeken.<br/>Maak een <resend>Resend</resend>-account aan.",
+ "imPlatform.email.resendSettings": "Resend-instellingen",
+ "imPlatform.email.senderEmail": "E-mailadres van afzender",
+ "imPlatform.email.senderEmailDescription": "Het e-mailadres dat als afzender wordt weergegeven. Het domein moet in Resend zijn geverifieerd.",
+ "imPlatform.email.senderName": "Naam van afzender",
+ "imPlatform.email.senderNameDescription": "Naam die in de inbox van de ontvanger wordt weergegeven.",
+ "imPlatform.email.testSucceeded": "Verbindingstest geslaagd.",
+ "imPlatform.email.title": "E-mail configureren",
+ "imPlatform.learnMore": "Meer informatie",
+ "imPlatform.loadError.description": "Probeer opnieuw de huidige koppeling en machtigingen te laden.",
+ "imPlatform.loadError.retry": "Opnieuw proberen",
+ "imPlatform.loadError.title": "Kanalen konden niet worden geladen",
+ "imPlatform.loading": "Kanalen worden geladen",
+ "imPlatform.provider.dingtalkDescription": "Verbind een DingTalk-applicatie.",
+ "imPlatform.provider.emailDescription": "Configureer de e-mailservice voor het verzenden van goedkeuringsverzoeken vanuit deze werkruimte.",
+ "imPlatform.provider.feishuDescription": "Verbind een Feishu-applicatie.",
+ "imPlatform.provider.larkDescription": "Verbind een Lark-applicatie.",
+ "imPlatform.provider.msTeamsDescription": "Verbind een Microsoft Teams-applicatie.",
+ "imPlatform.provider.slackDescription": "Synchroniseer personen en hun Slack-identiteiten.",
+ "imPlatform.provider.weComDescription": "Verbind een WeCom-applicatie.",
+ "imPlatform.replacement.confirm": "Vervangen",
+ "imPlatform.replacement.description": "Het vervangen van de actieve provider maakt zijn chatkoppelingen en werkruimteaanpassingen ongeldig. Synchroniseer na de vervanging de adresboekgegevens van de nieuwe provider opnieuw.",
+ "imPlatform.replacement.title": "{{current}} vervangen door {{next}}?",
+ "imPlatform.status.configured": "Geconfigureerd",
+ "imPlatform.status.connected": "Verbonden",
+ "imPlatform.status.connection_error": "Verbindingsfout",
+ "imPlatform.status.permission_issue": "Machtigingsprobleem",
+ "imPlatform.sync.latestSynced": "Laatst gesynchroniseerd op {{date}}",
+ "imPlatform.sync.loading": "Controleren of er een actieve synchronisatie is.",
+ "imPlatform.sync.noPermission": "Alleen eigenaren en beheerders van de werkruimte kunnen een adresboeksynchronisatie starten.",
+ "imPlatform.sync.noRuns": "Er is nog geen adresboeksynchronisatie uitgevoerd.",
+ "imPlatform.sync.notConnected": "Verbind een provider en test de verbinding voordat je de adresboeksynchronisatie start.",
+ "imPlatform.sync.startFailed": "De adresboeksynchronisatie kon niet worden gestart of vernieuwd. Probeer het opnieuw.",
+ "imPlatform.sync.status.failure": "Mislukt",
+ "imPlatform.sync.status.queued": "In wachtrij",
+ "imPlatform.sync.status.running": "Wordt uitgevoerd",
+ "imPlatform.sync.status.success": "Geslaagd",
+ "imPlatform.title": "Kanalen"
}
diff --git a/web/i18n/locales/nl-NL/share.json b/web/i18n/locales/nl-NL/share.json
index 45c272bc22d..f298e87dd57 100644
--- a/web/i18n/locales/nl-NL/share.json
+++ b/web/i18n/locales/nl-NL/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Thanks!",
"humanInput.unavailableDescription": "De link is mogelijk niet beschikbaar of hoort niet bij het account waarmee je bent aangemeld. Open het formulier vanuit de melding die je hebt ontvangen of probeer van account te wisselen.",
"humanInput.unavailableTitle": "Dit formulier kan niet worden geopend",
+ "humanInputV2.accessRateLimited": "Er zijn te veel verificatie-e-mails aangevraagd. Probeer het later opnieuw.",
+ "humanInputV2.alreadySubmitted": "Dit verzoek is al voltooid.",
+ "humanInputV2.challengeExpired": "Deze verificatiecode is verlopen. Vraag een nieuwe code aan om door te gaan.",
+ "humanInputV2.challengeStale": "Deze verificatiecode is vervangen. Vraag een nieuwe code aan om door te gaan.",
+ "humanInputV2.codeExpiresIn": "Code verloopt over {{seconds}} s",
+ "humanInputV2.codeRequired": "Vraag een verificatiecode aan om door te gaan.",
+ "humanInputV2.codeSent": "Er is een verificatiecode naar uw e-mailadres verzonden.",
+ "humanInputV2.deliveryFailed": "De verificatie-e-mail kon niet worden verzonden. Probeer het opnieuw.",
+ "humanInputV2.formExpired": "Dit verzoek is verlopen.",
+ "humanInputV2.formNotFound": "Formulier niet gevonden.",
+ "humanInputV2.formRateLimited": "Te veel formulierverzoeken. Probeer het later opnieuw.",
+ "humanInputV2.invalidOtp": "De verificatiecode is onjuist. Controleer de code en probeer het opnieuw.",
+ "humanInputV2.networkError": "Het verzoek kon niet worden voltooid. Controleer uw verbinding en probeer het opnieuw.",
+ "humanInputV2.otpLabel": "Verificatiecode per e-mail",
+ "humanInputV2.otpPlaceholder": "Voer de 6-cijferige code in",
+ "humanInputV2.requestingCode": "Verificatiecode verzenden…",
+ "humanInputV2.resendCode": "Code opnieuw verzenden",
+ "humanInputV2.retry": "Opnieuw proberen",
+ "humanInputV2.sendCode": "Nieuwe code verzenden",
+ "humanInputV2.unavailable": "Dit formulier is tijdelijk niet beschikbaar.",
+ "humanInputV2.unknownError": "Er is iets misgegaan. Probeer het opnieuw.",
+ "humanInputV2.uploadFailed": "Het bestand kon niet worden geüpload. Probeer het opnieuw.",
"login.backToHome": "Back to Home"
}
diff --git a/web/i18n/locales/nl-NL/workflow-human-input.json b/web/i18n/locales/nl-NL/workflow-human-input.json
index 93e6fb4ee37..fa4eecca795 100644
--- a/web/i18n/locales/nl-NL/workflow-human-input.json
+++ b/web/i18n/locales/nl-NL/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Actiewaarde",
"nodes.humanInput.userActions.buttonTextTooLong": "Button text must be {{maxLength}} characters or less",
"nodes.humanInput.userActions.chooseStyle": "Choose a button style",
+ "nodes.humanInput.userActions.defaultTitle": "Knoptekst {{index}}",
"nodes.humanInput.userActions.emptyTip": "Click the '+' button to add user actions",
"nodes.humanInput.userActions.title": "User Actions",
"nodes.humanInput.userActions.tooltip": "Definieer knoppen waarop gebruikers kunnen klikken om op dit formulier te reageren. Actie-ID bepaalt de vertakking. De Actiewaarde wordt stroomafwaarts beschikbaar gesteld als de geselecteerde ingebouwde uitvoer. Actie-ID moet beginnen met een letter of onderstrepingsteken, gevolgd door letters, cijfers of onderstrepingstekens.",
diff --git a/web/i18n/locales/nl-NL/workflow.json b/web/i18n/locales/nl-NL/workflow.json
index 7f9912b924f..81f9760056f 100644
--- a/web/i18n/locales/nl-NL/workflow.json
+++ b/web/i18n/locales/nl-NL/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Output",
"blocks.http-request": "HTTP Request",
"blocks.human-input": "Human Input",
+ "blocks.human-input-v2": "Human Input v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "Iteration",
"blocks.iteration-start": "Iteration Start",
@@ -45,6 +46,7 @@
"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.human-input-v2": "Vraag invoer van ingestelde contacten, e-mailontvangers of de initiatiefnemer van de workflow",
"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",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Aggregate multi-branch variables into a single variable for unified configuration of downstream nodes.",
"blocksAbout.variable-assigner": "Aggregate multi-branch variables into a single variable for unified configuration of downstream nodes.",
"changeHistory.edgeDelete": "Node disconnected",
+ "changeHistory.humanInputMigration": "Human Input-nodes gemigreerd",
"changeHistory.nodeAdd": "Node added",
"changeHistory.nodeChange": "Node changed",
"changeHistory.nodeConnect": "Node connected",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Please enable at least one delivery method",
"nodes.humanInput.errorMsg.noUserActions": "Please add at least one user action",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} is gereserveerd voor de time-outtak. Kies een andere actie-ID.",
+ "nodes.humanInput.output.actionId": "ID van de actie die de gebruiker heeft geactiveerd",
+ "nodes.humanInput.output.actionValue": "Waarde van de geselecteerde actie",
+ "nodes.humanInput.output.formInput": "Ingevoerde formulierwaarde",
+ "nodes.humanInput.output.renderedContent": "Weergegeven inhoud",
"nodes.humanInput.timeout.title": "Timeout",
+ "nodes.humanInputMigration.action.migrate": "Migreren",
+ "nodes.humanInputMigration.action.migrateNow": "Nu migreren",
+ "nodes.humanInputMigration.action.migrating": "Bezig met migreren...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Melding over Human Input-migratie",
+ "nodes.humanInputMigration.banner.description": "Deze workflow gebruikt de oude Human Input-node. Migreer alle oude nodes voordat u nieuwe toevoegt.",
+ "nodes.humanInputMigration.banner.learnMore": "Meer informatie",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "een uitgeschakelde bezorgmethode bevat nog configuratie",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "ingeschakelde e-mailmethoden gebruiken conflicterende sjablonen",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Ongeldige standaardwaarde",
+ "nodes.humanInputMigration.blocker.invalidEmail": "het e-mailadres van een ontvanger is ongeldig",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "een ingeschakelde e-mailmethode is onvolledig",
+ "nodes.humanInputMigration.blocker.missingRecipients": "de node heeft geen ondersteunde ontvangers",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "een lid van de werkruimte kan niet aan een contact of geverifieerd e-mailadres worden gekoppeld",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "een ingeschakelde bezorgmethode wordt niet ondersteund door Human Input v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Het veld {{field}} kan nog niet worden gemigreerd. Je kunt de oude Human Input-nodes blijven gebruiken.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "de node heeft een niet-ondersteunde versiewaarde",
+ "nodes.humanInputMigration.dialog.description": "Uw ontvangers, formulier en acties worden overgenomen.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Alleen dit concept wordt gewijzigd. Gepubliceerde versies blijven werken totdat u opnieuw publiceert.",
+ "nodes.humanInputMigration.dialog.review": "Controleer de nodes en publiceer wanneer u klaar bent.",
+ "nodes.humanInputMigration.dialog.title": "{{count}} Human Input-nodes migreren",
+ "nodes.humanInputMigration.disabledBadge": "MIGRATIE VEREIST",
+ "nodes.humanInputMigration.disabledReason": "Migreer oude Human Input-nodes voordat u een nieuwe toevoegt.",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} kon niet worden gemigreerd: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "De workflow is tijdens de migratie gewijzigd. Probeer het opnieuw; uw huidige wijzigingen zijn behouden.",
+ "nodes.humanInputMigration.error.preflight": "De migratie kon niet worden voorbereid. Uw workflow is niet gewijzigd. Probeer het opnieuw.",
"nodes.humanInputMigration.error.sync": "De gemigreerde workflow kon niet worden opgeslagen. Controleer het huidige concept en probeer het opnieuw.",
+ "nodes.humanInputMigration.incompatibleVersions": "Oude en nieuwe Human Input-knooppunten kunnen niet in dezelfde workflow worden gebruikt.",
+ "nodes.humanInputMigration.oldVersion": "OUDE VERSIE",
+ "nodes.humanInputMigration.preview.author": "Door het Dify-team",
+ "nodes.humanInputMigration.preview.description": "Migreer oude Human Input-nodes voordat u een nieuwe toevoegt.",
+ "nodes.humanInputMigration.success": "Human Input-nodes succesvol gemigreerd",
+ "nodes.humanInputV2.card.configured": "{{count}} ontvangers ingesteld",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} contacten",
+ "nodes.humanInputV2.card.empty": "Nog niemand kan deze stap goedkeuren",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Initiatiefnemer en {{count}} contacten",
+ "nodes.humanInputV2.card.initiatorOnly": "Alleen de initiatiefnemer",
+ "nodes.humanInputV2.card.invalid": "De configuratie van ontvangers vereist aandacht",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-mail",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Debugmodus configureren",
"nodes.humanInputV2.debug.keepOneChannel": "Houd minstens één kanaal ingeschakeld",
+ "nodes.humanInputV2.debug.sendVia": "Debugmeldingen verzenden via",
+ "nodes.humanInputV2.debug.title": "Debugmodus",
+ "nodes.humanInputV2.debug.toggle": "Debugmodus inschakelen",
+ "nodes.humanInputV2.debug.unsupported": "Niet-ondersteunde geïmporteerde kanalen: {{channels}}. Verwijder of werk ze bij voordat u deze workflow uitvoert.",
"nodes.humanInputV2.disabled": "Human Input v2 is niet beschikbaar zolang HITL IM is uitgeschakeld.",
+ "nodes.humanInputV2.error.bodyRequired": "De berichttekst is vereist",
+ "nodes.humanInputV2.error.debugChannelRequired": "Selecteer ten minste één kanaal voor de debugmodus",
+ "nodes.humanInputV2.error.recipientDuplicate": "Verwijder dubbele ontvangers",
+ "nodes.humanInputV2.error.recipientInvalid": "Herstel de ongeldige configuratie van ontvangers",
+ "nodes.humanInputV2.error.recipientRequired": "Voeg ten minste één ontvanger toe",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Contactontvangers konden niet worden gecontroleerd",
"nodes.humanInputV2.error.requestURLDuplicate": "De berichttekst mag maar één aanvraag-URL bevatten.",
"nodes.humanInputV2.error.requestURLRequired": "Voeg een aanvraag-URL in de berichttekst in.",
+ "nodes.humanInputV2.error.subjectRequired": "Het berichtonderwerp is vereist",
+ "nodes.humanInputV2.error.version": "Human Input v2 vereist de versiewaarde 2 als tekenreeks",
+ "nodes.humanInputV2.recipients.addContact": "Contact toevoegen",
+ "nodes.humanInputV2.recipients.addEmail": "Toevoegen",
+ "nodes.humanInputV2.recipients.addRecipient": "Ontvanger toevoegen",
+ "nodes.humanInputV2.recipients.added": "Toegevoegd",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Alle contacten in de werkruimte",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Stuur een melding naar alle contacten in de werkruimte; ieder van hen kan goedkeuren",
+ "nodes.humanInputV2.recipients.cancel": "Annuleren",
+ "nodes.humanInputV2.recipients.chooseVariable": "Variabele kiezen",
+ "nodes.humanInputV2.recipients.confirm": "Bevestigen",
+ "nodes.humanInputV2.recipients.contactInfo": "Contactgegevens van {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Alle",
+ "nodes.humanInputV2.recipients.contactSource.external": "Extern",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organisatie",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Werkruimte",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Contactbron",
"nodes.humanInputV2.recipients.duplicateSource": "Al toegevoegd via {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} bewerken",
+ "nodes.humanInputV2.recipients.editRecipient": "Ontvanger bewerken",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Elk e-mailadres kan maar één keer worden geselecteerd.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Voer een geldig e-mailadres in dat nog niet is toegevoegd",
+ "nodes.humanInputV2.recipients.emailLabel": "Eenmalige e-mailontvanger",
+ "nodes.humanInputV2.recipients.empty": "Geen ontvangers ingesteld",
+ "nodes.humanInputV2.recipients.help": "Kies wie op deze Human Input-stap kan reageren.",
"nodes.humanInputV2.recipients.initiator": "De gebruiker die deze uitvoering via Web App of CLI start, kan goedkeuren",
+ "nodes.humanInputV2.recipients.initiatorDescription": "De persoon die deze workflowuitvoering start, kan reageren.",
"nodes.humanInputV2.recipients.inputHelp": "Typ of plak meerdere e-mailadressen, gescheiden door komma’s. Druk op / om een variabele in te voegen.",
+ "nodes.humanInputV2.recipients.insertVariable": "Variabele invoegen",
+ "nodes.humanInputV2.recipients.loadError": "Contacten konden niet worden geladen. Opgeslagen contact-ID’s blijven behouden.",
+ "nodes.humanInputV2.recipients.loading": "Contacten laden…",
+ "nodes.humanInputV2.recipients.noResults": "Geen contacten gevonden",
+ "nodes.humanInputV2.recipients.placeholder": "Contacten zoeken of e-mailadressen toevoegen",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} verwijderen",
+ "nodes.humanInputV2.recipients.removeHint": "Druk op Backspace of Delete om te verwijderen.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} overeenkomende ontvangers",
+ "nodes.humanInputV2.recipients.search": "Contacten zoeken",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Zoeken op naam of e-mailadres",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} ontvangers geselecteerd. Druk aan het begin van het invoerveld op de pijl naar links om ze te selecteren.",
+ "nodes.humanInputV2.recipients.title": "Ontvangers",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Alle contacten in de werkruimte",
+ "nodes.humanInputV2.recipients.type.contact": "Contact",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Dynamische e-mail",
+ "nodes.humanInputV2.recipients.type.initiator": "Initiatiefnemer",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Eenmalige e-mail",
+ "nodes.humanInputV2.recipients.typeLabel": "Type ontvanger",
"nodes.humanInputV2.recipients.useThisInstead": "Gebruik dit in plaats daarvan",
+ "nodes.humanInputV2.recipients.variableRequired": "Kies een e-mailvariabele",
+ "nodes.humanInputV2.template.body": "Berichttekst",
+ "nodes.humanInputV2.template.description": "Terugvaltekst voor e-mail en chatberichten",
"nodes.humanInputV2.template.insertRequestURL": "Aanvraag-URL invoegen",
+ "nodes.humanInputV2.template.insertVariable": "Variabele invoegen",
+ "nodes.humanInputV2.template.notConfigured": "Niet geconfigureerd",
"nodes.humanInputV2.template.requestURLHint": "Ontvangers openen het goedkeuringsformulier via deze link. Voeg precies één aanvraag-URL toe.",
"nodes.humanInputV2.template.requestURLInserted": "Aanvraag-URL ingevoegd",
"nodes.humanInputV2.template.saveAndTest": "Opslaan en testen",
+ "nodes.humanInputV2.template.subject": "Onderwerp",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Voer het berichtonderwerp in",
"nodes.humanInputV2.template.test": "Bericht testen",
"nodes.humanInputV2.template.testChannel": "Testkanaal",
"nodes.humanInputV2.template.testCompleted": "Het testverzoek is voltooid. Bekijk het bericht in het geselecteerde kanaal.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Vul alle waarden voor de testvariabelen in.",
"nodes.humanInputV2.template.testSaveFailed": "Het workflowconcept kon niet worden opgeslagen. De test is niet verzonden.",
"nodes.humanInputV2.template.testUnavailable": "Deze omgeving ondersteunt het testen van berichtsjablonen nog niet.",
+ "nodes.humanInputV2.template.title": "Berichtsjabloon",
"nodes.ifElse.operator": "Operator",
"nodes.iteration.currentIteration": "Current Iteration",
"nodes.iteration.deleteDesc": "Deleting the iteration node will delete all child nodes",
diff --git a/web/i18n/locales/pl-PL/contacts.json b/web/i18n/locales/pl-PL/contacts.json
index d2bd48b67fc..b00f1da8935 100644
--- a/web/i18n/locales/pl-PL/contacts.json
+++ b/web/i18n/locales/pl-PL/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Usunąć kontakty ({{count}})?",
"directory.removalDescription": "Wybrane kontakty zostaną trwale usunięte z tego obszaru roboczego. Tej czynności nie można cofnąć.",
- "directory.removalTitle": "Usunąć kontakty?",
+ "directory.removalSingleDescription": "Kontakt {{name}} zostanie trwale usunięty z tego obszaru roboczego. Tej czynności nie można cofnąć.",
+ "directory.removalSingleFailed": "Nie udało się usunąć kontaktu. Spróbuj ponownie.",
+ "directory.removalSingleTitle": "Usunąć {{name}}?",
+ "directory.resultCount": "Wyniki: {{count}}",
+ "imPlatform.action.configure": "Skonfiguruj",
+ "imPlatform.action.configureChannel": "Skonfiguruj {{provider}}",
+ "imPlatform.action.connect": "Połącz",
+ "imPlatform.action.copied": "Kopiowane",
+ "imPlatform.action.copyCallback": "Kopiuj adres URL wywołania zwrotnego",
+ "imPlatform.action.deleteChannel": "Usuń {{provider}}",
+ "imPlatform.action.loadMore": "Załaduj więcej",
+ "imPlatform.action.replace": "Zastępować",
+ "imPlatform.action.retry": "Ponów próbę",
+ "imPlatform.action.save": "Zapisz",
+ "imPlatform.action.saving": "Zapisywanie",
+ "imPlatform.action.setupGuide": "Instrukcja konfiguracji",
+ "imPlatform.action.syncNow": "Synchronizuj teraz",
+ "imPlatform.action.syncing": "Synchronizacja",
+ "imPlatform.action.testConnection": "Testuj połączenie",
+ "imPlatform.action.testing": "Testowanie",
+ "imPlatform.action.viewDetails": "Zobacz szczegóły",
+ "imPlatform.bindingDialog.back": "Wstecz",
+ "imPlatform.bindingDialog.callback": "Adres URL zwrotny",
+ "imPlatform.bindingDialog.callbackDescription": "Dokończ konfigurację wywołań zwrotnych w {{provider}}, aby włączyć działania kart.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Aby obsługiwać działania kart, wklej ten adres URL w <console>konsoli deweloperskiej Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Zdarzenia i wywołania zwrotne → Konfiguracja wywołań zwrotnych → Adres URL żądania",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Aby obsługiwać działania kart, wklej ten adres URL w <console>konsoli deweloperskiej Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Zdarzenia i wywołania zwrotne → Konfiguracja wywołań zwrotnych → Adres URL żądania",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Aby obsługiwać działania kart, wklej ten adres URL w <console>konsoli deweloperskiej Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interaktywność i skróty → Interaktywność → Adres URL żądania",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Aby obsługiwać działania kart, wklej ten adres URL w <console>konfiguracji Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Ustawienia → Konfiguracja → Punkt końcowy wiadomości",
+ "imPlatform.bindingDialog.callbackStep": "Konfiguruj wywołania zwrotne",
"imPlatform.bindingDialog.clearSavedCredential": "Wyczyść zapisaną wartość",
+ "imPlatform.bindingDialog.configureTitle": "Skonfiguruj {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Połącz {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Ta zapisana wartość zostanie wyczyszczona podczas zapisywania.",
+ "imPlatform.bindingDialog.credentialsDescription": "Najpierw połącz aplikację {{provider}}, a następnie skonfiguruj jej adres URL wywołania zwrotnego.",
+ "imPlatform.bindingDialog.credentialsStep": "Dane uwierzytelniające aplikacji",
+ "imPlatform.bindingDialog.description": "Wprowadź dane uwierzytelniające aplikacji tego dostawcy komunikatora.",
+ "imPlatform.bindingDialog.field.agentId": "Identyfikator agenta",
+ "imPlatform.bindingDialog.field.appId": "Identyfikator aplikacji",
+ "imPlatform.bindingDialog.field.appToken": "Token aplikacji (opcjonalny)",
+ "imPlatform.bindingDialog.field.botToken": "Token bota",
+ "imPlatform.bindingDialog.field.clientId": "ID klienta",
+ "imPlatform.bindingDialog.field.clientSecret": "Tajny klucz klienta",
+ "imPlatform.bindingDialog.field.corpId": "Identyfikator firmy",
+ "imPlatform.bindingDialog.field.encryptKey": "Klucz szyfrowania (opcjonalny)",
+ "imPlatform.bindingDialog.field.genericSecret": "Tajny",
+ "imPlatform.bindingDialog.field.secret": "Sekret aplikacji",
+ "imPlatform.bindingDialog.field.signingSecret": "Sekret podpisywania",
+ "imPlatform.bindingDialog.field.tenantId": "Identyfikator dzierżawy",
+ "imPlatform.bindingDialog.field.verificationToken": "Token weryfikacyjny (opcjonalny)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Wprowadź klucz szyfrowania, jeśli jest włączony",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Wprowadź sekret aplikacji",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Wprowadź token weryfikacyjny, jeśli jest skonfigurowany",
+ "imPlatform.bindingDialog.finish": "Zakończ",
+ "imPlatform.bindingDialog.freshCredentials": "Nie można odzyskać zapisanych sekretów. Wprowadź ponownie wszystkie wymagane dane uwierzytelniające, aby przetestować lub zapisać tę konfigurację.",
+ "imPlatform.bindingDialog.openSetupGuide": "Otwórz instrukcję konfiguracji",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Zastąpić poświadczenia dzierżawy dla {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Te dane uwierzytelniające należą do innego dzierżawcy IM i nie można ich zapisać bezpośrednio. Zmiana dzierżawcy wymaga zastąpienia bieżącego kanału IM, co usuwa wszystkie automatyczne i ręczne powiązania IM. Po zastąpieniu ponownie zsynchronizuj kontakty.",
+ "imPlatform.bindingDialog.required": "To pole jest wymagane.",
+ "imPlatform.bindingDialog.saveAndContinue": "Zapisz i kontynuuj",
+ "imPlatform.bindingDialog.saveFailed": "Nie udało się zapisać konfiguracji. Sprawdź pola i spróbuj ponownie.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Konfiguracja została zapisana, ale nie udało się wczytać jej szczegółów. Zamknij to okno i otwórz je ponownie.",
- "imPlatform.bindingDialog.undoClearCredential": "Cofnij wyczyszczenie"
+ "imPlatform.bindingDialog.secretConfigured": "Sekret jest już skonfigurowany. Pozostaw to pole puste, aby go zachować.",
+ "imPlatform.bindingDialog.step": "Krok {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Test połączenia nie powiódł się. Sprawdź konfigurację i spróbuj ponownie.",
+ "imPlatform.bindingDialog.undoClearCredential": "Cofnij wyczyszczenie",
+ "imPlatform.bindingDialog.viewSetupGuide": "Wyświetl instrukcję konfiguracji",
+ "imPlatform.chooseProvider": "Wybierz kanał do połączenia",
+ "imPlatform.configurationUpdated": "Konfiguracja tego kanału uległa zmianie. Zamknij to okno i odśwież stronę przed ponowną próbą.",
+ "imPlatform.connectMore": "Połącz więcej kanałów",
+ "imPlatform.delete.confirm": "Usuń",
+ "imPlatform.delete.description": "Usunięcie tego kanału usuwa jego konfigurację. Wysyłanie powiadomień o zatwierdzeniach i synchronizacja katalogu korzystające z tego kanału zostaną zatrzymane.",
+ "imPlatform.delete.failed": "Nie udało się usunąć kanału. Nic się nie zmieniło; spróbuj ponownie.",
+ "imPlatform.delete.title": "Usunąć kanał {{provider}}?",
+ "imPlatform.description": "Połącz kanały firmowe, aby prośby o zatwierdzenie docierały do osób tam, gdzie pracują.",
+ "imPlatform.details.column.contact": "Kontakty",
+ "imPlatform.details.column.platform": "Platforma komunikatora",
+ "imPlatform.details.description": "Wyświetl wyniki ostatniej synchronizacji w trybie tylko do odczytu.",
+ "imPlatform.details.downloadFailed": "Nie udało się pobrać raportu. Spróbuj ponownie.",
+ "imPlatform.details.downloadReport": "Pobierz raport",
+ "imPlatform.details.downloadingReport": "Pobieranie raportu…",
+ "imPlatform.details.empty": "Brak wyników w tej kategorii.",
+ "imPlatform.details.filter.added": "Dodano",
+ "imPlatform.details.filter.failed": "Niepowodzenie",
+ "imPlatform.details.filter.not_matched": "Nie dopasowano",
+ "imPlatform.details.filter.removed": "Usunięto",
+ "imPlatform.details.filter.skipped": "Pominięto",
+ "imPlatform.details.filters": "Filtry wyników synchronizacji",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Nie udało się wczytać szczegółów synchronizacji.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Nie udało się wczytać kolejnych wyników. Ponów próbę wczytania tej strony.",
+ "imPlatform.details.removalReason.binding_invalidated": "Powiązanie unieważnione",
+ "imPlatform.details.removalReason.binding_replaced": "Powiązanie zastąpione",
+ "imPlatform.details.removalReason.not_present_in_directory": "Nie ma już w katalogu",
+ "imPlatform.details.reportChanged": "Wyniki synchronizacji uległy zmianie. Otwórz ponownie szczegóły ostatniej synchronizacji i spróbuj jeszcze raz.",
+ "imPlatform.details.title": "Szczegóły synchronizacji",
+ "imPlatform.email.apiKey": "Klucz API",
+ "imPlatform.email.apiKeyConfigured": "Ze względów bezpieczeństwa nie można wyświetlić zapisanego klucza API. Pozostaw to pole puste, aby go zachować.",
+ "imPlatform.email.apiKeyDescription": "Ze względów bezpieczeństwa nie można wyświetlić tego klucza API po zapisaniu.",
+ "imPlatform.email.apiKeyPlaceholder": "Wprowadź klucz API Resend",
+ "imPlatform.email.description": "Ta konfiguracja dotyczy wszystkich węzłów interwencji człowieka w tym obszarze roboczym z włączoną opcją <emphasis>Wysyłaj powiadomienia debugowania pocztą e-mail</emphasis>.",
+ "imPlatform.email.invalidEmail": "Wprowadź prawidłowy adres e-mail.",
+ "imPlatform.email.provider": "Dostawca poczty e-mail",
+ "imPlatform.email.resendDescription": "Twój <apiKey>klucz API Resend</apiKey> zostanie zaszyfrowany i nie będzie można go wyświetlić po zapisaniu.<br/>Zarejestruj konto <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Ustawienia Resend",
+ "imPlatform.email.senderEmail": "Adres e-mail nadawcy",
+ "imPlatform.email.senderEmailDescription": "Adres e-mail wyświetlany jako nadawca. Jego domena musi zostać zweryfikowana w Resend.",
+ "imPlatform.email.senderName": "Nazwa nadawcy",
+ "imPlatform.email.senderNameDescription": "Nazwa wyświetlana w skrzynce odbiorczej adresata.",
+ "imPlatform.email.testSucceeded": "Test połączenia zakończył się pomyślnie.",
+ "imPlatform.email.title": "Konfiguruj pocztę e-mail",
+ "imPlatform.learnMore": "Dowiedz się więcej",
+ "imPlatform.loadError.description": "Spróbuj ponownie odczytać bieżące powiązanie i uprawnienia.",
+ "imPlatform.loadError.retry": "Spróbuj ponownie",
+ "imPlatform.loadError.title": "Nie udało się wczytać kanałów",
+ "imPlatform.loading": "Wczytywanie kanałów",
+ "imPlatform.provider.dingtalkDescription": "Połącz aplikację DingTalk.",
+ "imPlatform.provider.emailDescription": "Skonfiguruj usługę poczty e-mail do wysyłania próśb o zatwierdzenie z tego obszaru roboczego.",
+ "imPlatform.provider.feishuDescription": "Połącz aplikację Feishu.",
+ "imPlatform.provider.larkDescription": "Połącz aplikację Lark.",
+ "imPlatform.provider.msTeamsDescription": "Połącz aplikację Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Synchronizuj osoby i ich tożsamości Slack.",
+ "imPlatform.provider.weComDescription": "Połącz aplikację WeCom.",
+ "imPlatform.replacement.confirm": "Zastępować",
+ "imPlatform.replacement.description": "Zastąpienie aktywnego dostawcy unieważnia jego powiązania komunikatora i nadpisania obszaru roboczego. Po zastąpieniu ponownie zsynchronizuj katalog nowego dostawcy.",
+ "imPlatform.replacement.title": "Zastąpić {{current}} przez {{next}}?",
+ "imPlatform.status.configured": "Skonfigurowano",
+ "imPlatform.status.connected": "Połączono",
+ "imPlatform.status.connection_error": "Błąd połączenia",
+ "imPlatform.status.permission_issue": "Problem z uprawnieniami",
+ "imPlatform.sync.latestSynced": "Ostatnia synchronizacja: {{date}}",
+ "imPlatform.sync.loading": "Sprawdzanie aktywnej synchronizacji.",
+ "imPlatform.sync.noPermission": "Tylko właściciele i administratorzy obszaru roboczego mogą uruchamiać synchronizację katalogu.",
+ "imPlatform.sync.noRuns": "Nie wykonano jeszcze synchronizacji katalogu.",
+ "imPlatform.sync.notConnected": "Połącz dostawcę i przetestuj połączenie przed rozpoczęciem synchronizacji katalogu.",
+ "imPlatform.sync.startFailed": "Nie udało się uruchomić lub odświeżyć synchronizacji katalogu. Spróbuj ponownie.",
+ "imPlatform.sync.status.failure": "Niepowodzenie",
+ "imPlatform.sync.status.queued": "W kolejce",
+ "imPlatform.sync.status.running": "W toku",
+ "imPlatform.sync.status.success": "Sukces",
+ "imPlatform.title": "Kanały"
}
diff --git a/web/i18n/locales/pl-PL/share.json b/web/i18n/locales/pl-PL/share.json
index 0d8b027f502..3997034b72b 100644
--- a/web/i18n/locales/pl-PL/share.json
+++ b/web/i18n/locales/pl-PL/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Dziękujemy!",
"humanInput.unavailableDescription": "Link może być niedostępny lub nie pasować do konta, na które jesteś zalogowany. Otwórz formularz z otrzymanego powiadomienia lub spróbuj zmienić konto.",
"humanInput.unavailableTitle": "Nie można otworzyć tego formularza",
+ "humanInputV2.accessRateLimited": "Zażądano zbyt wielu wiadomości weryfikacyjnych. Spróbuj ponownie później.",
+ "humanInputV2.alreadySubmitted": "Ta prośba została już zrealizowana.",
+ "humanInputV2.challengeExpired": "Ten kod weryfikacyjny wygasł. Poproś o nowy kod, aby kontynuować.",
+ "humanInputV2.challengeStale": "Ten kod weryfikacyjny został zastąpiony. Poproś o nowy kod, aby kontynuować.",
+ "humanInputV2.codeExpiresIn": "Kod wygaśnie za {{seconds}} s",
+ "humanInputV2.codeRequired": "Poproś o kod weryfikacyjny, aby kontynuować.",
+ "humanInputV2.codeSent": "Kod weryfikacyjny został wysłany na Twój adres e-mail.",
+ "humanInputV2.deliveryFailed": "Nie udało się wysłać wiadomości weryfikacyjnej. Spróbuj ponownie.",
+ "humanInputV2.formExpired": "Ta prośba wygasła.",
+ "humanInputV2.formNotFound": "Nie znaleziono formularza.",
+ "humanInputV2.formRateLimited": "Zbyt wiele żądań formularza. Spróbuj ponownie później.",
+ "humanInputV2.invalidOtp": "Kod weryfikacyjny jest nieprawidłowy. Sprawdź kod i spróbuj ponownie.",
+ "humanInputV2.networkError": "Nie udało się zrealizować żądania. Sprawdź połączenie i spróbuj ponownie.",
+ "humanInputV2.otpLabel": "Kod weryfikacyjny e-mail",
+ "humanInputV2.otpPlaceholder": "Wprowadź 6-cyfrowy kod",
+ "humanInputV2.requestingCode": "Wysyłanie kodu weryfikacyjnego…",
+ "humanInputV2.resendCode": "Wyślij kod ponownie",
+ "humanInputV2.retry": "Spróbuj ponownie",
+ "humanInputV2.sendCode": "Wyślij nowy kod",
+ "humanInputV2.unavailable": "Ten formularz jest tymczasowo niedostępny.",
+ "humanInputV2.unknownError": "Coś poszło nie tak. Spróbuj ponownie.",
+ "humanInputV2.uploadFailed": "Nie udało się przesłać pliku. Spróbuj ponownie.",
"login.backToHome": "Powrót do strony głównej"
}
diff --git a/web/i18n/locales/pl-PL/workflow-human-input.json b/web/i18n/locales/pl-PL/workflow-human-input.json
index ee05fd6be4b..332840c5f06 100644
--- a/web/i18n/locales/pl-PL/workflow-human-input.json
+++ b/web/i18n/locales/pl-PL/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Wartość akcji",
"nodes.humanInput.userActions.buttonTextTooLong": "Tekst przycisku musi mieć {{maxLength}} znaków lub mniej",
"nodes.humanInput.userActions.chooseStyle": "Wybierz styl przycisku",
+ "nodes.humanInput.userActions.defaultTitle": "Tekst przycisku {{index}}",
"nodes.humanInput.userActions.emptyTip": "Kliknij przycisk '+', aby dodać akcje użytkownika",
"nodes.humanInput.userActions.title": "Akcje użytkownika",
"nodes.humanInput.userActions.tooltip": "Zdefiniuj przyciski, które użytkownicy mogą klikać, aby odpowiedzieć na ten formularz. Identyfikator akcji kontroluje rozgałęzianie. Wartość akcji jest udostępniana w dalszej części jako wybrane wbudowane wyjście. Identyfikator akcji musi zaczynać się od litery lub podkreślenia, po którym następują litery, cyfry lub podkreślenia.",
diff --git a/web/i18n/locales/pl-PL/workflow.json b/web/i18n/locales/pl-PL/workflow.json
index 30c41416846..ee6b26e1958 100644
--- a/web/i18n/locales/pl-PL/workflow.json
+++ b/web/i18n/locales/pl-PL/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Wyjście",
"blocks.http-request": "Żądanie HTTP",
"blocks.human-input": "Dane wprowadzone przez człowieka",
+ "blocks.human-input-v2": "Dane wprowadzone przez człowieka v2",
"blocks.if-else": "JEŚLI/W PRZECIWNYM WYPADKU",
"blocks.iteration": "Iteracja",
"blocks.iteration-start": "Początek iteracji",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Zdefiniuj wyjście i typ wyniku przepływu pracy",
"blocksAbout.http-request": "Pozwala na wysyłanie żądań serwera za pomocą protokołu HTTP",
"blocksAbout.human-input": "Poproś o potwierdzenie przez człowieka przed wygenerowaniem kolejnego kroku",
+ "blocksAbout.human-input-v2": "Poproś skonfigurowane kontakty, odbiorców e-mail lub osobę uruchamiającą przepływ pracy o wprowadzenie danych",
"blocksAbout.if-else": "Pozwala na podział przepływu pracy na dwie gałęzie na podstawie warunków if/else",
"blocksAbout.iteration": "Wykonuj wielokrotne kroki na liście obiektów, aż wszystkie wyniki zostaną wypisane.",
"blocksAbout.iteration-start": "Węzeł początkowy iteracji",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Zbierz zmienne z wielu gałęzi do jednej zmiennej dla jednolitej konfiguracji węzłów końcowych.",
"blocksAbout.variable-assigner": "Zbierz zmienne z wielu gałęzi do jednej zmiennej dla jednolitej konfiguracji węzłów końcowych.",
"changeHistory.edgeDelete": "Węzeł rozłączony",
+ "changeHistory.humanInputMigration": "Przeniesiono węzły danych wprowadzanych przez człowieka",
"changeHistory.nodeAdd": "Węzeł dodany",
"changeHistory.nodeChange": "Węzeł zmieniony",
"changeHistory.nodeConnect": "Węzeł połączony",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Włącz co najmniej jedną metodę dostarczania",
"nodes.humanInput.errorMsg.noUserActions": "Dodaj co najmniej jedną akcję użytkownika",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} jest zarezerwowany dla gałęzi przekroczenia czasu. Wybierz inny identyfikator akcji.",
+ "nodes.humanInput.output.actionId": "ID akcji wywołanej przez użytkownika",
+ "nodes.humanInput.output.actionValue": "Wartość wybranej akcji",
+ "nodes.humanInput.output.formInput": "Wartość wprowadzona w formularzu",
+ "nodes.humanInput.output.renderedContent": "Wyrenderowana treść",
"nodes.humanInput.timeout.title": "Limit czasu",
+ "nodes.humanInputMigration.action.migrate": "Migruj",
+ "nodes.humanInputMigration.action.migrateNow": "Migruj teraz",
+ "nodes.humanInputMigration.action.migrating": "Trwa migracja...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Powiadomienie o migracji węzłów danych wprowadzanych przez człowieka",
+ "nodes.humanInputMigration.banner.description": "Ten przepływ pracy używa starego węzła danych wprowadzanych przez człowieka. Przed dodaniem nowych węzłów przeprowadź migrację wszystkich starych.",
+ "nodes.humanInputMigration.banner.learnMore": "Dowiedz się więcej",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "wyłączona metoda dostarczania nadal zawiera konfigurację",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "włączone metody e-mail używają sprzecznych szablonów",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Nieprawidłowa wartość domyślna",
+ "nodes.humanInputMigration.blocker.invalidEmail": "adres e-mail odbiorcy jest nieprawidłowy",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "włączona metoda e-mail jest niekompletna",
+ "nodes.humanInputMigration.blocker.missingRecipients": "węzeł nie ma obsługiwanych odbiorców",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "nie można powiązać członka obszaru roboczego z kontaktem ani zweryfikowanym adresem e-mail",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "włączona metoda dostarczania nie jest obsługiwana przez Human Input v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Pola {{field}} nie można jeszcze przenieść. Możesz nadal korzystać ze starszych węzłów wprowadzania danych przez człowieka.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "węzeł ma nieobsługiwaną wartość wersji",
+ "nodes.humanInputMigration.dialog.description": "Odbiorcy, formularz i akcje zostaną zachowane.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Zmieni się tylko ta wersja robocza. Opublikowane wersje będą działać do czasu ponownej publikacji.",
+ "nodes.humanInputMigration.dialog.review": "Sprawdź węzły i opublikuj, gdy wszystko będzie gotowe.",
+ "nodes.humanInputMigration.dialog.title": "Migruj {{count}} węzłów danych wprowadzanych przez człowieka",
+ "nodes.humanInputMigration.disabledBadge": "WYMAGANA MIGRACJA",
+ "nodes.humanInputMigration.disabledReason": "Przed dodaniem nowego węzła przeprowadź migrację starych węzłów danych wprowadzanych przez człowieka.",
+ "nodes.humanInputMigration.error.blocked": "Nie udało się przeprowadzić migracji {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Przepływ pracy zmienił się podczas migracji. Spróbuj ponownie; bieżące zmiany zostały zachowane.",
+ "nodes.humanInputMigration.error.preflight": "Nie udało się przygotować migracji. Przepływ pracy nie został zmieniony. Spróbuj ponownie.",
"nodes.humanInputMigration.error.sync": "Nie udało się zapisać zmigrowanego przepływu pracy. Sprawdź bieżący szkic i spróbuj ponownie.",
+ "nodes.humanInputMigration.incompatibleVersions": "Stare i nowe węzły interwencji człowieka nie mogą być używane w tym samym przepływie pracy.",
+ "nodes.humanInputMigration.oldVersion": "STARA WERSJA",
+ "nodes.humanInputMigration.preview.author": "Autor: zespół Dify",
+ "nodes.humanInputMigration.preview.description": "Przed dodaniem nowego węzła przeprowadź migrację starych węzłów danych wprowadzanych przez człowieka.",
+ "nodes.humanInputMigration.success": "Migracja węzłów danych wprowadzanych przez człowieka zakończyła się pomyślnie",
+ "nodes.humanInputV2.card.configured": "Skonfigurowani odbiorcy: {{count}}",
+ "nodes.humanInputV2.card.contactsOnly": "Kontakty: {{count}}",
+ "nodes.humanInputV2.card.empty": "Nikt nie może jeszcze zatwierdzić tego kroku",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Osoba uruchamiająca i kontakty: {{count}}",
+ "nodes.humanInputV2.card.initiatorOnly": "Tylko osoba uruchamiająca",
+ "nodes.humanInputV2.card.invalid": "Konfiguracja odbiorców wymaga uwagi",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-mail",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Skonfiguruj tryb debugowania",
"nodes.humanInputV2.debug.keepOneChannel": "Pozostaw włączony co najmniej jeden kanał",
+ "nodes.humanInputV2.debug.sendVia": "Wysyłaj powiadomienia debugowania przez",
+ "nodes.humanInputV2.debug.title": "Tryb debugowania",
+ "nodes.humanInputV2.debug.toggle": "Włącz tryb debugowania",
+ "nodes.humanInputV2.debug.unsupported": "Nieobsługiwane zaimportowane kanały: {{channels}}. Usuń je lub zaktualizuj przed uruchomieniem tego przepływu pracy.",
"nodes.humanInputV2.disabled": "Human Input v2 jest niedostępny, gdy HITL IM jest wyłączony.",
+ "nodes.humanInputV2.error.bodyRequired": "Treść wiadomości jest wymagana",
+ "nodes.humanInputV2.error.debugChannelRequired": "Wybierz co najmniej jeden kanał trybu debugowania",
+ "nodes.humanInputV2.error.recipientDuplicate": "Usuń zduplikowanych odbiorców",
+ "nodes.humanInputV2.error.recipientInvalid": "Popraw nieprawidłową konfigurację odbiorców",
+ "nodes.humanInputV2.error.recipientRequired": "Dodaj co najmniej jednego odbiorcę",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Nie udało się zweryfikować odbiorców z kontaktów",
"nodes.humanInputV2.error.requestURLDuplicate": "Treść wiadomości może zawierać tylko jeden adres URL wniosku.",
"nodes.humanInputV2.error.requestURLRequired": "Wstaw adres URL wniosku w treści wiadomości.",
+ "nodes.humanInputV2.error.subjectRequired": "Temat wiadomości jest wymagany",
+ "nodes.humanInputV2.error.version": "Human Input v2 wymaga wartości wersji 2 w postaci ciągu znaków",
+ "nodes.humanInputV2.recipients.addContact": "Dodaj kontakt",
+ "nodes.humanInputV2.recipients.addEmail": "Dodaj",
+ "nodes.humanInputV2.recipients.addRecipient": "Dodaj odbiorcę",
+ "nodes.humanInputV2.recipients.added": "Dodano",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Wszystkie kontakty w obszarze roboczym",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Powiadom wszystkie kontakty w obszarze roboczym; każdy z nich może zatwierdzić",
+ "nodes.humanInputV2.recipients.cancel": "Anuluj",
+ "nodes.humanInputV2.recipients.chooseVariable": "Wybierz zmienną",
+ "nodes.humanInputV2.recipients.confirm": "Potwierdź",
+ "nodes.humanInputV2.recipients.contactInfo": "Dane kontaktowe: {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Wszystkie",
+ "nodes.humanInputV2.recipients.contactSource.external": "Zewnętrzne",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organizacja",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Obszar roboczy",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Źródło kontaktu",
"nodes.humanInputV2.recipients.duplicateSource": "Dodano już przez {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Edytuj {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Edytuj odbiorcę",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Każdy adres e-mail można wybrać tylko raz.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Wprowadź prawidłowy adres e-mail, który nie został jeszcze dodany",
+ "nodes.humanInputV2.recipients.emailLabel": "Jednorazowy odbiorca e-mail",
+ "nodes.humanInputV2.recipients.empty": "Brak skonfigurowanych odbiorców",
+ "nodes.humanInputV2.recipients.help": "Wybierz, kto może odpowiedzieć w tym kroku danych wprowadzanych przez człowieka.",
"nodes.humanInputV2.recipients.initiator": "Użytkownik, który uruchomi to wykonanie przez Web App lub CLI, może je zatwierdzić",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Osoba rozpoczynająca to uruchomienie przepływu pracy może odpowiedzieć.",
"nodes.humanInputV2.recipients.inputHelp": "Wpisz lub wklej wiele adresów e-mail oddzielonych przecinkami. Naciśnij /, aby wstawić zmienną.",
+ "nodes.humanInputV2.recipients.insertVariable": "Wstaw zmienną",
+ "nodes.humanInputV2.recipients.loadError": "Nie udało się wczytać kontaktów. Zapisane identyfikatory kontaktów zostały zachowane.",
+ "nodes.humanInputV2.recipients.loading": "Wczytywanie kontaktów…",
+ "nodes.humanInputV2.recipients.noResults": "Nie znaleziono kontaktów",
+ "nodes.humanInputV2.recipients.placeholder": "Szukaj kontaktów lub dodaj adresy e-mail",
+ "nodes.humanInputV2.recipients.remove": "Usuń {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Naciśnij Backspace lub Delete, aby usunąć.",
+ "nodes.humanInputV2.recipients.resultCount": "Pasujący odbiorcy: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Szukaj kontaktów",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Szukaj według nazwy lub adresu e-mail",
+ "nodes.humanInputV2.recipients.selectionHint": "Wybrani odbiorcy: {{count}}. Na początku pola naciśnij strzałkę w lewo, aby przenieść na nich fokus.",
+ "nodes.humanInputV2.recipients.title": "Odbiorcy",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Wszystkie kontakty w obszarze roboczym",
+ "nodes.humanInputV2.recipients.type.contact": "Kontakt",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Dynamiczny e-mail",
+ "nodes.humanInputV2.recipients.type.initiator": "Osoba uruchamiająca",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Jednorazowy e-mail",
+ "nodes.humanInputV2.recipients.typeLabel": "Typ odbiorcy",
"nodes.humanInputV2.recipients.useThisInstead": "Użyj tego zamiast",
+ "nodes.humanInputV2.recipients.variableRequired": "Wybierz zmienną adresu e-mail",
+ "nodes.humanInputV2.template.body": "Treść",
+ "nodes.humanInputV2.template.description": "Tekst zastępczy dla e-maili i wiadomości błyskawicznych",
"nodes.humanInputV2.template.insertRequestURL": "Wstaw adres URL wniosku",
+ "nodes.humanInputV2.template.insertVariable": "Wstaw zmienną",
+ "nodes.humanInputV2.template.notConfigured": "Nie skonfigurowano",
"nodes.humanInputV2.template.requestURLHint": "Odbiorcy otwierają formularz zatwierdzenia za pomocą tego linku. Dodaj dokładnie jeden adres URL wniosku.",
"nodes.humanInputV2.template.requestURLInserted": "Adres URL wniosku wstawiony",
"nodes.humanInputV2.template.saveAndTest": "Zapisz i przetestuj",
+ "nodes.humanInputV2.template.subject": "Temat",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Wprowadź temat wiadomości",
"nodes.humanInputV2.template.test": "Testuj wiadomość",
"nodes.humanInputV2.template.testChannel": "Kanał testowy",
"nodes.humanInputV2.template.testCompleted": "Żądanie testowe zostało ukończone. Sprawdź wiadomość w wybranym kanale.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Wprowadź wartości wszystkich zmiennych testowych.",
"nodes.humanInputV2.template.testSaveFailed": "Nie udało się zapisać wersji roboczej przepływu pracy. Test nie został wysłany.",
"nodes.humanInputV2.template.testUnavailable": "To środowisko nie obsługuje jeszcze testowania szablonów wiadomości.",
+ "nodes.humanInputV2.template.title": "Szablon wiadomości",
"nodes.ifElse.operator": "Operator",
"nodes.iteration.currentIteration": "Bieżąca iteracja",
"nodes.iteration.deleteDesc": "Usunięcie węzła iteracji usunie wszystkie węzły potomne",
diff --git a/web/i18n/locales/pt-BR/contacts.json b/web/i18n/locales/pt-BR/contacts.json
index 5c326c6e5f9..b1a92e3693c 100644
--- a/web/i18n/locales/pt-BR/contacts.json
+++ b/web/i18n/locales/pt-BR/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Remover contatos ({{count}})?",
"directory.removalDescription": "Os contatos selecionados serão removidos permanentemente deste espaço de trabalho. Esta ação não pode ser desfeita.",
- "directory.removalTitle": "Remover contatos?",
+ "directory.removalSingleDescription": "{{name}} será removido permanentemente deste espaço de trabalho. Esta ação não pode ser desfeita.",
+ "directory.removalSingleFailed": "Não foi possível remover o contato. Tente novamente.",
+ "directory.removalSingleTitle": "Remover {{name}}?",
+ "directory.resultCount": "Resultados: {{count}}",
+ "imPlatform.action.configure": "Configurar",
+ "imPlatform.action.configureChannel": "Configurar {{provider}}",
+ "imPlatform.action.connect": "Conectar",
+ "imPlatform.action.copied": "Copiado",
+ "imPlatform.action.copyCallback": "Copiar URL de retorno",
+ "imPlatform.action.deleteChannel": "Excluir {{provider}}",
+ "imPlatform.action.loadMore": "Carregar mais",
+ "imPlatform.action.replace": "Substituir",
+ "imPlatform.action.retry": "Repetir",
+ "imPlatform.action.save": "Salvar",
+ "imPlatform.action.saving": "Salvando",
+ "imPlatform.action.setupGuide": "Guia de configuração",
+ "imPlatform.action.syncNow": "Sincronize agora",
+ "imPlatform.action.syncing": "Sincronizando",
+ "imPlatform.action.testConnection": "Testar conexão",
+ "imPlatform.action.testing": "Testando",
+ "imPlatform.action.viewDetails": "Ver detalhes",
+ "imPlatform.bindingDialog.back": "Voltar",
+ "imPlatform.bindingDialog.callback": "URL de Retorno de Chamada",
+ "imPlatform.bindingDialog.callbackDescription": "Conclua a configuração de retornos em {{provider}} para habilitar as ações dos cartões.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Para as ações dos cartões, cole esta URL no <console>Console de Desenvolvedores do Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Eventos e retornos → Configuração de retornos → URL da solicitação",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Para as ações dos cartões, cole esta URL no <console>Console de Desenvolvedores do Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Eventos e retornos → Configuração de retornos → URL da solicitação",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Para as ações dos cartões, cole esta URL no <console>Console de Desenvolvedores do Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interatividade e atalhos → Interatividade → URL da solicitação",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Para as ações dos cartões, cole esta URL na <console>configuração do Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Configurações → Configuração → Ponto de extremidade de mensagens",
+ "imPlatform.bindingDialog.callbackStep": "Configurar retornos",
"imPlatform.bindingDialog.clearSavedCredential": "Limpar valor salvo",
+ "imPlatform.bindingDialog.configureTitle": "Configurar {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Conectar {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Este valor salvo será apagado ao salvar.",
+ "imPlatform.bindingDialog.credentialsDescription": "Primeiro conecte seu aplicativo {{provider}} e depois configure a URL de retorno.",
+ "imPlatform.bindingDialog.credentialsStep": "Credenciais do aplicativo",
+ "imPlatform.bindingDialog.description": "Insira as credenciais do aplicativo deste provedor de mensagens instantâneas.",
+ "imPlatform.bindingDialog.field.agentId": "ID do agente",
+ "imPlatform.bindingDialog.field.appId": "ID do aplicativo",
+ "imPlatform.bindingDialog.field.appToken": "Token do aplicativo (opcional)",
+ "imPlatform.bindingDialog.field.botToken": "Token do bot",
+ "imPlatform.bindingDialog.field.clientId": "ID do Cliente",
+ "imPlatform.bindingDialog.field.clientSecret": "Segredo do Cliente",
+ "imPlatform.bindingDialog.field.corpId": "ID da empresa",
+ "imPlatform.bindingDialog.field.encryptKey": "Chave de criptografia (opcional)",
+ "imPlatform.bindingDialog.field.genericSecret": "Secreto",
+ "imPlatform.bindingDialog.field.secret": "Segredo do aplicativo",
+ "imPlatform.bindingDialog.field.signingSecret": "Segredo de assinatura",
+ "imPlatform.bindingDialog.field.tenantId": "ID do locatário",
+ "imPlatform.bindingDialog.field.verificationToken": "Token de verificação (opcional)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Insira a chave de criptografia, se estiver habilitada",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Insira o segredo do aplicativo",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Insira o token de verificação, se estiver configurado",
+ "imPlatform.bindingDialog.finish": "Concluir",
+ "imPlatform.bindingDialog.freshCredentials": "Não é possível recuperar os segredos salvos. Insira novamente todas as credenciais necessárias para testar ou salvar esta configuração.",
+ "imPlatform.bindingDialog.openSetupGuide": "Abrir guia de configuração",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Substituir as credenciais do locatário de {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Estas credenciais pertencem a outro locatário de IM e não podem ser salvas diretamente. Para mudar de locatário, é necessário substituir o canal de IM atual, o que remove todos os vínculos de IM automáticos e manuais. Sincronize os contatos novamente após a substituição.",
+ "imPlatform.bindingDialog.required": "Este campo é obrigatório.",
+ "imPlatform.bindingDialog.saveAndContinue": "Salvar e continuar",
+ "imPlatform.bindingDialog.saveFailed": "Não foi possível salvar a configuração. Verifique os campos e tente novamente.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "A configuração foi salva, mas não foi possível carregar seus detalhes. Feche esta janela e abra-a novamente.",
- "imPlatform.bindingDialog.undoClearCredential": "Desfazer limpeza"
+ "imPlatform.bindingDialog.secretConfigured": "Um segredo já está configurado. Deixe este campo em branco para mantê-lo.",
+ "imPlatform.bindingDialog.step": "Etapa {{step}}",
+ "imPlatform.bindingDialog.testFailed": "O teste de conexão falhou. Verifique a configuração e tente novamente.",
+ "imPlatform.bindingDialog.undoClearCredential": "Desfazer limpeza",
+ "imPlatform.bindingDialog.viewSetupGuide": "Ver guia de configuração",
+ "imPlatform.chooseProvider": "Escolha um canal para conectar",
+ "imPlatform.configurationUpdated": "A configuração deste canal foi alterada. Feche esta caixa de diálogo e atualize a página antes de tentar novamente.",
+ "imPlatform.connectMore": "Conectar mais canais",
+ "imPlatform.delete.confirm": "Excluir",
+ "imPlatform.delete.description": "Excluir este canal remove sua configuração. O envio de notificações de aprovação e a sincronização de diretório que utilizam este canal serão interrompidos.",
+ "imPlatform.delete.failed": "Não foi possível excluir o canal. Nada foi alterado; tente novamente.",
+ "imPlatform.delete.title": "Excluir o canal {{provider}}?",
+ "imPlatform.description": "Conecte os canais da sua empresa para que as solicitações de aprovação cheguem às pessoas onde elas trabalham.",
+ "imPlatform.details.column.contact": "Contatos",
+ "imPlatform.details.column.platform": "Plataforma de mensagens instantâneas",
+ "imPlatform.details.description": "Veja os resultados somente leitura da sincronização mais recente.",
+ "imPlatform.details.downloadFailed": "Não foi possível baixar o relatório. Tente novamente.",
+ "imPlatform.details.downloadReport": "Baixar relatório",
+ "imPlatform.details.downloadingReport": "Baixando relatório…",
+ "imPlatform.details.empty": "Nenhum resultado nesta categoria.",
+ "imPlatform.details.filter.added": "Adicionado",
+ "imPlatform.details.filter.failed": "Falhou",
+ "imPlatform.details.filter.not_matched": "Sem correspondência",
+ "imPlatform.details.filter.removed": "Removido",
+ "imPlatform.details.filter.skipped": "Ignorado",
+ "imPlatform.details.filters": "Filtros dos resultados de sincronização",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Não foi possível carregar os detalhes da sincronização.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Não foi possível carregar mais resultados. Tente carregar esta página novamente.",
+ "imPlatform.details.removalReason.binding_invalidated": "Vínculo invalidado",
+ "imPlatform.details.removalReason.binding_replaced": "Vínculo substituído",
+ "imPlatform.details.removalReason.not_present_in_directory": "Não consta mais no diretório",
+ "imPlatform.details.reportChanged": "Os resultados da sincronização foram alterados. Reabra os detalhes da sincronização mais recente e tente novamente.",
+ "imPlatform.details.title": "Detalhes da sincronização",
+ "imPlatform.email.apiKey": "Chave de API",
+ "imPlatform.email.apiKeyConfigured": "Por motivos de segurança, não é possível visualizar a chave de API salva. Deixe este campo em branco para mantê-la.",
+ "imPlatform.email.apiKeyDescription": "Por motivos de segurança, esta chave de API não pode ser visualizada depois de salva.",
+ "imPlatform.email.apiKeyPlaceholder": "Insira sua chave de API do Resend",
+ "imPlatform.email.description": "Esta configuração se aplica a todos os nós de intervenção humana deste espaço de trabalho com a opção <emphasis>Enviar notificações de depuração por e-mail</emphasis> habilitada.",
+ "imPlatform.email.invalidEmail": "Insira um endereço de e-mail válido.",
+ "imPlatform.email.provider": "Provedor de e-mail",
+ "imPlatform.email.resendDescription": "Sua <apiKey>chave de API do Resend</apiKey> será criptografada e não poderá ser visualizada depois de salva.<br/>Crie uma conta no <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Configurações do Resend",
+ "imPlatform.email.senderEmail": "Endereço de e-mail do remetente",
+ "imPlatform.email.senderEmailDescription": "O endereço de e-mail exibido como remetente. Seu domínio deve ser verificado no Resend.",
+ "imPlatform.email.senderName": "Nome do remetente",
+ "imPlatform.email.senderNameDescription": "Nome exibido na caixa de entrada do destinatário.",
+ "imPlatform.email.testSucceeded": "Teste de conexão concluído com sucesso.",
+ "imPlatform.email.title": "Configurar e-mail",
+ "imPlatform.learnMore": "Saiba mais",
+ "imPlatform.loadError.description": "Tente novamente para consultar a vinculação atual e as permissões.",
+ "imPlatform.loadError.retry": "Tentar novamente",
+ "imPlatform.loadError.title": "Não foi possível carregar os canais",
+ "imPlatform.loading": "Carregando canais",
+ "imPlatform.provider.dingtalkDescription": "Conecte um aplicativo DingTalk.",
+ "imPlatform.provider.emailDescription": "Configure o serviço de e-mail usado para enviar solicitações de aprovação deste espaço de trabalho.",
+ "imPlatform.provider.feishuDescription": "Conecte um aplicativo Feishu.",
+ "imPlatform.provider.larkDescription": "Conecte um aplicativo Lark.",
+ "imPlatform.provider.msTeamsDescription": "Conecte um aplicativo Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Sincronize as pessoas e suas identidades do Slack.",
+ "imPlatform.provider.weComDescription": "Conecte um aplicativo WeCom.",
+ "imPlatform.replacement.confirm": "Substituir",
+ "imPlatform.replacement.description": "Substituir o provedor ativo invalida suas vinculações de mensagens instantâneas e as personalizações do espaço de trabalho. Após a substituição, sincronize novamente o diretório do novo provedor.",
+ "imPlatform.replacement.title": "Substituir {{current}} por {{next}}?",
+ "imPlatform.status.configured": "Configurado",
+ "imPlatform.status.connected": "Conectado",
+ "imPlatform.status.connection_error": "Erro de conexão",
+ "imPlatform.status.permission_issue": "Problema de permissão",
+ "imPlatform.sync.latestSynced": "Última sincronização: {{date}}",
+ "imPlatform.sync.loading": "Verificando se há uma sincronização ativa.",
+ "imPlatform.sync.noPermission": "Somente proprietários e administradores do espaço de trabalho podem iniciar a sincronização do diretório.",
+ "imPlatform.sync.noRuns": "Nenhuma sincronização de diretório foi executada ainda.",
+ "imPlatform.sync.notConnected": "Conecte um provedor e teste a conexão antes de iniciar a sincronização do diretório.",
+ "imPlatform.sync.startFailed": "Não foi possível iniciar ou atualizar a sincronização do diretório. Tente novamente.",
+ "imPlatform.sync.status.failure": "Falhou",
+ "imPlatform.sync.status.queued": "Na fila",
+ "imPlatform.sync.status.running": "Em execução",
+ "imPlatform.sync.status.success": "Sucesso",
+ "imPlatform.title": "Canais"
}
diff --git a/web/i18n/locales/pt-BR/share.json b/web/i18n/locales/pt-BR/share.json
index df93b43c014..a181e630983 100644
--- a/web/i18n/locales/pt-BR/share.json
+++ b/web/i18n/locales/pt-BR/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Obrigado!",
"humanInput.unavailableDescription": "O link pode estar indisponível ou não corresponder à conta com a qual você está conectado. Abra o formulário pela notificação que recebeu ou tente mudar de conta.",
"humanInput.unavailableTitle": "Não foi possível abrir este formulário",
+ "humanInputV2.accessRateLimited": "Foram solicitados muitos e-mails de verificação. Tente novamente mais tarde.",
+ "humanInputV2.alreadySubmitted": "Esta solicitação já foi concluída.",
+ "humanInputV2.challengeExpired": "Este código de verificação expirou. Solicite um novo código para continuar.",
+ "humanInputV2.challengeStale": "Este código de verificação foi substituído. Solicite um novo código para continuar.",
+ "humanInputV2.codeExpiresIn": "O código expira em {{seconds}} s",
+ "humanInputV2.codeRequired": "Solicite um código de verificação para continuar.",
+ "humanInputV2.codeSent": "Um código de verificação foi enviado para seu e-mail.",
+ "humanInputV2.deliveryFailed": "Não foi possível enviar o e-mail de verificação. Tente novamente.",
+ "humanInputV2.formExpired": "Esta solicitação expirou.",
+ "humanInputV2.formNotFound": "Formulário não encontrado.",
+ "humanInputV2.formRateLimited": "Muitas solicitações de formulário. Tente novamente mais tarde.",
+ "humanInputV2.invalidOtp": "O código de verificação está incorreto. Confira o código e tente novamente.",
+ "humanInputV2.networkError": "Não foi possível concluir a solicitação. Verifique sua conexão e tente novamente.",
+ "humanInputV2.otpLabel": "Código de verificação por e-mail",
+ "humanInputV2.otpPlaceholder": "Insira o código de 6 dígitos",
+ "humanInputV2.requestingCode": "Enviando um código de verificação…",
+ "humanInputV2.resendCode": "Reenviar código",
+ "humanInputV2.retry": "Tentar novamente",
+ "humanInputV2.sendCode": "Enviar um novo código",
+ "humanInputV2.unavailable": "Este formulário está temporariamente indisponível.",
+ "humanInputV2.unknownError": "Algo deu errado. Tente novamente.",
+ "humanInputV2.uploadFailed": "Não foi possível enviar o arquivo. Tente novamente.",
"login.backToHome": "Voltar para a página inicial"
}
diff --git a/web/i18n/locales/pt-BR/workflow-human-input.json b/web/i18n/locales/pt-BR/workflow-human-input.json
index 16272113f93..5b7c0f3791a 100644
--- a/web/i18n/locales/pt-BR/workflow-human-input.json
+++ b/web/i18n/locales/pt-BR/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Valor da Ação",
"nodes.humanInput.userActions.buttonTextTooLong": "O texto do botão deve ter {{maxLength}} caracteres ou menos",
"nodes.humanInput.userActions.chooseStyle": "Escolha um estilo de botão",
+ "nodes.humanInput.userActions.defaultTitle": "Texto do botão {{index}}",
"nodes.humanInput.userActions.emptyTip": "Clique no botão '+' para adicionar ações do usuário",
"nodes.humanInput.userActions.title": "Ações do Usuário",
"nodes.humanInput.userActions.tooltip": "Defina botões em que os usuários podem clicar para responder a este formulário. O ID da ação controla a ramificação. O Valor da Ação é exposto posteriormente como a saída integrada selecionada. O ID da ação deve começar com uma letra ou sublinhados, seguido de letras, números ou sublinhados.",
diff --git a/web/i18n/locales/pt-BR/workflow.json b/web/i18n/locales/pt-BR/workflow.json
index 304fa472599..5958b92c5de 100644
--- a/web/i18n/locales/pt-BR/workflow.json
+++ b/web/i18n/locales/pt-BR/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Saída",
"blocks.http-request": "Requisição HTTP",
"blocks.human-input": "Entrada Humana",
+ "blocks.human-input-v2": "Entrada Humana v2",
"blocks.if-else": "SE/SENÃO",
"blocks.iteration": "Iteração",
"blocks.iteration-start": "Início de iteração",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Definir a saída e o tipo de resultado de um fluxo de trabalho",
"blocksAbout.http-request": "Permitir que solicitações de servidor sejam enviadas pelo protocolo HTTP",
"blocksAbout.human-input": "Solicitar confirmação humana antes de gerar a próxima etapa",
+ "blocksAbout.human-input-v2": "Solicite dados aos contatos configurados, destinatários de e-mail ou à pessoa que iniciou o fluxo de trabalho",
"blocksAbout.if-else": "Permite dividir o fluxo de trabalho em dois ramos com base nas condições if/else",
"blocksAbout.iteration": "Execute múltiplos passos em um objeto lista até que todos os resultados sejam produzidos.",
"blocksAbout.iteration-start": "Nó de Início da Iteração",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Agregue variáveis de vários ramos em uma única variável para configuração unificada dos nós finais.",
"blocksAbout.variable-assigner": "Agregue variáveis de vários ramos em uma única variável para configuração unificada dos nós finais.",
"changeHistory.edgeDelete": "Nó desconectado",
+ "changeHistory.humanInputMigration": "Nós de Entrada Humana migrados",
"changeHistory.nodeAdd": "Nó adicionado",
"changeHistory.nodeChange": "Nó alterado",
"changeHistory.nodeConnect": "Nó conectado",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Ative pelo menos um método de entrega",
"nodes.humanInput.errorMsg.noUserActions": "Adicione pelo menos uma ação do usuário",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} está reservado para o ramo de tempo limite. Escolha outro ID de ação.",
+ "nodes.humanInput.output.actionId": "ID da ação acionada pelo usuário",
+ "nodes.humanInput.output.actionValue": "Valor da ação selecionada",
+ "nodes.humanInput.output.formInput": "Valor inserido no formulário",
+ "nodes.humanInput.output.renderedContent": "Conteúdo renderizado",
"nodes.humanInput.timeout.title": "Tempo Limite",
+ "nodes.humanInputMigration.action.migrate": "Migrar",
+ "nodes.humanInputMigration.action.migrateNow": "Migrar agora",
+ "nodes.humanInputMigration.action.migrating": "Migrando...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Aviso de migração de Entrada Humana",
+ "nodes.humanInputMigration.banner.description": "Este fluxo de trabalho usa o nó antigo de Entrada Humana. Migre todos os nós antigos antes de adicionar novos.",
+ "nodes.humanInputMigration.banner.learnMore": "Saiba mais",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "um método de entrega desativado ainda contém configurações",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "os métodos de e-mail ativados usam modelos conflitantes",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Valor padrão inválido",
+ "nodes.humanInputMigration.blocker.invalidEmail": "o e-mail de um destinatário é inválido",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "um método de e-mail ativado está incompleto",
+ "nodes.humanInputMigration.blocker.missingRecipients": "o nó não tem destinatários compatíveis",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "não é possível associar um membro do espaço de trabalho a um contato ou e-mail verificado",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "um método de entrega ativado não é compatível com Human Input v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "O campo {{field}} ainda não pode ser migrado. Você pode continuar usando os nós antigos de entrada humana.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "o nó tem um valor de versão não compatível",
+ "nodes.humanInputMigration.dialog.description": "Seus destinatários, formulário e ações serão mantidos.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Apenas este rascunho será alterado. As versões publicadas continuarão funcionando até que você publique novamente.",
+ "nodes.humanInputMigration.dialog.review": "Revise os nós e publique quando estiver tudo pronto.",
+ "nodes.humanInputMigration.dialog.title": "Migrar {{count}} nós de Entrada Humana",
+ "nodes.humanInputMigration.disabledBadge": "MIGRAÇÃO NECESSÁRIA",
+ "nodes.humanInputMigration.disabledReason": "Migre os nós antigos de Entrada Humana antes de adicionar um novo.",
+ "nodes.humanInputMigration.error.blocked": "Não foi possível migrar {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "O fluxo de trabalho mudou durante a migração. Tente novamente; suas edições atuais foram mantidas.",
+ "nodes.humanInputMigration.error.preflight": "Não foi possível preparar a migração. Seu fluxo de trabalho não foi alterado. Tente novamente.",
"nodes.humanInputMigration.error.sync": "Não foi possível salvar o fluxo de trabalho migrado. Revise o rascunho atual e tente novamente.",
+ "nodes.humanInputMigration.incompatibleVersions": "Nós antigos e novos de entrada humana não podem ser usados no mesmo fluxo de trabalho.",
+ "nodes.humanInputMigration.oldVersion": "VERSÃO ANTIGA",
+ "nodes.humanInputMigration.preview.author": "Pela equipe Dify",
+ "nodes.humanInputMigration.preview.description": "Migre os nós antigos de Entrada Humana antes de adicionar um novo.",
+ "nodes.humanInputMigration.success": "Nós de Entrada Humana migrados com sucesso",
+ "nodes.humanInputV2.card.configured": "{{count}} destinatários configurados",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} contatos",
+ "nodes.humanInputV2.card.empty": "Ninguém pode aprovar esta etapa ainda",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Iniciador e {{count}} contatos",
+ "nodes.humanInputV2.card.initiatorOnly": "Apenas o iniciador",
+ "nodes.humanInputV2.card.invalid": "A configuração de destinatários precisa de atenção",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-mail",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Configurar o modo de depuração",
"nodes.humanInputV2.debug.keepOneChannel": "Mantenha pelo menos um canal ativado",
+ "nodes.humanInputV2.debug.sendVia": "Enviar notificações de depuração por",
+ "nodes.humanInputV2.debug.title": "Modo de depuração",
+ "nodes.humanInputV2.debug.toggle": "Ativar o modo de depuração",
+ "nodes.humanInputV2.debug.unsupported": "Canais importados não compatíveis: {{channels}}. Remova ou atualize esses canais antes de executar este fluxo de trabalho.",
"nodes.humanInputV2.disabled": "Human Input v2 fica indisponível enquanto o HITL IM estiver desativado.",
+ "nodes.humanInputV2.error.bodyRequired": "O corpo da mensagem é obrigatório",
+ "nodes.humanInputV2.error.debugChannelRequired": "Selecione pelo menos um canal do modo de depuração",
+ "nodes.humanInputV2.error.recipientDuplicate": "Remova os destinatários duplicados",
+ "nodes.humanInputV2.error.recipientInvalid": "Corrija a configuração inválida dos destinatários",
+ "nodes.humanInputV2.error.recipientRequired": "Adicione pelo menos um destinatário",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Não foi possível verificar os destinatários dos contatos",
"nodes.humanInputV2.error.requestURLDuplicate": "O corpo da mensagem pode conter apenas uma URL de solicitação.",
"nodes.humanInputV2.error.requestURLRequired": "Insira uma URL de solicitação no corpo da mensagem.",
+ "nodes.humanInputV2.error.subjectRequired": "O assunto da mensagem é obrigatório",
+ "nodes.humanInputV2.error.version": "Human Input v2 exige o valor de versão 2 como string",
+ "nodes.humanInputV2.recipients.addContact": "Adicionar contato",
+ "nodes.humanInputV2.recipients.addEmail": "Adicionar",
+ "nodes.humanInputV2.recipients.addRecipient": "Adicionar destinatário",
+ "nodes.humanInputV2.recipients.added": "Adicionado",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Todos os contatos do espaço de trabalho",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Notifique todos os contatos do espaço de trabalho; qualquer um deles pode aprovar",
+ "nodes.humanInputV2.recipients.cancel": "Cancelar",
+ "nodes.humanInputV2.recipients.chooseVariable": "Escolher variável",
+ "nodes.humanInputV2.recipients.confirm": "Confirmar",
+ "nodes.humanInputV2.recipients.contactInfo": "Detalhes do contato de {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Todos",
+ "nodes.humanInputV2.recipients.contactSource.external": "Externo",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organização",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Espaço de trabalho",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Origem do contato",
"nodes.humanInputV2.recipients.duplicateSource": "Já adicionado por meio de {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Editar {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Editar destinatário",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Cada endereço de e-mail só pode ser selecionado uma vez.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Insira um e-mail válido que ainda não tenha sido adicionado",
+ "nodes.humanInputV2.recipients.emailLabel": "Destinatário de e-mail avulso",
+ "nodes.humanInputV2.recipients.empty": "Nenhum destinatário configurado",
+ "nodes.humanInputV2.recipients.help": "Escolha quem pode responder a esta etapa de Entrada Humana.",
"nodes.humanInputV2.recipients.initiator": "O usuário que inicia esta execução pelo Web App ou CLI pode aprovar",
+ "nodes.humanInputV2.recipients.initiatorDescription": "A pessoa que inicia esta execução do fluxo de trabalho pode responder.",
"nodes.humanInputV2.recipients.inputHelp": "Digite ou cole vários endereços de e-mail separados por vírgulas. Pressione / para inserir uma variável.",
+ "nodes.humanInputV2.recipients.insertVariable": "Inserir variável",
+ "nodes.humanInputV2.recipients.loadError": "Não foi possível carregar os contatos. Os IDs de contato armazenados foram preservados.",
+ "nodes.humanInputV2.recipients.loading": "Carregando contatos…",
+ "nodes.humanInputV2.recipients.noResults": "Nenhum contato encontrado",
+ "nodes.humanInputV2.recipients.placeholder": "Pesquisar contatos ou adicionar e-mails",
+ "nodes.humanInputV2.recipients.remove": "Remover {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Pressione Backspace ou Delete para remover.",
+ "nodes.humanInputV2.recipients.resultCount": "Destinatários correspondentes: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Pesquisar contatos",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Pesquisar por nome ou e-mail",
+ "nodes.humanInputV2.recipients.selectionHint": "Destinatários selecionados: {{count}}. No início do campo, pressione a seta para a esquerda para focá-los.",
+ "nodes.humanInputV2.recipients.title": "Destinatários",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Todos os contatos do espaço de trabalho",
+ "nodes.humanInputV2.recipients.type.contact": "Contato",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "E-mail dinâmico",
+ "nodes.humanInputV2.recipients.type.initiator": "Iniciador",
+ "nodes.humanInputV2.recipients.type.onetime_email": "E-mail avulso",
+ "nodes.humanInputV2.recipients.typeLabel": "Tipo de destinatário",
"nodes.humanInputV2.recipients.useThisInstead": "Usar este em vez disso",
+ "nodes.humanInputV2.recipients.variableRequired": "Escolha uma variável de e-mail",
+ "nodes.humanInputV2.template.body": "Corpo",
+ "nodes.humanInputV2.template.description": "Texto alternativo para e-mail e mensagens instantâneas",
"nodes.humanInputV2.template.insertRequestURL": "Inserir URL da solicitação",
+ "nodes.humanInputV2.template.insertVariable": "Inserir variável",
+ "nodes.humanInputV2.template.notConfigured": "Não configurado",
"nodes.humanInputV2.template.requestURLHint": "Os destinatários usam este link para abrir o formulário de aprovação. Inclua exatamente uma URL de solicitação.",
"nodes.humanInputV2.template.requestURLInserted": "URL da solicitação inserida",
"nodes.humanInputV2.template.saveAndTest": "Salvar e testar",
+ "nodes.humanInputV2.template.subject": "Assunto",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Insira o assunto da mensagem",
"nodes.humanInputV2.template.test": "Testar mensagem",
"nodes.humanInputV2.template.testChannel": "Canal de teste",
"nodes.humanInputV2.template.testCompleted": "A solicitação de teste foi concluída. Confira a mensagem no canal selecionado.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Preencha todos os valores das variáveis de teste.",
"nodes.humanInputV2.template.testSaveFailed": "Não foi possível salvar o rascunho do fluxo de trabalho. O teste não foi enviado.",
"nodes.humanInputV2.template.testUnavailable": "Este ambiente ainda não oferece suporte a testes de modelos de mensagem.",
+ "nodes.humanInputV2.template.title": "Modelo de mensagem",
"nodes.ifElse.operator": "Operador",
"nodes.iteration.currentIteration": "Iteração atual",
"nodes.iteration.deleteDesc": "Excluir o nó de iteração excluirá todos os nós filhos",
diff --git a/web/i18n/locales/ro-RO/contacts.json b/web/i18n/locales/ro-RO/contacts.json
index 80e78b5a30a..9d6fe209c21 100644
--- a/web/i18n/locales/ro-RO/contacts.json
+++ b/web/i18n/locales/ro-RO/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Eliminați contactele ({{count}})?",
"directory.removalDescription": "Contactele selectate vor fi eliminate definitiv din acest spațiu de lucru. Această acțiune nu poate fi anulată.",
- "directory.removalTitle": "Elimini contactele?",
+ "directory.removalSingleDescription": "{{name}} va fi eliminat definitiv din acest spațiu de lucru. Această acțiune nu poate fi anulată.",
+ "directory.removalSingleFailed": "Contactul nu a putut fi eliminat. Încercați din nou.",
+ "directory.removalSingleTitle": "Eliminați {{name}}?",
+ "directory.resultCount": "Rezultate: {{count}}",
+ "imPlatform.action.configure": "Configurează",
+ "imPlatform.action.configureChannel": "Configurați {{provider}}",
+ "imPlatform.action.connect": "Conectează",
+ "imPlatform.action.copied": "Copiat",
+ "imPlatform.action.copyCallback": "Copiază URL-ul de callback",
+ "imPlatform.action.deleteChannel": "Șterge {{provider}}",
+ "imPlatform.action.loadMore": "Încarcă mai multe",
+ "imPlatform.action.replace": "Înlocui",
+ "imPlatform.action.retry": "Reîncercare",
+ "imPlatform.action.save": "Salvați",
+ "imPlatform.action.saving": "Se salvează",
+ "imPlatform.action.setupGuide": "Ghid de configurare",
+ "imPlatform.action.syncNow": "Sincronizează acum",
+ "imPlatform.action.syncing": "Se sincronizează",
+ "imPlatform.action.testConnection": "Testează conexiunea",
+ "imPlatform.action.testing": "Se testează",
+ "imPlatform.action.viewDetails": "Vezi detalii",
+ "imPlatform.bindingDialog.back": "Înapoi",
+ "imPlatform.bindingDialog.callback": "URL de returnare",
+ "imPlatform.bindingDialog.callbackDescription": "Finalizează configurarea callbackurilor în {{provider}} pentru a activa acțiunile cardurilor.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Pentru acțiunile cardurilor, lipește acest URL în <console>Consola pentru dezvoltatori Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Evenimente și callbackuri → Configurarea callbackurilor → URL de solicitare",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Pentru acțiunile cardurilor, lipește acest URL în <console>Consola pentru dezvoltatori Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Evenimente și callbackuri → Configurarea callbackurilor → URL de solicitare",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Pentru acțiunile cardurilor, lipește acest URL în <console>Consola pentru dezvoltatori Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interactivitate și comenzi rapide → Interactivitate → URL de solicitare",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Pentru acțiunile cardurilor, lipește acest URL în <console>configurarea Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Setări → Configurare → Punct final de mesagerie",
+ "imPlatform.bindingDialog.callbackStep": "Configurează callbackurile",
"imPlatform.bindingDialog.clearSavedCredential": "Șterge valoarea salvată",
+ "imPlatform.bindingDialog.configureTitle": "Configurați {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Conectați {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Această valoare salvată va fi ștearsă la salvare.",
+ "imPlatform.bindingDialog.credentialsDescription": "Conectează mai întâi aplicația {{provider}}, apoi configurează URL-ul de callback.",
+ "imPlatform.bindingDialog.credentialsStep": "Datele de autentificare ale aplicației",
+ "imPlatform.bindingDialog.description": "Introdu datele de autentificare ale aplicației pentru acest furnizor de mesagerie instantanee.",
+ "imPlatform.bindingDialog.field.agentId": "ID agent",
+ "imPlatform.bindingDialog.field.appId": "ID aplicație",
+ "imPlatform.bindingDialog.field.appToken": "Token aplicație (opțional)",
+ "imPlatform.bindingDialog.field.botToken": "Token bot",
+ "imPlatform.bindingDialog.field.clientId": "ID client",
+ "imPlatform.bindingDialog.field.clientSecret": "Secretul Clientului",
+ "imPlatform.bindingDialog.field.corpId": "ID companie",
+ "imPlatform.bindingDialog.field.encryptKey": "Cheie de criptare (opțională)",
+ "imPlatform.bindingDialog.field.genericSecret": "Cheie secretă",
+ "imPlatform.bindingDialog.field.secret": "Secretul aplicației",
+ "imPlatform.bindingDialog.field.signingSecret": "Secret de semnare",
+ "imPlatform.bindingDialog.field.tenantId": "ID entitate găzduită",
+ "imPlatform.bindingDialog.field.verificationToken": "Token de verificare (opțional)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Introdu cheia de criptare, dacă este activată",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Introdu secretul aplicației",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Introdu tokenul de verificare, dacă este configurat",
+ "imPlatform.bindingDialog.finish": "Finalizează",
+ "imPlatform.bindingDialog.freshCredentials": "Secretele salvate nu pot fi recuperate. Introdu din nou toate datele de autentificare necesare pentru a testa sau salva această configurare.",
+ "imPlatform.bindingDialog.openSetupGuide": "Deschide ghidul de configurare",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Înlocuiți acreditările entității găzduite pentru {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Aceste date de autentificare aparțin unui alt tenant IM și nu pot fi salvate direct. Pentru a schimba tenantul, trebuie înlocuit canalul IM curent, ceea ce șterge toate asocierile IM automate și manuale. Sincronizează din nou contactele după înlocuire.",
+ "imPlatform.bindingDialog.required": "Acest câmp este obligatoriu.",
+ "imPlatform.bindingDialog.saveAndContinue": "Salvează și continuă",
+ "imPlatform.bindingDialog.saveFailed": "Configurarea nu a putut fi salvată. Verifică câmpurile și încearcă din nou.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Configurația a fost salvată, dar detaliile ei nu au putut fi încărcate. Închide acest dialog și deschide-l din nou.",
- "imPlatform.bindingDialog.undoClearCredential": "Anulează ștergerea"
+ "imPlatform.bindingDialog.secretConfigured": "Un secret este deja configurat. Lasă acest câmp necompletat pentru a-l păstra.",
+ "imPlatform.bindingDialog.step": "Pasul {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Testul conexiunii a eșuat. Verifică configurarea și încearcă din nou.",
+ "imPlatform.bindingDialog.undoClearCredential": "Anulează ștergerea",
+ "imPlatform.bindingDialog.viewSetupGuide": "Vezi ghidul de configurare",
+ "imPlatform.chooseProvider": "Alege un canal de conectat",
+ "imPlatform.configurationUpdated": "Configurarea acestui canal s-a schimbat. Închide această fereastră și reîmprospătează pagina înainte de a reîncerca.",
+ "imPlatform.connectMore": "Conectează mai multe canale",
+ "imPlatform.delete.confirm": "Şterge",
+ "imPlatform.delete.description": "Ștergerea acestui canal elimină configurarea sa. Livrarea notificărilor de aprobare și sincronizările directorului care îl folosesc se vor opri.",
+ "imPlatform.delete.failed": "Canalul nu a putut fi șters. Nu s-a schimbat nimic; încearcă din nou.",
+ "imPlatform.delete.title": "Ștergi canalul {{provider}}?",
+ "imPlatform.description": "Conectează canalele companiei pentru ca solicitările de aprobare să ajungă la persoane acolo unde lucrează.",
+ "imPlatform.details.column.contact": "Contacte",
+ "imPlatform.details.column.platform": "Platformă de mesagerie instantanee",
+ "imPlatform.details.description": "Vezi rezultatele doar în citire ale celei mai recente sincronizări.",
+ "imPlatform.details.downloadFailed": "Raportul nu a putut fi descărcat. Încearcă din nou.",
+ "imPlatform.details.downloadReport": "Descarcă raportul",
+ "imPlatform.details.downloadingReport": "Se descarcă raportul…",
+ "imPlatform.details.empty": "Niciun rezultat în această categorie.",
+ "imPlatform.details.filter.added": "Adăugat",
+ "imPlatform.details.filter.failed": "Eșuat",
+ "imPlatform.details.filter.not_matched": "Fără corespondență",
+ "imPlatform.details.filter.removed": "Eliminat",
+ "imPlatform.details.filter.skipped": "Omis",
+ "imPlatform.details.filters": "Filtre pentru rezultatele sincronizării",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Detaliile sincronizării nu au putut fi încărcate.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Nu s-au putut încărca mai multe rezultate. Reîncearcă această pagină.",
+ "imPlatform.details.removalReason.binding_invalidated": "Asociere invalidată",
+ "imPlatform.details.removalReason.binding_replaced": "Asociere înlocuită",
+ "imPlatform.details.removalReason.not_present_in_directory": "Nu mai apare în director",
+ "imPlatform.details.reportChanged": "Rezultatele sincronizării s-au schimbat. Redeschide detaliile ultimei sincronizări și încearcă din nou.",
+ "imPlatform.details.title": "Detaliile sincronizării",
+ "imPlatform.email.apiKey": "Cheie API",
+ "imPlatform.email.apiKeyConfigured": "Din motive de securitate, cheia API salvată nu poate fi vizualizată. Lasă acest câmp necompletat pentru a o păstra.",
+ "imPlatform.email.apiKeyDescription": "Din motive de securitate, această cheie API nu poate fi vizualizată după salvare.",
+ "imPlatform.email.apiKeyPlaceholder": "Introdu cheia API Resend",
+ "imPlatform.email.description": "Această configurare se aplică tuturor nodurilor de intervenție umană din acest spațiu de lucru care au activată opțiunea <emphasis>Trimite notificări de depanare prin e-mail</emphasis>.",
+ "imPlatform.email.invalidEmail": "Introdu o adresă de e-mail validă.",
+ "imPlatform.email.provider": "Furnizor de e-mail",
+ "imPlatform.email.resendDescription": "<apiKey>Cheia API Resend</apiKey> va fi criptată și nu va mai putea fi vizualizată după salvare.<br/>Creează un cont <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Setări Resend",
+ "imPlatform.email.senderEmail": "Adresa de e-mail a expeditorului",
+ "imPlatform.email.senderEmailDescription": "Adresa de e-mail afișată ca expeditor. Domeniul său trebuie verificat în Resend.",
+ "imPlatform.email.senderName": "Numele expeditorului",
+ "imPlatform.email.senderNameDescription": "Numele afișat în căsuța de e-mail a destinatarului.",
+ "imPlatform.email.testSucceeded": "Testul conexiunii a reușit.",
+ "imPlatform.email.title": "Configurează e-mailul",
+ "imPlatform.learnMore": "Află mai multe",
+ "imPlatform.loadError.description": "Încearcă din nou să citești asocierea curentă și permisiunile.",
+ "imPlatform.loadError.retry": "Încearcă din nou",
+ "imPlatform.loadError.title": "Canalele nu au putut fi încărcate",
+ "imPlatform.loading": "Se încarcă canalele",
+ "imPlatform.provider.dingtalkDescription": "Conectează o aplicație DingTalk.",
+ "imPlatform.provider.emailDescription": "Configurează serviciul de e-mail folosit pentru a trimite solicitări de aprobare din acest spațiu de lucru.",
+ "imPlatform.provider.feishuDescription": "Conectează o aplicație Feishu.",
+ "imPlatform.provider.larkDescription": "Conectează o aplicație Lark.",
+ "imPlatform.provider.msTeamsDescription": "Conectează o aplicație Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Sincronizează persoanele și identitățile lor Slack.",
+ "imPlatform.provider.weComDescription": "Conectează o aplicație WeCom.",
+ "imPlatform.replacement.confirm": "Înlocui",
+ "imPlatform.replacement.description": "Înlocuirea furnizorului activ invalidează asocierile sale de mesagerie instantanee și personalizările spațiului de lucru. După înlocuire, sincronizează din nou directorul noului furnizor.",
+ "imPlatform.replacement.title": "Înlocuiești {{current}} cu {{next}}?",
+ "imPlatform.status.configured": "Configurat",
+ "imPlatform.status.connected": "Conectat",
+ "imPlatform.status.connection_error": "Eroare de conexiune",
+ "imPlatform.status.permission_issue": "Problemă de permisiuni",
+ "imPlatform.sync.latestSynced": "Ultima sincronizare: {{date}}",
+ "imPlatform.sync.loading": "Se verifică dacă există o sincronizare activă.",
+ "imPlatform.sync.noPermission": "Numai proprietarii și administratorii spațiului de lucru pot porni sincronizarea directorului.",
+ "imPlatform.sync.noRuns": "Nu a fost efectuată încă nicio sincronizare a directorului.",
+ "imPlatform.sync.notConnected": "Conectează un furnizor și testează conexiunea înainte de a porni sincronizarea directorului.",
+ "imPlatform.sync.startFailed": "Sincronizarea directorului nu a putut fi pornită sau reîmprospătată. Încearcă din nou.",
+ "imPlatform.sync.status.failure": "Eșuat",
+ "imPlatform.sync.status.queued": "În așteptare",
+ "imPlatform.sync.status.running": "În curs",
+ "imPlatform.sync.status.success": "Reușit",
+ "imPlatform.title": "Canale"
}
diff --git a/web/i18n/locales/ro-RO/share.json b/web/i18n/locales/ro-RO/share.json
index 56c0035b8a5..e399ebac116 100644
--- a/web/i18n/locales/ro-RO/share.json
+++ b/web/i18n/locales/ro-RO/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Mulțumim!",
"humanInput.unavailableDescription": "Linkul poate fi indisponibil sau poate să nu corespundă contului cu care ești conectat. Deschide formularul din notificarea primită sau încearcă să schimbi contul.",
"humanInput.unavailableTitle": "Acest formular nu poate fi deschis",
+ "humanInputV2.accessRateLimited": "Au fost solicitate prea multe e-mailuri de verificare. Încearcă din nou mai târziu.",
+ "humanInputV2.alreadySubmitted": "Această solicitare a fost deja finalizată.",
+ "humanInputV2.challengeExpired": "Acest cod de verificare a expirat. Solicită un cod nou pentru a continua.",
+ "humanInputV2.challengeStale": "Acest cod de verificare a fost înlocuit. Solicită un cod nou pentru a continua.",
+ "humanInputV2.codeExpiresIn": "Codul expiră în {{seconds}} s",
+ "humanInputV2.codeRequired": "Solicită un cod de verificare pentru a continua.",
+ "humanInputV2.codeSent": "Un cod de verificare a fost trimis la adresa ta de e-mail.",
+ "humanInputV2.deliveryFailed": "E-mailul de verificare nu a putut fi trimis. Încearcă din nou.",
+ "humanInputV2.formExpired": "Această solicitare a expirat.",
+ "humanInputV2.formNotFound": "Formularul nu a fost găsit.",
+ "humanInputV2.formRateLimited": "Prea multe solicitări de formular. Încearcă din nou mai târziu.",
+ "humanInputV2.invalidOtp": "Codul de verificare este incorect. Verifică-l și încearcă din nou.",
+ "humanInputV2.networkError": "Solicitarea nu a putut fi finalizată. Verifică-ți conexiunea și încearcă din nou.",
+ "humanInputV2.otpLabel": "Cod de verificare prin e-mail",
+ "humanInputV2.otpPlaceholder": "Introdu codul din 6 cifre",
+ "humanInputV2.requestingCode": "Se trimite un cod de verificare…",
+ "humanInputV2.resendCode": "Retrimite codul",
+ "humanInputV2.retry": "Încearcă din nou",
+ "humanInputV2.sendCode": "Trimite un cod nou",
+ "humanInputV2.unavailable": "Acest formular este temporar indisponibil.",
+ "humanInputV2.unknownError": "A apărut o eroare. Încearcă din nou.",
+ "humanInputV2.uploadFailed": "Fișierul nu a putut fi încărcat. Încearcă din nou.",
"login.backToHome": "Înapoi la Acasă"
}
diff --git a/web/i18n/locales/ro-RO/workflow-human-input.json b/web/i18n/locales/ro-RO/workflow-human-input.json
index fb6df028517..83479ee931b 100644
--- a/web/i18n/locales/ro-RO/workflow-human-input.json
+++ b/web/i18n/locales/ro-RO/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Valoarea Acțiunii",
"nodes.humanInput.userActions.buttonTextTooLong": "Textul butonului trebuie să fie de {{maxLength}} caractere sau mai puțin",
"nodes.humanInput.userActions.chooseStyle": "Alegeți un stil de buton",
+ "nodes.humanInput.userActions.defaultTitle": "Textul butonului {{index}}",
"nodes.humanInput.userActions.emptyTip": "Faceți clic pe butonul '+' pentru a adăuga acțiuni utilizator",
"nodes.humanInput.userActions.title": "Acțiuni utilizator",
"nodes.humanInput.userActions.tooltip": "Definiți butoane pe care utilizatorii le pot apăsa pentru a răspunde la acest formular. ID-ul acțiunii controlează ramificarea. Valoarea Acțiunii este expusă în aval ca ieșirea integrată selectată. ID-ul acțiunii trebuie să înceapă cu o literă sau underscore, urmat de litere, cifre sau underscore.",
diff --git a/web/i18n/locales/ro-RO/workflow.json b/web/i18n/locales/ro-RO/workflow.json
index 0d07130c529..bcfae9b1b9c 100644
--- a/web/i18n/locales/ro-RO/workflow.json
+++ b/web/i18n/locales/ro-RO/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Ieșire",
"blocks.http-request": "Cerere HTTP",
"blocks.human-input": "Input uman",
+ "blocks.human-input-v2": "Input uman v2",
"blocks.if-else": "Dacă/Altminteri",
"blocks.iteration": "Iterație",
"blocks.iteration-start": "Început de iterație",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Definiți ieșirea și tipul rezultatului unui flux de lucru",
"blocksAbout.http-request": "Permite trimiterea cererilor de server prin protocolul HTTP",
"blocksAbout.human-input": "Cere confirmarea umană înainte de a genera următorul pas",
+ "blocksAbout.human-input-v2": "Solicită date de la contactele configurate, destinatarii de e-mail sau persoana care inițiază fluxul de lucru",
"blocksAbout.if-else": "Permite împărțirea fluxului de lucru în două ramuri pe baza condițiilor if/else",
"blocksAbout.iteration": "Efectuați mai mulți pași pe un obiect listă până când toate rezultatele sunt produse.",
"blocksAbout.iteration-start": "Nod de început al iterației",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Agregarea variabilelor din mai multe ramuri într-o singură variabilă pentru configurarea unificată a nodurilor ulterioare.",
"blocksAbout.variable-assigner": "Agregarea variabilelor din mai multe ramuri într-o singură variabilă pentru configurarea unificată a nodurilor ulterioare.",
"changeHistory.edgeDelete": "Nod deconectat",
+ "changeHistory.humanInputMigration": "Nodurile de input uman au fost migrate",
"changeHistory.nodeAdd": "Nod adăugat",
"changeHistory.nodeChange": "Nodul s-a schimbat",
"changeHistory.nodeConnect": "Nod conectat",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Vă rugăm activați cel puțin o metodă de livrare",
"nodes.humanInput.errorMsg.noUserActions": "Vă rugăm adăugați cel puțin o acțiune utilizator",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} este rezervat pentru ramura de expirare. Alegeți un alt ID de acțiune.",
+ "nodes.humanInput.output.actionId": "ID-ul acțiunii declanșate de utilizator",
+ "nodes.humanInput.output.actionValue": "Valoarea acțiunii selectate",
+ "nodes.humanInput.output.formInput": "Valoarea introdusă în formular",
+ "nodes.humanInput.output.renderedContent": "Conținut randat",
"nodes.humanInput.timeout.title": "Timeout",
+ "nodes.humanInputMigration.action.migrate": "Migrează",
+ "nodes.humanInputMigration.action.migrateNow": "Migrează acum",
+ "nodes.humanInputMigration.action.migrating": "Migrare în curs...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Notificare privind migrarea nodurilor de input uman",
+ "nodes.humanInputMigration.banner.description": "Acest flux de lucru utilizează vechiul nod de input uman. Migrează toate nodurile vechi înainte de a adăuga unele noi.",
+ "nodes.humanInputMigration.banner.learnMore": "Află mai multe",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "o metodă de livrare dezactivată conține încă o configurație",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "metodele de e-mail activate utilizează șabloane incompatibile între ele",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Valoare implicită nevalidă",
+ "nodes.humanInputMigration.blocker.invalidEmail": "adresa de e-mail a unui destinatar este nevalidă",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "o metodă de e-mail activată este incompletă",
+ "nodes.humanInputMigration.blocker.missingRecipients": "nodul nu are destinatari acceptați",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "un membru al spațiului de lucru nu poate fi asociat cu un contact sau o adresă de e-mail verificată",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "o metodă de livrare activată nu este acceptată de Human Input v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Câmpul {{field}} nu poate fi încă migrat. Puteți continua să utilizați nodurile vechi de intrare umană.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "nodul are o valoare de versiune neacceptată",
+ "nodes.humanInputMigration.dialog.description": "Destinatarii, formularul și acțiunile sunt păstrate.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Se modifică doar această schiță. Versiunile publicate continuă să funcționeze până la o nouă publicare.",
+ "nodes.humanInputMigration.dialog.review": "Verifică nodurile și publică atunci când totul este pregătit.",
+ "nodes.humanInputMigration.dialog.title": "Migrează {{count}} noduri de input uman",
+ "nodes.humanInputMigration.disabledBadge": "MIGRARE NECESARĂ",
+ "nodes.humanInputMigration.disabledReason": "Migrează nodurile vechi de input uman înainte de a adăuga unul nou.",
+ "nodes.humanInputMigration.error.blocked": "Nu s-a putut migra {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Fluxul de lucru s-a modificat în timpul migrării. Încercați din nou; modificările curente au fost păstrate.",
+ "nodes.humanInputMigration.error.preflight": "Migrarea nu a putut fi pregătită. Fluxul de lucru nu a fost modificat. Încearcă din nou.",
"nodes.humanInputMigration.error.sync": "Fluxul de lucru migrat nu a putut fi salvat. Verificați schița curentă și încercați din nou.",
+ "nodes.humanInputMigration.incompatibleVersions": "Nodurile vechi și noi de intervenție umană nu pot fi folosite în același flux de lucru.",
+ "nodes.humanInputMigration.oldVersion": "VERSIUNE VECHE",
+ "nodes.humanInputMigration.preview.author": "De echipa Dify",
+ "nodes.humanInputMigration.preview.description": "Migrează nodurile vechi de input uman înainte de a adăuga unul nou.",
+ "nodes.humanInputMigration.success": "Nodurile de input uman au fost migrate cu succes",
+ "nodes.humanInputV2.card.configured": "{{count}} destinatari configurați",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} contacte",
+ "nodes.humanInputV2.card.empty": "Nimeni nu poate aproba încă acest pas",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Inițiatorul și {{count}} contacte",
+ "nodes.humanInputV2.card.initiatorOnly": "Doar inițiatorul",
+ "nodes.humanInputV2.card.invalid": "Configurația destinatarilor necesită atenție",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-mail",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Configurează modul de depanare",
"nodes.humanInputV2.debug.keepOneChannel": "Păstrează cel puțin un canal activ",
+ "nodes.humanInputV2.debug.sendVia": "Trimite notificări de depanare prin",
+ "nodes.humanInputV2.debug.title": "Mod de depanare",
+ "nodes.humanInputV2.debug.toggle": "Activează modul de depanare",
+ "nodes.humanInputV2.debug.unsupported": "Canale importate neacceptate: {{channels}}. Elimină-le sau actualizează-le înainte de a rula acest flux de lucru.",
"nodes.humanInputV2.disabled": "Human Input v2 nu este disponibil când HITL IM este dezactivat.",
+ "nodes.humanInputV2.error.bodyRequired": "Corpul mesajului este obligatoriu",
+ "nodes.humanInputV2.error.debugChannelRequired": "Selectează cel puțin un canal pentru modul de depanare",
+ "nodes.humanInputV2.error.recipientDuplicate": "Elimină destinatarii duplicați",
+ "nodes.humanInputV2.error.recipientInvalid": "Corectează configurația nevalidă a destinatarilor",
+ "nodes.humanInputV2.error.recipientRequired": "Adaugă cel puțin un destinatar",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Destinatarii din contacte nu au putut fi verificați",
"nodes.humanInputV2.error.requestURLDuplicate": "Corpul mesajului poate conține un singur URL al cererii.",
"nodes.humanInputV2.error.requestURLRequired": "Inserează un URL al cererii în corpul mesajului.",
+ "nodes.humanInputV2.error.subjectRequired": "Subiectul mesajului este obligatoriu",
+ "nodes.humanInputV2.error.version": "Human Input v2 necesită valoarea de versiune 2 ca șir de caractere",
+ "nodes.humanInputV2.recipients.addContact": "Adaugă un contact",
+ "nodes.humanInputV2.recipients.addEmail": "Adaugă",
+ "nodes.humanInputV2.recipients.addRecipient": "Adaugă un destinatar",
+ "nodes.humanInputV2.recipients.added": "Adăugat",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Toate contactele din spațiul de lucru",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Trimite o notificare tuturor contactelor din spațiul de lucru; oricare dintre ele poate aproba",
+ "nodes.humanInputV2.recipients.cancel": "Anulează",
+ "nodes.humanInputV2.recipients.chooseVariable": "Alege o variabilă",
+ "nodes.humanInputV2.recipients.confirm": "Confirmă",
+ "nodes.humanInputV2.recipients.contactInfo": "Detalii de contact pentru {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Toate",
+ "nodes.humanInputV2.recipients.contactSource.external": "Extern",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organizație",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Spațiu de lucru",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Sursa contactului",
"nodes.humanInputV2.recipients.duplicateSource": "Adăugat deja prin {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Editează {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Editează destinatarul",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Fiecare adresă de e-mail poate fi selectată o singură dată.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Introdu o adresă de e-mail validă care nu a fost deja adăugată",
+ "nodes.humanInputV2.recipients.emailLabel": "Destinatar de e-mail ocazional",
+ "nodes.humanInputV2.recipients.empty": "Niciun destinatar configurat",
+ "nodes.humanInputV2.recipients.help": "Alege cine poate răspunde la acest pas de input uman.",
"nodes.humanInputV2.recipients.initiator": "Utilizatorul care pornește această execuție prin Web App sau CLI poate aproba",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Persoana care pornește această rulare a fluxului de lucru poate răspunde.",
"nodes.humanInputV2.recipients.inputHelp": "Introdu sau lipește mai multe adrese de e-mail separate prin virgule. Apasă / pentru a insera o variabilă.",
+ "nodes.humanInputV2.recipients.insertVariable": "Inserează o variabilă",
+ "nodes.humanInputV2.recipients.loadError": "Contactele nu au putut fi încărcate. ID-urile de contact salvate sunt păstrate.",
+ "nodes.humanInputV2.recipients.loading": "Se încarcă contactele…",
+ "nodes.humanInputV2.recipients.noResults": "Nu s-au găsit contacte",
+ "nodes.humanInputV2.recipients.placeholder": "Caută contacte sau adaugă adrese de e-mail",
+ "nodes.humanInputV2.recipients.remove": "Elimină {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Apăsați Backspace sau Delete pentru a elimina.",
+ "nodes.humanInputV2.recipients.resultCount": "Destinatari care corespund: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Caută contacte",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Caută după nume sau e-mail",
+ "nodes.humanInputV2.recipients.selectionHint": "Destinatari selectați: {{count}}. La începutul câmpului, apăsați săgeata stânga pentru a-i focaliza.",
+ "nodes.humanInputV2.recipients.title": "Destinatari",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Toate contactele din spațiul de lucru",
+ "nodes.humanInputV2.recipients.type.contact": "Contact",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "E-mail dinamic",
+ "nodes.humanInputV2.recipients.type.initiator": "Inițiator",
+ "nodes.humanInputV2.recipients.type.onetime_email": "E-mail ocazional",
+ "nodes.humanInputV2.recipients.typeLabel": "Tip de destinatar",
"nodes.humanInputV2.recipients.useThisInstead": "Folosește acest element în schimb",
+ "nodes.humanInputV2.recipients.variableRequired": "Alege o variabilă de e-mail",
+ "nodes.humanInputV2.template.body": "Corp",
+ "nodes.humanInputV2.template.description": "Text de rezervă pentru e-mail și mesagerie instantanee",
"nodes.humanInputV2.template.insertRequestURL": "Inserează URL-ul cererii",
+ "nodes.humanInputV2.template.insertVariable": "Inserează o variabilă",
+ "nodes.humanInputV2.template.notConfigured": "Neconfigurat",
"nodes.humanInputV2.template.requestURLHint": "Destinatarii folosesc acest link pentru a deschide formularul de aprobare. Include exact un URL al cererii.",
"nodes.humanInputV2.template.requestURLInserted": "URL-ul cererii a fost inserat",
"nodes.humanInputV2.template.saveAndTest": "Salvează și testează",
+ "nodes.humanInputV2.template.subject": "Subiect",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Introdu subiectul mesajului",
"nodes.humanInputV2.template.test": "Testează mesajul",
"nodes.humanInputV2.template.testChannel": "Canal de test",
"nodes.humanInputV2.template.testCompleted": "Solicitarea de test a fost finalizată. Verifică mesajul pe canalul selectat.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Completează toate valorile variabilelor de test.",
"nodes.humanInputV2.template.testSaveFailed": "Ciorna fluxului de lucru nu a putut fi salvată. Testul nu a fost trimis.",
"nodes.humanInputV2.template.testUnavailable": "Acest mediu nu acceptă încă testarea șabloanelor de mesaje.",
+ "nodes.humanInputV2.template.title": "Șablon de mesaj",
"nodes.ifElse.operator": "Operator",
"nodes.iteration.currentIteration": "Iterație curentă",
"nodes.iteration.deleteDesc": "Ștergerea nodului de iterație va șterge toate nodurile copil",
diff --git a/web/i18n/locales/ru-RU/contacts.json b/web/i18n/locales/ru-RU/contacts.json
index 1aaec8434e7..7cd802a4df1 100644
--- a/web/i18n/locales/ru-RU/contacts.json
+++ b/web/i18n/locales/ru-RU/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Удалить контакты ({{count}})?",
"directory.removalDescription": "Выбранные контакты будут навсегда удалены из этого рабочего пространства. Это действие нельзя отменить.",
- "directory.removalTitle": "Удалить контакты?",
+ "directory.removalSingleDescription": "Контакт {{name}} будет навсегда удалён из этого рабочего пространства. Это действие нельзя отменить.",
+ "directory.removalSingleFailed": "Не удалось удалить контакт. Повторите попытку.",
+ "directory.removalSingleTitle": "Удалить {{name}}?",
+ "directory.resultCount": "Результаты: {{count}}",
+ "imPlatform.action.configure": "Настроить",
+ "imPlatform.action.configureChannel": "Настроить {{provider}}",
+ "imPlatform.action.connect": "Подключить",
+ "imPlatform.action.copied": "Скопированы",
+ "imPlatform.action.copyCallback": "Копировать URL обратного вызова",
+ "imPlatform.action.deleteChannel": "Удалить {{provider}}",
+ "imPlatform.action.loadMore": "Загрузить ещё",
+ "imPlatform.action.replace": "Заменять",
+ "imPlatform.action.retry": "Снова пробовать",
+ "imPlatform.action.save": "Сохранить",
+ "imPlatform.action.saving": "Сохранение",
+ "imPlatform.action.setupGuide": "Руководство по настройке",
+ "imPlatform.action.syncNow": "Синхронизировать сейчас",
+ "imPlatform.action.syncing": "Синхронизация",
+ "imPlatform.action.testConnection": "Проверить подключение",
+ "imPlatform.action.testing": "Проверка",
+ "imPlatform.action.viewDetails": "Подробнее",
+ "imPlatform.bindingDialog.back": "Назад",
+ "imPlatform.bindingDialog.callback": "URL для обратного вызова",
+ "imPlatform.bindingDialog.callbackDescription": "Завершите настройку обратных вызовов в {{provider}}, чтобы включить действия с карточками.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Для действий с карточками вставьте этот URL в <console>консоли разработчика Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "События и обратные вызовы → Настройка обратных вызовов → URL запроса",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Для действий с карточками вставьте этот URL в <console>консоли разработчика Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "События и обратные вызовы → Настройка обратных вызовов → URL запроса",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Для действий с карточками вставьте этот URL в <console>консоли разработчика Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Интерактивность и сочетания клавиш → Интерактивность → URL запроса",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Для действий с карточками вставьте этот URL в <console>настройках Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Настройки → Конфигурация → Конечная точка обмена сообщениями",
+ "imPlatform.bindingDialog.callbackStep": "Настройка обратных вызовов",
"imPlatform.bindingDialog.clearSavedCredential": "Очистить сохранённое значение",
+ "imPlatform.bindingDialog.configureTitle": "Настроить {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Подключите {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Это сохранённое значение будет очищено при сохранении.",
+ "imPlatform.bindingDialog.credentialsDescription": "Сначала подключите приложение {{provider}}, затем настройте его URL обратного вызова.",
+ "imPlatform.bindingDialog.credentialsStep": "Учётные данные приложения",
+ "imPlatform.bindingDialog.description": "Введите учётные данные приложения для этой платформы обмена сообщениями.",
+ "imPlatform.bindingDialog.field.agentId": "ID агента",
+ "imPlatform.bindingDialog.field.appId": "ID приложения",
+ "imPlatform.bindingDialog.field.appToken": "Токен приложения (необязательно)",
+ "imPlatform.bindingDialog.field.botToken": "Токен бота",
+ "imPlatform.bindingDialog.field.clientId": "Идентификатор клиента",
+ "imPlatform.bindingDialog.field.clientSecret": "Секрет клиента",
+ "imPlatform.bindingDialog.field.corpId": "ID организации",
+ "imPlatform.bindingDialog.field.encryptKey": "Ключ шифрования (необязательно)",
+ "imPlatform.bindingDialog.field.genericSecret": "Секрет",
+ "imPlatform.bindingDialog.field.secret": "Секрет приложения",
+ "imPlatform.bindingDialog.field.signingSecret": "Секрет подписи",
+ "imPlatform.bindingDialog.field.tenantId": "ID арендатора",
+ "imPlatform.bindingDialog.field.verificationToken": "Токен проверки (необязательно)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Введите ключ шифрования, если он включён",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Введите секрет приложения",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Введите токен проверки, если он настроен",
+ "imPlatform.bindingDialog.finish": "Завершить",
+ "imPlatform.bindingDialog.freshCredentials": "Сохранённые секреты нельзя получить повторно. Чтобы проверить или сохранить эту конфигурацию, заново введите все необходимые учётные данные.",
+ "imPlatform.bindingDialog.openSetupGuide": "Открыть руководство по настройке",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Заменить учётные данные арендатора для {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Эти учётные данные принадлежат другому арендатору IM, и их нельзя сохранить напрямую. Для смены арендатора необходимо заменить текущий канал IM. При этом будут удалены все автоматические и ручные привязки IM. После замены повторно синхронизируйте контакты.",
+ "imPlatform.bindingDialog.required": "Это поле обязательно.",
+ "imPlatform.bindingDialog.saveAndContinue": "Сохранить и продолжить",
+ "imPlatform.bindingDialog.saveFailed": "Не удалось сохранить конфигурацию. Проверьте поля и повторите попытку.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Конфигурация сохранена, но загрузить её сведения не удалось. Закройте это диалоговое окно и откройте снова.",
- "imPlatform.bindingDialog.undoClearCredential": "Отменить очистку"
+ "imPlatform.bindingDialog.secretConfigured": "Секрет уже настроен. Оставьте поле пустым, чтобы сохранить его.",
+ "imPlatform.bindingDialog.step": "Шаг {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Проверка подключения не удалась. Проверьте конфигурацию и повторите попытку.",
+ "imPlatform.bindingDialog.undoClearCredential": "Отменить очистку",
+ "imPlatform.bindingDialog.viewSetupGuide": "Посмотреть руководство по настройке",
+ "imPlatform.chooseProvider": "Выберите канал для подключения",
+ "imPlatform.configurationUpdated": "Конфигурация этого канала изменилась. Закройте диалог и обновите страницу перед повторной попыткой.",
+ "imPlatform.connectMore": "Подключить другие каналы",
+ "imPlatform.delete.confirm": "Удалить",
+ "imPlatform.delete.description": "При удалении канала удаляется его конфигурация. Отправка запросов на согласование и синхронизация каталога через этот канал прекратятся.",
+ "imPlatform.delete.failed": "Не удалось удалить канал. Ничего не изменилось; повторите попытку.",
+ "imPlatform.delete.title": "Удалить канал {{provider}}?",
+ "imPlatform.description": "Подключите корпоративные каналы, чтобы запросы на согласование поступали туда, где работают ваши сотрудники.",
+ "imPlatform.details.column.contact": "Контакты",
+ "imPlatform.details.column.platform": "Платформа обмена сообщениями",
+ "imPlatform.details.description": "Просмотрите результаты последней синхронизации в режиме только для чтения.",
+ "imPlatform.details.downloadFailed": "Не удалось скачать отчёт. Повторите попытку.",
+ "imPlatform.details.downloadReport": "Скачать отчёт",
+ "imPlatform.details.downloadingReport": "Скачивание отчёта…",
+ "imPlatform.details.empty": "В этой категории нет результатов.",
+ "imPlatform.details.filter.added": "Добавлено",
+ "imPlatform.details.filter.failed": "Ошибка",
+ "imPlatform.details.filter.not_matched": "Нет совпадений",
+ "imPlatform.details.filter.removed": "Удалено",
+ "imPlatform.details.filter.skipped": "Пропущено",
+ "imPlatform.details.filters": "Фильтры результатов синхронизации",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Не удалось загрузить сведения о синхронизации.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Не удалось загрузить следующие результаты. Повторите загрузку этой страницы.",
+ "imPlatform.details.removalReason.binding_invalidated": "Привязка недействительна",
+ "imPlatform.details.removalReason.binding_replaced": "Привязка заменена",
+ "imPlatform.details.removalReason.not_present_in_directory": "Больше нет в каталоге",
+ "imPlatform.details.reportChanged": "Результаты синхронизации изменились. Откройте сведения о последней синхронизации и повторите попытку.",
+ "imPlatform.details.title": "Сведения о синхронизации",
+ "imPlatform.email.apiKey": "API ключ",
+ "imPlatform.email.apiKeyConfigured": "Из соображений безопасности сохранённый API-ключ нельзя посмотреть. Оставьте поле пустым, чтобы сохранить его.",
+ "imPlatform.email.apiKeyDescription": "Из соображений безопасности этот API-ключ нельзя посмотреть после сохранения.",
+ "imPlatform.email.apiKeyPlaceholder": "Введите API-ключ Resend",
+ "imPlatform.email.description": "Эта конфигурация применяется ко всем узлам Human Input в этой рабочей области, у которых включена опция <emphasis>Отправлять отладочные уведомления по электронной почте</emphasis>.",
+ "imPlatform.email.invalidEmail": "Введите действительный адрес электронной почты.",
+ "imPlatform.email.provider": "Провайдер электронной почты",
+ "imPlatform.email.resendDescription": "Ваш <apiKey>API-ключ Resend</apiKey> будет зашифрован и недоступен для просмотра после сохранения.<br/>Зарегистрируйте аккаунт <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Настройки Resend",
+ "imPlatform.email.senderEmail": "Адрес электронной почты отправителя",
+ "imPlatform.email.senderEmailDescription": "Адрес, который отображается в поле отправителя. Его домен должен быть подтверждён в Resend.",
+ "imPlatform.email.senderName": "Имя отправителя",
+ "imPlatform.email.senderNameDescription": "Имя, которое отображается в почтовом ящике получателя.",
+ "imPlatform.email.testSucceeded": "Проверка подключения выполнена успешно.",
+ "imPlatform.email.title": "Настройка электронной почты",
+ "imPlatform.learnMore": "Узнать больше",
+ "imPlatform.loadError.description": "Повторите попытку, чтобы загрузить текущую привязку и разрешения.",
+ "imPlatform.loadError.retry": "Повторить попытку",
+ "imPlatform.loadError.title": "Не удалось загрузить каналы",
+ "imPlatform.loading": "Загрузка каналов",
+ "imPlatform.provider.dingtalkDescription": "Подключите приложение DingTalk.",
+ "imPlatform.provider.emailDescription": "Настройте почтовый сервис для отправки запросов на согласование из этой рабочей области.",
+ "imPlatform.provider.feishuDescription": "Подключите приложение Feishu.",
+ "imPlatform.provider.larkDescription": "Подключите приложение Lark.",
+ "imPlatform.provider.msTeamsDescription": "Подключите приложение Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Синхронизируйте сотрудников и их учётные записи Slack.",
+ "imPlatform.provider.weComDescription": "Подключите приложение WeCom.",
+ "imPlatform.replacement.confirm": "Заменять",
+ "imPlatform.replacement.description": "При замене активного провайдера его привязки к платформе обмена сообщениями и переопределения рабочей области станут недействительными. После замены заново синхронизируйте каталог нового провайдера.",
+ "imPlatform.replacement.title": "Заменить {{current}} на {{next}}?",
+ "imPlatform.status.configured": "Настроено",
+ "imPlatform.status.connected": "Подключено",
+ "imPlatform.status.connection_error": "Ошибка подключения",
+ "imPlatform.status.permission_issue": "Проблема с разрешениями",
+ "imPlatform.sync.latestSynced": "Последняя синхронизация: {{date}}",
+ "imPlatform.sync.loading": "Проверка наличия активной синхронизации.",
+ "imPlatform.sync.noPermission": "Только владельцы и администраторы рабочей области могут запускать синхронизацию каталога.",
+ "imPlatform.sync.noRuns": "Синхронизация каталога ещё не выполнялась.",
+ "imPlatform.sync.notConnected": "Перед запуском синхронизации каталога подключите и проверьте провайдера.",
+ "imPlatform.sync.startFailed": "Не удалось запустить или обновить синхронизацию каталога. Повторите попытку.",
+ "imPlatform.sync.status.failure": "Ошибка",
+ "imPlatform.sync.status.queued": "В очереди",
+ "imPlatform.sync.status.running": "Выполняется",
+ "imPlatform.sync.status.success": "Успешно",
+ "imPlatform.title": "Каналы"
}
diff --git a/web/i18n/locales/ru-RU/share.json b/web/i18n/locales/ru-RU/share.json
index 132f556f9ac..ea9940442ee 100644
--- a/web/i18n/locales/ru-RU/share.json
+++ b/web/i18n/locales/ru-RU/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Спасибо!",
"humanInput.unavailableDescription": "Возможно, ссылка недоступна или не соответствует аккаунту, в который вы вошли. Откройте форму из полученного уведомления или попробуйте сменить аккаунт.",
"humanInput.unavailableTitle": "Не удалось открыть эту форму",
+ "humanInputV2.accessRateLimited": "Запрошено слишком много писем с кодом подтверждения. Повторите попытку позже.",
+ "humanInputV2.alreadySubmitted": "Этот запрос уже выполнен.",
+ "humanInputV2.challengeExpired": "Срок действия кода подтверждения истёк. Запросите новый код, чтобы продолжить.",
+ "humanInputV2.challengeStale": "Этот код подтверждения был заменён. Запросите новый код, чтобы продолжить.",
+ "humanInputV2.codeExpiresIn": "Срок действия кода истечёт через {{seconds}} с",
+ "humanInputV2.codeRequired": "Запросите код подтверждения, чтобы продолжить.",
+ "humanInputV2.codeSent": "Код подтверждения отправлен на вашу электронную почту.",
+ "humanInputV2.deliveryFailed": "Не удалось отправить письмо с кодом подтверждения. Попробуйте ещё раз.",
+ "humanInputV2.formExpired": "Срок действия запроса истёк.",
+ "humanInputV2.formNotFound": "Форма не найдена.",
+ "humanInputV2.formRateLimited": "Слишком много запросов к форме. Повторите попытку позже.",
+ "humanInputV2.invalidOtp": "Неверный код подтверждения. Проверьте код и попробуйте ещё раз.",
+ "humanInputV2.networkError": "Не удалось выполнить запрос. Проверьте подключение и попробуйте ещё раз.",
+ "humanInputV2.otpLabel": "Код подтверждения электронной почты",
+ "humanInputV2.otpPlaceholder": "Введите шестизначный код",
+ "humanInputV2.requestingCode": "Отправка кода подтверждения…",
+ "humanInputV2.resendCode": "Отправить код повторно",
+ "humanInputV2.retry": "Попробовать ещё раз",
+ "humanInputV2.sendCode": "Отправить новый код",
+ "humanInputV2.unavailable": "Эта форма временно недоступна.",
+ "humanInputV2.unknownError": "Произошла ошибка. Попробуйте ещё раз.",
+ "humanInputV2.uploadFailed": "Не удалось загрузить файл. Попробуйте ещё раз.",
"login.backToHome": "Назад на главную"
}
diff --git a/web/i18n/locales/ru-RU/workflow-human-input.json b/web/i18n/locales/ru-RU/workflow-human-input.json
index d28577b0036..5f0a552f84e 100644
--- a/web/i18n/locales/ru-RU/workflow-human-input.json
+++ b/web/i18n/locales/ru-RU/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Значение действия",
"nodes.humanInput.userActions.buttonTextTooLong": "Текст кнопки должен содержать не более {{maxLength}} символов",
"nodes.humanInput.userActions.chooseStyle": "Выберите стиль кнопки",
+ "nodes.humanInput.userActions.defaultTitle": "Текст кнопки {{index}}",
"nodes.humanInput.userActions.emptyTip": "Нажмите кнопку '+' для добавления действий пользователя",
"nodes.humanInput.userActions.title": "Действия пользователя",
"nodes.humanInput.userActions.tooltip": "Определите кнопки, на которые пользователи могут нажимать, чтобы ответить на эту форму. Идентификатор действия управляет ветвлением. Значение действия передаётся далее как выбранный встроенный вывод. Идентификатор действия должен начинаться с буквы или подчеркивания, за которым следуют буквы, цифры или подчеркивания.",
diff --git a/web/i18n/locales/ru-RU/workflow.json b/web/i18n/locales/ru-RU/workflow.json
index 4a5b1014268..ce3563a19d8 100644
--- a/web/i18n/locales/ru-RU/workflow.json
+++ b/web/i18n/locales/ru-RU/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Вывод",
"blocks.http-request": "HTTP-запрос",
"blocks.human-input": "Ввод человека",
+ "blocks.human-input-v2": "Ввод человека v2",
"blocks.if-else": "ЕСЛИ/ИНАЧЕ",
"blocks.iteration": "Итерация",
"blocks.iteration-start": "Начало итерации",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Определите вывод и тип результата рабочего процесса",
"blocksAbout.http-request": "Разрешить отправку запросов на сервер по протоколу HTTP",
"blocksAbout.human-input": "Запросить подтверждение человека перед генерацией следующего шага",
+ "blocksAbout.human-input-v2": "Запросить ввод у настроенных контактов, получателей электронной почты или инициатора рабочего процесса",
"blocksAbout.if-else": "Позволяет разделить рабочий процесс на две ветки на основе условий if/else",
"blocksAbout.iteration": "Выполнение нескольких шагов над объектом списка до тех пор, пока не будут выведены все результаты.",
"blocksAbout.iteration-start": "Начальный узел итерации",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Объединение переменных из нескольких ветвей в одну переменную для унифицированной настройки подчиненных узлов.",
"blocksAbout.variable-assigner": "Объединение переменных из нескольких ветвей в одну переменную для унифицированной настройки подчиненных узлов.",
"changeHistory.edgeDelete": "Узел отключен",
+ "changeHistory.humanInputMigration": "Узлы ввода человека перенесены",
"changeHistory.nodeAdd": "Узел добавлен",
"changeHistory.nodeChange": "Узел изменен",
"changeHistory.nodeConnect": "Узел подключен",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Пожалуйста, включите хотя бы один способ доставки",
"nodes.humanInput.errorMsg.noUserActions": "Пожалуйста, добавьте хотя бы одно действие пользователя",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} зарезервирован для ветки тайм-аута. Выберите другой идентификатор действия.",
+ "nodes.humanInput.output.actionId": "ID действия, выполненного пользователем",
+ "nodes.humanInput.output.actionValue": "Значение выбранного действия",
+ "nodes.humanInput.output.formInput": "Значение поля формы",
+ "nodes.humanInput.output.renderedContent": "Отображаемое содержимое",
"nodes.humanInput.timeout.title": "Тайм-аут",
+ "nodes.humanInputMigration.action.migrate": "Перенести",
+ "nodes.humanInputMigration.action.migrateNow": "Перенести сейчас",
+ "nodes.humanInputMigration.action.migrating": "Перенос...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Уведомление о переносе узлов ввода человека",
+ "nodes.humanInputMigration.banner.description": "Этот рабочий процесс использует старый узел ввода человека. Перенесите все старые узлы перед добавлением новых.",
+ "nodes.humanInputMigration.banner.learnMore": "Подробнее",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "отключённый способ доставки всё ещё содержит настройки",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "включённые способы доставки по электронной почте используют несовместимые шаблоны",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Недопустимое значение по умолчанию",
+ "nodes.humanInputMigration.blocker.invalidEmail": "адрес электронной почты получателя недействителен",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "настройка включённого способа доставки по электронной почте не завершена",
+ "nodes.humanInputMigration.blocker.missingRecipients": "в узле нет поддерживаемых получателей",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "невозможно определить контакт или подтверждённый адрес электронной почты участника рабочего пространства",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "включённый способ доставки не поддерживается узлом ввода человека v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Поле {{field}} пока нельзя перенести. Вы можете продолжать использовать прежние узлы ввода данных человеком.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "в узле указана неподдерживаемая версия",
+ "nodes.humanInputMigration.dialog.description": "Получатели, форма и действия будут сохранены.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Изменится только этот черновик. Опубликованные версии продолжат работать до следующей публикации.",
+ "nodes.humanInputMigration.dialog.review": "Проверьте узлы и опубликуйте рабочий процесс, когда будете готовы.",
+ "nodes.humanInputMigration.dialog.title": "Перенести узлы ввода человека: {{count}}",
+ "nodes.humanInputMigration.disabledBadge": "ТРЕБУЕТСЯ ПЕРЕНОС",
+ "nodes.humanInputMigration.disabledReason": "Перенесите старые узлы ввода человека перед добавлением нового.",
+ "nodes.humanInputMigration.error.blocked": "Не удалось перенести {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Рабочий процесс изменился во время миграции. Повторите попытку; текущие изменения сохранены.",
+ "nodes.humanInputMigration.error.preflight": "Не удалось подготовить перенос. Рабочий процесс не изменён. Попробуйте ещё раз.",
"nodes.humanInputMigration.error.sync": "Не удалось сохранить перенесённый рабочий процесс. Проверьте текущий черновик и повторите попытку.",
+ "nodes.humanInputMigration.incompatibleVersions": "Старые и новые узлы пользовательского ввода нельзя использовать в одном рабочем процессе.",
+ "nodes.humanInputMigration.oldVersion": "СТАРАЯ ВЕРСИЯ",
+ "nodes.humanInputMigration.preview.author": "От команды Dify",
+ "nodes.humanInputMigration.preview.description": "Перенесите старые узлы ввода человека перед добавлением нового.",
+ "nodes.humanInputMigration.success": "Узлы ввода человека успешно перенесены",
+ "nodes.humanInputV2.card.configured": "Настроено получателей: {{count}}",
+ "nodes.humanInputV2.card.contactsOnly": "Контактов: {{count}}",
+ "nodes.humanInputV2.card.empty": "Пока никто не может согласовать этот шаг",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Инициатор и контакты: {{count}}",
+ "nodes.humanInputV2.card.initiatorOnly": "Только инициатор",
+ "nodes.humanInputV2.card.invalid": "Проверьте настройки получателей",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "Электронная почта",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Настроить режим отладки",
"nodes.humanInputV2.debug.keepOneChannel": "Оставьте включённым хотя бы один канал",
+ "nodes.humanInputV2.debug.sendVia": "Отправлять уведомления отладки через",
+ "nodes.humanInputV2.debug.title": "Режим отладки",
+ "nodes.humanInputV2.debug.toggle": "Включить режим отладки",
+ "nodes.humanInputV2.debug.unsupported": "Импортированы неподдерживаемые каналы: {{channels}}. Удалите или обновите их перед запуском рабочего процесса.",
"nodes.humanInputV2.disabled": "Human Input v2 недоступен, пока HITL IM отключён.",
+ "nodes.humanInputV2.error.bodyRequired": "Текст сообщения обязателен",
+ "nodes.humanInputV2.error.debugChannelRequired": "Выберите хотя бы один канал режима отладки",
+ "nodes.humanInputV2.error.recipientDuplicate": "Удалите повторяющихся получателей",
+ "nodes.humanInputV2.error.recipientInvalid": "Исправьте недопустимые настройки получателей",
+ "nodes.humanInputV2.error.recipientRequired": "Добавьте хотя бы одного получателя",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Не удалось проверить получателей из контактов",
"nodes.humanInputV2.error.requestURLDuplicate": "Текст сообщения может содержать только один URL запроса.",
"nodes.humanInputV2.error.requestURLRequired": "Вставьте URL запроса в текст сообщения.",
+ "nodes.humanInputV2.error.subjectRequired": "Тема сообщения обязательна",
+ "nodes.humanInputV2.error.version": "Для ввода человека v2 требуется строковое значение версии 2",
+ "nodes.humanInputV2.recipients.addContact": "Добавить контакт",
+ "nodes.humanInputV2.recipients.addEmail": "Добавить",
+ "nodes.humanInputV2.recipients.addRecipient": "Добавить получателя",
+ "nodes.humanInputV2.recipients.added": "Добавлено",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Все контакты рабочего пространства",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Отправить уведомление всем контактам рабочего пространства; любой из них может одобрить",
+ "nodes.humanInputV2.recipients.cancel": "Отмена",
+ "nodes.humanInputV2.recipients.chooseVariable": "Выбрать переменную",
+ "nodes.humanInputV2.recipients.confirm": "Подтвердить",
+ "nodes.humanInputV2.recipients.contactInfo": "Контактные данные: {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Все",
+ "nodes.humanInputV2.recipients.contactSource.external": "Внешние",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Организация",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Рабочее пространство",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Источник контактов",
"nodes.humanInputV2.recipients.duplicateSource": "Уже добавлено через {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Изменить {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Изменить получателя",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Каждый адрес электронной почты можно выбрать только один раз.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Введите действительный адрес электронной почты, который ещё не добавлен",
+ "nodes.humanInputV2.recipients.emailLabel": "Разовый получатель электронной почты",
+ "nodes.humanInputV2.recipients.empty": "Получатели не настроены",
+ "nodes.humanInputV2.recipients.help": "Выберите, кто может ответить на этом шаге ввода человека.",
"nodes.humanInputV2.recipients.initiator": "Пользователь, запустивший это выполнение через Web App или CLI, может его одобрить",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Ответить может пользователь, запустивший этот рабочий процесс.",
"nodes.humanInputV2.recipients.inputHelp": "Введите или вставьте несколько адресов электронной почты через запятую. Нажмите /, чтобы вставить переменную.",
+ "nodes.humanInputV2.recipients.insertVariable": "Вставить переменную",
+ "nodes.humanInputV2.recipients.loadError": "Не удалось загрузить контакты. Сохранённые ID контактов не изменены.",
+ "nodes.humanInputV2.recipients.loading": "Загрузка контактов…",
+ "nodes.humanInputV2.recipients.noResults": "Контакты не найдены",
+ "nodes.humanInputV2.recipients.placeholder": "Найдите контакты или добавьте адреса электронной почты",
+ "nodes.humanInputV2.recipients.remove": "Удалить {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Нажмите Backspace или Delete для удаления.",
+ "nodes.humanInputV2.recipients.resultCount": "Подходящих получателей: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Поиск контактов",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Поиск по имени или электронной почте",
+ "nodes.humanInputV2.recipients.selectionHint": "Выбрано получателей: {{count}}. В начале поля нажмите стрелку влево, чтобы перейти к ним.",
+ "nodes.humanInputV2.recipients.title": "Получатели",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Все контакты рабочего пространства",
+ "nodes.humanInputV2.recipients.type.contact": "Контакт",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Динамический адрес электронной почты",
+ "nodes.humanInputV2.recipients.type.initiator": "Инициатор",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Разовый адрес электронной почты",
+ "nodes.humanInputV2.recipients.typeLabel": "Тип получателя",
"nodes.humanInputV2.recipients.useThisInstead": "Использовать этот вариант",
+ "nodes.humanInputV2.recipients.variableRequired": "Выберите переменную с адресом электронной почты",
+ "nodes.humanInputV2.template.body": "Текст",
+ "nodes.humanInputV2.template.description": "Резервный текст для электронной почты и мессенджеров",
"nodes.humanInputV2.template.insertRequestURL": "Вставить URL запроса",
+ "nodes.humanInputV2.template.insertVariable": "Вставить переменную",
+ "nodes.humanInputV2.template.notConfigured": "Не настроено",
"nodes.humanInputV2.template.requestURLHint": "Получатели открывают форму согласования по этой ссылке. Добавьте ровно один URL запроса.",
"nodes.humanInputV2.template.requestURLInserted": "URL запроса вставлен",
"nodes.humanInputV2.template.saveAndTest": "Сохранить и проверить",
+ "nodes.humanInputV2.template.subject": "Тема",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Введите тему сообщения",
"nodes.humanInputV2.template.test": "Проверить сообщение",
"nodes.humanInputV2.template.testChannel": "Канал для теста",
"nodes.humanInputV2.template.testCompleted": "Тестовый запрос выполнен. Проверьте сообщение в выбранном канале.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Заполните значения всех тестовых переменных.",
"nodes.humanInputV2.template.testSaveFailed": "Не удалось сохранить черновик рабочего процесса. Тест не был отправлен.",
"nodes.humanInputV2.template.testUnavailable": "Эта среда пока не поддерживает тестирование шаблонов сообщений.",
+ "nodes.humanInputV2.template.title": "Шаблон сообщения",
"nodes.ifElse.operator": "Оператор",
"nodes.iteration.currentIteration": "Текущая итерация",
"nodes.iteration.deleteDesc": "Удаление узла итерации приведет к удалению всех дочерних узлов",
diff --git a/web/i18n/locales/sl-SI/contacts.json b/web/i18n/locales/sl-SI/contacts.json
index a405615bad7..0c00c8583a5 100644
--- a/web/i18n/locales/sl-SI/contacts.json
+++ b/web/i18n/locales/sl-SI/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Odstranim stike ({{count}})?",
"directory.removalDescription": "Izbrani stiki bodo trajno odstranjeni iz tega delovnega prostora. Tega dejanja ni mogoče razveljaviti.",
- "directory.removalTitle": "Odstranim stike?",
+ "directory.removalSingleDescription": "Stik {{name}} bo trajno odstranjen iz tega delovnega prostora. Tega dejanja ni mogoče razveljaviti.",
+ "directory.removalSingleFailed": "Stika ni bilo mogoče odstraniti. Poskusite znova.",
+ "directory.removalSingleTitle": "Odstranim {{name}}?",
+ "directory.resultCount": "Rezultati: {{count}}",
+ "imPlatform.action.configure": "Konfiguriraj",
+ "imPlatform.action.configureChannel": "Konfigurirajte {{provider}}",
+ "imPlatform.action.connect": "Poveži",
+ "imPlatform.action.copied": "Kopirati",
+ "imPlatform.action.copyCallback": "Kopiraj URL povratnega klica",
+ "imPlatform.action.deleteChannel": "Izbriši {{provider}}",
+ "imPlatform.action.loadMore": "Naloži več",
+ "imPlatform.action.replace": "Zamenjaj",
+ "imPlatform.action.retry": "Poskusi znova",
+ "imPlatform.action.save": "Shrani",
+ "imPlatform.action.saving": "Shranjevanje",
+ "imPlatform.action.setupGuide": "Vodnik za nastavitev",
+ "imPlatform.action.syncNow": "Sinhroniziraj zdaj",
+ "imPlatform.action.syncing": "Sinhroniziranje",
+ "imPlatform.action.testConnection": "Preizkusi povezavo",
+ "imPlatform.action.testing": "Preizkušanje",
+ "imPlatform.action.viewDetails": "Poglej podrobnosti",
+ "imPlatform.bindingDialog.back": "Nazaj",
+ "imPlatform.bindingDialog.callback": "URL za povratni klic",
+ "imPlatform.bindingDialog.callbackDescription": "Dokončajte nastavitev povratnih klicev v {{provider}}, da omogočite dejanja kartic.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Za dejanja kartic prilepite ta URL v <console>razvijalsko konzolo Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Dogodki in povratni klici → Konfiguracija povratnih klicev → URL zahteve",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Za dejanja kartic prilepite ta URL v <console>razvijalsko konzolo Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Dogodki in povratni klici → Konfiguracija povratnih klicev → URL zahteve",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Za dejanja kartic prilepite ta URL v <console>razvijalsko konzolo Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Interaktivnost in bližnjice → Interaktivnost → URL zahteve",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Za dejanja kartic prilepite ta URL v <console>konfiguracijo Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Nastavitve → Konfiguracija → Končna točka za sporočila",
+ "imPlatform.bindingDialog.callbackStep": "Konfiguriraj povratne klice",
"imPlatform.bindingDialog.clearSavedCredential": "Počisti shranjeno vrednost",
+ "imPlatform.bindingDialog.configureTitle": "Konfigurirajte {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Povežite {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Ta shranjena vrednost bo ob shranjevanju počiščena.",
+ "imPlatform.bindingDialog.credentialsDescription": "Najprej povežite aplikacijo {{provider}}, nato konfigurirajte njen URL povratnega klica.",
+ "imPlatform.bindingDialog.credentialsStep": "Poverilnice aplikacije",
+ "imPlatform.bindingDialog.description": "Vnesite poverilnice aplikacije za tega ponudnika neposrednega sporočanja.",
+ "imPlatform.bindingDialog.field.agentId": "ID agenta",
+ "imPlatform.bindingDialog.field.appId": "ID aplikacije",
+ "imPlatform.bindingDialog.field.appToken": "Žeton aplikacije (izbirno)",
+ "imPlatform.bindingDialog.field.botToken": "Žeton bota",
+ "imPlatform.bindingDialog.field.clientId": "ID odjemalca",
+ "imPlatform.bindingDialog.field.clientSecret": "Skrivnost odjemalca",
+ "imPlatform.bindingDialog.field.corpId": "ID podjetja",
+ "imPlatform.bindingDialog.field.encryptKey": "Šifrirni ključ (izbirno)",
+ "imPlatform.bindingDialog.field.genericSecret": "Skrivnost",
+ "imPlatform.bindingDialog.field.secret": "Skrivnost aplikacije",
+ "imPlatform.bindingDialog.field.signingSecret": "Skrivnost za podpisovanje",
+ "imPlatform.bindingDialog.field.tenantId": "ID najemnika",
+ "imPlatform.bindingDialog.field.verificationToken": "Preveritveni žeton (izbirno)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Vnesite šifrirni ključ, če je omogočen",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Vnesite skrivnost aplikacije",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Vnesite preveritveni žeton, če je konfiguriran",
+ "imPlatform.bindingDialog.finish": "Dokončaj",
+ "imPlatform.bindingDialog.freshCredentials": "Shranjenih skrivnosti ni mogoče pridobiti. Za preizkus ali shranjevanje te konfiguracije znova vnesite vse zahtevane poverilnice.",
+ "imPlatform.bindingDialog.openSetupGuide": "Odpri vodnik za nastavitev",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Zamenjam poverilnice najemnika za {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Ti prijavni podatki pripadajo drugemu najemniku IM in jih ni mogoče neposredno shraniti. Za zamenjavo najemnika morate zamenjati trenutni kanal IM, s čimer se izbrišejo vse samodejne in ročne povezave IM. Po zamenjavi znova sinhronizirajte stike.",
+ "imPlatform.bindingDialog.required": "To polje je obvezno.",
+ "imPlatform.bindingDialog.saveAndContinue": "Shrani in nadaljuj",
+ "imPlatform.bindingDialog.saveFailed": "Konfiguracije ni bilo mogoče shraniti. Preverite polja in poskusite znova.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Konfiguracija je bila shranjena, vendar podrobnosti ni bilo mogoče naložiti. Zaprite to pogovorno okno in ga znova odprite.",
- "imPlatform.bindingDialog.undoClearCredential": "Razveljavi čiščenje"
+ "imPlatform.bindingDialog.secretConfigured": "Skrivnost je že konfigurirana. Če jo želite ohraniti, pustite to polje prazno.",
+ "imPlatform.bindingDialog.step": "Korak {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Preizkus povezave ni uspel. Preverite konfiguracijo in poskusite znova.",
+ "imPlatform.bindingDialog.undoClearCredential": "Razveljavi čiščenje",
+ "imPlatform.bindingDialog.viewSetupGuide": "Prikaži vodnik za nastavitev",
+ "imPlatform.chooseProvider": "Izberite kanal za povezavo",
+ "imPlatform.configurationUpdated": "Konfiguracija tega kanala se je spremenila. Zaprite to pogovorno okno in osvežite stran, preden poskusite znova.",
+ "imPlatform.connectMore": "Poveži več kanalov",
+ "imPlatform.delete.confirm": "Izbriši",
+ "imPlatform.delete.description": "Izbris tega kanala odstrani njegovo konfiguracijo. Obvestila o odobritvah in sinhronizacije imenika, ki ga uporabljajo, se bodo ustavile.",
+ "imPlatform.delete.failed": "Kanala ni bilo mogoče izbrisati. Nič se ni spremenilo; poskusite znova.",
+ "imPlatform.delete.title": "Izbrišem kanal {{provider}}?",
+ "imPlatform.description": "Povežite kanale svojega podjetja, da zahteve za odobritev dosežejo ljudi tam, kjer delajo.",
+ "imPlatform.details.column.contact": "Stiki",
+ "imPlatform.details.column.platform": "Platforma za neposredno sporočanje",
+ "imPlatform.details.description": "Prikažite rezultate zadnje sinhronizacije samo za branje.",
+ "imPlatform.details.downloadFailed": "Poročila ni bilo mogoče prenesti. Poskusite znova.",
+ "imPlatform.details.downloadReport": "Prenesi poročilo",
+ "imPlatform.details.downloadingReport": "Prenašanje poročila…",
+ "imPlatform.details.empty": "V tej kategoriji ni rezultatov.",
+ "imPlatform.details.filter.added": "Dodano",
+ "imPlatform.details.filter.failed": "Neuspešno",
+ "imPlatform.details.filter.not_matched": "Ni ujemanja",
+ "imPlatform.details.filter.removed": "Odstranjeno",
+ "imPlatform.details.filter.skipped": "Preskočeno",
+ "imPlatform.details.filters": "Filtri rezultatov sinhronizacije",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Podrobnosti sinhronizacije ni bilo mogoče naložiti.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Več rezultatov ni bilo mogoče naložiti. Znova poskusite naložiti to stran.",
+ "imPlatform.details.removalReason.binding_invalidated": "Povezava razveljavljena",
+ "imPlatform.details.removalReason.binding_replaced": "Povezava zamenjana",
+ "imPlatform.details.removalReason.not_present_in_directory": "Ni več v imeniku",
+ "imPlatform.details.reportChanged": "Rezultati sinhronizacije so se spremenili. Znova odprite podrobnosti zadnje sinhronizacije in poskusite znova.",
+ "imPlatform.details.title": "Podrobnosti sinhronizacije",
+ "imPlatform.email.apiKey": "API ključ",
+ "imPlatform.email.apiKeyConfigured": "Zaradi varnosti shranjenega ključa API ni mogoče prikazati. Če ga želite ohraniti, pustite to polje prazno.",
+ "imPlatform.email.apiKeyDescription": "Zaradi varnosti tega ključa API po shranjevanju ni mogoče prikazati.",
+ "imPlatform.email.apiKeyPlaceholder": "Vnesite svoj ključ API Resend",
+ "imPlatform.email.description": "Ta konfiguracija velja za vsa vozlišča človeškega vnosa v tem delovnem prostoru, pri katerih je omogočeno <emphasis>Pošiljanje obvestil za odpravljanje napak po e-pošti</emphasis>.",
+ "imPlatform.email.invalidEmail": "Vnesite veljaven e-poštni naslov.",
+ "imPlatform.email.provider": "Ponudnik e-pošte",
+ "imPlatform.email.resendDescription": "Vaš <apiKey>ključ API Resend</apiKey> bo šifriran in ga po shranjevanju ne bo mogoče prikazati.<br/>Ustvarite račun <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Nastavitve Resend",
+ "imPlatform.email.senderEmail": "E-poštni naslov pošiljatelja",
+ "imPlatform.email.senderEmailDescription": "E-poštni naslov, ki je prikazan kot pošiljatelj. Njegova domena mora biti preverjena v Resend.",
+ "imPlatform.email.senderName": "Ime pošiljatelja",
+ "imPlatform.email.senderNameDescription": "Ime, prikazano v prejemnikovem poštnem predalu.",
+ "imPlatform.email.testSucceeded": "Preizkus povezave je uspel.",
+ "imPlatform.email.title": "Konfiguriraj e-pošto",
+ "imPlatform.learnMore": "Več o tem",
+ "imPlatform.loadError.description": "Znova poskusite prebrati trenutno povezavo in dovoljenja.",
+ "imPlatform.loadError.retry": "Poskusi znova",
+ "imPlatform.loadError.title": "Kanalov ni bilo mogoče naložiti",
+ "imPlatform.loading": "Nalaganje kanalov",
+ "imPlatform.provider.dingtalkDescription": "Povežite aplikacijo DingTalk.",
+ "imPlatform.provider.emailDescription": "Konfigurirajte e-poštno storitev za pošiljanje zahtev za odobritev iz tega delovnega prostora.",
+ "imPlatform.provider.feishuDescription": "Povežite aplikacijo Feishu.",
+ "imPlatform.provider.larkDescription": "Povežite aplikacijo Lark.",
+ "imPlatform.provider.msTeamsDescription": "Povežite aplikacijo Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Sinhronizirajte osebe in njihove identitete Slack.",
+ "imPlatform.provider.weComDescription": "Povežite aplikacijo WeCom.",
+ "imPlatform.replacement.confirm": "Zamenjaj",
+ "imPlatform.replacement.description": "Zamenjava aktivnega ponudnika razveljavi njegove povezave za neposredno sporočanje in prilagoditve delovnega prostora. Po zamenjavi znova sinhronizirajte imenik novega ponudnika.",
+ "imPlatform.replacement.title": "Zamenjam {{current}} z {{next}}?",
+ "imPlatform.status.configured": "Konfigurirano",
+ "imPlatform.status.connected": "Povezani",
+ "imPlatform.status.connection_error": "Napaka povezave",
+ "imPlatform.status.permission_issue": "Težava z dovoljenji",
+ "imPlatform.sync.latestSynced": "Nazadnje sinhronizirano: {{date}}",
+ "imPlatform.sync.loading": "Preverjanje aktivne sinhronizacije.",
+ "imPlatform.sync.noPermission": "Sinhronizacijo imenika lahko zaženejo samo lastniki in skrbniki delovnega prostora.",
+ "imPlatform.sync.noRuns": "Sinhronizacija imenika še ni bila izvedena.",
+ "imPlatform.sync.notConnected": "Pred začetkom sinhronizacije imenika povežite ponudnika in preizkusite povezavo.",
+ "imPlatform.sync.startFailed": "Sinhronizacije imenika ni bilo mogoče zagnati ali osvežiti. Poskusite znova.",
+ "imPlatform.sync.status.failure": "Neuspešno",
+ "imPlatform.sync.status.queued": "V čakalni vrsti",
+ "imPlatform.sync.status.running": "Se izvaja",
+ "imPlatform.sync.status.success": "Uspešno",
+ "imPlatform.title": "Kanali"
}
diff --git a/web/i18n/locales/sl-SI/share.json b/web/i18n/locales/sl-SI/share.json
index 779682cdd36..bd1256a6c91 100644
--- a/web/i18n/locales/sl-SI/share.json
+++ b/web/i18n/locales/sl-SI/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Hvala!",
"humanInput.unavailableDescription": "Povezava morda ni na voljo ali se ne ujema z računom, s katerim ste prijavljeni. Obrazec odprite iz prejetega obvestila ali poskusite zamenjati račun.",
"humanInput.unavailableTitle": "Tega obrazca ni mogoče odpreti",
+ "humanInputV2.accessRateLimited": "Zahtevanih je bilo preveč potrditvenih e-poštnih sporočil. Poskusite znova pozneje.",
+ "humanInputV2.alreadySubmitted": "Ta zahteva je že zaključena.",
+ "humanInputV2.challengeExpired": "Ta potrditvena koda je potekla. Za nadaljevanje zahtevajte novo kodo.",
+ "humanInputV2.challengeStale": "Ta potrditvena koda je bila zamenjana. Za nadaljevanje zahtevajte novo kodo.",
+ "humanInputV2.codeExpiresIn": "Koda poteče čez {{seconds}} s",
+ "humanInputV2.codeRequired": "Za nadaljevanje zahtevajte potrditveno kodo.",
+ "humanInputV2.codeSent": "Potrditvena koda je bila poslana na vaš e-poštni naslov.",
+ "humanInputV2.deliveryFailed": "Potrditvenega e-poštnega sporočila ni bilo mogoče poslati. Poskusite znova.",
+ "humanInputV2.formExpired": "Ta zahteva je potekla.",
+ "humanInputV2.formNotFound": "Obrazca ni mogoče najti.",
+ "humanInputV2.formRateLimited": "Preveč zahtev za obrazec. Poskusite znova pozneje.",
+ "humanInputV2.invalidOtp": "Potrditvena koda ni pravilna. Preverite jo in poskusite znova.",
+ "humanInputV2.networkError": "Zahteve ni bilo mogoče dokončati. Preverite povezavo in poskusite znova.",
+ "humanInputV2.otpLabel": "Koda za potrditev e-poštnega naslova",
+ "humanInputV2.otpPlaceholder": "Vnesite šestmestno kodo",
+ "humanInputV2.requestingCode": "Pošiljanje potrditvene kode…",
+ "humanInputV2.resendCode": "Znova pošlji kodo",
+ "humanInputV2.retry": "Poskusi znova",
+ "humanInputV2.sendCode": "Pošlji novo kodo",
+ "humanInputV2.unavailable": "Ta obrazec začasno ni na voljo.",
+ "humanInputV2.unknownError": "Prišlo je do napake. Poskusite znova.",
+ "humanInputV2.uploadFailed": "Datoteke ni bilo mogoče naložiti. Poskusite znova.",
"login.backToHome": "Nazaj na začetno stran"
}
diff --git a/web/i18n/locales/sl-SI/workflow-human-input.json b/web/i18n/locales/sl-SI/workflow-human-input.json
index 80725c05db7..39db6172943 100644
--- a/web/i18n/locales/sl-SI/workflow-human-input.json
+++ b/web/i18n/locales/sl-SI/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Vrednost dejanja",
"nodes.humanInput.userActions.buttonTextTooLong": "Besedilo gumba mora biti {{maxLength}} znakov ali manj",
"nodes.humanInput.userActions.chooseStyle": "Izberite slog gumba",
+ "nodes.humanInput.userActions.defaultTitle": "Besedilo gumba {{index}}",
"nodes.humanInput.userActions.emptyTip": "Kliknite gumb '+' za dodajanje uporabniških dejanj",
"nodes.humanInput.userActions.title": "Uporabniška dejanja",
"nodes.humanInput.userActions.tooltip": "Definirajte gumbe, ki jih lahko uporabniki kliknejo, da se odzovejo na ta obrazec. ID dejanja nadzoruje razvejanje. Vrednost dejanja je izpostavljena navzdol kot izbrani vgrajeni izhod. ID dejanja se mora začeti s črko ali podčrtajem, ki mu sledijo črke, številke ali podčrtaji.",
diff --git a/web/i18n/locales/sl-SI/workflow.json b/web/i18n/locales/sl-SI/workflow.json
index 59aa50214f5..fd7cfe1126a 100644
--- a/web/i18n/locales/sl-SI/workflow.json
+++ b/web/i18n/locales/sl-SI/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Izhod",
"blocks.http-request": "HTTP zahteva",
"blocks.human-input": "Človeški vnos",
+ "blocks.human-input-v2": "Človeški vnos v2",
"blocks.if-else": "Če/Drugače",
"blocks.iteration": "Iteracija",
"blocks.iteration-start": "Začetek iteracije",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Določite izhod in tip rezultata delovnega toka",
"blocksAbout.http-request": "Dovoli pošiljanje zahtevkov strežniku prek protokola HTTP",
"blocksAbout.human-input": "Prosite za človeško potrditev pred ustvarjanjem naslednjega koraka",
+ "blocksAbout.human-input-v2": "Zahtevajte vnos od nastavljenih stikov, e-poštnih prejemnikov ali pobudnika delovnega toka",
"blocksAbout.if-else": "Omogoča vam, da razdelite delovni tok na dve veji na podlagi pogojev if/else.",
"blocksAbout.iteration": "Izvedite več korakov na seznamu objektov, dokler niso vsi rezultati izpisani.",
"blocksAbout.iteration-start": "Začetni vozel iteracije",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Združite večpodružnične spremenljivke v eno samo spremenljivko za enotno konfiguracijo spodnjih vozlišč.",
"blocksAbout.variable-assigner": "Združite večpodružinske spremenljivke v eno samo spremenljivko za enotno konfiguracijo spodnjih vozlišč.",
"changeHistory.edgeDelete": "Vozlišče je odklopljeno",
+ "changeHistory.humanInputMigration": "Vozlišča človeškega vnosa so preseljena",
"changeHistory.nodeAdd": "Vozlišče dodano",
"changeHistory.nodeChange": "Vozlišče se je spremenilo",
"changeHistory.nodeConnect": "Povezana vozlišča",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Omogočite vsaj en način dostave",
"nodes.humanInput.errorMsg.noUserActions": "Dodajte vsaj eno uporabniško dejanje",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} je rezerviran za vejo časovne omejitve. Izberite drug ID dejanja.",
+ "nodes.humanInput.output.actionId": "ID dejanja, ki ga je sprožil uporabnik",
+ "nodes.humanInput.output.actionValue": "Vrednost izbranega dejanja",
+ "nodes.humanInput.output.formInput": "Vrednost vnosa v obrazec",
+ "nodes.humanInput.output.renderedContent": "Izrisana vsebina",
"nodes.humanInput.timeout.title": "Časovna omejitev",
+ "nodes.humanInputMigration.action.migrate": "Preseli",
+ "nodes.humanInputMigration.action.migrateNow": "Preseli zdaj",
+ "nodes.humanInputMigration.action.migrating": "Selitev...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Obvestilo o selitvi človeškega vnosa",
+ "nodes.humanInputMigration.banner.description": "Ta delovni tok uporablja staro vozlišče človeškega vnosa. Pred dodajanjem novih preselite vsa stara vozlišča.",
+ "nodes.humanInputMigration.banner.learnMore": "Več informacij",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "onemogočen način dostave še vedno vsebuje nastavitve",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "omogočeni načini e-poštne dostave uporabljajo neusklajene predloge",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Neveljavna privzeta vrednost",
+ "nodes.humanInputMigration.blocker.invalidEmail": "e-poštni naslov prejemnika ni veljaven",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "nastavitev omogočenega načina e-poštne dostave ni dokončana",
+ "nodes.humanInputMigration.blocker.missingRecipients": "vozlišče nima podprtih prejemnikov",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "člana delovnega prostora ni mogoče povezati s stikom ali potrjenim e-poštnim naslovom",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "omogočenega načina dostave človeški vnos v2 ne podpira",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Polja {{field}} še ni mogoče preseliti. Še naprej lahko uporabljate stare vozle za človeški vnos.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "vozlišče ima nepodprto vrednost različice",
+ "nodes.humanInputMigration.dialog.description": "Prejemniki, obrazec in dejanja se bodo ohranili.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Spremeni se le ta osnutek. Objavljene različice se bodo izvajale do ponovne objave.",
+ "nodes.humanInputMigration.dialog.review": "Preglejte vozlišča in objavite, ko boste pripravljeni.",
+ "nodes.humanInputMigration.dialog.title": "Preseli vozlišča človeškega vnosa: {{count}}",
+ "nodes.humanInputMigration.disabledBadge": "POTREBNA JE SELITEV",
+ "nodes.humanInputMigration.disabledReason": "Pred dodajanjem novega vozlišča preselite stara vozlišča človeškega vnosa.",
+ "nodes.humanInputMigration.error.blocked": "Vozlišča {{nodeTitle}} ni bilo mogoče preseliti: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Delovni tok se je med selitvijo spremenil. Poskusite znova; trenutne spremembe so ohranjene.",
+ "nodes.humanInputMigration.error.preflight": "Selitve ni bilo mogoče pripraviti. Delovni tok ni bil spremenjen. Poskusite znova.",
"nodes.humanInputMigration.error.sync": "Preseljenega delovnega toka ni bilo mogoče shraniti. Preglejte trenutni osnutek in poskusite znova.",
+ "nodes.humanInputMigration.incompatibleVersions": "Starih in novih vozlišč za človeški vnos ni mogoče uporabljati v istem delovnem toku.",
+ "nodes.humanInputMigration.oldVersion": "STARA RAZLIČICA",
+ "nodes.humanInputMigration.preview.author": "Ekipa Dify",
+ "nodes.humanInputMigration.preview.description": "Pred dodajanjem novega vozlišča preselite stara vozlišča človeškega vnosa.",
+ "nodes.humanInputMigration.success": "Vozlišča človeškega vnosa so bila uspešno preseljena",
+ "nodes.humanInputV2.card.configured": "Nastavljeni prejemniki: {{count}}",
+ "nodes.humanInputV2.card.contactsOnly": "Stiki: {{count}}",
+ "nodes.humanInputV2.card.empty": "Tega koraka še nihče ne more odobriti",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Pobudnik in stiki: {{count}}",
+ "nodes.humanInputV2.card.initiatorOnly": "Samo pobudnik",
+ "nodes.humanInputV2.card.invalid": "Preverite nastavitve prejemnikov",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-pošta",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Nastavi način razhroščevanja",
"nodes.humanInputV2.debug.keepOneChannel": "Ohranite vklopljen vsaj en kanal",
+ "nodes.humanInputV2.debug.sendVia": "Pošlji obvestila razhroščevanja prek",
+ "nodes.humanInputV2.debug.title": "Način razhroščevanja",
+ "nodes.humanInputV2.debug.toggle": "Omogoči način razhroščevanja",
+ "nodes.humanInputV2.debug.unsupported": "Nepodprti uvoženi kanali: {{channels}}. Pred zagonom tega delovnega toka jih odstranite ali posodobite.",
"nodes.humanInputV2.disabled": "Human Input v2 ni na voljo, ko je HITL IM onemogočen.",
+ "nodes.humanInputV2.error.bodyRequired": "Vsebina sporočila je obvezna",
+ "nodes.humanInputV2.error.debugChannelRequired": "Izberite vsaj en kanal načina razhroščevanja",
+ "nodes.humanInputV2.error.recipientDuplicate": "Odstranite podvojene prejemnike",
+ "nodes.humanInputV2.error.recipientInvalid": "Popravite neveljavne nastavitve prejemnikov",
+ "nodes.humanInputV2.error.recipientRequired": "Dodajte vsaj enega prejemnika",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Prejemnikov iz stikov ni bilo mogoče preveriti",
"nodes.humanInputV2.error.requestURLDuplicate": "Besedilo sporočila lahko vsebuje samo en URL zahteve.",
"nodes.humanInputV2.error.requestURLRequired": "V besedilo sporočila vstavite URL zahteve.",
+ "nodes.humanInputV2.error.subjectRequired": "Zadeva sporočila je obvezna",
+ "nodes.humanInputV2.error.version": "Človeški vnos v2 zahteva različico 2, zapisano kot niz",
+ "nodes.humanInputV2.recipients.addContact": "Dodaj stik",
+ "nodes.humanInputV2.recipients.addEmail": "Dodaj",
+ "nodes.humanInputV2.recipients.addRecipient": "Dodaj prejemnika",
+ "nodes.humanInputV2.recipients.added": "Dodano",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Vsi stiki v delovnem prostoru",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Pošljite obvestilo vsem stikom v delovnem prostoru; odobri lahko kateri koli od njih",
+ "nodes.humanInputV2.recipients.cancel": "Prekliči",
+ "nodes.humanInputV2.recipients.chooseVariable": "Izberi spremenljivko",
+ "nodes.humanInputV2.recipients.confirm": "Potrdi",
+ "nodes.humanInputV2.recipients.contactInfo": "Kontaktni podatki za {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Vsi",
+ "nodes.humanInputV2.recipients.contactSource.external": "Zunanji",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Organizacija",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Delovni prostor",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Vir stikov",
"nodes.humanInputV2.recipients.duplicateSource": "Že dodano prek {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Uredi {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Uredi prejemnika",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Vsak e-poštni naslov lahko izberete samo enkrat.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Vnesite veljaven e-poštni naslov, ki še ni dodan",
+ "nodes.humanInputV2.recipients.emailLabel": "Enkratni e-poštni prejemnik",
+ "nodes.humanInputV2.recipients.empty": "Prejemniki niso nastavljeni",
+ "nodes.humanInputV2.recipients.help": "Izberite, kdo lahko odgovori v tem koraku človeškega vnosa.",
"nodes.humanInputV2.recipients.initiator": "Uporabnik, ki zažene to izvajanje prek Web App ali CLI, lahko odobri",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Odgovori lahko oseba, ki zažene ta delovni tok.",
"nodes.humanInputV2.recipients.inputHelp": "Vnesite ali prilepite več e-poštnih naslovov, ločenih z vejicami. Pritisnite /, da vstavite spremenljivko.",
+ "nodes.humanInputV2.recipients.insertVariable": "Vstavi spremenljivko",
+ "nodes.humanInputV2.recipients.loadError": "Stikov ni bilo mogoče naložiti. Shranjeni ID-ji stikov so ohranjeni.",
+ "nodes.humanInputV2.recipients.loading": "Nalaganje stikov…",
+ "nodes.humanInputV2.recipients.noResults": "Ni najdenih stikov",
+ "nodes.humanInputV2.recipients.placeholder": "Poiščite stike ali dodajte e-poštne naslove",
+ "nodes.humanInputV2.recipients.remove": "Odstrani {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Za odstranitev pritisnite Backspace ali Delete.",
+ "nodes.humanInputV2.recipients.resultCount": "Ujemajoči se prejemniki: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Poišči stike",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Išči po imenu ali e-poštnem naslovu",
+ "nodes.humanInputV2.recipients.selectionHint": "Izbrani prejemniki: {{count}}. Na začetku vnosnega polja pritisnite puščico levo, da jih izberete.",
+ "nodes.humanInputV2.recipients.title": "Prejemniki",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Vsi stiki v delovnem prostoru",
+ "nodes.humanInputV2.recipients.type.contact": "Stik",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Dinamični e-poštni naslov",
+ "nodes.humanInputV2.recipients.type.initiator": "Pobudnik",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Enkratni e-poštni naslov",
+ "nodes.humanInputV2.recipients.typeLabel": "Vrsta prejemnika",
"nodes.humanInputV2.recipients.useThisInstead": "Uporabi to namesto tega",
+ "nodes.humanInputV2.recipients.variableRequired": "Izberite spremenljivko z e-poštnim naslovom",
+ "nodes.humanInputV2.template.body": "Vsebina",
+ "nodes.humanInputV2.template.description": "Nadomestno besedilo za e-pošto in neposredna sporočila",
"nodes.humanInputV2.template.insertRequestURL": "Vstavi URL zahteve",
+ "nodes.humanInputV2.template.insertVariable": "Vstavi spremenljivko",
+ "nodes.humanInputV2.template.notConfigured": "Ni nastavljeno",
"nodes.humanInputV2.template.requestURLHint": "Prejemniki prek te povezave odprejo obrazec za odobritev. Vključite natanko en URL zahteve.",
"nodes.humanInputV2.template.requestURLInserted": "URL zahteve je vstavljen",
"nodes.humanInputV2.template.saveAndTest": "Shrani in preizkusi",
+ "nodes.humanInputV2.template.subject": "Zadeva",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Vnesite zadevo sporočila",
"nodes.humanInputV2.template.test": "Preizkusi sporočilo",
"nodes.humanInputV2.template.testChannel": "Preizkusni kanal",
"nodes.humanInputV2.template.testCompleted": "Preizkusna zahteva je zaključena. Preverite sporočilo v izbranem kanalu.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Vnesite vse vrednosti preizkusnih spremenljivk.",
"nodes.humanInputV2.template.testSaveFailed": "Osnutka poteka dela ni bilo mogoče shraniti. Preizkus ni bil poslan.",
"nodes.humanInputV2.template.testUnavailable": "To okolje še ne podpira preizkušanja predlog sporočil.",
+ "nodes.humanInputV2.template.title": "Predloga sporočila",
"nodes.ifElse.operator": "Operater",
"nodes.iteration.currentIteration": "Trenutna iteracija",
"nodes.iteration.deleteDesc": "Izbris iteracijskega vozlišča bo izbrisal vsa otroška vozlišča.",
diff --git a/web/i18n/locales/th-TH/contacts.json b/web/i18n/locales/th-TH/contacts.json
index 06a255c33ca..03395bafd32 100644
--- a/web/i18n/locales/th-TH/contacts.json
+++ b/web/i18n/locales/th-TH/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "นำผู้ติดต่อออก ({{count}}) หรือไม่",
"directory.removalDescription": "ผู้ติดต่อที่เลือกจะถูกลบออกจากพื้นที่ทำงานนี้อย่างถาวร การดำเนินการนี้ไม่สามารถยกเลิกได้",
- "directory.removalTitle": "ลบผู้ติดต่อหรือไม่?",
+ "directory.removalSingleDescription": "{{name}} จะถูกนำออกจากพื้นที่ทำงานนี้อย่างถาวร การดำเนินการนี้ไม่สามารถยกเลิกได้",
+ "directory.removalSingleFailed": "ไม่สามารถนำผู้ติดต่อออกได้ โปรดลองอีกครั้ง",
+ "directory.removalSingleTitle": "นำ {{name}} ออกหรือไม่",
+ "directory.resultCount": "ผลลัพธ์: {{count}}",
+ "imPlatform.action.configure": "กําหนดค่า",
+ "imPlatform.action.configureChannel": "กำหนดค่า {{provider}}",
+ "imPlatform.action.connect": "ติด",
+ "imPlatform.action.copied": "คัด ลอก",
+ "imPlatform.action.copyCallback": "คัดลอก URL คอลแบ็ก",
+ "imPlatform.action.deleteChannel": "ลบ {{provider}}",
+ "imPlatform.action.loadMore": "โหลดเพิ่มเติม",
+ "imPlatform.action.replace": "แทนที่",
+ "imPlatform.action.retry": "ลอง",
+ "imPlatform.action.save": "บันทึก",
+ "imPlatform.action.saving": "กำลังบันทึก",
+ "imPlatform.action.setupGuide": "คู่มือการตั้งค่า",
+ "imPlatform.action.syncNow": "ซิงค์เลย",
+ "imPlatform.action.syncing": "กำลังซิงค์",
+ "imPlatform.action.testConnection": "ทดสอบการเชื่อมต่อ",
+ "imPlatform.action.testing": "กำลังทดสอบ",
+ "imPlatform.action.viewDetails": "ดูรายละเอียด",
+ "imPlatform.bindingDialog.back": "ย้อนกลับ",
+ "imPlatform.bindingDialog.callback": "URL สำหรับเรียกกลับ",
+ "imPlatform.bindingDialog.callbackDescription": "ตั้งค่าคอลแบ็กใน {{provider}} ให้เสร็จเพื่อเปิดใช้งานการดำเนินการบนการ์ด",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "เพื่อรับการดำเนินการบนการ์ด ให้วาง URL นี้ใน <console>คอนโซลนักพัฒนา Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "เหตุการณ์และคอลแบ็ก → การกำหนดค่าคอลแบ็ก → URL คำขอ",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "เพื่อรับการดำเนินการบนการ์ด ให้วาง URL นี้ใน <console>คอนโซลนักพัฒนา Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "เหตุการณ์และคอลแบ็ก → การกำหนดค่าคอลแบ็ก → URL คำขอ",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "เพื่อรับการดำเนินการบนการ์ด ให้วาง URL นี้ใน <console>คอนโซลนักพัฒนา Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "การโต้ตอบและทางลัด → การโต้ตอบ → URL คำขอ",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "เพื่อรับการดำเนินการบนการ์ด ให้วาง URL นี้ใน <console>การกำหนดค่า Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "การตั้งค่า → การกำหนดค่า → จุดเชื่อมต่อการรับส่งข้อความ",
+ "imPlatform.bindingDialog.callbackStep": "กำหนดค่าคอลแบ็ก",
"imPlatform.bindingDialog.clearSavedCredential": "ล้างค่าที่บันทึกไว้",
+ "imPlatform.bindingDialog.configureTitle": "กำหนดค่า {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "เชื่อมต่อ {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "ค่าที่บันทึกไว้นี้จะถูกล้างเมื่อคุณบันทึก",
+ "imPlatform.bindingDialog.credentialsDescription": "เชื่อมต่อแอป {{provider}} ก่อน แล้วจึงกำหนดค่า URL คอลแบ็ก",
+ "imPlatform.bindingDialog.credentialsStep": "ข้อมูลรับรองแอป",
+ "imPlatform.bindingDialog.description": "ป้อนข้อมูลรับรองแอปของผู้ให้บริการ IM นี้",
+ "imPlatform.bindingDialog.field.agentId": "ID เอเจนต์",
+ "imPlatform.bindingDialog.field.appId": "ID แอป",
+ "imPlatform.bindingDialog.field.appToken": "โทเค็นแอป (ไม่บังคับ)",
+ "imPlatform.bindingDialog.field.botToken": "โทเค็นบอต",
+ "imPlatform.bindingDialog.field.clientId": "รหัสลูกค้า",
+ "imPlatform.bindingDialog.field.clientSecret": "รหัสลับของลูกค้า",
+ "imPlatform.bindingDialog.field.corpId": "ID องค์กร",
+ "imPlatform.bindingDialog.field.encryptKey": "คีย์เข้ารหัส (ไม่บังคับ)",
+ "imPlatform.bindingDialog.field.genericSecret": "ความลับ",
+ "imPlatform.bindingDialog.field.secret": "ข้อมูลลับของแอป",
+ "imPlatform.bindingDialog.field.signingSecret": "ข้อมูลลับสำหรับการลงนาม",
+ "imPlatform.bindingDialog.field.tenantId": "ID ผู้เช่า",
+ "imPlatform.bindingDialog.field.verificationToken": "โทเค็นการตรวจสอบ (ไม่บังคับ)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "ป้อนคีย์เข้ารหัสหากเปิดใช้งาน",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "ป้อนข้อมูลลับของแอป",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "ป้อนโทเค็นการตรวจสอบหากกำหนดค่าไว้",
+ "imPlatform.bindingDialog.finish": "เสร็จสิ้น",
+ "imPlatform.bindingDialog.freshCredentials": "ไม่สามารถเรียกดูข้อมูลลับที่บันทึกไว้ได้ ป้อนข้อมูลรับรองที่จำเป็นทั้งหมดอีกครั้งเพื่อทดสอบหรือบันทึกการกำหนดค่านี้",
+ "imPlatform.bindingDialog.openSetupGuide": "เปิดคู่มือการตั้งค่า",
+ "imPlatform.bindingDialog.replaceTenantTitle": "แทนที่ข้อมูลรับรองผู้เช่าของ {{identity}} หรือไม่?",
"imPlatform.bindingDialog.replacementRequired": "ข้อมูลรับรองเหล่านี้เป็นของเทนเนนต์ IM อื่น จึงไม่สามารถบันทึกได้โดยตรง การเปลี่ยนเทนเนนต์จำเป็นต้องแทนที่ช่องทาง IM ปัจจุบัน ซึ่งจะลบการเชื่อมโยง IM ทั้งหมด ทั้งแบบอัตโนมัติและแบบกำหนดด้วยตนเอง หลังจากแทนที่แล้ว ให้ซิงค์รายชื่อผู้ติดต่ออีกครั้ง",
+ "imPlatform.bindingDialog.required": "จำเป็นต้องกรอกฟิลด์นี้",
+ "imPlatform.bindingDialog.saveAndContinue": "บันทึกและดำเนินการต่อ",
+ "imPlatform.bindingDialog.saveFailed": "บันทึกการกำหนดค่าไม่ได้ ตรวจสอบฟิลด์แล้วลองอีกครั้ง",
"imPlatform.bindingDialog.savedDetailsUnavailable": "บันทึกการกำหนดค่าแล้ว แต่โหลดรายละเอียดไม่ได้ ปิดกล่องโต้ตอบนี้แล้วเปิดอีกครั้ง",
- "imPlatform.bindingDialog.undoClearCredential": "เลิกทำการล้าง"
+ "imPlatform.bindingDialog.secretConfigured": "มีการกำหนดค่าข้อมูลลับแล้ว เว้นฟิลด์นี้ว่างไว้เพื่อเก็บค่าเดิม",
+ "imPlatform.bindingDialog.step": "ขั้นตอนที่ {{step}}",
+ "imPlatform.bindingDialog.testFailed": "ทดสอบการเชื่อมต่อไม่สำเร็จ ตรวจสอบการกำหนดค่าแล้วลองอีกครั้ง",
+ "imPlatform.bindingDialog.undoClearCredential": "เลิกทำการล้าง",
+ "imPlatform.bindingDialog.viewSetupGuide": "ดูคู่มือการตั้งค่า",
+ "imPlatform.chooseProvider": "เลือกช่องทางที่จะเชื่อมต่อ",
+ "imPlatform.configurationUpdated": "การกำหนดค่าช่องทางนี้เปลี่ยนไปแล้ว ปิดกล่องโต้ตอบนี้และรีเฟรชก่อนลองอีกครั้ง",
+ "imPlatform.connectMore": "เชื่อมต่อช่องทางเพิ่มเติม",
+ "imPlatform.delete.confirm": "ลบ",
+ "imPlatform.delete.description": "การลบช่องทางนี้จะลบการกำหนดค่าด้วย การส่งคำขออนุมัติหรือการซิงค์ไดเรกทอรีที่ใช้ช่องทางนี้จะหยุดทำงาน",
+ "imPlatform.delete.failed": "ลบช่องทางไม่ได้ ไม่มีการเปลี่ยนแปลงใด ๆ โปรดลองอีกครั้ง",
+ "imPlatform.delete.title": "ลบช่องทาง {{provider}} หรือไม่?",
+ "imPlatform.description": "เชื่อมต่อช่องทางของบริษัทเพื่อให้คำขออนุมัติส่งถึงผู้ใช้ในที่ทำงาน",
+ "imPlatform.details.column.contact": "ผู้ติดต่อ",
+ "imPlatform.details.column.platform": "แพลตฟอร์ม IM",
+ "imPlatform.details.description": "ดูผลลัพธ์แบบอ่านอย่างเดียวของการซิงค์ครั้งล่าสุด",
+ "imPlatform.details.downloadFailed": "ดาวน์โหลดรายงานไม่ได้ โปรดลองอีกครั้ง",
+ "imPlatform.details.downloadReport": "ดาวน์โหลดรายงาน",
+ "imPlatform.details.downloadingReport": "กำลังดาวน์โหลดรายงาน…",
+ "imPlatform.details.empty": "ไม่มีผลลัพธ์ในหมวดหมู่นี้",
+ "imPlatform.details.filter.added": "เพิ่มแล้ว",
+ "imPlatform.details.filter.failed": "ล้มเหลว",
+ "imPlatform.details.filter.not_matched": "ไม่ตรงกัน",
+ "imPlatform.details.filter.removed": "ถูก เอา ออก",
+ "imPlatform.details.filter.skipped": "ข้ามแล้ว",
+ "imPlatform.details.filters": "ตัวกรองผลการซิงค์",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "โหลดรายละเอียดการซิงค์ไม่ได้",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "โหลดผลลัพธ์เพิ่มเติมไม่ได้ ลองโหลดหน้านี้อีกครั้ง",
+ "imPlatform.details.removalReason.binding_invalidated": "การผูกถูกยกเลิก",
+ "imPlatform.details.removalReason.binding_replaced": "แทนที่การผูกแล้ว",
+ "imPlatform.details.removalReason.not_present_in_directory": "ไม่มีอยู่ในไดเรกทอรีแล้ว",
+ "imPlatform.details.reportChanged": "ผลการซิงค์เปลี่ยนไปแล้ว เปิดรายละเอียดการซิงค์ล่าสุดอีกครั้งแล้วลองใหม่",
+ "imPlatform.details.title": "รายละเอียดการซิงค์",
+ "imPlatform.email.apiKey": "คีย์ API",
+ "imPlatform.email.apiKeyConfigured": "เพื่อความปลอดภัย ไม่สามารถดูคีย์ API ที่บันทึกไว้ได้ เว้นฟิลด์นี้ว่างไว้เพื่อเก็บค่าเดิม",
+ "imPlatform.email.apiKeyDescription": "เพื่อความปลอดภัย ไม่สามารถดูคีย์ API นี้ได้หลังจากบันทึกแล้ว",
+ "imPlatform.email.apiKeyPlaceholder": "ป้อนคีย์ API ของ Resend",
+ "imPlatform.email.description": "การกำหนดค่านี้ใช้กับโหนด Human Input ทั้งหมดในเวิร์กสเปซนี้ที่เปิดใช้งาน <emphasis>ส่งการแจ้งเตือนการแก้จุดบกพร่องทางอีเมล</emphasis>",
+ "imPlatform.email.invalidEmail": "ป้อนที่อยู่อีเมลที่ถูกต้อง",
+ "imPlatform.email.provider": "ผู้ให้บริการอีเมล",
+ "imPlatform.email.resendDescription": "<apiKey>คีย์ API ของ Resend</apiKey> จะถูกเข้ารหัสและไม่สามารถดูได้หลังจากบันทึกแล้ว<br/>สมัครบัญชี <resend>Resend</resend>",
+ "imPlatform.email.resendSettings": "การตั้งค่า Resend",
+ "imPlatform.email.senderEmail": "ที่อยู่อีเมลผู้ส่ง",
+ "imPlatform.email.senderEmailDescription": "ที่อยู่อีเมลที่แสดงเป็นผู้ส่ง ต้องยืนยันโดเมนใน Resend",
+ "imPlatform.email.senderName": "ชื่อผู้ส่ง",
+ "imPlatform.email.senderNameDescription": "ชื่อที่แสดงในกล่องจดหมายของผู้รับ",
+ "imPlatform.email.testSucceeded": "ทดสอบการเชื่อมต่อสำเร็จ",
+ "imPlatform.email.title": "กำหนดค่าอีเมล",
+ "imPlatform.learnMore": "เรียนรู้เพิ่มเติม",
+ "imPlatform.loadError.description": "ลองอีกครั้งเพื่ออ่านการผูกและสิทธิ์ปัจจุบัน",
+ "imPlatform.loadError.retry": "ลองอีกครั้ง",
+ "imPlatform.loadError.title": "โหลดช่องทางไม่ได้",
+ "imPlatform.loading": "กำลังโหลดช่องทาง",
+ "imPlatform.provider.dingtalkDescription": "เชื่อมต่อแอป DingTalk",
+ "imPlatform.provider.emailDescription": "กำหนดค่าบริการอีเมลที่ใช้ส่งคำขออนุมัติจากเวิร์กสเปซนี้",
+ "imPlatform.provider.feishuDescription": "เชื่อมต่อแอป Feishu",
+ "imPlatform.provider.larkDescription": "เชื่อมต่อแอป Lark",
+ "imPlatform.provider.msTeamsDescription": "เชื่อมต่อแอป Microsoft Teams",
+ "imPlatform.provider.slackDescription": "ซิงค์ผู้ใช้และข้อมูลประจำตัว Slack",
+ "imPlatform.provider.weComDescription": "เชื่อมต่อแอป WeCom",
+ "imPlatform.replacement.confirm": "แทนที่",
+ "imPlatform.replacement.description": "การแทนที่ผู้ให้บริการที่ใช้งานอยู่จะทำให้การผูก IM และการกำหนดค่าทับของเวิร์กสเปซใช้งานไม่ได้ หลังจากแทนที่ ให้ซิงค์ไดเรกทอรีของผู้ให้บริการใหม่อีกครั้ง",
+ "imPlatform.replacement.title": "แทนที่ {{current}} ด้วย {{next}} หรือไม่?",
+ "imPlatform.status.configured": "กําหนดค่าแล้ว",
+ "imPlatform.status.connected": "เชื่อม ต่อ",
+ "imPlatform.status.connection_error": "ข้อผิดพลาดในการเชื่อมต่อ",
+ "imPlatform.status.permission_issue": "ปัญหาด้านสิทธิ์",
+ "imPlatform.sync.latestSynced": "ซิงค์ล่าสุด {{date}}",
+ "imPlatform.sync.loading": "กำลังตรวจสอบการซิงค์ที่ใช้งานอยู่",
+ "imPlatform.sync.noPermission": "เฉพาะเจ้าของและผู้ดูแลเวิร์กสเปซเท่านั้นที่เริ่มซิงค์ไดเรกทอรีได้",
+ "imPlatform.sync.noRuns": "ยังไม่เคยซิงค์ไดเรกทอรี",
+ "imPlatform.sync.notConnected": "เชื่อมต่อและทดสอบผู้ให้บริการก่อนเริ่มซิงค์ไดเรกทอรี",
+ "imPlatform.sync.startFailed": "เริ่มหรือรีเฟรชการซิงค์ไดเรกทอรีไม่ได้ โปรดลองอีกครั้ง",
+ "imPlatform.sync.status.failure": "ล้มเหลว",
+ "imPlatform.sync.status.queued": "อยู่ในคิว",
+ "imPlatform.sync.status.running": "กำลังทำงาน",
+ "imPlatform.sync.status.success": "สำเร็จ",
+ "imPlatform.title": "ช่องทาง"
}
diff --git a/web/i18n/locales/th-TH/share.json b/web/i18n/locales/th-TH/share.json
index 1d5ef99fa66..0e25b7738b8 100644
--- a/web/i18n/locales/th-TH/share.json
+++ b/web/i18n/locales/th-TH/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "ขอบคุณ!",
"humanInput.unavailableDescription": "ลิงก์อาจไม่พร้อมใช้งานหรือไม่ตรงกับบัญชีที่คุณลงชื่อเข้าใช้ โปรดเปิดแบบฟอร์มจากการแจ้งเตือนที่คุณได้รับ หรือลองเปลี่ยนบัญชี",
"humanInput.unavailableTitle": "ไม่สามารถเปิดแบบฟอร์มนี้ได้",
+ "humanInputV2.accessRateLimited": "มีการขออีเมลยืนยันมากเกินไป โปรดลองอีกครั้งในภายหลัง",
+ "humanInputV2.alreadySubmitted": "คำขอนี้เสร็จสมบูรณ์แล้ว",
+ "humanInputV2.challengeExpired": "รหัสยืนยันนี้หมดอายุแล้ว ขอรหัสใหม่เพื่อดำเนินการต่อ",
+ "humanInputV2.challengeStale": "รหัสยืนยันนี้ถูกแทนที่แล้ว ขอรหัสใหม่เพื่อดำเนินการต่อ",
+ "humanInputV2.codeExpiresIn": "รหัสจะหมดอายุใน {{seconds}} วินาที",
+ "humanInputV2.codeRequired": "ขอรหัสยืนยันเพื่อดำเนินการต่อ",
+ "humanInputV2.codeSent": "ส่งรหัสยืนยันไปยังอีเมลของคุณแล้ว",
+ "humanInputV2.deliveryFailed": "ไม่สามารถส่งอีเมลยืนยันได้ โปรดลองอีกครั้ง",
+ "humanInputV2.formExpired": "คำขอนี้หมดอายุแล้ว",
+ "humanInputV2.formNotFound": "ไม่พบแบบฟอร์ม",
+ "humanInputV2.formRateLimited": "มีคำขอแบบฟอร์มมากเกินไป โปรดลองอีกครั้งในภายหลัง",
+ "humanInputV2.invalidOtp": "รหัสยืนยันไม่ถูกต้อง ตรวจสอบรหัสแล้วลองอีกครั้ง",
+ "humanInputV2.networkError": "ไม่สามารถดำเนินการตามคำขอได้ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง",
+ "humanInputV2.otpLabel": "รหัสยืนยันอีเมล",
+ "humanInputV2.otpPlaceholder": "ป้อนรหัส 6 หลัก",
+ "humanInputV2.requestingCode": "กำลังส่งรหัสยืนยัน…",
+ "humanInputV2.resendCode": "ส่งรหัสอีกครั้ง",
+ "humanInputV2.retry": "ลองอีกครั้ง",
+ "humanInputV2.sendCode": "ส่งรหัสใหม่",
+ "humanInputV2.unavailable": "แบบฟอร์มนี้ไม่พร้อมใช้งานชั่วคราว",
+ "humanInputV2.unknownError": "เกิดข้อผิดพลาด โปรดลองอีกครั้ง",
+ "humanInputV2.uploadFailed": "ไม่สามารถอัปโหลดไฟล์ได้ โปรดลองอีกครั้ง",
"login.backToHome": "กลับไปที่หน้าแรก"
}
diff --git a/web/i18n/locales/th-TH/workflow-human-input.json b/web/i18n/locales/th-TH/workflow-human-input.json
index 78e1acc0574..be36f80a263 100644
--- a/web/i18n/locales/th-TH/workflow-human-input.json
+++ b/web/i18n/locales/th-TH/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "ค่าการดำเนินการ",
"nodes.humanInput.userActions.buttonTextTooLong": "ข้อความบนปุ่มต้องมีความยาว {{maxLength}} ตัวอักษรหรือน้อยกว่า",
"nodes.humanInput.userActions.chooseStyle": "เลือกสไตล์ปุ่ม",
+ "nodes.humanInput.userActions.defaultTitle": "ข้อความปุ่ม {{index}}",
"nodes.humanInput.userActions.emptyTip": "คลิกปุ่ม '+' เพื่อเพิ่มการดำเนินการของผู้ใช้",
"nodes.humanInput.userActions.title": "การดำเนินการของผู้ใช้",
"nodes.humanInput.userActions.tooltip": "กำหนดปุ่มที่ผู้ใช้สามารถคลิกเพื่อตอบสนองต่อแบบฟอร์มนี้ ID การดำเนินการควบคุมการแยกสาขา ค่าการดำเนินการถูกเปิดเผยในระดับถัดไปเป็นเอาต์พุตในตัวที่เลือก ID การดำเนินการต้องเริ่มต้นด้วยตัวอักษรหรือขีดล่าง ตามด้วยตัวอักษร ตัวเลข หรือขีดล่าง",
diff --git a/web/i18n/locales/th-TH/workflow.json b/web/i18n/locales/th-TH/workflow.json
index 55c6ee9245d..e2487b8c778 100644
--- a/web/i18n/locales/th-TH/workflow.json
+++ b/web/i18n/locales/th-TH/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "เอาต์พุต",
"blocks.http-request": "คําขอ HTTP",
"blocks.human-input": "ข้อมูลจากมนุษย์",
+ "blocks.human-input-v2": "ข้อมูลจากมนุษย์ v2",
"blocks.if-else": "ถ้า/อื่น",
"blocks.iteration": "เกิด ซ้ำ",
"blocks.iteration-start": "เริ่มการทําซ้ํา",
@@ -45,6 +46,7 @@
"blocksAbout.end": "กำหนดเอาต์พุตและประเภทผลลัพธ์ของเวิร์กโฟลว์",
"blocksAbout.http-request": "อนุญาตให้ส่งคําขอเซิร์ฟเวอร์ผ่านโปรโตคอล HTTP",
"blocksAbout.human-input": "ขอให้มนุษย์ยืนยันก่อนที่จะสร้างขั้นตอนถัดไป",
+ "blocksAbout.human-input-v2": "ขอข้อมูลจากผู้ติดต่อ ผู้รับอีเมล หรือผู้เริ่มเวิร์กโฟลว์ที่กำหนดไว้",
"blocksAbout.if-else": "ช่วยให้คุณสามารถแบ่งเวิร์กโฟลว์ออกเป็นสองสาขาตามเงื่อนไข if/else",
"blocksAbout.iteration": "ดําเนินการหลายขั้นตอนกับวัตถุรายการจนกว่าจะส่งออกผลลัพธ์ทั้งหมด",
"blocksAbout.iteration-start": "จุดเริ่มต้นของการวนซ้ำ",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "รวมตัวแปรหลายสาขาเป็นตัวแปรเดียวสําหรับการกําหนดค่าแบบรวมของโหนดดาวน์สตรีม",
"blocksAbout.variable-assigner": "รวมตัวแปรหลายสาขาเป็นตัวแปรเดียวสําหรับการกําหนดค่าแบบรวมของโหนดดาวน์สตรีม",
"changeHistory.edgeDelete": "เชื่อมต่อ Node ขาดหาย",
+ "changeHistory.humanInputMigration": "ย้ายโหนดข้อมูลจากมนุษย์แล้ว",
"changeHistory.nodeAdd": "เพิ่มโนด",
"changeHistory.nodeChange": "โหนดเปลี่ยนแปลง",
"changeHistory.nodeConnect": "เชื่อมต่อ Node",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "โปรดเปิดใช้งานวิธีการส่งมอบอย่างน้อยหนึ่งวิธี",
"nodes.humanInput.errorMsg.noUserActions": "โปรดเพิ่มการดำเนินการของผู้ใช้อย่างน้อยหนึ่งรายการ",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} สงวนไว้สำหรับสาขาที่หมดเวลา โปรดเลือก ID การดำเนินการอื่น",
+ "nodes.humanInput.output.actionId": "ID ของการกระทำที่ผู้ใช้เรียกใช้",
+ "nodes.humanInput.output.actionValue": "ค่าของการกระทำที่เลือก",
+ "nodes.humanInput.output.formInput": "ค่าที่ป้อนในแบบฟอร์ม",
+ "nodes.humanInput.output.renderedContent": "เนื้อหาที่แสดงผล",
"nodes.humanInput.timeout.title": "หมดเวลา",
+ "nodes.humanInputMigration.action.migrate": "ย้าย",
+ "nodes.humanInputMigration.action.migrateNow": "ย้ายตอนนี้",
+ "nodes.humanInputMigration.action.migrating": "กำลังย้าย...",
+ "nodes.humanInputMigration.banner.ariaLabel": "แจ้งการย้ายโหนดข้อมูลจากมนุษย์",
+ "nodes.humanInputMigration.banner.description": "เวิร์กโฟลว์นี้ใช้โหนดข้อมูลจากมนุษย์รุ่นเก่า โปรดย้ายโหนดเก่าทั้งหมดก่อนเพิ่มโหนดใหม่",
+ "nodes.humanInputMigration.banner.learnMore": "เรียนรู้เพิ่มเติม",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "วิธีส่งที่ปิดใช้งานยังมีการกำหนดค่าอยู่",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "วิธีส่งอีเมลที่เปิดใช้งานใช้เทมเพลตที่ขัดแย้งกัน",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "ค่าเริ่มต้นไม่ถูกต้อง",
+ "nodes.humanInputMigration.blocker.invalidEmail": "อีเมลของผู้รับไม่ถูกต้อง",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "การกำหนดค่าวิธีส่งอีเมลที่เปิดใช้งานยังไม่สมบูรณ์",
+ "nodes.humanInputMigration.blocker.missingRecipients": "โหนดไม่มีผู้รับที่รองรับ",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "ไม่สามารถระบุผู้ติดต่อหรืออีเมลที่ยืนยันแล้วของสมาชิกพื้นที่ทำงานได้",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "ข้อมูลจากมนุษย์ v2 ไม่รองรับวิธีส่งที่เปิดใช้งาน",
"nodes.humanInputMigration.blocker.unsupportedInputType": "ยังไม่สามารถย้ายฟิลด์ {{field}} ได้ คุณสามารถใช้โหนดอินพุตจากมนุษย์เวอร์ชันเดิมต่อไปได้",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "โหนดมีค่าเวอร์ชันที่ไม่รองรับ",
+ "nodes.humanInputMigration.dialog.description": "ผู้รับ แบบฟอร์ม และการกระทำของคุณจะถูกโอนย้ายไปด้วย",
+ "nodes.humanInputMigration.dialog.draftNotice": "จะเปลี่ยนเฉพาะฉบับร่างนี้ เวอร์ชันที่เผยแพร่แล้วจะยังทำงานต่อจนกว่าคุณจะเผยแพร่อีกครั้ง",
+ "nodes.humanInputMigration.dialog.review": "ตรวจสอบโหนดและเผยแพร่เมื่อพร้อม",
+ "nodes.humanInputMigration.dialog.title": "ย้ายโหนดข้อมูลจากมนุษย์ {{count}} โหนด",
+ "nodes.humanInputMigration.disabledBadge": "ต้องย้ายข้อมูล",
+ "nodes.humanInputMigration.disabledReason": "ย้ายโหนดข้อมูลจากมนุษย์รุ่นเก่าก่อนเพิ่มโหนดใหม่",
+ "nodes.humanInputMigration.error.blocked": "ไม่สามารถย้าย {{nodeTitle}} ได้: {{reason}}",
"nodes.humanInputMigration.error.graphChanged": "เวิร์กโฟลว์เปลี่ยนแปลงระหว่างการย้าย กรุณาลองอีกครั้ง การแก้ไขปัจจุบันของคุณยังคงอยู่",
+ "nodes.humanInputMigration.error.preflight": "ไม่สามารถเตรียมการย้ายได้ เวิร์กโฟลว์ของคุณยังไม่ถูกเปลี่ยนแปลง โปรดลองอีกครั้ง",
"nodes.humanInputMigration.error.sync": "ไม่สามารถบันทึกเวิร์กโฟลว์ที่ย้ายแล้วได้ โปรดตรวจสอบแบบร่างปัจจุบันแล้วลองอีกครั้ง",
+ "nodes.humanInputMigration.incompatibleVersions": "ไม่สามารถใช้โหนดอินพุตจากมนุษย์เวอร์ชันเก่าและใหม่ร่วมกันในเวิร์กโฟลว์เดียวกันได้",
+ "nodes.humanInputMigration.oldVersion": "เวอร์ชันเก่า",
+ "nodes.humanInputMigration.preview.author": "โดยทีม Dify",
+ "nodes.humanInputMigration.preview.description": "ย้ายโหนดข้อมูลจากมนุษย์รุ่นเก่าก่อนเพิ่มโหนดใหม่",
+ "nodes.humanInputMigration.success": "ย้ายโหนดข้อมูลจากมนุษย์สำเร็จแล้ว",
+ "nodes.humanInputV2.card.configured": "กำหนดค่าผู้รับแล้ว {{count}} ราย",
+ "nodes.humanInputV2.card.contactsOnly": "ผู้ติดต่อ {{count}} ราย",
+ "nodes.humanInputV2.card.empty": "ยังไม่มีใครสามารถอนุมัติขั้นตอนนี้ได้",
+ "nodes.humanInputV2.card.initiatorAndContacts": "ผู้เริ่มและผู้ติดต่อ {{count}} ราย",
+ "nodes.humanInputV2.card.initiatorOnly": "เฉพาะผู้เริ่ม",
+ "nodes.humanInputV2.card.invalid": "โปรดตรวจสอบการกำหนดค่าผู้รับ",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "อีเมล",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "กำหนดค่าโหมดแก้ไขข้อบกพร่อง",
"nodes.humanInputV2.debug.keepOneChannel": "เปิดใช้งานอย่างน้อยหนึ่งช่องทางไว้",
+ "nodes.humanInputV2.debug.sendVia": "ส่งการแจ้งเตือนการแก้ไขข้อบกพร่องผ่าน",
+ "nodes.humanInputV2.debug.title": "โหมดแก้ไขข้อบกพร่อง",
+ "nodes.humanInputV2.debug.toggle": "เปิดใช้โหมดแก้ไขข้อบกพร่อง",
+ "nodes.humanInputV2.debug.unsupported": "ช่องทางที่นำเข้าแต่ไม่รองรับ: {{channels}} โปรดลบหรืออัปเดตก่อนเรียกใช้เวิร์กโฟลว์นี้",
"nodes.humanInputV2.disabled": "ไม่สามารถใช้งาน Human Input v2 ได้ขณะที่ปิดใช้งาน HITL IM",
+ "nodes.humanInputV2.error.bodyRequired": "ต้องระบุเนื้อหาข้อความ",
+ "nodes.humanInputV2.error.debugChannelRequired": "เลือกช่องทางโหมดแก้ไขข้อบกพร่องอย่างน้อยหนึ่งช่องทาง",
+ "nodes.humanInputV2.error.recipientDuplicate": "ลบผู้รับที่ซ้ำกัน",
+ "nodes.humanInputV2.error.recipientInvalid": "แก้ไขการกำหนดค่าผู้รับที่ไม่ถูกต้อง",
+ "nodes.humanInputV2.error.recipientRequired": "เพิ่มผู้รับอย่างน้อยหนึ่งราย",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "ไม่สามารถตรวจสอบผู้รับจากรายชื่อผู้ติดต่อได้",
"nodes.humanInputV2.error.requestURLDuplicate": "เนื้อหาข้อความมี URL คำขอได้เพียงหนึ่งรายการเท่านั้น",
"nodes.humanInputV2.error.requestURLRequired": "โปรดแทรก URL คำขอในเนื้อหาข้อความ",
+ "nodes.humanInputV2.error.subjectRequired": "ต้องระบุหัวเรื่องข้อความ",
+ "nodes.humanInputV2.error.version": "ข้อมูลจากมนุษย์ v2 ต้องใช้ค่าเวอร์ชัน 2 ที่เป็นสตริง",
+ "nodes.humanInputV2.recipients.addContact": "เพิ่มผู้ติดต่อ",
+ "nodes.humanInputV2.recipients.addEmail": "เพิ่ม",
+ "nodes.humanInputV2.recipients.addRecipient": "เพิ่มผู้รับ",
+ "nodes.humanInputV2.recipients.added": "เพิ่มแล้ว",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "ผู้ติดต่อทั้งหมดในพื้นที่ทำงาน",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "ส่งการแจ้งเตือนไปยังผู้ติดต่อทั้งหมดในพื้นที่ทำงาน โดยคนใดก็สามารถอนุมัติได้",
+ "nodes.humanInputV2.recipients.cancel": "ยกเลิก",
+ "nodes.humanInputV2.recipients.chooseVariable": "เลือกตัวแปร",
+ "nodes.humanInputV2.recipients.confirm": "ยืนยัน",
+ "nodes.humanInputV2.recipients.contactInfo": "รายละเอียดผู้ติดต่อของ {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "ทั้งหมด",
+ "nodes.humanInputV2.recipients.contactSource.external": "ภายนอก",
+ "nodes.humanInputV2.recipients.contactSource.organization": "องค์กร",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "พื้นที่ทำงาน",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "แหล่งที่มาของผู้ติดต่อ",
"nodes.humanInputV2.recipients.duplicateSource": "เพิ่มผ่าน {{name}} ({{source}}) แล้ว",
+ "nodes.humanInputV2.recipients.edit": "แก้ไข {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "แก้ไขผู้รับ",
"nodes.humanInputV2.recipients.emailAlreadySelected": "แต่ละอีเมลสามารถเลือกได้เพียงครั้งเดียว",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "ป้อนอีเมลที่ถูกต้องและยังไม่ได้เพิ่ม",
+ "nodes.humanInputV2.recipients.emailLabel": "ผู้รับอีเมลแบบครั้งเดียว",
+ "nodes.humanInputV2.recipients.empty": "ยังไม่ได้กำหนดค่าผู้รับ",
+ "nodes.humanInputV2.recipients.help": "เลือกผู้ที่สามารถตอบในขั้นตอนข้อมูลจากมนุษย์นี้",
"nodes.humanInputV2.recipients.initiator": "ผู้ใช้ที่เริ่มการทำงานครั้งนี้ผ่าน Web App หรือ CLI สามารถอนุมัติได้",
+ "nodes.humanInputV2.recipients.initiatorDescription": "ผู้ที่เริ่มการเรียกใช้เวิร์กโฟลว์นี้สามารถตอบได้",
"nodes.humanInputV2.recipients.inputHelp": "พิมพ์หรือวางหลายอีเมลโดยคั่นด้วยเครื่องหมายจุลภาค กด / เพื่อแทรกตัวแปร",
+ "nodes.humanInputV2.recipients.insertVariable": "แทรกตัวแปร",
+ "nodes.humanInputV2.recipients.loadError": "ไม่สามารถโหลดผู้ติดต่อได้ ID ผู้ติดต่อที่บันทึกไว้ยังคงอยู่",
+ "nodes.humanInputV2.recipients.loading": "กำลังโหลดผู้ติดต่อ…",
+ "nodes.humanInputV2.recipients.noResults": "ไม่พบผู้ติดต่อ",
+ "nodes.humanInputV2.recipients.placeholder": "ค้นหาผู้ติดต่อหรือเพิ่มอีเมล",
+ "nodes.humanInputV2.recipients.remove": "ลบ {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "กด Backspace หรือ Delete เพื่อลบ",
+ "nodes.humanInputV2.recipients.resultCount": "พบผู้รับที่ตรงกัน {{count}} คน",
+ "nodes.humanInputV2.recipients.search": "ค้นหาผู้ติดต่อ",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "ค้นหาด้วยชื่อหรืออีเมล",
+ "nodes.humanInputV2.recipients.selectionHint": "เลือกผู้รับแล้ว {{count}} คน กดลูกศรซ้ายที่จุดเริ่มต้นของช่องป้อนข้อมูลเพื่อย้ายโฟกัสไปยังผู้รับ",
+ "nodes.humanInputV2.recipients.title": "ผู้รับ",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "ผู้ติดต่อทั้งหมดในพื้นที่ทำงาน",
+ "nodes.humanInputV2.recipients.type.contact": "ผู้ติดต่อ",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "อีเมลแบบไดนามิก",
+ "nodes.humanInputV2.recipients.type.initiator": "ผู้เริ่ม",
+ "nodes.humanInputV2.recipients.type.onetime_email": "อีเมลแบบครั้งเดียว",
+ "nodes.humanInputV2.recipients.typeLabel": "ประเภทผู้รับ",
"nodes.humanInputV2.recipients.useThisInstead": "ใช้รายการนี้แทน",
+ "nodes.humanInputV2.recipients.variableRequired": "เลือกตัวแปรอีเมล",
+ "nodes.humanInputV2.template.body": "เนื้อหา",
+ "nodes.humanInputV2.template.description": "ข้อความสำรองสำหรับอีเมลและข้อความโต้ตอบแบบทันที",
"nodes.humanInputV2.template.insertRequestURL": "แทรก URL คำขอ",
+ "nodes.humanInputV2.template.insertVariable": "แทรกตัวแปร",
+ "nodes.humanInputV2.template.notConfigured": "ยังไม่ได้กำหนดค่า",
"nodes.humanInputV2.template.requestURLHint": "ผู้รับใช้ลิงก์นี้เพื่อเปิดแบบฟอร์มอนุมัติ เนื้อหาต้องมี URL คำขอเพียงหนึ่งรายการ",
"nodes.humanInputV2.template.requestURLInserted": "แทรก URL คำขอแล้ว",
"nodes.humanInputV2.template.saveAndTest": "บันทึกและทดสอบ",
+ "nodes.humanInputV2.template.subject": "หัวเรื่อง",
+ "nodes.humanInputV2.template.subjectPlaceholder": "ป้อนหัวเรื่องข้อความ",
"nodes.humanInputV2.template.test": "ทดสอบข้อความ",
"nodes.humanInputV2.template.testChannel": "ช่องทางทดสอบ",
"nodes.humanInputV2.template.testCompleted": "คำขอทดสอบเสร็จสมบูรณ์แล้ว โปรดตรวจสอบข้อความในช่องทางที่เลือก",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "กรอกค่าตัวแปรทดสอบทั้งหมด",
"nodes.humanInputV2.template.testSaveFailed": "ไม่สามารถบันทึกฉบับร่างเวิร์กโฟลว์ได้ จึงยังไม่ได้ส่งการทดสอบ",
"nodes.humanInputV2.template.testUnavailable": "สภาพแวดล้อมนี้ยังไม่รองรับการทดสอบเทมเพลตข้อความ",
+ "nodes.humanInputV2.template.title": "เทมเพลตข้อความ",
"nodes.ifElse.operator": "ผู้ปฏิบัติการ",
"nodes.iteration.currentIteration": "การทําซ้ําปัจจุบัน",
"nodes.iteration.deleteDesc": "การลบโหนดการวนซ้ําจะเป็นการลบโหนดย่อยทั้งหมด",
diff --git a/web/i18n/locales/tr-TR/contacts.json b/web/i18n/locales/tr-TR/contacts.json
index 12d8d3081e1..763c97becae 100644
--- a/web/i18n/locales/tr-TR/contacts.json
+++ b/web/i18n/locales/tr-TR/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Kişiler kaldırılsın mı ({{count}})?",
"directory.removalDescription": "Seçilen kişiler bu çalışma alanından kalıcı olarak kaldırılacak. Bu işlem geri alınamaz.",
- "directory.removalTitle": "Kişiler kaldırılsın mı?",
+ "directory.removalSingleDescription": "{{name}} bu çalışma alanından kalıcı olarak kaldırılacak. Bu işlem geri alınamaz.",
+ "directory.removalSingleFailed": "Kişi kaldırılamadı. Tekrar deneyin.",
+ "directory.removalSingleTitle": "{{name}} kaldırılsın mı?",
+ "directory.resultCount": "Sonuçlar: {{count}}",
+ "imPlatform.action.configure": "Yapılandır",
+ "imPlatform.action.configureChannel": "{{provider}}'ı Yapılandır",
+ "imPlatform.action.connect": "Bağlan",
+ "imPlatform.action.copied": "Kopyalandı",
+ "imPlatform.action.copyCallback": "Geri çağırma URL’sini kopyala",
+ "imPlatform.action.deleteChannel": "{{provider}} sil",
+ "imPlatform.action.loadMore": "Daha fazla yükle",
+ "imPlatform.action.replace": "Yer değiştirmek",
+ "imPlatform.action.retry": "Yeniden deneme",
+ "imPlatform.action.save": "Kaydet",
+ "imPlatform.action.saving": "Kaydediliyor",
+ "imPlatform.action.setupGuide": "Kurulum kılavuzu",
+ "imPlatform.action.syncNow": "Şimdi senkronize et",
+ "imPlatform.action.syncing": "Senkronize ediliyor",
+ "imPlatform.action.testConnection": "Bağlantıyı test et",
+ "imPlatform.action.testing": "Test ediliyor",
+ "imPlatform.action.viewDetails": "Ayrıntıları görüntüleme",
+ "imPlatform.bindingDialog.back": "Geri",
+ "imPlatform.bindingDialog.callback": "Geri Arama URL'si",
+ "imPlatform.bindingDialog.callbackDescription": "Kart eylemlerini etkinleştirmek için {{provider}} geri çağırma kurulumunu tamamlayın.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Kart eylemleri için bu URL’yi <console>Feishu Geliştirici Konsolu</console>na yapıştırın:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Olaylar ve Geri Çağırmalar → Geri çağırma yapılandırması → İstek URL’si",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Kart eylemleri için bu URL’yi <console>Lark Geliştirici Konsolu</console>na yapıştırın:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Olaylar ve Geri Çağırmalar → Geri çağırma yapılandırması → İstek URL’si",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Kart eylemleri için bu URL’yi <console>Slack Geliştirici Konsolu</console>na yapıştırın:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Etkileşim ve Kısayollar → Etkileşim → İstek URL’si",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Kart eylemleri için bu URL’yi <console>Azure Bot yapılandırmasına</console> yapıştırın:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Ayarlar → Yapılandırma → Mesajlaşma uç noktası",
+ "imPlatform.bindingDialog.callbackStep": "Geri çağırmaları yapılandır",
"imPlatform.bindingDialog.clearSavedCredential": "Kayıtlı değeri temizle",
+ "imPlatform.bindingDialog.configureTitle": "{{provider}}'ı Yapılandır",
+ "imPlatform.bindingDialog.connectTitle": "{{provider}}'a bağlanın",
"imPlatform.bindingDialog.credentialWillBeCleared": "Kaydettiğinizde bu kayıtlı değer temizlenecek.",
+ "imPlatform.bindingDialog.credentialsDescription": "Önce {{provider}} uygulamanızı bağlayın, ardından geri çağırma URL’sini yapılandırın.",
+ "imPlatform.bindingDialog.credentialsStep": "Uygulama kimlik bilgileri",
+ "imPlatform.bindingDialog.description": "Bu anlık mesajlaşma sağlayıcısının uygulama kimlik bilgilerini girin.",
+ "imPlatform.bindingDialog.field.agentId": "Aracı kimliği",
+ "imPlatform.bindingDialog.field.appId": "Uygulama kimliği",
+ "imPlatform.bindingDialog.field.appToken": "Uygulama belirteci (isteğe bağlı)",
+ "imPlatform.bindingDialog.field.botToken": "Bot belirteci",
+ "imPlatform.bindingDialog.field.clientId": "Müşteri Kimliği",
+ "imPlatform.bindingDialog.field.clientSecret": "İstemci Sırrı",
+ "imPlatform.bindingDialog.field.corpId": "Kurum kimliği",
+ "imPlatform.bindingDialog.field.encryptKey": "Şifreleme anahtarı (isteğe bağlı)",
+ "imPlatform.bindingDialog.field.genericSecret": "Gizli",
+ "imPlatform.bindingDialog.field.secret": "Uygulama sırrı",
+ "imPlatform.bindingDialog.field.signingSecret": "İmzalama sırrı",
+ "imPlatform.bindingDialog.field.tenantId": "Kiracı kimliği",
+ "imPlatform.bindingDialog.field.verificationToken": "Doğrulama belirteci (isteğe bağlı)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Etkinleştirildiyse şifreleme anahtarını girin",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Uygulama sırrını girin",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Yapılandırıldıysa doğrulama belirtecini girin",
+ "imPlatform.bindingDialog.finish": "Bitir",
+ "imPlatform.bindingDialog.freshCredentials": "Kaydedilmiş sırlar geri alınamaz. Bu yapılandırmayı test etmek veya kaydetmek için gerekli tüm kimlik bilgilerini yeniden girin.",
+ "imPlatform.bindingDialog.openSetupGuide": "Kurulum kılavuzunu aç",
+ "imPlatform.bindingDialog.replaceTenantTitle": "{{identity}} için kiracı kimlik bilgileri değiştirilsin mi?",
"imPlatform.bindingDialog.replacementRequired": "Bu kimlik bilgileri farklı bir IM kiracısına aittir ve doğrudan kaydedilemez. Kiracı değiştirmek, mevcut IM kanalını yenisiyle değiştirmeyi gerektirir; bu işlem tüm otomatik ve manuel IM bağlamalarını siler. Değiştirme işleminden sonra kişileri yeniden eşitleyin.",
+ "imPlatform.bindingDialog.required": "Bu alan zorunludur.",
+ "imPlatform.bindingDialog.saveAndContinue": "Kaydet ve devam et",
+ "imPlatform.bindingDialog.saveFailed": "Yapılandırma kaydedilemedi. Alanları kontrol edip tekrar deneyin.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Yapılandırma kaydedildi ancak ayrıntıları yüklenemedi. Bu iletişim kutusunu kapatıp yeniden açın.",
- "imPlatform.bindingDialog.undoClearCredential": "Temizlemeyi geri al"
+ "imPlatform.bindingDialog.secretConfigured": "Bir sır zaten yapılandırılmış. Korumak için bu alanı boş bırakın.",
+ "imPlatform.bindingDialog.step": "Adım {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Bağlantı testi başarısız oldu. Yapılandırmayı kontrol edip tekrar deneyin.",
+ "imPlatform.bindingDialog.undoClearCredential": "Temizlemeyi geri al",
+ "imPlatform.bindingDialog.viewSetupGuide": "Kurulum kılavuzunu görüntüle",
+ "imPlatform.chooseProvider": "Bağlanacak bir kanal seçin",
+ "imPlatform.configurationUpdated": "Bu kanalın yapılandırması değişti. Yeniden denemeden önce bu iletişim kutusunu kapatıp sayfayı yenileyin.",
+ "imPlatform.connectMore": "Daha fazla kanal bağla",
+ "imPlatform.delete.confirm": "Silmek",
+ "imPlatform.delete.description": "Bu kanalı silmek yapılandırmasını kaldırır. Kanalı kullanan onay bildirimleri ve dizin eşitlemeleri durur.",
+ "imPlatform.delete.failed": "Kanal silinemedi. Hiçbir şey değişmedi; tekrar deneyin.",
+ "imPlatform.delete.title": "{{provider}} kanalı silinsin mi?",
+ "imPlatform.description": "Onay isteklerinin kişilere çalıştıkları yerde ulaşması için şirket kanallarınızı bağlayın.",
+ "imPlatform.details.column.contact": "Kişiler",
+ "imPlatform.details.column.platform": "Anlık mesajlaşma platformu",
+ "imPlatform.details.description": "Son eşitleme çalıştırmasının salt okunur sonuçlarını görüntüleyin.",
+ "imPlatform.details.downloadFailed": "Rapor indirilemedi. Tekrar deneyin.",
+ "imPlatform.details.downloadReport": "Raporu indir",
+ "imPlatform.details.downloadingReport": "Rapor indiriliyor…",
+ "imPlatform.details.empty": "Bu kategoride sonuç yok.",
+ "imPlatform.details.filter.added": "Eklendi",
+ "imPlatform.details.filter.failed": "Başarısız",
+ "imPlatform.details.filter.not_matched": "Eşleşmedi",
+ "imPlatform.details.filter.removed": "Kaldırıldı",
+ "imPlatform.details.filter.skipped": "Atlandı",
+ "imPlatform.details.filters": "Eşitleme sonucu filtreleri",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Eşitleme ayrıntıları yüklenemedi.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Daha fazla sonuç yüklenemedi. Bu sayfayı yeniden deneyin.",
+ "imPlatform.details.removalReason.binding_invalidated": "Bağlantı geçersiz kılındı",
+ "imPlatform.details.removalReason.binding_replaced": "Bağlantı değiştirildi",
+ "imPlatform.details.removalReason.not_present_in_directory": "Artık dizinde yok",
+ "imPlatform.details.reportChanged": "Eşitleme sonuçları değişti. Son eşitlemenin ayrıntılarını yeniden açıp tekrar deneyin.",
+ "imPlatform.details.title": "Eşitleme ayrıntıları",
+ "imPlatform.email.apiKey": "API Anahtarı",
+ "imPlatform.email.apiKeyConfigured": "Güvenlik nedeniyle kayıtlı API anahtarı görüntülenemez. Korumak için bu alanı boş bırakın.",
+ "imPlatform.email.apiKeyDescription": "Güvenlik nedeniyle bu API anahtarı kaydedildikten sonra görüntülenemez.",
+ "imPlatform.email.apiKeyPlaceholder": "Resend API anahtarınızı girin",
+ "imPlatform.email.description": "Bu yapılandırma, bu çalışma alanında <emphasis>Hata ayıklama bildirimlerini e-postayla gönder</emphasis> seçeneği etkin olan tüm İnsan Girdisi düğümleri için geçerlidir.",
+ "imPlatform.email.invalidEmail": "Geçerli bir e-posta adresi girin.",
+ "imPlatform.email.provider": "E-posta sağlayıcısı",
+ "imPlatform.email.resendDescription": "<apiKey>Resend API anahtarınız</apiKey> şifrelenir ve kaydedildikten sonra görüntülenemez.<br/>Bir <resend>Resend</resend> hesabı oluşturun.",
+ "imPlatform.email.resendSettings": "Resend ayarları",
+ "imPlatform.email.senderEmail": "Gönderen e-posta adresi",
+ "imPlatform.email.senderEmailDescription": "Gönderen olarak gösterilen e-posta adresi. Alan adı Resend’de doğrulanmış olmalıdır.",
+ "imPlatform.email.senderName": "Gönderen adı",
+ "imPlatform.email.senderNameDescription": "Alıcının gelen kutusunda gösterilen ad.",
+ "imPlatform.email.testSucceeded": "Bağlantı testi başarılı.",
+ "imPlatform.email.title": "E-postayı yapılandır",
+ "imPlatform.learnMore": "Daha fazla bilgi",
+ "imPlatform.loadError.description": "Mevcut bağlamayı ve izinleri okumak için tekrar deneyin.",
+ "imPlatform.loadError.retry": "Tekrar dene",
+ "imPlatform.loadError.title": "Kanallar yüklenemedi",
+ "imPlatform.loading": "Kanallar yükleniyor",
+ "imPlatform.provider.dingtalkDescription": "Bir DingTalk uygulaması bağlayın.",
+ "imPlatform.provider.emailDescription": "Bu çalışma alanından onay istekleri göndermek için kullanılan e-posta hizmetini yapılandırın.",
+ "imPlatform.provider.feishuDescription": "Bir Feishu uygulaması bağlayın.",
+ "imPlatform.provider.larkDescription": "Bir Lark uygulaması bağlayın.",
+ "imPlatform.provider.msTeamsDescription": "Bir Microsoft Teams uygulaması bağlayın.",
+ "imPlatform.provider.slackDescription": "Kişileri ve Slack kimliklerini eşitleyin.",
+ "imPlatform.provider.weComDescription": "Bir WeCom uygulaması bağlayın.",
+ "imPlatform.replacement.confirm": "Yer değiştirmek",
+ "imPlatform.replacement.description": "Etkin sağlayıcıyı değiştirmek, onun anlık mesajlaşma bağlamalarını ve çalışma alanı özelleştirmelerini geçersiz kılar. Değiştirdikten sonra yeni sağlayıcının dizinini yeniden eşitleyin.",
+ "imPlatform.replacement.title": "{{current}} yerine {{next}} kullanılsın mı?",
+ "imPlatform.status.configured": "Yapılandırıldı",
+ "imPlatform.status.connected": "Bağlandı",
+ "imPlatform.status.connection_error": "Bağlantı hatası",
+ "imPlatform.status.permission_issue": "İzin sorunu",
+ "imPlatform.sync.latestSynced": "Son eşitleme: {{date}}",
+ "imPlatform.sync.loading": "Etkin bir eşitleme olup olmadığı kontrol ediliyor.",
+ "imPlatform.sync.noPermission": "Yalnızca çalışma alanı sahipleri ve yöneticileri dizin eşitlemesini başlatabilir.",
+ "imPlatform.sync.noRuns": "Henüz dizin eşitlemesi çalıştırılmadı.",
+ "imPlatform.sync.notConnected": "Dizin eşitlemesini başlatmadan önce bir sağlayıcı bağlayıp bağlantıyı test edin.",
+ "imPlatform.sync.startFailed": "Dizin eşitlemesi başlatılamadı veya yenilenemedi. Tekrar deneyin.",
+ "imPlatform.sync.status.failure": "Başarısız",
+ "imPlatform.sync.status.queued": "Kuyrukta",
+ "imPlatform.sync.status.running": "Çalışıyor",
+ "imPlatform.sync.status.success": "Başarılı",
+ "imPlatform.title": "Kanallar"
}
diff --git a/web/i18n/locales/tr-TR/share.json b/web/i18n/locales/tr-TR/share.json
index 2cb37dd646d..24b94ce0936 100644
--- a/web/i18n/locales/tr-TR/share.json
+++ b/web/i18n/locales/tr-TR/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Teşekkürler!",
"humanInput.unavailableDescription": "Bağlantı kullanılamıyor olabilir veya oturum açtığınız hesapla eşleşmiyor olabilir. Formu aldığınız bildirimden açın veya hesap değiştirmeyi deneyin.",
"humanInput.unavailableTitle": "Bu form açılamıyor",
+ "humanInputV2.accessRateLimited": "Çok fazla doğrulama e-postası istendi. Lütfen daha sonra tekrar deneyin.",
+ "humanInputV2.alreadySubmitted": "Bu istek zaten tamamlandı.",
+ "humanInputV2.challengeExpired": "Bu doğrulama kodunun süresi doldu. Devam etmek için yeni bir kod isteyin.",
+ "humanInputV2.challengeStale": "Bu doğrulama kodu değiştirildi. Devam etmek için yeni bir kod isteyin.",
+ "humanInputV2.codeExpiresIn": "Kodun süresi {{seconds}} saniye sonra dolacak",
+ "humanInputV2.codeRequired": "Devam etmek için bir doğrulama kodu isteyin.",
+ "humanInputV2.codeSent": "E-posta adresinize bir doğrulama kodu gönderildi.",
+ "humanInputV2.deliveryFailed": "Doğrulama e-postası gönderilemedi. Lütfen tekrar deneyin.",
+ "humanInputV2.formExpired": "Bu isteğin süresi doldu.",
+ "humanInputV2.formNotFound": "Form bulunamadı.",
+ "humanInputV2.formRateLimited": "Çok fazla form isteği yapıldı. Lütfen daha sonra tekrar deneyin.",
+ "humanInputV2.invalidOtp": "Doğrulama kodu yanlış. Kodu kontrol edip tekrar deneyin.",
+ "humanInputV2.networkError": "İstek tamamlanamadı. Bağlantınızı kontrol edip tekrar deneyin.",
+ "humanInputV2.otpLabel": "E-posta doğrulama kodu",
+ "humanInputV2.otpPlaceholder": "6 haneli kodu girin",
+ "humanInputV2.requestingCode": "Doğrulama kodu gönderiliyor…",
+ "humanInputV2.resendCode": "Kodu yeniden gönder",
+ "humanInputV2.retry": "Tekrar dene",
+ "humanInputV2.sendCode": "Yeni kod gönder",
+ "humanInputV2.unavailable": "Bu form geçici olarak kullanılamıyor.",
+ "humanInputV2.unknownError": "Bir hata oluştu. Lütfen tekrar deneyin.",
+ "humanInputV2.uploadFailed": "Dosya yüklenemedi. Lütfen tekrar deneyin.",
"login.backToHome": "Ana Sayfaya Dön"
}
diff --git a/web/i18n/locales/tr-TR/workflow-human-input.json b/web/i18n/locales/tr-TR/workflow-human-input.json
index 32bb0a2af86..6adaa04cf6b 100644
--- a/web/i18n/locales/tr-TR/workflow-human-input.json
+++ b/web/i18n/locales/tr-TR/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Eylem Değeri",
"nodes.humanInput.userActions.buttonTextTooLong": "Düğme metni {{maxLength}} karakter veya daha az olmalıdır",
"nodes.humanInput.userActions.chooseStyle": "Bir düğme stili seçin",
+ "nodes.humanInput.userActions.defaultTitle": "Düğme Metni {{index}}",
"nodes.humanInput.userActions.emptyTip": "Kullanıcı eylemleri eklemek için '+' düğmesine tıklayın",
"nodes.humanInput.userActions.title": "Kullanıcı Eylemleri",
"nodes.humanInput.userActions.tooltip": "Kullanıcıların bu forma yanıt vermek için tıklayabileceği düğmeleri tanımlayın. Eylem kimliği dallanmayı kontrol eder. Eylem Değeri, seçilen yerleşik çıktı olarak aşağı akışta sunulur. Eylem kimliği bir harf veya alt çizgi ile başlamalı, ardından harf, rakam veya alt çizgi gelmelidir.",
diff --git a/web/i18n/locales/tr-TR/workflow.json b/web/i18n/locales/tr-TR/workflow.json
index 122e17ba5c6..7049b4f7903 100644
--- a/web/i18n/locales/tr-TR/workflow.json
+++ b/web/i18n/locales/tr-TR/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Çıktı",
"blocks.http-request": "HTTP İsteği",
"blocks.human-input": "İnsan Girdisi",
+ "blocks.human-input-v2": "İnsan Girdisi v2",
"blocks.if-else": "IF/ELSE",
"blocks.iteration": "Yineleme",
"blocks.iteration-start": "Yineleme Başlat",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Bir iş akışının çıktısını ve sonuç türünü tanımlayın",
"blocksAbout.http-request": "HTTP protokolü üzerinden sunucu isteklerinin gönderilmesine izin verin",
"blocksAbout.human-input": "Sonraki adımı oluşturmadan önce insan onayı iste",
+ "blocksAbout.human-input-v2": "Yapılandırılmış kişilerden, e-posta alıcılarından veya iş akışını başlatan kişiden girdi isteyin",
"blocksAbout.if-else": "İş akışını if/else koşullarına göre iki dala ayırmanızı sağlar",
"blocksAbout.iteration": "Bir liste nesnesinde birden fazla adım gerçekleştirir ve tüm sonuçlar çıkana kadar devam eder.",
"blocksAbout.iteration-start": "Yineleme Başlangıç düğümü",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Çoklu dal değişkenlerini tek bir değişkende toplayın ve sonraki düğümler için birleşik bir yapılandırma sağlayın.",
"blocksAbout.variable-assigner": "Çoklu dal değişkenlerini tek bir değişkende toplayın ve sonraki düğümler için birleşik bir yapılandırma sağlayın.",
"changeHistory.edgeDelete": "Düğüm bağlantısı kesildi",
+ "changeHistory.humanInputMigration": "İnsan Girdisi düğümleri taşındı",
"changeHistory.nodeAdd": "Düğüm eklendi",
"changeHistory.nodeChange": "Düğüm değişti",
"changeHistory.nodeConnect": "Düğüm bağlandı",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Lütfen en az bir teslimat yöntemini etkinleştirin",
"nodes.humanInput.errorMsg.noUserActions": "Lütfen en az bir kullanıcı eylemi ekleyin",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} zaman aşımı dalı için ayrılmıştır. Başka bir eylem kimliği seçin.",
+ "nodes.humanInput.output.actionId": "Kullanıcının tetiklediği eylemin kimliği",
+ "nodes.humanInput.output.actionValue": "Seçilen eylemin değeri",
+ "nodes.humanInput.output.formInput": "Form girdisinin değeri",
+ "nodes.humanInput.output.renderedContent": "İşlenmiş içerik",
"nodes.humanInput.timeout.title": "Zaman Aşımı",
+ "nodes.humanInputMigration.action.migrate": "Taşı",
+ "nodes.humanInputMigration.action.migrateNow": "Şimdi taşı",
+ "nodes.humanInputMigration.action.migrating": "Taşınıyor...",
+ "nodes.humanInputMigration.banner.ariaLabel": "İnsan Girdisi geçiş bildirimi",
+ "nodes.humanInputMigration.banner.description": "Bu iş akışı eski İnsan Girdisi düğümünü kullanıyor. Yeni düğümler eklemeden önce tüm eski düğümleri taşıyın.",
+ "nodes.humanInputMigration.banner.learnMore": "Daha fazla bilgi",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "devre dışı bir iletim yöntemi hâlâ yapılandırma içeriyor",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "etkin e-posta yöntemleri birbiriyle çelişen şablonlar kullanıyor",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Geçersiz varsayılan değer",
+ "nodes.humanInputMigration.blocker.invalidEmail": "bir alıcının e-posta adresi geçersiz",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "etkin bir e-posta yönteminin yapılandırması eksik",
+ "nodes.humanInputMigration.blocker.missingRecipients": "düğümde desteklenen alıcı yok",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "bir çalışma alanı üyesi bir kişiyle veya doğrulanmış e-posta adresiyle eşleştirilemiyor",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "etkin bir iletim yöntemi İnsan Girdisi v2 tarafından desteklenmiyor",
"nodes.humanInputMigration.blocker.unsupportedInputType": "{{field}} alanı henüz taşınamıyor. Eski İnsan Girdisi düğümlerini kullanmaya devam edebilirsiniz.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "düğümde desteklenmeyen bir sürüm değeri var",
+ "nodes.humanInputMigration.dialog.description": "Alıcılarınız, formunuz ve eylemleriniz korunur.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Yalnızca bu taslak değişir. Yayımlanmış sürümler siz yeniden yayımlayana kadar çalışmaya devam eder.",
+ "nodes.humanInputMigration.dialog.review": "Düğümleri gözden geçirin ve hazır olduğunuzda yayımlayın.",
+ "nodes.humanInputMigration.dialog.title": "{{count}} İnsan Girdisi düğümünü taşı",
+ "nodes.humanInputMigration.disabledBadge": "GEÇİŞ GEREKLİ",
+ "nodes.humanInputMigration.disabledReason": "Yeni bir düğüm eklemeden önce eski İnsan Girdisi düğümlerini taşıyın.",
+ "nodes.humanInputMigration.error.blocked": "{{nodeTitle}} taşınamadı: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "İş akışı geçiş sırasında değişti. Tekrar deneyin; mevcut düzenlemeleriniz korundu.",
+ "nodes.humanInputMigration.error.preflight": "Geçiş hazırlanamadı. İş akışınız değiştirilmedi. Lütfen tekrar deneyin.",
"nodes.humanInputMigration.error.sync": "Taşınan iş akışı kaydedilemedi. Mevcut taslağı inceleyip tekrar deneyin.",
+ "nodes.humanInputMigration.incompatibleVersions": "Eski ve yeni İnsan Girdisi düğümleri aynı iş akışında kullanılamaz.",
+ "nodes.humanInputMigration.oldVersion": "ESKİ SÜRÜM",
+ "nodes.humanInputMigration.preview.author": "Dify Ekibi tarafından",
+ "nodes.humanInputMigration.preview.description": "Yeni bir düğüm eklemeden önce eski İnsan Girdisi düğümlerini taşıyın.",
+ "nodes.humanInputMigration.success": "İnsan Girdisi düğümleri başarıyla taşındı",
+ "nodes.humanInputV2.card.configured": "{{count}} alıcı yapılandırıldı",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} kişi",
+ "nodes.humanInputV2.card.empty": "Bu adımı henüz kimse onaylayamıyor",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Başlatan kişi ve {{count}} kişi",
+ "nodes.humanInputV2.card.initiatorOnly": "Yalnızca başlatan kişi",
+ "nodes.humanInputV2.card.invalid": "Alıcı yapılandırmasını kontrol edin",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "E-posta",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Hata Ayıklama Modunu Yapılandır",
"nodes.humanInputV2.debug.keepOneChannel": "En az bir kanalı açık tutun",
+ "nodes.humanInputV2.debug.sendVia": "Hata ayıklama bildirimlerini şu yolla gönder",
+ "nodes.humanInputV2.debug.title": "Hata Ayıklama Modu",
+ "nodes.humanInputV2.debug.toggle": "Hata Ayıklama Modunu Etkinleştir",
+ "nodes.humanInputV2.debug.unsupported": "İçe aktarılan desteklenmeyen kanallar: {{channels}}. Bu iş akışını çalıştırmadan önce bunları kaldırın veya güncelleyin.",
"nodes.humanInputV2.disabled": "HITL IM devre dışıyken Human Input v2 kullanılamaz.",
+ "nodes.humanInputV2.error.bodyRequired": "İleti gövdesi gerekli",
+ "nodes.humanInputV2.error.debugChannelRequired": "En az bir Hata Ayıklama Modu kanalı seçin",
+ "nodes.humanInputV2.error.recipientDuplicate": "Yinelenen alıcıları kaldırın",
+ "nodes.humanInputV2.error.recipientInvalid": "Geçersiz alıcı yapılandırmasını düzeltin",
+ "nodes.humanInputV2.error.recipientRequired": "En az bir alıcı ekleyin",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Kişi alıcıları doğrulanamadı",
"nodes.humanInputV2.error.requestURLDuplicate": "Mesaj gövdesi yalnızca bir istek URL’si içerebilir.",
"nodes.humanInputV2.error.requestURLRequired": "Mesaj gövdesine bir istek URL’si ekleyin.",
+ "nodes.humanInputV2.error.subjectRequired": "İleti konusu gerekli",
+ "nodes.humanInputV2.error.version": "İnsan Girdisi v2, sürüm değerinin 2 metin dizesi olmasını gerektirir",
+ "nodes.humanInputV2.recipients.addContact": "Kişi ekle",
+ "nodes.humanInputV2.recipients.addEmail": "Ekle",
+ "nodes.humanInputV2.recipients.addRecipient": "Alıcı ekle",
+ "nodes.humanInputV2.recipients.added": "Eklendi",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Çalışma alanındaki tüm kişiler",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Çalışma alanındaki tüm kişilere bildirim gönderin; herhangi biri onaylayabilir",
+ "nodes.humanInputV2.recipients.cancel": "İptal",
+ "nodes.humanInputV2.recipients.chooseVariable": "Değişken seç",
+ "nodes.humanInputV2.recipients.confirm": "Onayla",
+ "nodes.humanInputV2.recipients.contactInfo": "{{name}} için kişi ayrıntıları",
+ "nodes.humanInputV2.recipients.contactSource.all": "Tümü",
+ "nodes.humanInputV2.recipients.contactSource.external": "Harici",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Kuruluş",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Çalışma alanı",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Kişi kaynağı",
"nodes.humanInputV2.recipients.duplicateSource": "{{name}} ({{source}}) üzerinden zaten eklendi.",
+ "nodes.humanInputV2.recipients.edit": "{{recipient}} alıcısını düzenle",
+ "nodes.humanInputV2.recipients.editRecipient": "Alıcıyı düzenle",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Her e-posta adresi yalnızca bir kez seçilebilir.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Henüz eklenmemiş geçerli bir e-posta adresi girin",
+ "nodes.humanInputV2.recipients.emailLabel": "Tek seferlik e-posta alıcısı",
+ "nodes.humanInputV2.recipients.empty": "Alıcı yapılandırılmadı",
+ "nodes.humanInputV2.recipients.help": "Bu İnsan Girdisi adımına kimlerin yanıt verebileceğini seçin.",
"nodes.humanInputV2.recipients.initiator": "Bu çalıştırmayı Web App veya CLI üzerinden başlatan kullanıcı onaylayabilir",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Bu iş akışını başlatan kişi yanıt verebilir.",
"nodes.humanInputV2.recipients.inputHelp": "Virgülle ayrılmış birden fazla e-posta adresi yazın veya yapıştırın. Değişken eklemek için / tuşuna basın.",
+ "nodes.humanInputV2.recipients.insertVariable": "Değişken ekle",
+ "nodes.humanInputV2.recipients.loadError": "Kişiler yüklenemedi. Saklanan kişi kimlikleri korunuyor.",
+ "nodes.humanInputV2.recipients.loading": "Kişiler yükleniyor…",
+ "nodes.humanInputV2.recipients.noResults": "Kişi bulunamadı",
+ "nodes.humanInputV2.recipients.placeholder": "Kişi arayın veya e-posta adresleri ekleyin",
+ "nodes.humanInputV2.recipients.remove": "{{recipient}} alıcısını kaldır",
+ "nodes.humanInputV2.recipients.removeHint": "Kaldırmak için Backspace veya Delete tuşuna basın.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} eşleşen alıcı",
+ "nodes.humanInputV2.recipients.search": "Kişi ara",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Ada veya e-posta adresine göre ara",
+ "nodes.humanInputV2.recipients.selectionHint": "{{count}} alıcı seçildi. Alıcılara odaklanmak için giriş alanının başında sol ok tuşuna basın.",
+ "nodes.humanInputV2.recipients.title": "Alıcılar",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Çalışma alanındaki tüm kişiler",
+ "nodes.humanInputV2.recipients.type.contact": "Kişi",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Dinamik e-posta",
+ "nodes.humanInputV2.recipients.type.initiator": "Başlatan kişi",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Tek seferlik e-posta",
+ "nodes.humanInputV2.recipients.typeLabel": "Alıcı türü",
"nodes.humanInputV2.recipients.useThisInstead": "Bunun yerine bunu kullan",
+ "nodes.humanInputV2.recipients.variableRequired": "Bir e-posta değişkeni seçin",
+ "nodes.humanInputV2.template.body": "Gövde",
+ "nodes.humanInputV2.template.description": "E-posta ve anlık iletiler için yedek metin",
"nodes.humanInputV2.template.insertRequestURL": "İstek URL’si ekle",
+ "nodes.humanInputV2.template.insertVariable": "Değişken ekle",
+ "nodes.humanInputV2.template.notConfigured": "Yapılandırılmadı",
"nodes.humanInputV2.template.requestURLHint": "Alıcılar bu bağlantıyla onay formunu açar. Tam olarak bir istek URL’si ekleyin.",
"nodes.humanInputV2.template.requestURLInserted": "İstek URL’si eklendi",
"nodes.humanInputV2.template.saveAndTest": "Kaydet ve test et",
+ "nodes.humanInputV2.template.subject": "Konu",
+ "nodes.humanInputV2.template.subjectPlaceholder": "İleti konusunu girin",
"nodes.humanInputV2.template.test": "Mesajı test et",
"nodes.humanInputV2.template.testChannel": "Test kanalı",
"nodes.humanInputV2.template.testCompleted": "Test isteği tamamlandı. Mesajı görmek için seçilen kanalı kontrol edin.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Tüm test değişkenlerinin değerlerini girin.",
"nodes.humanInputV2.template.testSaveFailed": "İş akışı taslağı kaydedilemedi. Test gönderilmedi.",
"nodes.humanInputV2.template.testUnavailable": "Bu ortam henüz mesaj şablonu testini desteklemiyor.",
+ "nodes.humanInputV2.template.title": "İleti şablonu",
"nodes.ifElse.operator": "Operatör",
"nodes.iteration.currentIteration": "Mevcut Yineleme",
"nodes.iteration.deleteDesc": "Yineleme düğümünü silmek tüm alt düğümleri silecektir",
diff --git a/web/i18n/locales/uk-UA/contacts.json b/web/i18n/locales/uk-UA/contacts.json
index c40d1856ef3..bae8e405b8c 100644
--- a/web/i18n/locales/uk-UA/contacts.json
+++ b/web/i18n/locales/uk-UA/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Видалити контакти ({{count}})?",
"directory.removalDescription": "Вибрані контакти буде назавжди видалено з цього робочого простору. Цю дію неможливо скасувати.",
- "directory.removalTitle": "Видалити контакти?",
+ "directory.removalSingleDescription": "Контакт {{name}} буде назавжди видалено з цього робочого простору. Цю дію неможливо скасувати.",
+ "directory.removalSingleFailed": "Не вдалося видалити контакт. Спробуйте ще раз.",
+ "directory.removalSingleTitle": "Видалити {{name}}?",
+ "directory.resultCount": "Результати: {{count}}",
+ "imPlatform.action.configure": "Налаштувати",
+ "imPlatform.action.configureChannel": "Налаштувати {{provider}}",
+ "imPlatform.action.connect": "Підключити",
+ "imPlatform.action.copied": "Скопійовані",
+ "imPlatform.action.copyCallback": "Копіювати URL зворотного виклику",
+ "imPlatform.action.deleteChannel": "Видалити {{provider}}",
+ "imPlatform.action.loadMore": "Завантажити ще",
+ "imPlatform.action.replace": "Замінити",
+ "imPlatform.action.retry": "Повторити",
+ "imPlatform.action.save": "Зберегти",
+ "imPlatform.action.saving": "Збереження",
+ "imPlatform.action.setupGuide": "Посібник із налаштування",
+ "imPlatform.action.syncNow": "Синхронізувати зараз",
+ "imPlatform.action.syncing": "Синхронізація",
+ "imPlatform.action.testConnection": "Перевірити підключення",
+ "imPlatform.action.testing": "Перевірка",
+ "imPlatform.action.viewDetails": "Перегляд докладних відомостей",
+ "imPlatform.bindingDialog.back": "Назад",
+ "imPlatform.bindingDialog.callback": "URL зворотного виклику",
+ "imPlatform.bindingDialog.callbackDescription": "Завершіть налаштування зворотних викликів у {{provider}}, щоб увімкнути дії з картками.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Для дій із картками вставте цей URL у <console>консолі розробника Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Події та зворотні виклики → Налаштування зворотних викликів → URL запиту",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Для дій із картками вставте цей URL у <console>консолі розробника Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Події та зворотні виклики → Налаштування зворотних викликів → URL запиту",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Для дій із картками вставте цей URL у <console>консолі розробника Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Інтерактивність і швидкі команди → Інтерактивність → URL запиту",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Для дій із картками вставте цей URL у <console>налаштуваннях Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Налаштування → Конфігурація → Кінцева точка обміну повідомленнями",
+ "imPlatform.bindingDialog.callbackStep": "Налаштування зворотних викликів",
"imPlatform.bindingDialog.clearSavedCredential": "Очистити збережене значення",
+ "imPlatform.bindingDialog.configureTitle": "Налаштувати {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Підключіть {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Це збережене значення буде очищено під час збереження.",
+ "imPlatform.bindingDialog.credentialsDescription": "Спочатку підключіть застосунок {{provider}}, потім налаштуйте його URL зворотного виклику.",
+ "imPlatform.bindingDialog.credentialsStep": "Облікові дані застосунку",
+ "imPlatform.bindingDialog.description": "Введіть облікові дані застосунку для цієї платформи обміну повідомленнями.",
+ "imPlatform.bindingDialog.field.agentId": "ID агента",
+ "imPlatform.bindingDialog.field.appId": "ID застосунку",
+ "imPlatform.bindingDialog.field.appToken": "Токен застосунку (необов’язково)",
+ "imPlatform.bindingDialog.field.botToken": "Токен бота",
+ "imPlatform.bindingDialog.field.clientId": "Ідентифікатор клієнта",
+ "imPlatform.bindingDialog.field.clientSecret": "Секрет клієнта",
+ "imPlatform.bindingDialog.field.corpId": "ID організації",
+ "imPlatform.bindingDialog.field.encryptKey": "Ключ шифрування (необов’язково)",
+ "imPlatform.bindingDialog.field.genericSecret": "Секрет",
+ "imPlatform.bindingDialog.field.secret": "Секрет застосунку",
+ "imPlatform.bindingDialog.field.signingSecret": "Секрет підпису",
+ "imPlatform.bindingDialog.field.tenantId": "ID орендаря",
+ "imPlatform.bindingDialog.field.verificationToken": "Токен перевірки (необов’язково)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Введіть ключ шифрування, якщо його ввімкнено",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Введіть секрет застосунку",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Введіть токен перевірки, якщо його налаштовано",
+ "imPlatform.bindingDialog.finish": "Завершити",
+ "imPlatform.bindingDialog.freshCredentials": "Збережені секрети неможливо отримати повторно. Щоб перевірити або зберегти цю конфігурацію, знову введіть усі необхідні облікові дані.",
+ "imPlatform.bindingDialog.openSetupGuide": "Відкрити посібник із налаштування",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Замінити облікові дані орендаря для {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Ці облікові дані належать іншому орендарю IM і не можуть бути збережені безпосередньо. Щоб змінити орендаря, потрібно замінити поточний канал IM. Це видалить усі автоматичні та ручні прив’язки IM. Після заміни повторно синхронізуйте контакти.",
+ "imPlatform.bindingDialog.required": "Це поле обов’язкове.",
+ "imPlatform.bindingDialog.saveAndContinue": "Зберегти й продовжити",
+ "imPlatform.bindingDialog.saveFailed": "Не вдалося зберегти конфігурацію. Перевірте поля та повторіть спробу.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Конфігурацію збережено, але не вдалося завантажити її дані. Закрийте це діалогове вікно та відкрийте його знову.",
- "imPlatform.bindingDialog.undoClearCredential": "Скасувати очищення"
+ "imPlatform.bindingDialog.secretConfigured": "Секрет уже налаштовано. Залиште поле порожнім, щоб зберегти його.",
+ "imPlatform.bindingDialog.step": "Крок {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Перевірка підключення не вдалася. Перевірте конфігурацію та повторіть спробу.",
+ "imPlatform.bindingDialog.undoClearCredential": "Скасувати очищення",
+ "imPlatform.bindingDialog.viewSetupGuide": "Переглянути посібник із налаштування",
+ "imPlatform.chooseProvider": "Виберіть канал для підключення",
+ "imPlatform.configurationUpdated": "Конфігурація цього каналу змінилася. Закрийте діалог і оновіть сторінку перед повторною спробою.",
+ "imPlatform.connectMore": "Підключити інші канали",
+ "imPlatform.delete.confirm": "Видалити",
+ "imPlatform.delete.description": "Після видалення каналу його конфігурацію буде видалено. Надсилання запитів на погодження та синхронізація каталогу через цей канал припиняться.",
+ "imPlatform.delete.failed": "Не вдалося видалити канал. Нічого не змінилося; повторіть спробу.",
+ "imPlatform.delete.title": "Видалити канал {{provider}}?",
+ "imPlatform.description": "Підключіть корпоративні канали, щоб запити на погодження надходили туди, де працюють ваші співробітники.",
+ "imPlatform.details.column.contact": "Контакти",
+ "imPlatform.details.column.platform": "Платформа обміну повідомленнями",
+ "imPlatform.details.description": "Перегляньте результати останньої синхронізації в режимі лише для читання.",
+ "imPlatform.details.downloadFailed": "Не вдалося завантажити звіт. Повторіть спробу.",
+ "imPlatform.details.downloadReport": "Завантажити звіт",
+ "imPlatform.details.downloadingReport": "Завантаження звіту…",
+ "imPlatform.details.empty": "У цій категорії немає результатів.",
+ "imPlatform.details.filter.added": "Додано",
+ "imPlatform.details.filter.failed": "Помилка",
+ "imPlatform.details.filter.not_matched": "Немає збігів",
+ "imPlatform.details.filter.removed": "Видалено",
+ "imPlatform.details.filter.skipped": "Пропущено",
+ "imPlatform.details.filters": "Фільтри результатів синхронізації",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Не вдалося завантажити відомості про синхронізацію.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Не вдалося завантажити наступні результати. Повторіть завантаження цієї сторінки.",
+ "imPlatform.details.removalReason.binding_invalidated": "Прив’язку анульовано",
+ "imPlatform.details.removalReason.binding_replaced": "Прив’язку замінено",
+ "imPlatform.details.removalReason.not_present_in_directory": "Більше немає в каталозі",
+ "imPlatform.details.reportChanged": "Результати синхронізації змінилися. Відкрийте відомості про останню синхронізацію та повторіть спробу.",
+ "imPlatform.details.title": "Відомості про синхронізацію",
+ "imPlatform.email.apiKey": "API ключ",
+ "imPlatform.email.apiKeyConfigured": "З міркувань безпеки збережений API-ключ неможливо переглянути. Залиште поле порожнім, щоб зберегти його.",
+ "imPlatform.email.apiKeyDescription": "З міркувань безпеки цей API-ключ неможливо переглянути після збереження.",
+ "imPlatform.email.apiKeyPlaceholder": "Введіть API-ключ Resend",
+ "imPlatform.email.description": "Ця конфігурація застосовується до всіх вузлів Human Input у цьому робочому просторі, у яких увімкнено опцію <emphasis>Надсилати сповіщення налагодження електронною поштою</emphasis>.",
+ "imPlatform.email.invalidEmail": "Введіть дійсну адресу електронної пошти.",
+ "imPlatform.email.provider": "Провайдер електронної пошти",
+ "imPlatform.email.resendDescription": "Ваш <apiKey>API-ключ Resend</apiKey> буде зашифровано, і його неможливо буде переглянути після збереження.<br/>Зареєструйте обліковий запис <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Налаштування Resend",
+ "imPlatform.email.senderEmail": "Електронна адреса відправника",
+ "imPlatform.email.senderEmailDescription": "Адреса, яка відображається в полі відправника. Її домен має бути підтверджено в Resend.",
+ "imPlatform.email.senderName": "Ім’я відправника",
+ "imPlatform.email.senderNameDescription": "Ім’я, яке відображається в поштовій скриньці одержувача.",
+ "imPlatform.email.testSucceeded": "Перевірку підключення виконано успішно.",
+ "imPlatform.email.title": "Налаштування електронної пошти",
+ "imPlatform.learnMore": "Дізнатися більше",
+ "imPlatform.loadError.description": "Повторіть спробу, щоб завантажити поточну прив’язку та дозволи.",
+ "imPlatform.loadError.retry": "Повторити спробу",
+ "imPlatform.loadError.title": "Не вдалося завантажити канали",
+ "imPlatform.loading": "Завантаження каналів",
+ "imPlatform.provider.dingtalkDescription": "Підключіть застосунок DingTalk.",
+ "imPlatform.provider.emailDescription": "Налаштуйте поштовий сервіс для надсилання запитів на погодження з цього робочого простору.",
+ "imPlatform.provider.feishuDescription": "Підключіть застосунок Feishu.",
+ "imPlatform.provider.larkDescription": "Підключіть застосунок Lark.",
+ "imPlatform.provider.msTeamsDescription": "Підключіть застосунок Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Синхронізуйте співробітників та їхні облікові записи Slack.",
+ "imPlatform.provider.weComDescription": "Підключіть застосунок WeCom.",
+ "imPlatform.replacement.confirm": "Замінити",
+ "imPlatform.replacement.description": "Після заміни активного провайдера його прив’язки до платформи обміну повідомленнями та перевизначення робочого простору стануть недійсними. Після заміни знову синхронізуйте каталог нового провайдера.",
+ "imPlatform.replacement.title": "Замінити {{current}} на {{next}}?",
+ "imPlatform.status.configured": "Налаштовано",
+ "imPlatform.status.connected": "Підключено",
+ "imPlatform.status.connection_error": "Помилка підключення",
+ "imPlatform.status.permission_issue": "Проблема з дозволами",
+ "imPlatform.sync.latestSynced": "Остання синхронізація: {{date}}",
+ "imPlatform.sync.loading": "Перевірка наявності активної синхронізації.",
+ "imPlatform.sync.noPermission": "Лише власники та адміністратори робочого простору можуть запускати синхронізацію каталогу.",
+ "imPlatform.sync.noRuns": "Синхронізація каталогу ще не виконувалася.",
+ "imPlatform.sync.notConnected": "Перед запуском синхронізації каталогу підключіть і перевірте провайдера.",
+ "imPlatform.sync.startFailed": "Не вдалося запустити або оновити синхронізацію каталогу. Повторіть спробу.",
+ "imPlatform.sync.status.failure": "Помилка",
+ "imPlatform.sync.status.queued": "У черзі",
+ "imPlatform.sync.status.running": "Виконується",
+ "imPlatform.sync.status.success": "Успішно",
+ "imPlatform.title": "Канали"
}
diff --git a/web/i18n/locales/uk-UA/share.json b/web/i18n/locales/uk-UA/share.json
index 732b7f37497..b7c2087baa4 100644
--- a/web/i18n/locales/uk-UA/share.json
+++ b/web/i18n/locales/uk-UA/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Дякуємо!",
"humanInput.unavailableDescription": "Можливо, посилання недоступне або не відповідає обліковому запису, у який ви ввійшли. Відкрийте форму з отриманого сповіщення або спробуйте змінити обліковий запис.",
"humanInput.unavailableTitle": "Не вдалося відкрити цю форму",
+ "humanInputV2.accessRateLimited": "Запитано забагато листів із кодом підтвердження. Спробуйте пізніше.",
+ "humanInputV2.alreadySubmitted": "Цей запит уже виконано.",
+ "humanInputV2.challengeExpired": "Термін дії цього коду підтвердження минув. Запросіть новий код, щоб продовжити.",
+ "humanInputV2.challengeStale": "Цей код підтвердження було замінено. Запросіть новий код, щоб продовжити.",
+ "humanInputV2.codeExpiresIn": "Термін дії коду мине через {{seconds}} с",
+ "humanInputV2.codeRequired": "Запросіть код підтвердження, щоб продовжити.",
+ "humanInputV2.codeSent": "Код підтвердження надіслано на вашу електронну пошту.",
+ "humanInputV2.deliveryFailed": "Не вдалося надіслати лист із кодом підтвердження. Спробуйте ще раз.",
+ "humanInputV2.formExpired": "Термін дії цього запиту минув.",
+ "humanInputV2.formNotFound": "Форму не знайдено.",
+ "humanInputV2.formRateLimited": "Забагато запитів до форми. Спробуйте пізніше.",
+ "humanInputV2.invalidOtp": "Неправильний код підтвердження. Перевірте код і спробуйте ще раз.",
+ "humanInputV2.networkError": "Не вдалося виконати запит. Перевірте з'єднання та спробуйте ще раз.",
+ "humanInputV2.otpLabel": "Код підтвердження електронної пошти",
+ "humanInputV2.otpPlaceholder": "Введіть шестизначний код",
+ "humanInputV2.requestingCode": "Надсилання коду підтвердження…",
+ "humanInputV2.resendCode": "Надіслати код повторно",
+ "humanInputV2.retry": "Спробувати ще раз",
+ "humanInputV2.sendCode": "Надіслати новий код",
+ "humanInputV2.unavailable": "Ця форма тимчасово недоступна.",
+ "humanInputV2.unknownError": "Сталася помилка. Спробуйте ще раз.",
+ "humanInputV2.uploadFailed": "Не вдалося завантажити файл. Спробуйте ще раз.",
"login.backToHome": "Повернутися на головну"
}
diff --git a/web/i18n/locales/uk-UA/workflow-human-input.json b/web/i18n/locales/uk-UA/workflow-human-input.json
index 787942df445..f3e76279eab 100644
--- a/web/i18n/locales/uk-UA/workflow-human-input.json
+++ b/web/i18n/locales/uk-UA/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Значення дії",
"nodes.humanInput.userActions.buttonTextTooLong": "Текст кнопки повинен містити не більше {{maxLength}} символів",
"nodes.humanInput.userActions.chooseStyle": "Виберіть стиль кнопки",
+ "nodes.humanInput.userActions.defaultTitle": "Текст кнопки {{index}}",
"nodes.humanInput.userActions.emptyTip": "Натисніть кнопку '+' для додавання дій користувача",
"nodes.humanInput.userActions.title": "Дії користувача",
"nodes.humanInput.userActions.tooltip": "Визначте кнопки, на які користувачі можуть натискати, щоб відповісти на цю форму. Ідентифікатор дії контролює розгалуження. Значення дії відкривається нижче за потоком як вибраний вбудований вивід. Ідентифікатор дії повинен починатися з літери або підкреслення, за яким слідують літери, цифри або підкреслення.",
diff --git a/web/i18n/locales/uk-UA/workflow.json b/web/i18n/locales/uk-UA/workflow.json
index 5b2246842b6..2c6a0d0b897 100644
--- a/web/i18n/locales/uk-UA/workflow.json
+++ b/web/i18n/locales/uk-UA/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Вивід",
"blocks.http-request": "HTTP-запит",
"blocks.human-input": "Введення людини",
+ "blocks.human-input-v2": "Введення людини v2",
"blocks.if-else": "ЯКЩО/ІНАКШЕ",
"blocks.iteration": "Ітерація",
"blocks.iteration-start": "Початок ітерації",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Визначте вивід і тип результату робочого потоку",
"blocksAbout.http-request": "Дозволяє відправляти серверні запити через протокол HTTP",
"blocksAbout.human-input": "Попросити підтвердження людини перед генерацією наступного кроку",
+ "blocksAbout.human-input-v2": "Запросити введення в налаштованих контактів, одержувачів електронної пошти або ініціатора робочого процесу",
"blocksAbout.if-else": "Дозволяє розділити робочий потік на дві гілки на основі умов if/else",
"blocksAbout.iteration": "Виконувати кілька кроків на об'єкті списку, поки не буде виведено всі результати.",
"blocksAbout.iteration-start": "Вузол початку ітерації",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Агрегує змінні з кількох гілок у одну змінну для уніфікованої конфігурації кінцевих вузлів.",
"blocksAbout.variable-assigner": "Агрегує змінні з кількох гілок у одну змінну для уніфікованої конфігурації кінцевих вузлів.",
"changeHistory.edgeDelete": "Вузол відключено",
+ "changeHistory.humanInputMigration": "Вузли введення людини перенесено",
"changeHistory.nodeAdd": "Додано вузол",
"changeHistory.nodeChange": "Вузол змінився",
"changeHistory.nodeConnect": "Вузол підключено",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Будь ласка, увімкніть принаймні один спосіб доставки",
"nodes.humanInput.errorMsg.noUserActions": "Будь ласка, додайте принаймні одну дію користувача",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} зарезервовано для гілки тайм-ауту. Виберіть інший ідентифікатор дії.",
+ "nodes.humanInput.output.actionId": "ID дії, яку виконав користувач",
+ "nodes.humanInput.output.actionValue": "Значення вибраної дії",
+ "nodes.humanInput.output.formInput": "Значення поля форми",
+ "nodes.humanInput.output.renderedContent": "Відображений вміст",
"nodes.humanInput.timeout.title": "Тайм-аут",
+ "nodes.humanInputMigration.action.migrate": "Перенести",
+ "nodes.humanInputMigration.action.migrateNow": "Перенести зараз",
+ "nodes.humanInputMigration.action.migrating": "Перенесення...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Сповіщення про перенесення вузлів введення людини",
+ "nodes.humanInputMigration.banner.description": "Цей робочий процес використовує старий вузол введення людини. Перенесіть усі старі вузли, перш ніж додавати нові.",
+ "nodes.humanInputMigration.banner.learnMore": "Докладніше",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "вимкнений спосіб доставки досі містить налаштування",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "увімкнені способи доставки електронною поштою використовують несумісні шаблони",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Недійсне значення за замовчуванням",
+ "nodes.humanInputMigration.blocker.invalidEmail": "адреса електронної пошти одержувача недійсна",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "налаштування увімкненого способу доставки електронною поштою не завершено",
+ "nodes.humanInputMigration.blocker.missingRecipients": "вузол не має підтримуваних одержувачів",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "неможливо визначити контакт або підтверджену адресу електронної пошти учасника робочого простору",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "увімкнений спосіб доставки не підтримується вузлом введення людини v2",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Поле {{field}} поки що не можна перенести. Ви можете й надалі використовувати попередні вузли введення даних людиною.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "вузол має непідтримуване значення версії",
+ "nodes.humanInputMigration.dialog.description": "Одержувачі, форма та дії будуть збережені.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Зміниться лише ця чернетка. Опубліковані версії працюватимуть до наступної публікації.",
+ "nodes.humanInputMigration.dialog.review": "Перегляньте вузли й опублікуйте, коли будете готові.",
+ "nodes.humanInputMigration.dialog.title": "Перенести вузли введення людини: {{count}}",
+ "nodes.humanInputMigration.disabledBadge": "ПОТРІБНЕ ПЕРЕНЕСЕННЯ",
+ "nodes.humanInputMigration.disabledReason": "Перенесіть старі вузли введення людини, перш ніж додавати новий.",
+ "nodes.humanInputMigration.error.blocked": "Не вдалося перенести {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Робочий процес змінився під час міграції. Спробуйте ще раз; поточні зміни збережено.",
+ "nodes.humanInputMigration.error.preflight": "Не вдалося підготувати перенесення. Робочий процес не змінено. Спробуйте ще раз.",
"nodes.humanInputMigration.error.sync": "Не вдалося зберегти перенесений робочий процес. Перегляньте поточну чернетку та спробуйте ще раз.",
+ "nodes.humanInputMigration.incompatibleVersions": "Старі та нові вузли введення користувача не можна використовувати в одному робочому процесі.",
+ "nodes.humanInputMigration.oldVersion": "СТАРА ВЕРСІЯ",
+ "nodes.humanInputMigration.preview.author": "Від команди Dify",
+ "nodes.humanInputMigration.preview.description": "Перенесіть старі вузли введення людини, перш ніж додавати новий.",
+ "nodes.humanInputMigration.success": "Вузли введення людини успішно перенесено",
+ "nodes.humanInputV2.card.configured": "Налаштовано одержувачів: {{count}}",
+ "nodes.humanInputV2.card.contactsOnly": "Контактів: {{count}}",
+ "nodes.humanInputV2.card.empty": "Поки ніхто не може схвалити цей крок",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Ініціатор і контакти: {{count}}",
+ "nodes.humanInputV2.card.initiatorOnly": "Лише ініціатор",
+ "nodes.humanInputV2.card.invalid": "Перевірте налаштування одержувачів",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "Електронна пошта",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Налаштувати режим налагодження",
"nodes.humanInputV2.debug.keepOneChannel": "Залиште ввімкненим принаймні один канал",
+ "nodes.humanInputV2.debug.sendVia": "Надсилати сповіщення налагодження через",
+ "nodes.humanInputV2.debug.title": "Режим налагодження",
+ "nodes.humanInputV2.debug.toggle": "Увімкнути режим налагодження",
+ "nodes.humanInputV2.debug.unsupported": "Імпортовано непідтримувані канали: {{channels}}. Видаліть або оновіть їх перед запуском цього робочого процесу.",
"nodes.humanInputV2.disabled": "Human Input v2 недоступний, поки HITL IM вимкнено.",
+ "nodes.humanInputV2.error.bodyRequired": "Текст повідомлення обов'язковий",
+ "nodes.humanInputV2.error.debugChannelRequired": "Виберіть принаймні один канал режиму налагодження",
+ "nodes.humanInputV2.error.recipientDuplicate": "Видаліть дублікати одержувачів",
+ "nodes.humanInputV2.error.recipientInvalid": "Виправте недійсні налаштування одержувачів",
+ "nodes.humanInputV2.error.recipientRequired": "Додайте принаймні одного одержувача",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Не вдалося перевірити одержувачів із контактів",
"nodes.humanInputV2.error.requestURLDuplicate": "Текст повідомлення може містити лише один URL запиту.",
"nodes.humanInputV2.error.requestURLRequired": "Вставте URL запиту в текст повідомлення.",
+ "nodes.humanInputV2.error.subjectRequired": "Тема повідомлення обов'язкова",
+ "nodes.humanInputV2.error.version": "Для введення людини v2 потрібне рядкове значення версії 2",
+ "nodes.humanInputV2.recipients.addContact": "Додати контакт",
+ "nodes.humanInputV2.recipients.addEmail": "Додати",
+ "nodes.humanInputV2.recipients.addRecipient": "Додати одержувача",
+ "nodes.humanInputV2.recipients.added": "Додано",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Усі контакти робочого простору",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Надіслати сповіщення всім контактам робочого простору; будь-хто з них може схвалити",
+ "nodes.humanInputV2.recipients.cancel": "Скасувати",
+ "nodes.humanInputV2.recipients.chooseVariable": "Вибрати змінну",
+ "nodes.humanInputV2.recipients.confirm": "Підтвердити",
+ "nodes.humanInputV2.recipients.contactInfo": "Контактні дані: {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Усі",
+ "nodes.humanInputV2.recipients.contactSource.external": "Зовнішні",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Організація",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Робочий простір",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Джерело контактів",
"nodes.humanInputV2.recipients.duplicateSource": "Уже додано через {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Редагувати {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Редагувати одержувача",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Кожну електронну адресу можна вибрати лише один раз.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Введіть дійсну адресу електронної пошти, яку ще не додано",
+ "nodes.humanInputV2.recipients.emailLabel": "Одноразовий одержувач електронної пошти",
+ "nodes.humanInputV2.recipients.empty": "Одержувачів не налаштовано",
+ "nodes.humanInputV2.recipients.help": "Виберіть, хто може відповісти на цьому кроці введення людини.",
"nodes.humanInputV2.recipients.initiator": "Користувач, який запускає це виконання через Web App або CLI, може його схвалити",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Відповісти може особа, яка запускає цей робочий процес.",
"nodes.humanInputV2.recipients.inputHelp": "Введіть або вставте кілька електронних адрес, розділених комами. Натисніть /, щоб вставити змінну.",
+ "nodes.humanInputV2.recipients.insertVariable": "Вставити змінну",
+ "nodes.humanInputV2.recipients.loadError": "Не вдалося завантажити контакти. Збережені ID контактів не змінено.",
+ "nodes.humanInputV2.recipients.loading": "Завантаження контактів…",
+ "nodes.humanInputV2.recipients.noResults": "Контактів не знайдено",
+ "nodes.humanInputV2.recipients.placeholder": "Знайдіть контакти або додайте адреси електронної пошти",
+ "nodes.humanInputV2.recipients.remove": "Видалити {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Натисніть Backspace або Delete, щоб видалити.",
+ "nodes.humanInputV2.recipients.resultCount": "Відповідних одержувачів: {{count}}",
+ "nodes.humanInputV2.recipients.search": "Пошук контактів",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Пошук за ім'ям або електронною поштою",
+ "nodes.humanInputV2.recipients.selectionHint": "Вибрано одержувачів: {{count}}. На початку поля натисніть стрілку вліво, щоб перейти до них.",
+ "nodes.humanInputV2.recipients.title": "Одержувачі",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Усі контакти робочого простору",
+ "nodes.humanInputV2.recipients.type.contact": "Контакт",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Динамічна адреса електронної пошти",
+ "nodes.humanInputV2.recipients.type.initiator": "Ініціатор",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Одноразова адреса електронної пошти",
+ "nodes.humanInputV2.recipients.typeLabel": "Тип одержувача",
"nodes.humanInputV2.recipients.useThisInstead": "Використати цей варіант",
+ "nodes.humanInputV2.recipients.variableRequired": "Виберіть змінну з адресою електронної пошти",
+ "nodes.humanInputV2.template.body": "Текст",
+ "nodes.humanInputV2.template.description": "Резервний текст для електронної пошти та миттєвих повідомлень",
"nodes.humanInputV2.template.insertRequestURL": "Вставити URL запиту",
+ "nodes.humanInputV2.template.insertVariable": "Вставити змінну",
+ "nodes.humanInputV2.template.notConfigured": "Не налаштовано",
"nodes.humanInputV2.template.requestURLHint": "Одержувачі відкривають форму погодження за цим посиланням. Додайте рівно один URL запиту.",
"nodes.humanInputV2.template.requestURLInserted": "URL запиту вставлено",
"nodes.humanInputV2.template.saveAndTest": "Зберегти й перевірити",
+ "nodes.humanInputV2.template.subject": "Тема",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Введіть тему повідомлення",
"nodes.humanInputV2.template.test": "Перевірити повідомлення",
"nodes.humanInputV2.template.testChannel": "Канал для тесту",
"nodes.humanInputV2.template.testCompleted": "Тестовий запит виконано. Перевірте повідомлення у вибраному каналі.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Заповніть значення всіх тестових змінних.",
"nodes.humanInputV2.template.testSaveFailed": "Не вдалося зберегти чернетку робочого процесу. Тест не було надіслано.",
"nodes.humanInputV2.template.testUnavailable": "Це середовище ще не підтримує тестування шаблонів повідомлень.",
+ "nodes.humanInputV2.template.title": "Шаблон повідомлення",
"nodes.ifElse.operator": "Оператор",
"nodes.iteration.currentIteration": "Поточна ітерація",
"nodes.iteration.deleteDesc": "Видалення вузла ітерації видалить усі дочірні вузли",
diff --git a/web/i18n/locales/vi-VN/contacts.json b/web/i18n/locales/vi-VN/contacts.json
index d5615eaff6f..8ac43361b1b 100644
--- a/web/i18n/locales/vi-VN/contacts.json
+++ b/web/i18n/locales/vi-VN/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "Xóa liên hệ ({{count}})?",
"directory.removalDescription": "Các liên hệ đã chọn sẽ bị xóa vĩnh viễn khỏi không gian làm việc này. Không thể hoàn tác hành động này.",
- "directory.removalTitle": "Xóa liên hệ?",
+ "directory.removalSingleDescription": "{{name}} sẽ bị xóa vĩnh viễn khỏi không gian làm việc này. Không thể hoàn tác hành động này.",
+ "directory.removalSingleFailed": "Không thể xóa liên hệ. Vui lòng thử lại.",
+ "directory.removalSingleTitle": "Xóa {{name}}?",
+ "directory.resultCount": "Kết quả: {{count}}",
+ "imPlatform.action.configure": "Cấu hình",
+ "imPlatform.action.configureChannel": "Định cấu hình {{provider}}",
+ "imPlatform.action.connect": "Kết nối",
+ "imPlatform.action.copied": "Sao chép",
+ "imPlatform.action.copyCallback": "Sao chép URL callback",
+ "imPlatform.action.deleteChannel": "Xóa {{provider}}",
+ "imPlatform.action.loadMore": "Tải thêm",
+ "imPlatform.action.replace": "Thay thế",
+ "imPlatform.action.retry": "Thử lại",
+ "imPlatform.action.save": "Lưu",
+ "imPlatform.action.saving": "Đang lưu",
+ "imPlatform.action.setupGuide": "Hướng dẫn thiết lập",
+ "imPlatform.action.syncNow": "Đồng bộ hóa ngay",
+ "imPlatform.action.syncing": "Đang đồng bộ hóa",
+ "imPlatform.action.testConnection": "Kiểm tra kết nối",
+ "imPlatform.action.testing": "Đang kiểm tra",
+ "imPlatform.action.viewDetails": "Xem chi tiết",
+ "imPlatform.bindingDialog.back": "Quay lại",
+ "imPlatform.bindingDialog.callback": "URL gọi lại",
+ "imPlatform.bindingDialog.callbackDescription": "Hoàn tất thiết lập callback trong {{provider}} để bật các thao tác trên thẻ.",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "Để nhận thao tác trên thẻ, hãy dán URL này vào <console>Bảng điều khiển nhà phát triển Feishu</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "Sự kiện & Callback → Cấu hình callback → URL yêu cầu",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "Để nhận thao tác trên thẻ, hãy dán URL này vào <console>Bảng điều khiển nhà phát triển Lark</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "Sự kiện & Callback → Cấu hình callback → URL yêu cầu",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "Để nhận thao tác trên thẻ, hãy dán URL này vào <console>Bảng điều khiển nhà phát triển Slack</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "Tương tác & Phím tắt → Tương tác → URL yêu cầu",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "Để nhận thao tác trên thẻ, hãy dán URL này vào <console>Cấu hình Azure Bot</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "Cài đặt → Cấu hình → Điểm cuối nhắn tin",
+ "imPlatform.bindingDialog.callbackStep": "Cấu hình callback",
"imPlatform.bindingDialog.clearSavedCredential": "Xóa giá trị đã lưu",
+ "imPlatform.bindingDialog.configureTitle": "Định cấu hình {{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "Kết nối {{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "Giá trị đã lưu này sẽ bị xóa khi bạn lưu.",
+ "imPlatform.bindingDialog.credentialsDescription": "Kết nối ứng dụng {{provider}} trước, sau đó cấu hình URL callback của ứng dụng.",
+ "imPlatform.bindingDialog.credentialsStep": "Thông tin xác thực ứng dụng",
+ "imPlatform.bindingDialog.description": "Nhập thông tin xác thực ứng dụng cho nhà cung cấp IM này.",
+ "imPlatform.bindingDialog.field.agentId": "ID tác nhân",
+ "imPlatform.bindingDialog.field.appId": "ID ứng dụng",
+ "imPlatform.bindingDialog.field.appToken": "Token ứng dụng (không bắt buộc)",
+ "imPlatform.bindingDialog.field.botToken": "Token bot",
+ "imPlatform.bindingDialog.field.clientId": "ID khách hàng",
+ "imPlatform.bindingDialog.field.clientSecret": "Bí mật của khách hàng",
+ "imPlatform.bindingDialog.field.corpId": "ID doanh nghiệp",
+ "imPlatform.bindingDialog.field.encryptKey": "Khóa mã hóa (không bắt buộc)",
+ "imPlatform.bindingDialog.field.genericSecret": "Bí mật",
+ "imPlatform.bindingDialog.field.secret": "Khóa bí mật ứng dụng",
+ "imPlatform.bindingDialog.field.signingSecret": "Khóa bí mật ký",
+ "imPlatform.bindingDialog.field.tenantId": "ID đối tượng thuê",
+ "imPlatform.bindingDialog.field.verificationToken": "Token xác minh (không bắt buộc)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "Nhập khóa mã hóa nếu đã bật",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "Nhập khóa bí mật ứng dụng",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "Nhập token xác minh nếu đã cấu hình",
+ "imPlatform.bindingDialog.finish": "Hoàn tất",
+ "imPlatform.bindingDialog.freshCredentials": "Không thể truy xuất các khóa bí mật đã lưu. Nhập lại toàn bộ thông tin xác thực bắt buộc để kiểm tra hoặc lưu cấu hình này.",
+ "imPlatform.bindingDialog.openSetupGuide": "Mở hướng dẫn thiết lập",
+ "imPlatform.bindingDialog.replaceTenantTitle": "Thay thông tin xác thực đối tượng thuê của {{identity}}?",
"imPlatform.bindingDialog.replacementRequired": "Thông tin xác thực này thuộc về một tenant IM khác nên không thể lưu trực tiếp. Để chuyển tenant, bạn phải thay thế kênh IM hiện tại; thao tác này sẽ xóa toàn bộ liên kết IM tự động và thủ công. Hãy đồng bộ lại danh bạ sau khi thay thế.",
+ "imPlatform.bindingDialog.required": "Trường này là bắt buộc.",
+ "imPlatform.bindingDialog.saveAndContinue": "Lưu và tiếp tục",
+ "imPlatform.bindingDialog.saveFailed": "Không thể lưu cấu hình. Kiểm tra các trường rồi thử lại.",
"imPlatform.bindingDialog.savedDetailsUnavailable": "Đã lưu cấu hình nhưng không thể tải thông tin chi tiết. Hãy đóng hộp thoại này rồi mở lại.",
- "imPlatform.bindingDialog.undoClearCredential": "Hoàn tác xóa"
+ "imPlatform.bindingDialog.secretConfigured": "Khóa bí mật đã được cấu hình. Để trống trường này nếu muốn giữ nguyên.",
+ "imPlatform.bindingDialog.step": "Bước {{step}}",
+ "imPlatform.bindingDialog.testFailed": "Kiểm tra kết nối thất bại. Kiểm tra cấu hình rồi thử lại.",
+ "imPlatform.bindingDialog.undoClearCredential": "Hoàn tác xóa",
+ "imPlatform.bindingDialog.viewSetupGuide": "Xem hướng dẫn thiết lập",
+ "imPlatform.chooseProvider": "Chọn một kênh để kết nối",
+ "imPlatform.configurationUpdated": "Cấu hình kênh này đã thay đổi. Đóng hộp thoại và làm mới trước khi thử lại.",
+ "imPlatform.connectMore": "Kết nối thêm kênh",
+ "imPlatform.delete.confirm": "Xóa bỏ",
+ "imPlatform.delete.description": "Xóa kênh này sẽ xóa cấu hình của kênh. Mọi hoạt động gửi yêu cầu phê duyệt hoặc đồng bộ danh bạ sử dụng kênh này sẽ dừng.",
+ "imPlatform.delete.failed": "Không thể xóa kênh. Không có thay đổi nào được thực hiện; hãy thử lại.",
+ "imPlatform.delete.title": "Xóa kênh {{provider}}?",
+ "imPlatform.description": "Kết nối các kênh công ty để yêu cầu phê duyệt đến được với mọi người ngay tại nơi họ làm việc.",
+ "imPlatform.details.column.contact": "Liên hệ",
+ "imPlatform.details.column.platform": "Nền tảng IM",
+ "imPlatform.details.description": "Xem kết quả chỉ đọc của lần đồng bộ gần nhất.",
+ "imPlatform.details.downloadFailed": "Không thể tải báo cáo xuống. Hãy thử lại.",
+ "imPlatform.details.downloadReport": "Tải báo cáo xuống",
+ "imPlatform.details.downloadingReport": "Đang tải báo cáo xuống…",
+ "imPlatform.details.empty": "Không có kết quả trong danh mục này.",
+ "imPlatform.details.filter.added": "Đã thêm",
+ "imPlatform.details.filter.failed": "Thất bại",
+ "imPlatform.details.filter.not_matched": "Không khớp",
+ "imPlatform.details.filter.removed": "Xóa",
+ "imPlatform.details.filter.skipped": "Đã bỏ qua",
+ "imPlatform.details.filters": "Bộ lọc kết quả đồng bộ",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "Không thể tải chi tiết đồng bộ.",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "Không thể tải thêm kết quả. Thử tải lại trang này.",
+ "imPlatform.details.removalReason.binding_invalidated": "Liên kết đã bị vô hiệu hóa",
+ "imPlatform.details.removalReason.binding_replaced": "Liên kết đã được thay thế",
+ "imPlatform.details.removalReason.not_present_in_directory": "Không còn trong danh bạ",
+ "imPlatform.details.reportChanged": "Kết quả đồng bộ đã thay đổi. Mở lại chi tiết lần đồng bộ gần nhất rồi thử lại.",
+ "imPlatform.details.title": "Chi tiết đồng bộ",
+ "imPlatform.email.apiKey": "Khóa API",
+ "imPlatform.email.apiKeyConfigured": "Vì lý do bảo mật, không thể xem Khóa API đã lưu. Để trống trường này nếu muốn giữ nguyên.",
+ "imPlatform.email.apiKeyDescription": "Vì lý do bảo mật, không thể xem Khóa API này sau khi lưu.",
+ "imPlatform.email.apiKeyPlaceholder": "Nhập Khóa API Resend của bạn",
+ "imPlatform.email.description": "Cấu hình này áp dụng cho tất cả nút Human Input trong không gian làm việc này đã bật <emphasis>Gửi thông báo gỡ lỗi qua Email</emphasis>.",
+ "imPlatform.email.invalidEmail": "Nhập địa chỉ email hợp lệ.",
+ "imPlatform.email.provider": "Nhà cung cấp email",
+ "imPlatform.email.resendDescription": "<apiKey>Khóa API Resend</apiKey> của bạn sẽ được mã hóa và không thể xem sau khi lưu.<br/>Đăng ký tài khoản <resend>Resend</resend>.",
+ "imPlatform.email.resendSettings": "Cài đặt Resend",
+ "imPlatform.email.senderEmail": "Địa chỉ email người gửi",
+ "imPlatform.email.senderEmailDescription": "Địa chỉ email hiển thị là người gửi. Miền của địa chỉ phải được xác minh trong Resend.",
+ "imPlatform.email.senderName": "Tên người gửi",
+ "imPlatform.email.senderNameDescription": "Tên hiển thị trong hộp thư đến của người nhận.",
+ "imPlatform.email.testSucceeded": "Kiểm tra kết nối thành công.",
+ "imPlatform.email.title": "Cấu hình Email",
+ "imPlatform.learnMore": "Tìm hiểu thêm",
+ "imPlatform.loadError.description": "Thử lại để đọc liên kết và quyền hiện tại.",
+ "imPlatform.loadError.retry": "Thử lại",
+ "imPlatform.loadError.title": "Không thể tải các kênh",
+ "imPlatform.loading": "Đang tải các kênh",
+ "imPlatform.provider.dingtalkDescription": "Kết nối ứng dụng DingTalk.",
+ "imPlatform.provider.emailDescription": "Cấu hình dịch vụ email dùng để gửi yêu cầu phê duyệt từ không gian làm việc này.",
+ "imPlatform.provider.feishuDescription": "Kết nối ứng dụng Feishu.",
+ "imPlatform.provider.larkDescription": "Kết nối ứng dụng Lark.",
+ "imPlatform.provider.msTeamsDescription": "Kết nối ứng dụng Microsoft Teams.",
+ "imPlatform.provider.slackDescription": "Đồng bộ người dùng và danh tính Slack của họ.",
+ "imPlatform.provider.weComDescription": "Kết nối ứng dụng WeCom.",
+ "imPlatform.replacement.confirm": "Thay thế",
+ "imPlatform.replacement.description": "Thay thế nhà cung cấp hiện tại sẽ vô hiệu hóa các liên kết IM và cấu hình ghi đè của không gian làm việc. Sau khi thay thế, hãy đồng bộ lại danh bạ của nhà cung cấp mới.",
+ "imPlatform.replacement.title": "Thay {{current}} bằng {{next}}?",
+ "imPlatform.status.configured": "Đã cấu hình",
+ "imPlatform.status.connected": "Đã kết nối",
+ "imPlatform.status.connection_error": "Lỗi kết nối",
+ "imPlatform.status.permission_issue": "Vấn đề về quyền",
+ "imPlatform.sync.latestSynced": "Đồng bộ gần nhất {{date}}",
+ "imPlatform.sync.loading": "Đang kiểm tra phiên đồng bộ đang hoạt động.",
+ "imPlatform.sync.noPermission": "Chỉ chủ sở hữu và quản trị viên không gian làm việc mới có thể bắt đầu đồng bộ danh bạ.",
+ "imPlatform.sync.noRuns": "Chưa có lần đồng bộ danh bạ nào được thực hiện.",
+ "imPlatform.sync.notConnected": "Kết nối và kiểm tra nhà cung cấp trước khi bắt đầu đồng bộ danh bạ.",
+ "imPlatform.sync.startFailed": "Không thể bắt đầu hoặc làm mới đồng bộ danh bạ. Hãy thử lại.",
+ "imPlatform.sync.status.failure": "Thất bại",
+ "imPlatform.sync.status.queued": "Đang chờ",
+ "imPlatform.sync.status.running": "Đang chạy",
+ "imPlatform.sync.status.success": "Thành công",
+ "imPlatform.title": "Kênh"
}
diff --git a/web/i18n/locales/vi-VN/share.json b/web/i18n/locales/vi-VN/share.json
index 6dc5b30ad57..185f821db20 100644
--- a/web/i18n/locales/vi-VN/share.json
+++ b/web/i18n/locales/vi-VN/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "Cảm ơn!",
"humanInput.unavailableDescription": "Liên kết có thể không khả dụng hoặc không khớp với tài khoản bạn đang đăng nhập. Hãy mở biểu mẫu từ thông báo bạn đã nhận hoặc thử chuyển tài khoản.",
"humanInput.unavailableTitle": "Không thể mở biểu mẫu này",
+ "humanInputV2.accessRateLimited": "Đã yêu cầu quá nhiều email xác minh. Vui lòng thử lại sau.",
+ "humanInputV2.alreadySubmitted": "Yêu cầu này đã hoàn tất.",
+ "humanInputV2.challengeExpired": "Mã xác minh này đã hết hạn. Hãy yêu cầu mã mới để tiếp tục.",
+ "humanInputV2.challengeStale": "Mã xác minh này đã được thay thế. Hãy yêu cầu mã mới để tiếp tục.",
+ "humanInputV2.codeExpiresIn": "Mã hết hạn sau {{seconds}} giây",
+ "humanInputV2.codeRequired": "Yêu cầu mã xác minh để tiếp tục.",
+ "humanInputV2.codeSent": "Mã xác minh đã được gửi đến email của bạn.",
+ "humanInputV2.deliveryFailed": "Không thể gửi email xác minh. Vui lòng thử lại.",
+ "humanInputV2.formExpired": "Yêu cầu này đã hết hạn.",
+ "humanInputV2.formNotFound": "Không tìm thấy biểu mẫu.",
+ "humanInputV2.formRateLimited": "Có quá nhiều yêu cầu biểu mẫu. Vui lòng thử lại sau.",
+ "humanInputV2.invalidOtp": "Mã xác minh không chính xác. Hãy kiểm tra mã và thử lại.",
+ "humanInputV2.networkError": "Không thể hoàn tất yêu cầu. Hãy kiểm tra kết nối và thử lại.",
+ "humanInputV2.otpLabel": "Mã xác minh email",
+ "humanInputV2.otpPlaceholder": "Nhập mã gồm 6 chữ số",
+ "humanInputV2.requestingCode": "Đang gửi mã xác minh…",
+ "humanInputV2.resendCode": "Gửi lại mã",
+ "humanInputV2.retry": "Thử lại",
+ "humanInputV2.sendCode": "Gửi mã mới",
+ "humanInputV2.unavailable": "Biểu mẫu này tạm thời không khả dụng.",
+ "humanInputV2.unknownError": "Đã xảy ra lỗi. Vui lòng thử lại.",
+ "humanInputV2.uploadFailed": "Không thể tải tệp lên. Vui lòng thử lại.",
"login.backToHome": "Trở về Trang Chủ"
}
diff --git a/web/i18n/locales/vi-VN/workflow-human-input.json b/web/i18n/locales/vi-VN/workflow-human-input.json
index 34f2d1d1810..987e1f03a18 100644
--- a/web/i18n/locales/vi-VN/workflow-human-input.json
+++ b/web/i18n/locales/vi-VN/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "Giá trị Hành động",
"nodes.humanInput.userActions.buttonTextTooLong": "Văn bản nút phải có {{maxLength}} ký tự trở xuống",
"nodes.humanInput.userActions.chooseStyle": "Chọn kiểu nút",
+ "nodes.humanInput.userActions.defaultTitle": "Văn bản nút {{index}}",
"nodes.humanInput.userActions.emptyTip": "Nhấp vào nút '+' để thêm hành động người dùng",
"nodes.humanInput.userActions.title": "Hành động Người dùng",
"nodes.humanInput.userActions.tooltip": "Xác định các nút mà người dùng có thể nhấp để phản hồi biểu mẫu này. ID hành động kiểm soát việc phân nhánh. Giá trị Hành động được hiển thị ở phía sau như là đầu ra tích hợp được chọn. ID hành động phải bắt đầu bằng chữ cái hoặc dấu gạch dưới, theo sau là chữ cái, số hoặc dấu gạch dưới.",
diff --git a/web/i18n/locales/vi-VN/workflow.json b/web/i18n/locales/vi-VN/workflow.json
index 416d72daca6..321730e0ef1 100644
--- a/web/i18n/locales/vi-VN/workflow.json
+++ b/web/i18n/locales/vi-VN/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "Đầu ra",
"blocks.http-request": "Yêu cầu HTTP",
"blocks.human-input": "Đầu vào của con người",
+ "blocks.human-input-v2": "Đầu vào của con người v2",
"blocks.if-else": "NẾU/NGƯỢC LẠI",
"blocks.iteration": "Lặp",
"blocks.iteration-start": "Bắt đầu lặp",
@@ -45,6 +46,7 @@
"blocksAbout.end": "Định nghĩa đầu ra và loại kết quả của quy trình làm việc",
"blocksAbout.http-request": "Cho phép gửi các yêu cầu máy chủ qua giao thức HTTP",
"blocksAbout.human-input": "Yêu cầu con người xác nhận trước khi tạo bước tiếp theo",
+ "blocksAbout.human-input-v2": "Yêu cầu đầu vào từ các liên hệ, người nhận email đã cấu hình hoặc người khởi tạo quy trình",
"blocksAbout.if-else": "Cho phép phân chia quy trình làm việc thành hai nhánh dựa trên điều kiện if/else",
"blocksAbout.iteration": "Thực hiện nhiều bước trên một đối tượng danh sách cho đến khi tất cả các kết quả được xuất ra.",
"blocksAbout.iteration-start": "Nút bắt đầu vòng lặp",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "Tổng hợp các biến từ nhiều nhánh thành một biến duy nhất để cấu hình đồng nhất các nút cuối.",
"blocksAbout.variable-assigner": "Tổng hợp các biến từ nhiều nhánh thành một biến duy nhất để cấu hình đồng nhất các nút cuối.",
"changeHistory.edgeDelete": "Nút đã bị ngắt kết nối",
+ "changeHistory.humanInputMigration": "Đã di chuyển các nút Đầu vào của con người",
"changeHistory.nodeAdd": "Đã thêm nút",
"changeHistory.nodeChange": "Node đã thay đổi",
"changeHistory.nodeConnect": "Nút đã kết nối",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "Vui lòng bật ít nhất một phương thức giao hàng",
"nodes.humanInput.errorMsg.noUserActions": "Vui lòng thêm ít nhất một hành động người dùng",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} được dành riêng cho nhánh hết thời gian. Hãy chọn ID hành động khác.",
+ "nodes.humanInput.output.actionId": "ID của hành động do người dùng kích hoạt",
+ "nodes.humanInput.output.actionValue": "Giá trị của hành động đã chọn",
+ "nodes.humanInput.output.formInput": "Giá trị nhập trong biểu mẫu",
+ "nodes.humanInput.output.renderedContent": "Nội dung đã hiển thị",
"nodes.humanInput.timeout.title": "Hết thời gian",
+ "nodes.humanInputMigration.action.migrate": "Di chuyển",
+ "nodes.humanInputMigration.action.migrateNow": "Di chuyển ngay",
+ "nodes.humanInputMigration.action.migrating": "Đang di chuyển...",
+ "nodes.humanInputMigration.banner.ariaLabel": "Thông báo di chuyển Đầu vào của con người",
+ "nodes.humanInputMigration.banner.description": "Quy trình này đang dùng nút Đầu vào của con người cũ. Hãy di chuyển tất cả các nút cũ trước khi thêm nút mới.",
+ "nodes.humanInputMigration.banner.learnMore": "Tìm hiểu thêm",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "một phương thức gửi đã tắt vẫn còn cấu hình",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "các phương thức email đang bật dùng mẫu xung đột nhau",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "Giá trị mặc định không hợp lệ",
+ "nodes.humanInputMigration.blocker.invalidEmail": "email của một người nhận không hợp lệ",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "cấu hình của một phương thức email đang bật chưa hoàn chỉnh",
+ "nodes.humanInputMigration.blocker.missingRecipients": "nút không có người nhận được hỗ trợ",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "không thể xác định liên hệ hoặc email đã xác minh của một thành viên không gian làm việc",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "Đầu vào của con người v2 không hỗ trợ một phương thức gửi đang bật",
"nodes.humanInputMigration.blocker.unsupportedInputType": "Chưa thể di chuyển trường {{field}}. Bạn có thể tiếp tục sử dụng các nút đầu vào con người phiên bản cũ.",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "nút có giá trị phiên bản không được hỗ trợ",
+ "nodes.humanInputMigration.dialog.description": "Người nhận, biểu mẫu và hành động của bạn sẽ được giữ lại.",
+ "nodes.humanInputMigration.dialog.draftNotice": "Chỉ bản nháp này thay đổi. Các phiên bản đã xuất bản tiếp tục chạy cho đến khi bạn xuất bản lại.",
+ "nodes.humanInputMigration.dialog.review": "Xem lại các nút và xuất bản khi sẵn sàng.",
+ "nodes.humanInputMigration.dialog.title": "Di chuyển {{count}} nút Đầu vào của con người",
+ "nodes.humanInputMigration.disabledBadge": "CẦN DI CHUYỂN",
+ "nodes.humanInputMigration.disabledReason": "Di chuyển các nút Đầu vào của con người cũ trước khi thêm nút mới.",
+ "nodes.humanInputMigration.error.blocked": "Không thể di chuyển {{nodeTitle}}: {{reason}}.",
"nodes.humanInputMigration.error.graphChanged": "Quy trình đã thay đổi trong khi di chuyển. Hãy thử lại; các chỉnh sửa hiện tại đã được giữ lại.",
+ "nodes.humanInputMigration.error.preflight": "Không thể chuẩn bị di chuyển. Quy trình của bạn chưa bị thay đổi. Vui lòng thử lại.",
"nodes.humanInputMigration.error.sync": "Không thể lưu quy trình đã di chuyển. Hãy kiểm tra bản nháp hiện tại và thử lại.",
+ "nodes.humanInputMigration.incompatibleVersions": "Không thể dùng chung các nút Đầu vào của con người phiên bản cũ và mới trong cùng một quy trình.",
+ "nodes.humanInputMigration.oldVersion": "PHIÊN BẢN CŨ",
+ "nodes.humanInputMigration.preview.author": "Bởi đội ngũ Dify",
+ "nodes.humanInputMigration.preview.description": "Di chuyển các nút Đầu vào của con người cũ trước khi thêm nút mới.",
+ "nodes.humanInputMigration.success": "Đã di chuyển thành công các nút Đầu vào của con người",
+ "nodes.humanInputV2.card.configured": "Đã cấu hình {{count}} người nhận",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} liên hệ",
+ "nodes.humanInputV2.card.empty": "Chưa ai có thể phê duyệt bước này",
+ "nodes.humanInputV2.card.initiatorAndContacts": "Người khởi tạo và {{count}} liên hệ",
+ "nodes.humanInputV2.card.initiatorOnly": "Chỉ người khởi tạo",
+ "nodes.humanInputV2.card.invalid": "Cần kiểm tra cấu hình người nhận",
+ "nodes.humanInputV2.debug.channel.ding_talk": "DingTalk",
+ "nodes.humanInputV2.debug.channel.email": "Thư điện tử",
+ "nodes.humanInputV2.debug.channel.feishu": "Feishu",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "WeCom",
+ "nodes.humanInputV2.debug.configure": "Cấu hình chế độ gỡ lỗi",
"nodes.humanInputV2.debug.keepOneChannel": "Giữ ít nhất một kênh được bật",
+ "nodes.humanInputV2.debug.sendVia": "Gửi thông báo gỡ lỗi qua",
+ "nodes.humanInputV2.debug.title": "Chế độ gỡ lỗi",
+ "nodes.humanInputV2.debug.toggle": "Bật chế độ gỡ lỗi",
+ "nodes.humanInputV2.debug.unsupported": "Các kênh đã nhập không được hỗ trợ: {{channels}}. Hãy xóa hoặc cập nhật chúng trước khi chạy quy trình này.",
"nodes.humanInputV2.disabled": "Human Input v2 không khả dụng khi HITL IM bị tắt.",
+ "nodes.humanInputV2.error.bodyRequired": "Nội dung tin nhắn là bắt buộc",
+ "nodes.humanInputV2.error.debugChannelRequired": "Chọn ít nhất một kênh cho chế độ gỡ lỗi",
+ "nodes.humanInputV2.error.recipientDuplicate": "Xóa những người nhận trùng lặp",
+ "nodes.humanInputV2.error.recipientInvalid": "Sửa cấu hình người nhận không hợp lệ",
+ "nodes.humanInputV2.error.recipientRequired": "Thêm ít nhất một người nhận",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "Không thể xác minh người nhận từ danh bạ",
"nodes.humanInputV2.error.requestURLDuplicate": "Nội dung tin nhắn chỉ được chứa một URL yêu cầu.",
"nodes.humanInputV2.error.requestURLRequired": "Chèn URL yêu cầu vào nội dung tin nhắn.",
+ "nodes.humanInputV2.error.subjectRequired": "Tiêu đề tin nhắn là bắt buộc",
+ "nodes.humanInputV2.error.version": "Đầu vào của con người v2 yêu cầu giá trị phiên bản 2 ở dạng chuỗi",
+ "nodes.humanInputV2.recipients.addContact": "Thêm liên hệ",
+ "nodes.humanInputV2.recipients.addEmail": "Thêm",
+ "nodes.humanInputV2.recipients.addRecipient": "Thêm người nhận",
+ "nodes.humanInputV2.recipients.added": "Đã thêm",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "Tất cả liên hệ trong không gian làm việc",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "Gửi thông báo đến tất cả liên hệ trong không gian làm việc; bất kỳ ai trong số họ đều có thể phê duyệt",
+ "nodes.humanInputV2.recipients.cancel": "Hủy",
+ "nodes.humanInputV2.recipients.chooseVariable": "Chọn biến",
+ "nodes.humanInputV2.recipients.confirm": "Xác nhận",
+ "nodes.humanInputV2.recipients.contactInfo": "Chi tiết liên hệ của {{name}}",
+ "nodes.humanInputV2.recipients.contactSource.all": "Tất cả",
+ "nodes.humanInputV2.recipients.contactSource.external": "Bên ngoài",
+ "nodes.humanInputV2.recipients.contactSource.organization": "Tổ chức",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "Không gian làm việc",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "Nguồn liên hệ",
"nodes.humanInputV2.recipients.duplicateSource": "Đã được thêm qua {{name}} ({{source}}).",
+ "nodes.humanInputV2.recipients.edit": "Chỉnh sửa {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "Chỉnh sửa người nhận",
"nodes.humanInputV2.recipients.emailAlreadySelected": "Mỗi email chỉ có thể được chọn một lần.",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "Nhập một địa chỉ email hợp lệ chưa được thêm",
+ "nodes.humanInputV2.recipients.emailLabel": "Người nhận email một lần",
+ "nodes.humanInputV2.recipients.empty": "Chưa cấu hình người nhận",
+ "nodes.humanInputV2.recipients.help": "Chọn người có thể phản hồi ở bước Đầu vào của con người này.",
"nodes.humanInputV2.recipients.initiator": "Người dùng bắt đầu lần chạy này qua Web App hoặc CLI có thể phê duyệt",
+ "nodes.humanInputV2.recipients.initiatorDescription": "Người bắt đầu lần chạy quy trình này có thể phản hồi.",
"nodes.humanInputV2.recipients.inputHelp": "Nhập hoặc dán nhiều email, phân tách bằng dấu phẩy. Nhấn / để chèn biến.",
+ "nodes.humanInputV2.recipients.insertVariable": "Chèn biến",
+ "nodes.humanInputV2.recipients.loadError": "Không thể tải các liên hệ. ID liên hệ đã lưu vẫn được giữ lại.",
+ "nodes.humanInputV2.recipients.loading": "Đang tải liên hệ…",
+ "nodes.humanInputV2.recipients.noResults": "Không tìm thấy liên hệ",
+ "nodes.humanInputV2.recipients.placeholder": "Tìm liên hệ hoặc thêm địa chỉ email",
+ "nodes.humanInputV2.recipients.remove": "Xóa {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "Nhấn Backspace hoặc Delete để xóa.",
+ "nodes.humanInputV2.recipients.resultCount": "{{count}} người nhận phù hợp",
+ "nodes.humanInputV2.recipients.search": "Tìm liên hệ",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "Tìm theo tên hoặc email",
+ "nodes.humanInputV2.recipients.selectionHint": "Đã chọn {{count}} người nhận. Ở đầu ô nhập, nhấn mũi tên trái để chuyển tiêu điểm đến người nhận.",
+ "nodes.humanInputV2.recipients.title": "Người nhận",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "Tất cả liên hệ trong không gian làm việc",
+ "nodes.humanInputV2.recipients.type.contact": "Liên hệ",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "Email động",
+ "nodes.humanInputV2.recipients.type.initiator": "Người khởi tạo",
+ "nodes.humanInputV2.recipients.type.onetime_email": "Email một lần",
+ "nodes.humanInputV2.recipients.typeLabel": "Loại người nhận",
"nodes.humanInputV2.recipients.useThisInstead": "Dùng mục này thay thế",
+ "nodes.humanInputV2.recipients.variableRequired": "Chọn một biến email",
+ "nodes.humanInputV2.template.body": "Nội dung",
+ "nodes.humanInputV2.template.description": "Nội dung dự phòng cho email và tin nhắn tức thời",
"nodes.humanInputV2.template.insertRequestURL": "Chèn URL yêu cầu",
+ "nodes.humanInputV2.template.insertVariable": "Chèn biến",
+ "nodes.humanInputV2.template.notConfigured": "Chưa cấu hình",
"nodes.humanInputV2.template.requestURLHint": "Người nhận dùng liên kết này để mở biểu mẫu phê duyệt. Nội dung phải có đúng một URL yêu cầu.",
"nodes.humanInputV2.template.requestURLInserted": "Đã chèn URL yêu cầu",
"nodes.humanInputV2.template.saveAndTest": "Lưu và kiểm tra",
+ "nodes.humanInputV2.template.subject": "Tiêu đề",
+ "nodes.humanInputV2.template.subjectPlaceholder": "Nhập tiêu đề tin nhắn",
"nodes.humanInputV2.template.test": "Kiểm tra tin nhắn",
"nodes.humanInputV2.template.testChannel": "Kênh thử nghiệm",
"nodes.humanInputV2.template.testCompleted": "Yêu cầu thử nghiệm đã hoàn tất. Hãy kiểm tra tin nhắn trên kênh đã chọn.",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "Nhập giá trị cho tất cả các biến thử nghiệm.",
"nodes.humanInputV2.template.testSaveFailed": "Không thể lưu bản nháp quy trình làm việc. Thử nghiệm chưa được gửi.",
"nodes.humanInputV2.template.testUnavailable": "Môi trường này chưa hỗ trợ kiểm tra mẫu tin nhắn.",
+ "nodes.humanInputV2.template.title": "Mẫu tin nhắn",
"nodes.ifElse.operator": "Toán tử",
"nodes.iteration.currentIteration": "Lặp hiện tại",
"nodes.iteration.deleteDesc": "Xóa nút lặp sẽ xóa tất cả các nút con",
diff --git a/web/i18n/locales/zh-Hans/contacts.json b/web/i18n/locales/zh-Hans/contacts.json
index b45498b40f9..10d3409a87d 100644
--- a/web/i18n/locales/zh-Hans/contacts.json
+++ b/web/i18n/locales/zh-Hans/contacts.json
@@ -42,7 +42,6 @@
"directory.externalEmptyDescription": "外部联系人是组织之外的人员,例如客户、合作伙伴或供应商,只能通过 Email 触达。",
"directory.externalEmptyTitle": "添加第一个外部联系人",
"directory.filters": "联系人类型筛选",
- "directory.learnMore": "了解联系人",
"directory.loading": "正在加载联系人",
"directory.noAccessDescription": "仅工作区所有者和管理员可以浏览完整联系人目录。",
"directory.noAccessTitle": "你没有联系人目录的访问权限",
@@ -50,10 +49,14 @@
"directory.noResultsTitle": "没有匹配的联系人",
"directory.openDetails": "打开 {{name}} 的联系人详情",
"directory.pageError": "无法加载更多联系人,请重试当前页。",
+ "directory.removalCountTitle": "移除联系人({{count}})?",
"directory.removalDescription": "所选联系人将从此工作区永久移除,此操作无法撤销。",
"directory.removalFailed": "无法移除所选联系人,当前选择已保留。",
- "directory.removalTitle": "移除联系人?",
+ "directory.removalSingleDescription": "{{name}} 将被永久移出此工作区,此操作无法撤销。",
+ "directory.removalSingleFailed": "无法移除此联系人,请重试。",
+ "directory.removalSingleTitle": "移除 {{name}}?",
"directory.removeSelected": "移除",
+ "directory.resultCount": "结果:{{count}}",
"directory.search": "搜索名称或 Email",
"directory.selectAll": "选择所有可移除联系人",
"directory.selectContact": "选择 {{name}}",
@@ -62,7 +65,6 @@
"directory.viewOnly": "你可以浏览联系人,但仅工作区所有者和管理员可以管理联系人。",
"external.add": "添加",
"external.adding": "正在添加",
- "external.avatarFallback": "外部联系人",
"external.description": "创建仅属于当前工作区、通过 Email 触达的联系人。",
"external.editDescription": "更新该外部联系人的姓名和 Email 地址。",
"external.editTitle": "编辑外部联系人",
@@ -71,8 +73,6 @@
"external.namePlaceholder": "姓名",
"external.result.duplicate_external_contact": "已存在使用此 Email 的外部联系人。",
"external.result.failed": "无法添加联系人,已保留填写内容,请重试。",
- "external.result.matches_platform_contact": "此 Email 属于 Platform contact,请改为从企业平台添加。",
- "external.result.matches_workspace_contact": "该用户已经是工作区联系人。",
"external.save": "保存",
"external.saving": "保存中",
"external.title": "添加外部联系人",
@@ -119,15 +119,12 @@
"imBinding.select": "选择 IM 联系人",
"imBinding.title": "绑定 IM 身份",
"imBinding.workspaceMode": "当前工作区自定义",
- "imPlatform.action.authorize": "授权",
- "imPlatform.action.authorizing": "正在授权",
"imPlatform.action.configure": "配置",
"imPlatform.action.configureChannel": "配置 {{provider}}",
"imPlatform.action.connect": "连接",
"imPlatform.action.copied": "已复制",
"imPlatform.action.copyCallback": "复制回调 URL",
"imPlatform.action.deleteChannel": "删除 {{provider}}",
- "imPlatform.action.disconnect": "断开连接",
"imPlatform.action.loadMore": "加载更多",
"imPlatform.action.replace": "替换",
"imPlatform.action.retry": "重试",
@@ -139,7 +136,6 @@
"imPlatform.action.testConnection": "测试连接",
"imPlatform.action.testing": "正在测试",
"imPlatform.action.viewDetails": "查看详情",
- "imPlatform.bindingDialog.authorizationFailed": "授权未完成,请重试。",
"imPlatform.bindingDialog.back": "返回",
"imPlatform.bindingDialog.callback": "回调 URL",
"imPlatform.bindingDialog.callbackDescription": "在 {{provider}} 中完成回调配置,以启用卡片操作。",
@@ -151,7 +147,6 @@
"imPlatform.bindingDialog.callbackInstruction.slack.path": "Interactivity & Shortcuts → Interactivity → Request URL",
"imPlatform.bindingDialog.callbackInstruction.teams.destination": "要启用卡片操作,请将此 URL 粘贴到 <console>Azure Bot 配置</console>:",
"imPlatform.bindingDialog.callbackInstruction.teams.path": "Settings → Configuration → Messaging endpoint",
- "imPlatform.bindingDialog.callbackPurpose": "此 URL 用于接收 {{provider}} 审批卡片的交互回调,请完整使用当前渠道显示的地址。",
"imPlatform.bindingDialog.callbackStep": "配置回调",
"imPlatform.bindingDialog.clearSavedCredential": "清空已保存的值",
"imPlatform.bindingDialog.configureTitle": "配置 {{provider}}",
@@ -179,15 +174,14 @@
"imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "如已配置,请输入 Verification Token",
"imPlatform.bindingDialog.finish": "完成",
"imPlatform.bindingDialog.freshCredentials": "无法读取已保存的密钥。测试或保存配置前,请重新填写所有必填凭证。",
- "imPlatform.bindingDialog.openProviderConsole": "打开 {{provider}} 开发者后台",
"imPlatform.bindingDialog.openSetupGuide": "打开设置指南",
+ "imPlatform.bindingDialog.replaceTenantTitle": "替换 {{identity}} 的租户凭据?",
"imPlatform.bindingDialog.replacementRequired": "此凭据属于另一个 IM 租户,不能直接保存。切换租户需要替换当前 IM 渠道,将清除所有自动和手动 IM 绑定;替换后请重新同步联系人。",
"imPlatform.bindingDialog.required": "此字段为必填项。",
"imPlatform.bindingDialog.saveAndContinue": "保存并继续",
"imPlatform.bindingDialog.saveFailed": "无法保存配置,请检查字段后重试。",
"imPlatform.bindingDialog.savedDetailsUnavailable": "配置已保存,但暂时无法读取详情。请关闭弹窗后重新打开。",
"imPlatform.bindingDialog.secretConfigured": "已配置密钥,留空可保留现有值。",
- "imPlatform.bindingDialog.secretPlaceholder": "输入新的 App Secret",
"imPlatform.bindingDialog.step": "第 {{step}} 步",
"imPlatform.bindingDialog.testFailed": "连接测试失败,请检查配置后重试。",
"imPlatform.bindingDialog.undoClearCredential": "撤销清空",
@@ -208,37 +202,20 @@
"imPlatform.details.downloadingReport": "正在下载报告…",
"imPlatform.details.empty": "此分类下暂无结果。",
"imPlatform.details.filter.added": "新增",
- "imPlatform.details.filter.all": "全部",
- "imPlatform.details.filter.created_binding": "已创建绑定",
"imPlatform.details.filter.failed": "失败",
- "imPlatform.details.filter.matched": "已匹配",
"imPlatform.details.filter.not_matched": "未匹配",
"imPlatform.details.filter.removed": "已移除",
"imPlatform.details.filter.skipped": "已跳过",
- "imPlatform.details.filter.unmatched": "未匹配",
- "imPlatform.details.filter.updated_binding": "已更新绑定",
"imPlatform.details.filters": "同步结果筛选",
"imPlatform.details.latestMetadata": "{{status}} · {{date}}",
"imPlatform.details.loadError": "无法加载同步详情。",
- "imPlatform.details.loading": "正在加载同步详情",
- "imPlatform.details.metadata": "{{status}} · {{date}} · {{user}} 发起",
"imPlatform.details.missing": "—",
"imPlatform.details.pageError": "无法加载更多结果,请重试当前页。",
+ "imPlatform.details.removalReason.binding_invalidated": "绑定已失效",
+ "imPlatform.details.removalReason.binding_replaced": "绑定已替换",
+ "imPlatform.details.removalReason.not_present_in_directory": "已不在通讯录中",
"imPlatform.details.reportChanged": "同步结果已变更,请重新打开最新同步详情后重试。",
- "imPlatform.details.safeReason.contact_update_failed": "无法更新联系人绑定。",
- "imPlatform.details.safeReason.duplicate_identity": "已跳过重复的 IM 平台身份。",
- "imPlatform.details.safeReason.missing_email": "该平台成员没有邮箱地址。",
- "imPlatform.details.safeReason.no_matching_contact": "没有与该平台成员匹配的现有联系人。",
- "imPlatform.details.safeReason.provider_request_failed": "IM 平台请求失败,未暴露任何凭据。",
"imPlatform.details.title": "同步详情",
- "imPlatform.diagnostics.configured": "配置已保存,请在同步联系人前测试连接。",
- "imPlatform.diagnostics.connected": "已可读取通讯录。",
- "imPlatform.diagnostics.notConfigured": "请选择一个 IM 平台开始绑定。",
- "imPlatform.diagnostics.title": "连接诊断",
- "imPlatform.disconnect.confirm": "断开",
- "imPlatform.disconnect.description": "通讯录同步将停止,并移除当前绑定。",
- "imPlatform.disconnect.failed": "无法断开 IM 平台连接,请重试。",
- "imPlatform.disconnect.title": "断开与 {{provider}} 的连接?",
"imPlatform.email.apiKey": "API Key",
"imPlatform.email.apiKeyConfigured": "出于安全原因,已保存的 API Key 无法查看。留空可保留现有值。",
"imPlatform.email.apiKeyDescription": "出于安全原因,API Key 保存后将无法查看。",
@@ -252,51 +229,27 @@
"imPlatform.email.senderEmailDescription": "收件人看到的发件地址,其域名必须已在 Resend 中验证。",
"imPlatform.email.senderName": "发件人名称",
"imPlatform.email.senderNameDescription": "收件箱中显示的发件人名称。",
- "imPlatform.email.summary": "Resend · {{email}}",
"imPlatform.email.testSucceeded": "连接测试成功。",
"imPlatform.email.title": "配置 Email",
- "imPlatform.lastChecked": "上次检查于 {{date}}",
"imPlatform.learnMore": "了解更多",
"imPlatform.loadError.description": "请重试以读取当前绑定和权限。",
"imPlatform.loadError.retry": "重试",
"imPlatform.loadError.title": "无法加载渠道",
"imPlatform.loading": "正在加载渠道",
- "imPlatform.notChecked": "尚未检查连接。",
- "imPlatform.permission.description": "仅工作区所有者和管理员可以管理渠道和通讯录同步。",
- "imPlatform.permission.title": "仅查看",
"imPlatform.provider.dingtalkDescription": "连接 DingTalk 应用。",
"imPlatform.provider.emailDescription": "配置当前工作区用于发送审批请求的 Email 服务。",
"imPlatform.provider.feishuDescription": "连接 Feishu 应用。",
"imPlatform.provider.larkDescription": "连接 Lark 应用。",
"imPlatform.provider.msTeamsDescription": "连接 Microsoft Teams 应用。",
"imPlatform.provider.slackDescription": "同步联系人及其 Slack 身份。",
- "imPlatform.provider.unavailable": "不可用",
- "imPlatform.provider.unavailableReason.deployment_unsupported": "当前部署不支持此 IM 平台。",
- "imPlatform.provider.unavailableReason.not_released": "此 IM 平台尚未开放。",
"imPlatform.provider.weComDescription": "连接企业微信应用。",
"imPlatform.replacement.confirm": "替换",
"imPlatform.replacement.description": "替换当前 IM 平台后,旧平台的 IM 绑定和工作区覆盖配置将失效。替换后需要重新同步新平台的通讯录。",
"imPlatform.replacement.title": "将 {{current}} 替换为 {{next}}?",
- "imPlatform.status.callback_error": "回调错误",
"imPlatform.status.configured": "已配置",
"imPlatform.status.connected": "已连接",
"imPlatform.status.connection_error": "连接错误",
- "imPlatform.status.not_configured": "未配置",
"imPlatform.status.permission_issue": "权限问题",
- "imPlatform.statusReason.callback_mismatch": "IM 平台回调 URL 与此工作区不匹配。",
- "imPlatform.statusReason.missing_directory_permission": "IM 平台应用缺少通讯录读取权限。",
- "imPlatform.statusReason.provider_request_failed": "无法连接 IM 平台,未暴露任何凭据。",
- "imPlatform.sync.count.added": "新增",
- "imPlatform.sync.count.created_binding": "已创建绑定",
- "imPlatform.sync.count.failed": "失败",
- "imPlatform.sync.count.matched": "已匹配",
- "imPlatform.sync.count.not_matched": "未匹配",
- "imPlatform.sync.count.removed": "已移除",
- "imPlatform.sync.count.skipped": "已跳过",
- "imPlatform.sync.count.unmatched": "未匹配",
- "imPlatform.sync.count.updated_binding": "已更新绑定",
- "imPlatform.sync.description": "通讯录同步需手动发起,并从已连接的 IM 平台读取成员以匹配联系人。",
- "imPlatform.sync.lastSynced": "上次同步于 {{date}},发起人:{{user}}",
"imPlatform.sync.latestSynced": "上次同步于 {{date}}",
"imPlatform.sync.loading": "正在检查进行中的同步。",
"imPlatform.sync.noPermission": "仅工作区所有者和管理员可以发起通讯录同步。",
@@ -304,27 +257,13 @@
"imPlatform.sync.notConnected": "请先连接并测试 IM 平台,再开始通讯录同步。",
"imPlatform.sync.startFailed": "无法启动或刷新通讯录同步,请重试。",
"imPlatform.sync.status.failure": "失败",
- "imPlatform.sync.status.partial_success": "部分成功",
"imPlatform.sync.status.queued": "已排队",
"imPlatform.sync.status.running": "进行中",
"imPlatform.sync.status.success": "成功",
- "imPlatform.sync.title": "通讯录同步",
- "imPlatform.sync.unsupported": "此 IM 平台不支持通讯录同步。",
"imPlatform.title": "渠道",
- "memberInviteUpgrade.confirm": "添加并升级",
- "memberInviteUpgrade.description_one": "此 Email 已被一个外部联系人使用。添加该成员会将联系人转换为工作区联系人,并保留现有工作流引用和历史记录。",
- "memberInviteUpgrade.description_other": "已有 {{count}} 个 Email 被外部联系人使用。添加这些成员会将联系人转换为工作区联系人,并保留现有工作流引用和历史记录。",
- "memberInviteUpgrade.title_one": "Email 已存在于联系人目录中",
- "memberInviteUpgrade.title_other": "多个 Email 已存在于联系人目录中",
"memberRemoval.accessImpact": "{{memberName}} 将立即失去此工作区的访问权限。",
"memberRemoval.contentImpact": "其创建的应用和知识库会保留在此工作区。此操作无法撤销。",
- "memberRemoval.eeDescription": "移除后该成员将失去工作区访问权限。请选择是否将同一联系人保留为 Platform contact。",
- "memberRemoval.failed": "无法移除成员,当前数据未发生变化,请重试。",
- "memberRemoval.keepPlatform": "保留为 Platform contact",
- "memberRemoval.keepPlatformDescription": "移除工作区访问权限后,继续在联系人目录中保留该身份。",
"memberRemoval.remove": "移除",
- "memberRemoval.removing": "正在移除",
- "memberRemoval.standardDescription": "移除此成员也会从当前联系人目录中移除对应的工作区联系人。",
"memberRemoval.title": "从工作区移除 {{memberName}}?",
"memberRemoval.workspaceTitle": "将 {{memberName}} 从 {{workspaceName}} 移除?",
"platformPicker.add": "添加联系人",
@@ -333,25 +272,14 @@
"platformPicker.addForbidden": "仅企业版工作空间管理员可添加平台联系人。",
"platformPicker.adding": "正在添加",
"platformPicker.allMembers": "所有成员",
- "platformPicker.backendTeam": "后端团队",
"platformPicker.description": "选择尚未加入当前工作区联系人目录的企业平台联系人。",
- "platformPicker.devTeam": "研发团队",
"platformPicker.empty": "没有符合搜索条件且可添加的 Platform contact。",
"platformPicker.error": "无法加载 Platform contact。",
- "platformPicker.externalUpgradeUnsupported": "此操作不支持升级外部联系人,未执行升级。",
- "platformPicker.frontendTeam": "前端团队",
"platformPicker.loading": "正在加载 Platform contact",
- "platformPicker.mobileDev": "移动端研发",
- "platformPicker.noExternalUpgrade": "平台联系人将独立添加,同邮箱的外部联系人及其已有工作流引用保持不变。",
"platformPicker.search": "搜索 Platform contact",
"platformPicker.selectContact": "选择 {{name}}",
"platformPicker.selected": "已选择 {{count}} 人",
"platformPicker.title": "从企业平台添加",
- "platformPicker.upgrade.confirm": "添加并升级",
- "platformPicker.upgrade.description_one": "此 Email 已被一个外部联系人使用。添加该 Platform contact 会升级现有联系人,并保留现有工作流引用和历史记录。",
- "platformPicker.upgrade.description_other": "已有 {{count}} 个 Email 被外部联系人使用。添加这些 Platform contact 会升级现有联系人,并保留现有工作流引用和历史记录。",
- "platformPicker.upgrade.title_one": "联系人已存在",
- "platformPicker.upgrade.title_other": "多个联系人已存在",
"type.external": "外部",
"type.platform": "企业平台",
"type.workspace": "工作区"
diff --git a/web/i18n/locales/zh-Hans/share.json b/web/i18n/locales/zh-Hans/share.json
index dc099800caf..11e56e45b33 100644
--- a/web/i18n/locales/zh-Hans/share.json
+++ b/web/i18n/locales/zh-Hans/share.json
@@ -79,7 +79,6 @@
"humanInputV2.otpPlaceholder": "输入 6 位验证码",
"humanInputV2.requestingCode": "正在发送验证码…",
"humanInputV2.resendCode": "重新发送",
- "humanInputV2.resendIn": "{{seconds}} 秒后可重新发送",
"humanInputV2.retry": "重试",
"humanInputV2.sendCode": "发送新验证码",
"humanInputV2.unavailable": "此表单暂时不可用。",
diff --git a/web/i18n/locales/zh-Hans/workflow.json b/web/i18n/locales/zh-Hans/workflow.json
index 54b8fed9475..41611157ccf 100644
--- a/web/i18n/locales/zh-Hans/workflow.json
+++ b/web/i18n/locales/zh-Hans/workflow.json
@@ -395,6 +395,7 @@
"nodes.humanInputMigration.error.graphChanged": "迁移期间工作流已更新,请重试。当前编辑已保留。",
"nodes.humanInputMigration.error.preflight": "无法准备迁移。工作流未发生变化,请重试。",
"nodes.humanInputMigration.error.sync": "无法保存迁移后的工作流。请检查当前草稿后重试。",
+ "nodes.humanInputMigration.incompatibleVersions": "同一个工作流中不能混用旧版和新版人工介入节点。",
"nodes.humanInputMigration.oldVersion": "旧版本",
"nodes.humanInputMigration.preview.author": "由 Dify 团队提供",
"nodes.humanInputMigration.preview.description": "请先迁移旧版人工介入节点,再添加新节点。",
@@ -424,6 +425,7 @@
"nodes.humanInputV2.error.recipientDuplicate": "请移除重复的收件人",
"nodes.humanInputV2.error.recipientInvalid": "请修复无效的收件人配置",
"nodes.humanInputV2.error.recipientRequired": "请至少添加一个收件人",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "无法验证联系人收件人",
"nodes.humanInputV2.error.requestURLDuplicate": "正文只能包含一个请求 URL。",
"nodes.humanInputV2.error.requestURLRequired": "请在正文中插入请求 URL。",
"nodes.humanInputV2.error.subjectRequired": "消息主题不能为空",
@@ -437,6 +439,7 @@
"nodes.humanInputV2.recipients.cancel": "取消",
"nodes.humanInputV2.recipients.chooseVariable": "选择变量",
"nodes.humanInputV2.recipients.confirm": "确认",
+ "nodes.humanInputV2.recipients.contactInfo": "查看 {{name}} 的联系人详情",
"nodes.humanInputV2.recipients.contactSource.all": "全部",
"nodes.humanInputV2.recipients.contactSource.external": "外部联系人",
"nodes.humanInputV2.recipients.contactSource.organization": "组织",
@@ -459,8 +462,11 @@
"nodes.humanInputV2.recipients.noResults": "未找到联系人",
"nodes.humanInputV2.recipients.placeholder": "搜索联系人或添加邮箱",
"nodes.humanInputV2.recipients.remove": "移除 {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "按 Backspace 或 Delete 删除。",
+ "nodes.humanInputV2.recipients.resultCount": "找到 {{count}} 个匹配的收件人",
"nodes.humanInputV2.recipients.search": "搜索联系人",
"nodes.humanInputV2.recipients.searchPlaceholder": "按姓名或邮箱搜索",
+ "nodes.humanInputV2.recipients.selectionHint": "已选择 {{count}} 个收件人。在输入框开头按左方向键可选中收件人。",
"nodes.humanInputV2.recipients.title": "收件人",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "工作区全部联系人",
"nodes.humanInputV2.recipients.type.contact": "联系人",
diff --git a/web/i18n/locales/zh-Hant/contacts.json b/web/i18n/locales/zh-Hant/contacts.json
index d868107d57d..71717cf2f06 100644
--- a/web/i18n/locales/zh-Hant/contacts.json
+++ b/web/i18n/locales/zh-Hant/contacts.json
@@ -1,9 +1,150 @@
{
+ "directory.removalCountTitle": "移除聯絡人({{count}})?",
"directory.removalDescription": "所選聯絡人將從此工作區永久移除,此操作無法復原。",
- "directory.removalTitle": "移除聯絡人?",
+ "directory.removalSingleDescription": "{{name}} 將被永久移出此工作區,此操作無法復原。",
+ "directory.removalSingleFailed": "無法移除此聯絡人,請重試。",
+ "directory.removalSingleTitle": "移除 {{name}}?",
+ "directory.resultCount": "結果:{{count}}",
+ "imPlatform.action.configure": "配置",
+ "imPlatform.action.configureChannel": "配置{{provider}}",
+ "imPlatform.action.connect": "繫結",
+ "imPlatform.action.copied": "複製",
+ "imPlatform.action.copyCallback": "複製回呼 URL",
+ "imPlatform.action.deleteChannel": "刪除 {{provider}}",
+ "imPlatform.action.loadMore": "載入更多",
+ "imPlatform.action.replace": "代替",
+ "imPlatform.action.retry": "重試",
+ "imPlatform.action.save": "保存",
+ "imPlatform.action.saving": "儲存中",
+ "imPlatform.action.setupGuide": "設定指南",
+ "imPlatform.action.syncNow": "立即同步",
+ "imPlatform.action.syncing": "正在同步",
+ "imPlatform.action.testConnection": "測試連線",
+ "imPlatform.action.testing": "測試中",
+ "imPlatform.action.viewDetails": "查看詳情",
+ "imPlatform.bindingDialog.back": "返回",
+ "imPlatform.bindingDialog.callback": "回呼網址",
+ "imPlatform.bindingDialog.callbackDescription": "在 {{provider}} 完成回呼設定,以啟用卡片操作。",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.destination": "若要使用卡片操作,請將此 URL 貼到 <console>飛書開發者主控台</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.feishu.path": "事件與回呼 → 回呼設定 → 請求網址",
+ "imPlatform.bindingDialog.callbackInstruction.lark.destination": "若要使用卡片操作,請將此 URL 貼到 <console>Lark 開發者主控台</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.lark.path": "事件與回呼 → 回呼設定 → 請求網址",
+ "imPlatform.bindingDialog.callbackInstruction.slack.destination": "若要使用卡片操作,請將此 URL 貼到 <console>Slack 開發者主控台</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.slack.path": "互動與捷徑 → 互動 → 請求網址",
+ "imPlatform.bindingDialog.callbackInstruction.teams.destination": "若要使用卡片操作,請將此 URL 貼到 <console>Azure Bot 設定</console>:",
+ "imPlatform.bindingDialog.callbackInstruction.teams.path": "設定 → 組態 → 訊息端點",
+ "imPlatform.bindingDialog.callbackStep": "設定回呼",
"imPlatform.bindingDialog.clearSavedCredential": "清除已儲存的值",
+ "imPlatform.bindingDialog.configureTitle": "配置{{provider}}",
+ "imPlatform.bindingDialog.connectTitle": "連接{{provider}}",
"imPlatform.bindingDialog.credentialWillBeCleared": "儲存時將清除此已儲存的值。",
+ "imPlatform.bindingDialog.credentialsDescription": "先連接你的 {{provider}} 應用程式,再設定其回呼 URL。",
+ "imPlatform.bindingDialog.credentialsStep": "應用程式憑證",
+ "imPlatform.bindingDialog.description": "輸入此即時通訊平台的應用程式憑證。",
+ "imPlatform.bindingDialog.field.agentId": "代理程式 ID",
+ "imPlatform.bindingDialog.field.appId": "應用程式 ID",
+ "imPlatform.bindingDialog.field.appToken": "應用程式權杖(選填)",
+ "imPlatform.bindingDialog.field.botToken": "機器人權杖",
+ "imPlatform.bindingDialog.field.clientId": "客戶編號",
+ "imPlatform.bindingDialog.field.clientSecret": "客戶端密鑰",
+ "imPlatform.bindingDialog.field.corpId": "企業 ID",
+ "imPlatform.bindingDialog.field.encryptKey": "加密金鑰(選填)",
+ "imPlatform.bindingDialog.field.genericSecret": "機密",
+ "imPlatform.bindingDialog.field.secret": "應用程式密鑰",
+ "imPlatform.bindingDialog.field.signingSecret": "簽署密鑰",
+ "imPlatform.bindingDialog.field.tenantId": "租戶 ID",
+ "imPlatform.bindingDialog.field.verificationToken": "驗證權杖(選填)",
+ "imPlatform.bindingDialog.fieldPlaceholder.appId": "cli_...",
+ "imPlatform.bindingDialog.fieldPlaceholder.encryptKey": "如已啟用,請輸入加密金鑰",
+ "imPlatform.bindingDialog.fieldPlaceholder.secret": "輸入應用程式密鑰",
+ "imPlatform.bindingDialog.fieldPlaceholder.verificationToken": "如已設定,請輸入驗證權杖",
+ "imPlatform.bindingDialog.finish": "完成",
+ "imPlatform.bindingDialog.freshCredentials": "無法取回已儲存的密鑰。請重新輸入所有必要憑證,以測試或儲存此設定。",
+ "imPlatform.bindingDialog.openSetupGuide": "開啟設定指南",
+ "imPlatform.bindingDialog.replaceTenantTitle": "替換 {{identity}} 的租戶憑證?",
"imPlatform.bindingDialog.replacementRequired": "此憑證屬於另一個 IM 租用戶,無法直接儲存。切換租用戶需要取代目前的 IM 頻道,這會清除所有自動和手動 IM 綁定;取代後請重新同步聯絡人。",
+ "imPlatform.bindingDialog.required": "此欄位為必填。",
+ "imPlatform.bindingDialog.saveAndContinue": "儲存並繼續",
+ "imPlatform.bindingDialog.saveFailed": "無法儲存設定,請檢查欄位後重試。",
"imPlatform.bindingDialog.savedDetailsUnavailable": "設定已儲存,但無法載入詳細資料。請關閉此對話方塊後重新開啟。",
- "imPlatform.bindingDialog.undoClearCredential": "復原清除"
+ "imPlatform.bindingDialog.secretConfigured": "已設定密鑰。將此欄位留空即可保留。",
+ "imPlatform.bindingDialog.step": "步驟 {{step}}",
+ "imPlatform.bindingDialog.testFailed": "連線測試失敗,請檢查設定後重試。",
+ "imPlatform.bindingDialog.undoClearCredential": "復原清除",
+ "imPlatform.bindingDialog.viewSetupGuide": "查看設定指南",
+ "imPlatform.chooseProvider": "選擇要連接的渠道",
+ "imPlatform.configurationUpdated": "此渠道設定已變更。請關閉此對話方塊並重新整理後重試。",
+ "imPlatform.connectMore": "連接更多渠道",
+ "imPlatform.delete.confirm": "刪除",
+ "imPlatform.delete.description": "刪除此渠道會移除其設定。所有使用此渠道的審批通知及通訊錄同步都會停止。",
+ "imPlatform.delete.failed": "無法刪除此渠道。未做任何變更,請重試。",
+ "imPlatform.delete.title": "刪除 {{provider}} 渠道?",
+ "imPlatform.description": "連接企業渠道,讓審批請求傳送至成員日常工作的地方。",
+ "imPlatform.details.column.contact": "聯絡人",
+ "imPlatform.details.column.platform": "即時通訊平台",
+ "imPlatform.details.description": "查看最近一次同步的唯讀結果。",
+ "imPlatform.details.downloadFailed": "無法下載報告,請重試。",
+ "imPlatform.details.downloadReport": "下載報告",
+ "imPlatform.details.downloadingReport": "正在下載報告…",
+ "imPlatform.details.empty": "此類別沒有結果。",
+ "imPlatform.details.filter.added": "已添加",
+ "imPlatform.details.filter.failed": "失敗",
+ "imPlatform.details.filter.not_matched": "未配對",
+ "imPlatform.details.filter.removed": "已移除",
+ "imPlatform.details.filter.skipped": "已略過",
+ "imPlatform.details.filters": "同步結果篩選",
+ "imPlatform.details.latestMetadata": "{{status}} · {{date}}",
+ "imPlatform.details.loadError": "無法載入同步詳情。",
+ "imPlatform.details.missing": "—",
+ "imPlatform.details.pageError": "無法載入更多結果,請重試此頁。",
+ "imPlatform.details.removalReason.binding_invalidated": "繫結已失效",
+ "imPlatform.details.removalReason.binding_replaced": "繫結已替換",
+ "imPlatform.details.removalReason.not_present_in_directory": "已不在通訊錄中",
+ "imPlatform.details.reportChanged": "同步結果已變更。請重新開啟最近一次同步的詳情後重試。",
+ "imPlatform.details.title": "同步詳情",
+ "imPlatform.email.apiKey": "API 金鑰",
+ "imPlatform.email.apiKeyConfigured": "基於安全考量,無法檢視已儲存的 API 金鑰。將此欄位留空即可保留。",
+ "imPlatform.email.apiKeyDescription": "基於安全考量,此 API 金鑰儲存後將無法檢視。",
+ "imPlatform.email.apiKeyPlaceholder": "輸入你的 Resend API 金鑰",
+ "imPlatform.email.description": "此設定適用於此工作區中已啟用<emphasis>透過電子郵件傳送偵錯通知</emphasis>的所有人工介入節點。",
+ "imPlatform.email.invalidEmail": "請輸入有效的電子郵件地址。",
+ "imPlatform.email.provider": "電子郵件服務供應商",
+ "imPlatform.email.resendDescription": "你的 <apiKey>Resend API 金鑰</apiKey>將被加密,儲存後將無法檢視。<br/>註冊 <resend>Resend</resend> 帳號。",
+ "imPlatform.email.resendSettings": "Resend 設定",
+ "imPlatform.email.senderEmail": "寄件者電子郵件地址",
+ "imPlatform.email.senderEmailDescription": "顯示為寄件者的電子郵件地址,其網域必須在 Resend 完成驗證。",
+ "imPlatform.email.senderName": "寄件者名稱",
+ "imPlatform.email.senderNameDescription": "顯示於收件者收件匣中的名稱。",
+ "imPlatform.email.testSucceeded": "連線測試成功。",
+ "imPlatform.email.title": "設定電子郵件",
+ "imPlatform.learnMore": "了解更多",
+ "imPlatform.loadError.description": "請重試以讀取目前的綁定和權限。",
+ "imPlatform.loadError.retry": "重試",
+ "imPlatform.loadError.title": "無法載入渠道",
+ "imPlatform.loading": "正在載入渠道",
+ "imPlatform.provider.dingtalkDescription": "連接釘釘應用程式。",
+ "imPlatform.provider.emailDescription": "設定用於傳送此工作區審批請求的電子郵件服務。",
+ "imPlatform.provider.feishuDescription": "連接飛書應用程式。",
+ "imPlatform.provider.larkDescription": "連接 Lark 應用程式。",
+ "imPlatform.provider.msTeamsDescription": "連接 Microsoft Teams 應用程式。",
+ "imPlatform.provider.slackDescription": "同步成員及其 Slack 身分。",
+ "imPlatform.provider.weComDescription": "連接企業微信應用程式。",
+ "imPlatform.replacement.confirm": "代替",
+ "imPlatform.replacement.description": "替換目前的平台會使其即時通訊綁定和工作區自訂綁定失效。替換後請重新同步新平台的通訊錄。",
+ "imPlatform.replacement.title": "將 {{current}} 替換為 {{next}}?",
+ "imPlatform.status.configured": "已配置",
+ "imPlatform.status.connected": "已繫結",
+ "imPlatform.status.connection_error": "連線錯誤",
+ "imPlatform.status.permission_issue": "權限問題",
+ "imPlatform.sync.latestSynced": "上次同步於 {{date}}",
+ "imPlatform.sync.loading": "正在檢查是否有進行中的同步。",
+ "imPlatform.sync.noPermission": "只有工作區擁有者和管理員可以啟動通訊錄同步。",
+ "imPlatform.sync.noRuns": "尚未執行任何通訊錄同步。",
+ "imPlatform.sync.notConnected": "開始通訊錄同步前,請先連接平台並測試連線。",
+ "imPlatform.sync.startFailed": "無法啟動或重新整理通訊錄同步,請重試。",
+ "imPlatform.sync.status.failure": "失敗",
+ "imPlatform.sync.status.queued": "排隊中",
+ "imPlatform.sync.status.running": "執行中",
+ "imPlatform.sync.status.success": "成功",
+ "imPlatform.title": "渠道"
}
diff --git a/web/i18n/locales/zh-Hant/share.json b/web/i18n/locales/zh-Hant/share.json
index c1d494273da..3bd41d2621b 100644
--- a/web/i18n/locales/zh-Hant/share.json
+++ b/web/i18n/locales/zh-Hant/share.json
@@ -62,5 +62,27 @@
"humanInput.thanks": "謝謝!",
"humanInput.unavailableDescription": "連結可能無法使用,或與你目前登入的帳戶不符。請從你收到的通知中開啟表單,或嘗試切換帳戶",
"humanInput.unavailableTitle": "無法開啟此表單",
+ "humanInputV2.accessRateLimited": "請求的驗證郵件過多,請稍後重試。",
+ "humanInputV2.alreadySubmitted": "此請求已完成。",
+ "humanInputV2.challengeExpired": "此驗證碼已過期,請索取新驗證碼以繼續。",
+ "humanInputV2.challengeStale": "此驗證碼已被取代,請索取新驗證碼以繼續。",
+ "humanInputV2.codeExpiresIn": "驗證碼將於 {{seconds}} 秒後過期",
+ "humanInputV2.codeRequired": "請索取驗證碼以繼續。",
+ "humanInputV2.codeSent": "驗證碼已發送至您的電子郵件信箱。",
+ "humanInputV2.deliveryFailed": "無法發送驗證郵件,請重試。",
+ "humanInputV2.formExpired": "此請求已過期。",
+ "humanInputV2.formNotFound": "找不到表單。",
+ "humanInputV2.formRateLimited": "表單請求過多,請稍後重試。",
+ "humanInputV2.invalidOtp": "驗證碼不正確,請檢查後重試。",
+ "humanInputV2.networkError": "無法完成請求,請檢查連線後重試。",
+ "humanInputV2.otpLabel": "電子郵件驗證碼",
+ "humanInputV2.otpPlaceholder": "輸入 6 位數驗證碼",
+ "humanInputV2.requestingCode": "正在發送驗證碼…",
+ "humanInputV2.resendCode": "重新發送驗證碼",
+ "humanInputV2.retry": "重試",
+ "humanInputV2.sendCode": "發送新驗證碼",
+ "humanInputV2.unavailable": "此表單暫時無法使用。",
+ "humanInputV2.unknownError": "發生錯誤,請重試。",
+ "humanInputV2.uploadFailed": "無法上傳檔案,請重試。",
"login.backToHome": "返回首頁"
}
diff --git a/web/i18n/locales/zh-Hant/workflow-human-input.json b/web/i18n/locales/zh-Hant/workflow-human-input.json
index 77242932dfd..bf4787579e4 100644
--- a/web/i18n/locales/zh-Hant/workflow-human-input.json
+++ b/web/i18n/locales/zh-Hant/workflow-human-input.json
@@ -94,6 +94,7 @@
"nodes.humanInput.userActions.buttonTextPlaceholder": "操作值",
"nodes.humanInput.userActions.buttonTextTooLong": "按鈕文本不能超過{{maxLength}}個字符",
"nodes.humanInput.userActions.chooseStyle": "選擇按鈕樣式",
+ "nodes.humanInput.userActions.defaultTitle": "按鈕文字 {{index}}",
"nodes.humanInput.userActions.emptyTip": "點擊 '+' 按鈕添加用戶操作",
"nodes.humanInput.userActions.title": "用戶操作",
"nodes.humanInput.userActions.tooltip": "定義用戶可以點擊以響應此表單的按鈕。操作 ID 控制分支。操作值作為所選內置輸出在下游公開。操作 ID 必須以字母或下劃線開頭,後跟字母、數字或下劃線。",
diff --git a/web/i18n/locales/zh-Hant/workflow.json b/web/i18n/locales/zh-Hant/workflow.json
index 945b155750a..d68b909d7b6 100644
--- a/web/i18n/locales/zh-Hant/workflow.json
+++ b/web/i18n/locales/zh-Hant/workflow.json
@@ -10,6 +10,7 @@
"blocks.end": "輸出",
"blocks.http-request": "HTTP 請求",
"blocks.human-input": "人工輸入",
+ "blocks.human-input-v2": "人工輸入 v2",
"blocks.if-else": "條件分支",
"blocks.iteration": "迭代",
"blocks.iteration-start": "迭代開始",
@@ -45,6 +46,7 @@
"blocksAbout.end": "定義一個 workflow 流程的輸出和結果類型",
"blocksAbout.http-request": "允許通過 HTTP 協議發送服務器請求",
"blocksAbout.human-input": "在生成下一步之前請求人工確認",
+ "blocksAbout.human-input-v2": "向已設定的聯絡人、電子郵件收件人或工作流程發起人請求輸入",
"blocksAbout.if-else": "允許你根據 if/else 條件將 workflow 拆分成兩個分支",
"blocksAbout.iteration": "對列表對象執行多次步驟直至輸出所有結果。",
"blocksAbout.iteration-start": "迭代起始節點",
@@ -68,6 +70,7 @@
"blocksAbout.variable-aggregator": "將多路分支的變數聚合為一個變數,以實現下游節點統一配置。",
"blocksAbout.variable-assigner": "將多路分支的變數聚合為一個變數,以實現下游節點統一配置。",
"changeHistory.edgeDelete": "區塊已斷開連接",
+ "changeHistory.humanInputMigration": "人工輸入節點已遷移",
"changeHistory.nodeAdd": "區塊已新增",
"changeHistory.nodeChange": "區塊已更改",
"changeHistory.nodeConnect": "區塊已連接",
@@ -361,28 +364,128 @@
"nodes.humanInput.errorMsg.noDeliveryMethodEnabled": "請至少啟用一種發送方式",
"nodes.humanInput.errorMsg.noUserActions": "請至少添加一個用戶操作",
"nodes.humanInput.errorMsg.reservedActionId": "{{id}} 是逾時分支的保留識別碼,請使用其他操作 ID。",
+ "nodes.humanInput.output.actionId": "使用者觸發的動作 ID",
+ "nodes.humanInput.output.actionValue": "所選動作的值",
+ "nodes.humanInput.output.formInput": "表單輸入值",
+ "nodes.humanInput.output.renderedContent": "已渲染的內容",
"nodes.humanInput.timeout.title": "超時",
+ "nodes.humanInputMigration.action.migrate": "遷移",
+ "nodes.humanInputMigration.action.migrateNow": "立即遷移",
+ "nodes.humanInputMigration.action.migrating": "正在遷移...",
+ "nodes.humanInputMigration.banner.ariaLabel": "人工輸入遷移通知",
+ "nodes.humanInputMigration.banner.description": "此工作流程使用舊版人工輸入節點。請先遷移所有舊節點,再新增節點。",
+ "nodes.humanInputMigration.banner.learnMore": "瞭解更多",
+ "nodes.humanInputMigration.blocker.configuredDisabledMethod": "已停用的發送方式仍含有設定",
+ "nodes.humanInputMigration.blocker.conflictingEmailTemplates": "已啟用的電子郵件發送方式使用的範本互相衝突",
"nodes.humanInputMigration.blocker.invalidDefaultValue": "預設值無效",
+ "nodes.humanInputMigration.blocker.invalidEmail": "收件人的電子郵件地址無效",
+ "nodes.humanInputMigration.blocker.invalidEmailConfiguration": "已啟用的電子郵件發送方式設定不完整",
+ "nodes.humanInputMigration.blocker.missingRecipients": "節點沒有支援的收件人",
+ "nodes.humanInputMigration.blocker.unresolvedMember": "無法將工作區成員解析為聯絡人或已驗證的電子郵件地址",
+ "nodes.humanInputMigration.blocker.unsupportedDeliveryMethod": "人工輸入 v2 不支援已啟用的發送方式",
"nodes.humanInputMigration.blocker.unsupportedInputType": "欄位 {{field}} 暫不支援遷移。你可以繼續使用舊版人工確認節點。",
+ "nodes.humanInputMigration.blocker.unsupportedVersion": "節點的版本值不受支援",
+ "nodes.humanInputMigration.dialog.description": "您的收件人、表單和動作將會保留。",
+ "nodes.humanInputMigration.dialog.draftNotice": "只會變更此草稿。已發佈的版本將繼續執行,直到您再次發佈。",
+ "nodes.humanInputMigration.dialog.review": "檢查節點,並在準備好後發佈。",
+ "nodes.humanInputMigration.dialog.title": "遷移 {{count}} 個人工輸入節點",
+ "nodes.humanInputMigration.disabledBadge": "需要遷移",
+ "nodes.humanInputMigration.disabledReason": "請先遷移舊版人工輸入節點,再新增節點。",
+ "nodes.humanInputMigration.error.blocked": "無法遷移 {{nodeTitle}}:{{reason}}。",
"nodes.humanInputMigration.error.graphChanged": "遷移期間工作流程已更新,請重試。目前的編輯已保留。",
+ "nodes.humanInputMigration.error.preflight": "無法準備遷移。您的工作流程未變更,請重試。",
"nodes.humanInputMigration.error.sync": "無法儲存遷移後的工作流程。請檢查目前的草稿後重試。",
+ "nodes.humanInputMigration.incompatibleVersions": "同一個工作流中不能混用舊版和新版人工介入節點。",
+ "nodes.humanInputMigration.oldVersion": "舊版本",
+ "nodes.humanInputMigration.preview.author": "由 Dify 團隊提供",
+ "nodes.humanInputMigration.preview.description": "請先遷移舊版人工輸入節點,再新增節點。",
+ "nodes.humanInputMigration.success": "人工輸入節點遷移成功",
+ "nodes.humanInputV2.card.configured": "已設定 {{count}} 位收件人",
+ "nodes.humanInputV2.card.contactsOnly": "{{count}} 位聯絡人",
+ "nodes.humanInputV2.card.empty": "目前尚無人可以核准此步驟",
+ "nodes.humanInputV2.card.initiatorAndContacts": "發起人及 {{count}} 位聯絡人",
+ "nodes.humanInputV2.card.initiatorOnly": "僅發起人",
+ "nodes.humanInputV2.card.invalid": "請檢查收件人設定",
+ "nodes.humanInputV2.debug.channel.ding_talk": "釘釘",
+ "nodes.humanInputV2.debug.channel.email": "電子郵件",
+ "nodes.humanInputV2.debug.channel.feishu": "飛書",
"nodes.humanInputV2.debug.channel.lark": "Lark",
+ "nodes.humanInputV2.debug.channel.ms_teams": "Microsoft Teams",
+ "nodes.humanInputV2.debug.channel.slack": "Slack",
+ "nodes.humanInputV2.debug.channel.we_com": "企業微信",
+ "nodes.humanInputV2.debug.configure": "設定除錯模式",
"nodes.humanInputV2.debug.keepOneChannel": "至少保留一個管道開啟",
+ "nodes.humanInputV2.debug.sendVia": "透過以下管道發送除錯通知",
+ "nodes.humanInputV2.debug.title": "除錯模式",
+ "nodes.humanInputV2.debug.toggle": "啟用除錯模式",
+ "nodes.humanInputV2.debug.unsupported": "匯入的管道不受支援:{{channels}}。請先移除或更新,再執行此工作流程。",
"nodes.humanInputV2.disabled": "HITL IM 已關閉,Human Input v2 暫不可用。",
+ "nodes.humanInputV2.error.bodyRequired": "訊息內文為必填項",
+ "nodes.humanInputV2.error.debugChannelRequired": "請至少選擇一個除錯模式管道",
+ "nodes.humanInputV2.error.recipientDuplicate": "請移除重複的收件人",
+ "nodes.humanInputV2.error.recipientInvalid": "請修正無效的收件人設定",
+ "nodes.humanInputV2.error.recipientRequired": "請至少新增一位收件人",
+ "nodes.humanInputV2.error.recipientVerificationFailed": "無法驗證聯絡人收件人",
"nodes.humanInputV2.error.requestURLDuplicate": "內文只能包含一個請求 URL。",
"nodes.humanInputV2.error.requestURLRequired": "請在內文中插入請求 URL。",
+ "nodes.humanInputV2.error.subjectRequired": "訊息主旨為必填項",
+ "nodes.humanInputV2.error.version": "人工輸入 v2 的版本值必須為字串 2",
+ "nodes.humanInputV2.recipients.addContact": "新增聯絡人",
+ "nodes.humanInputV2.recipients.addEmail": "新增",
+ "nodes.humanInputV2.recipients.addRecipient": "新增收件人",
+ "nodes.humanInputV2.recipients.added": "已新增",
"nodes.humanInputV2.recipients.allWorkspaceContacts": "工作區所有聯絡人",
"nodes.humanInputV2.recipients.allWorkspaceContactsDescription": "向工作區所有聯絡人傳送通知,任一人均可審批",
+ "nodes.humanInputV2.recipients.cancel": "取消",
+ "nodes.humanInputV2.recipients.chooseVariable": "選擇變數",
+ "nodes.humanInputV2.recipients.confirm": "確認",
+ "nodes.humanInputV2.recipients.contactInfo": "查看 {{name}} 的聯絡人詳情",
+ "nodes.humanInputV2.recipients.contactSource.all": "全部",
+ "nodes.humanInputV2.recipients.contactSource.external": "外部",
+ "nodes.humanInputV2.recipients.contactSource.organization": "組織",
+ "nodes.humanInputV2.recipients.contactSource.workspace": "工作區",
+ "nodes.humanInputV2.recipients.contactSourceLabel": "聯絡人來源",
"nodes.humanInputV2.recipients.duplicateSource": "已透過 {{name}}({{source}})新增。",
+ "nodes.humanInputV2.recipients.edit": "編輯 {{recipient}}",
+ "nodes.humanInputV2.recipients.editRecipient": "編輯收件人",
"nodes.humanInputV2.recipients.emailAlreadySelected": "每個電子郵件地址只能選取一次。",
+ "nodes.humanInputV2.recipients.emailInvalidOrDuplicate": "請輸入有效且尚未新增的電子郵件地址",
+ "nodes.humanInputV2.recipients.emailLabel": "一次性電子郵件收件人",
+ "nodes.humanInputV2.recipients.empty": "尚未設定收件人",
+ "nodes.humanInputV2.recipients.help": "選擇可以回應此人工輸入步驟的人員。",
"nodes.humanInputV2.recipients.initiator": "透過 Web App 或 CLI 發起本次執行的使用者可審批",
+ "nodes.humanInputV2.recipients.initiatorDescription": "啟動此次工作流程執行的人員可以回應。",
"nodes.humanInputV2.recipients.inputHelp": "輸入或貼上多個電子郵件地址,以逗號分隔。按 / 插入變數。",
+ "nodes.humanInputV2.recipients.insertVariable": "插入變數",
+ "nodes.humanInputV2.recipients.loadError": "無法載入聯絡人。已保留儲存的聯絡人 ID。",
+ "nodes.humanInputV2.recipients.loading": "正在載入聯絡人…",
+ "nodes.humanInputV2.recipients.noResults": "找不到聯絡人",
+ "nodes.humanInputV2.recipients.placeholder": "搜尋聯絡人或新增電子郵件地址",
+ "nodes.humanInputV2.recipients.remove": "移除 {{recipient}}",
+ "nodes.humanInputV2.recipients.removeHint": "按 Backspace 或 Delete 刪除。",
+ "nodes.humanInputV2.recipients.resultCount": "找到 {{count}} 個符合的收件人",
+ "nodes.humanInputV2.recipients.search": "搜尋聯絡人",
+ "nodes.humanInputV2.recipients.searchPlaceholder": "依姓名或電子郵件搜尋",
+ "nodes.humanInputV2.recipients.selectionHint": "已選擇 {{count}} 個收件人。在輸入框開頭按左方向鍵可選取收件人。",
+ "nodes.humanInputV2.recipients.title": "收件人",
"nodes.humanInputV2.recipients.type.all_workspace_contacts": "工作區所有聯絡人",
+ "nodes.humanInputV2.recipients.type.contact": "聯絡人",
+ "nodes.humanInputV2.recipients.type.dynamic_email": "動態電子郵件",
+ "nodes.humanInputV2.recipients.type.initiator": "發起人",
+ "nodes.humanInputV2.recipients.type.onetime_email": "一次性電子郵件",
+ "nodes.humanInputV2.recipients.typeLabel": "收件人類型",
"nodes.humanInputV2.recipients.useThisInstead": "改用此項",
+ "nodes.humanInputV2.recipients.variableRequired": "請選擇電子郵件變數",
+ "nodes.humanInputV2.template.body": "內文",
+ "nodes.humanInputV2.template.description": "電子郵件及即時通訊的備用文案",
"nodes.humanInputV2.template.insertRequestURL": "插入請求 URL",
+ "nodes.humanInputV2.template.insertVariable": "插入變數",
+ "nodes.humanInputV2.template.notConfigured": "尚未設定",
"nodes.humanInputV2.template.requestURLHint": "收件人透過此連結開啟審批表單,內文必須包含一個請求 URL。",
"nodes.humanInputV2.template.requestURLInserted": "已插入請求 URL",
"nodes.humanInputV2.template.saveAndTest": "儲存並測試",
+ "nodes.humanInputV2.template.subject": "主旨",
+ "nodes.humanInputV2.template.subjectPlaceholder": "輸入訊息主旨",
"nodes.humanInputV2.template.test": "測試訊息",
"nodes.humanInputV2.template.testChannel": "測試管道",
"nodes.humanInputV2.template.testCompleted": "測試請求已完成,請前往所選管道查看訊息。",
@@ -391,6 +494,7 @@
"nodes.humanInputV2.template.testInputsRequired": "請填寫所有測試變數的值。",
"nodes.humanInputV2.template.testSaveFailed": "工作流程草稿儲存失敗,未傳送測試。",
"nodes.humanInputV2.template.testUnavailable": "目前環境尚未支援訊息範本測試。",
+ "nodes.humanInputV2.template.title": "訊息範本",
"nodes.ifElse.operator": "操作符",
"nodes.iteration.currentIteration": "當前迭代",
"nodes.iteration.deleteDesc": "刪除迭代節點將刪除所有子節點",
diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.ts
index 57bbf14f6db..1737338953f 100644
--- a/web/i18n/resources.generated.d.ts
+++ b/web/i18n/resources.generated.d.ts
@@ -2070,7 +2070,6 @@ export default interface Resources {
'directory.externalEmptyDescription': "External contacts are people outside your organization. Think clients, partners, or vendors. They're reached by email only."
'directory.externalEmptyTitle': 'Add your first external contact'
'directory.filters': 'Contact type filters'
- 'directory.learnMore': 'Learn more about Contacts'
'directory.loading': 'Loading contacts'
'directory.noAccessDescription': 'Only workspace owners and admins can browse the full Contacts directory.'
'directory.noAccessTitle': "You don't have access to Contacts"
@@ -2078,10 +2077,14 @@ export default interface Resources {
'directory.noResultsTitle': 'No matching contacts'
'directory.openDetails': 'Open contact details for {{name}}'
'directory.pageError': "More contacts couldn't be loaded. Retry this page."
+ 'directory.removalCountTitle': 'Remove contacts ({{count}})?'
'directory.removalDescription': 'The selected contacts will be permanently removed from this workspace. This action cannot be undone.'
'directory.removalFailed': "The selected contacts couldn't be removed. Your selection has been kept."
- 'directory.removalTitle': 'Remove contacts?'
+ 'directory.removalSingleDescription': '{{name}} will be permanently removed from this workspace. This action cannot be undone.'
+ 'directory.removalSingleFailed': "The contact couldn't be removed. Try again."
+ 'directory.removalSingleTitle': 'Remove {{name}}?'
'directory.removeSelected': 'Remove'
+ 'directory.resultCount': 'Results: {{count}}'
'directory.search': 'Search name or email'
'directory.selectAll': 'Select all removable contacts'
'directory.selectContact': 'Select {{name}}'
@@ -2090,7 +2093,6 @@ export default interface Resources {
'directory.viewOnly': 'You can browse Contacts, but only workspace owners and admins can manage contacts.'
'external.add': 'Add'
'external.adding': 'Adding'
- 'external.avatarFallback': 'External contact'
'external.description': 'Create a workspace-only contact that can be reached by email.'
'external.editDescription': "Update this external contact's name and email address."
'external.editTitle': 'Edit External Contact'
@@ -2099,8 +2101,6 @@ export default interface Resources {
'external.namePlaceholder': 'Full name'
'external.result.duplicate_external_contact': 'An external contact with this email already exists.'
'external.result.failed': "The contact couldn't be added. Keep these details and try again."
- 'external.result.matches_platform_contact': 'This email belongs to a Platform contact. Add it from Platform instead.'
- 'external.result.matches_workspace_contact': 'This person is already a workspace contact.'
'external.save': 'Save'
'external.saving': 'Saving'
'external.title': 'Add External Contact'
@@ -2147,15 +2147,12 @@ export default interface Resources {
'imBinding.select': 'Select an IM contact'
'imBinding.title': 'Bind IM identity'
'imBinding.workspaceMode': 'Custom for this workspace'
- 'imPlatform.action.authorize': 'Authorize'
- 'imPlatform.action.authorizing': 'Authorizing'
'imPlatform.action.configure': 'Configure'
'imPlatform.action.configureChannel': 'Configure {{provider}}'
'imPlatform.action.connect': 'Connect'
'imPlatform.action.copied': 'Copied'
'imPlatform.action.copyCallback': 'Copy callback URL'
'imPlatform.action.deleteChannel': 'Delete {{provider}}'
- 'imPlatform.action.disconnect': 'Disconnect'
'imPlatform.action.loadMore': 'Load more'
'imPlatform.action.replace': 'Replace'
'imPlatform.action.retry': 'Retry'
@@ -2167,7 +2164,6 @@ export default interface Resources {
'imPlatform.action.testConnection': 'Test connection'
'imPlatform.action.testing': 'Testing'
'imPlatform.action.viewDetails': 'View details'
- 'imPlatform.bindingDialog.authorizationFailed': "Authorization couldn't be completed. Try again."
'imPlatform.bindingDialog.back': 'Back'
'imPlatform.bindingDialog.callback': 'Callback URL'
'imPlatform.bindingDialog.callbackDescription': 'Complete callback setup in {{provider}} to enable card actions.'
@@ -2179,7 +2175,6 @@ export default interface Resources {
'imPlatform.bindingDialog.callbackInstruction.slack.path': 'Interactivity & Shortcuts → Interactivity → Request URL'
'imPlatform.bindingDialog.callbackInstruction.teams.destination': 'For card actions, paste this URL in the <console>Azure Bot configuration</console>:'
'imPlatform.bindingDialog.callbackInstruction.teams.path': 'Settings → Configuration → Messaging endpoint'
- 'imPlatform.bindingDialog.callbackPurpose': 'This URL receives approval card interactions from {{provider}}. Use the exact URL shown for this channel.'
'imPlatform.bindingDialog.callbackStep': 'Configure callbacks'
'imPlatform.bindingDialog.clearSavedCredential': 'Clear saved value'
'imPlatform.bindingDialog.configureTitle': 'Configure {{provider}}'
@@ -2207,15 +2202,14 @@ export default interface Resources {
'imPlatform.bindingDialog.fieldPlaceholder.verificationToken': 'Enter Verification Token, if configured'
'imPlatform.bindingDialog.finish': 'Finish'
'imPlatform.bindingDialog.freshCredentials': 'Saved secrets cannot be retrieved. Re-enter all required credentials to test or save this configuration.'
- 'imPlatform.bindingDialog.openProviderConsole': 'Open {{provider}} developer console'
'imPlatform.bindingDialog.openSetupGuide': 'Open setup guide'
+ 'imPlatform.bindingDialog.replaceTenantTitle': 'Replace tenant credentials for {{identity}}?'
'imPlatform.bindingDialog.replacementRequired': 'These credentials belong to a different IM tenant and cannot be saved directly. Switching tenants requires replacing the current IM channel, which clears all automatic and manual IM bindings. Sync contacts again after replacement.'
'imPlatform.bindingDialog.required': 'This field is required.'
'imPlatform.bindingDialog.saveAndContinue': 'Save and continue'
'imPlatform.bindingDialog.saveFailed': "Configuration couldn't be saved. Check the fields and try again."
'imPlatform.bindingDialog.savedDetailsUnavailable': 'The configuration was saved, but its details could not be loaded. Close this dialog and reopen it.'
'imPlatform.bindingDialog.secretConfigured': 'A secret is already configured. Leave this field blank to keep it.'
- 'imPlatform.bindingDialog.secretPlaceholder': 'Enter a new secret'
'imPlatform.bindingDialog.step': 'Step {{step}}'
'imPlatform.bindingDialog.testFailed': 'The connection test failed. Check the configuration and try again.'
'imPlatform.bindingDialog.undoClearCredential': 'Undo clear'
@@ -2236,37 +2230,20 @@ export default interface Resources {
'imPlatform.details.downloadingReport': 'Downloading report…'
'imPlatform.details.empty': 'No results in this category.'
'imPlatform.details.filter.added': 'Added'
- 'imPlatform.details.filter.all': 'All'
- 'imPlatform.details.filter.created_binding': 'Binding created'
'imPlatform.details.filter.failed': 'Failed'
- 'imPlatform.details.filter.matched': 'Matched'
'imPlatform.details.filter.not_matched': 'Not matched'
'imPlatform.details.filter.removed': 'Removed'
'imPlatform.details.filter.skipped': 'Skipped'
- 'imPlatform.details.filter.unmatched': 'Unmatched'
- 'imPlatform.details.filter.updated_binding': 'Binding updated'
'imPlatform.details.filters': 'Sync result filters'
'imPlatform.details.latestMetadata': '{{status}} · {{date}}'
'imPlatform.details.loadError': "Sync details couldn't be loaded."
- 'imPlatform.details.loading': 'Loading sync details'
- 'imPlatform.details.metadata': '{{status}} · {{date}} by {{user}}'
'imPlatform.details.missing': '—'
'imPlatform.details.pageError': "More results couldn't be loaded. Retry this page."
+ 'imPlatform.details.removalReason.binding_invalidated': 'Binding invalidated'
+ 'imPlatform.details.removalReason.binding_replaced': 'Binding replaced'
+ 'imPlatform.details.removalReason.not_present_in_directory': 'No longer in the directory'
'imPlatform.details.reportChanged': 'The sync results changed. Reopen the latest sync details and try again.'
- 'imPlatform.details.safeReason.contact_update_failed': "The Contact binding couldn't be updated."
- 'imPlatform.details.safeReason.duplicate_identity': 'A duplicate platform identity was skipped.'
- 'imPlatform.details.safeReason.missing_email': 'The platform member has no Email address.'
- 'imPlatform.details.safeReason.no_matching_contact': 'No existing Contact matched this platform member.'
- 'imPlatform.details.safeReason.provider_request_failed': 'The provider request failed without exposing credentials.'
'imPlatform.details.title': 'Sync details'
- 'imPlatform.diagnostics.configured': 'Configuration is saved. Test the connection before syncing Contacts.'
- 'imPlatform.diagnostics.connected': 'Directory access is ready.'
- 'imPlatform.diagnostics.notConfigured': 'Choose a provider to start the binding flow.'
- 'imPlatform.diagnostics.title': 'Connection diagnostics'
- 'imPlatform.disconnect.confirm': 'Disconnect'
- 'imPlatform.disconnect.description': 'Directory sync will stop and the current binding will be removed.'
- 'imPlatform.disconnect.failed': "The provider couldn't be disconnected. Try again."
- 'imPlatform.disconnect.title': 'Disconnect {{provider}}?'
'imPlatform.email.apiKey': 'API Key'
'imPlatform.email.apiKeyConfigured': 'For security reasons, the saved API Key cannot be viewed. Leave this field blank to keep it.'
'imPlatform.email.apiKeyDescription': 'For security reasons, this API Key cannot be viewed once saved.'
@@ -2280,51 +2257,27 @@ export default interface Resources {
'imPlatform.email.senderEmailDescription': 'The email address shown as the sender. Its domain must be verified in Resend.'
'imPlatform.email.senderName': 'Sender name'
'imPlatform.email.senderNameDescription': "Name displayed in the recipient's inbox."
- 'imPlatform.email.summary': 'Resend · {{email}}'
'imPlatform.email.testSucceeded': 'Connection test succeeded.'
'imPlatform.email.title': 'Configure Email'
- 'imPlatform.lastChecked': 'Last checked {{date}}'
'imPlatform.learnMore': 'Learn more'
'imPlatform.loadError.description': 'Try again to read the current binding and permissions.'
'imPlatform.loadError.retry': 'Try again'
'imPlatform.loadError.title': "Channels couldn't be loaded"
'imPlatform.loading': 'Loading channels'
- 'imPlatform.notChecked': "Connection hasn't been checked yet."
- 'imPlatform.permission.description': 'Only workspace owners and admins can manage channels and directory sync.'
- 'imPlatform.permission.title': 'View only'
'imPlatform.provider.dingtalkDescription': 'Connect a DingTalk application.'
'imPlatform.provider.emailDescription': 'Configure the email service used to send approval requests from this workspace.'
'imPlatform.provider.feishuDescription': 'Connect a Feishu application.'
'imPlatform.provider.larkDescription': 'Connect a Lark application.'
'imPlatform.provider.msTeamsDescription': 'Connect a Microsoft Teams application.'
'imPlatform.provider.slackDescription': 'Sync people and their Slack identities.'
- 'imPlatform.provider.unavailable': 'Unavailable'
- 'imPlatform.provider.unavailableReason.deployment_unsupported': "This provider isn't supported in the current deployment."
- 'imPlatform.provider.unavailableReason.not_released': "This provider isn't available yet."
'imPlatform.provider.weComDescription': 'Connect a WeCom application.'
'imPlatform.replacement.confirm': 'Replace'
'imPlatform.replacement.description': 'Replacing the active provider invalidates its IM bindings and workspace overrides. Sync the new provider directory again after replacement.'
'imPlatform.replacement.title': 'Replace {{current}} with {{next}}?'
- 'imPlatform.status.callback_error': 'Callback error'
'imPlatform.status.configured': 'Configured'
'imPlatform.status.connected': 'Connected'
'imPlatform.status.connection_error': 'Connection error'
- 'imPlatform.status.not_configured': 'Not configured'
'imPlatform.status.permission_issue': 'Permission issue'
- 'imPlatform.statusReason.callback_mismatch': "The provider callback URL doesn't match this workspace."
- 'imPlatform.statusReason.missing_directory_permission': 'The provider app is missing directory read permission.'
- 'imPlatform.statusReason.provider_request_failed': "The provider couldn't be reached. No credentials were exposed."
- 'imPlatform.sync.count.added': 'Added'
- 'imPlatform.sync.count.created_binding': 'Binding created'
- 'imPlatform.sync.count.failed': 'Failed'
- 'imPlatform.sync.count.matched': 'Matched'
- 'imPlatform.sync.count.not_matched': 'Not matched'
- 'imPlatform.sync.count.removed': 'Removed'
- 'imPlatform.sync.count.skipped': 'Skipped'
- 'imPlatform.sync.count.unmatched': 'Unmatched'
- 'imPlatform.sync.count.updated_binding': 'Binding updated'
- 'imPlatform.sync.description': 'Sync is manual and reads the connected provider directory into Contacts matching results.'
- 'imPlatform.sync.lastSynced': 'Last synced {{date}} by {{user}}'
'imPlatform.sync.latestSynced': 'Last synced {{date}}'
'imPlatform.sync.loading': 'Checking for an active sync.'
'imPlatform.sync.noPermission': 'Only workspace owners and admins can start directory sync.'
@@ -2332,29 +2285,13 @@ export default interface Resources {
'imPlatform.sync.notConnected': 'Connect and test a provider before starting directory sync.'
'imPlatform.sync.startFailed': "Directory sync couldn't be started or refreshed. Try again."
'imPlatform.sync.status.failure': 'Failed'
- 'imPlatform.sync.status.partial_success': 'Partial success'
'imPlatform.sync.status.queued': 'Queued'
'imPlatform.sync.status.running': 'Running'
'imPlatform.sync.status.success': 'Success'
- 'imPlatform.sync.title': 'Directory sync'
- 'imPlatform.sync.unsupported': "This provider doesn't support directory sync."
'imPlatform.title': 'Channels'
- 'memberInviteUpgrade.confirm': 'Add and upgrade'
- 'memberInviteUpgrade.description':
- | 'This email is already used by an External Contact. Adding this member will convert the contact to a Workspace Contact. Existing workflow references and history will be preserved.'
- | '{{count}} emails are already used by External Contacts. Adding these members will convert the contacts to Workspace Contacts. Existing workflow references and history will be preserved.'
- 'memberInviteUpgrade.title':
- | 'Email already exists in Contacts'
- | 'Emails already exist in Contacts'
'memberRemoval.accessImpact': '{{memberName}} will immediately lose access to this workspace.'
'memberRemoval.contentImpact': 'Apps and knowledge they created stay here. This action cannot be undone.'
- 'memberRemoval.eeDescription': 'Removing this member ends their workspace access. Choose whether to keep the same contact as a Platform contact.'
- 'memberRemoval.failed': "The member couldn't be removed. Nothing has changed; try again."
- 'memberRemoval.keepPlatform': 'Keep as Platform contact'
- 'memberRemoval.keepPlatformDescription': 'Keep this identity available in Contacts after workspace access is removed.'
'memberRemoval.remove': 'Remove'
- 'memberRemoval.removing': 'Removing'
- 'memberRemoval.standardDescription': 'Removing this member also removes their workspace contact from the current Contacts directory.'
'memberRemoval.title': 'Remove {{memberName}} from the workspace?'
'memberRemoval.workspaceTitle': 'Remove {{memberName}} from {{workspaceName}}?'
'platformPicker.add': 'Add contacts'
@@ -2363,25 +2300,14 @@ export default interface Resources {
'platformPicker.addForbidden': 'Only workspace administrators in an Enterprise deployment can add Platform contacts.'
'platformPicker.adding': 'Adding'
'platformPicker.allMembers': 'All Members'
- 'platformPicker.backendTeam': 'Backend Team'
'platformPicker.description': 'Choose Platform contacts that are not already in this workspace Contacts directory.'
- 'platformPicker.devTeam': 'Dev Team'
'platformPicker.empty': 'No available Platform contacts match this search.'
'platformPicker.error': "Platform contacts couldn't be loaded."
- 'platformPicker.externalUpgradeUnsupported': 'External contacts cannot be upgraded through this action. No upgrade was performed.'
- 'platformPicker.frontendTeam': 'Frontend Team'
'platformPicker.loading': 'Loading Platform contacts'
- 'platformPicker.mobileDev': 'Mobile Dev'
- 'platformPicker.noExternalUpgrade': 'Platform contacts are added separately. External contacts with the same email and their existing workflow references remain unchanged.'
'platformPicker.search': 'Search Platform contacts'
'platformPicker.selectContact': 'Select {{name}}'
'platformPicker.selected': '{{count}} selected'
'platformPicker.title': 'Add from Platform'
- 'platformPicker.upgrade.confirm': 'Add and upgrade'
- 'platformPicker.upgrade.description':
- | 'This email is already used by an External Contact. Adding this Platform Contact will upgrade the existing contact. Existing workflow references and history will be preserved.'
- | '{{count}} emails are already used by External Contacts. Adding these Platform Contacts will upgrade the existing contacts. Existing workflow references and history will be preserved.'
- 'platformPicker.upgrade.title': 'Contact already exists' | 'Contacts already exist'
'type.external': 'External'
'type.platform': 'Platform'
'type.workspace': 'Workspace'
@@ -5291,7 +5217,6 @@ export default interface Resources {
'humanInputV2.otpPlaceholder': 'Enter the 6-digit code'
'humanInputV2.requestingCode': 'Sending a verification code…'
'humanInputV2.resendCode': 'Resend code'
- 'humanInputV2.resendIn': 'Resend in {{seconds}}s'
'humanInputV2.retry': 'Try again'
'humanInputV2.sendCode': 'Send a new code'
'humanInputV2.unavailable': 'This form is temporarily unavailable.'
@@ -6170,6 +6095,7 @@ export default interface Resources {
'nodes.humanInputMigration.error.graphChanged': 'The workflow changed during migration. Try again; your current edits have been kept.'
'nodes.humanInputMigration.error.preflight': 'Migration could not be prepared. Your workflow was not changed. Please try again.'
'nodes.humanInputMigration.error.sync': 'The migrated workflow could not be saved. Review the current draft and try again.'
+ 'nodes.humanInputMigration.incompatibleVersions': 'Old and new Human Input nodes cannot be used in the same workflow.'
'nodes.humanInputMigration.oldVersion': 'OLD VERSION'
'nodes.humanInputMigration.preview.author': 'By Dify Team'
'nodes.humanInputMigration.preview.description': 'Migrate old Human Input nodes before adding a new one.'
@@ -6199,6 +6125,7 @@ export default interface Resources {
'nodes.humanInputV2.error.recipientDuplicate': 'Remove duplicate recipients'
'nodes.humanInputV2.error.recipientInvalid': 'Repair invalid recipient configuration'
'nodes.humanInputV2.error.recipientRequired': 'Add at least one recipient'
+ 'nodes.humanInputV2.error.recipientVerificationFailed': "Couldn't verify contact recipients"
'nodes.humanInputV2.error.requestURLDuplicate': 'The message body can contain only one Request URL.'
'nodes.humanInputV2.error.requestURLRequired': 'Insert a Request URL in the message body.'
'nodes.humanInputV2.error.subjectRequired': 'Message subject is required'
@@ -6212,6 +6139,7 @@ export default interface Resources {
'nodes.humanInputV2.recipients.cancel': 'Cancel'
'nodes.humanInputV2.recipients.chooseVariable': 'Choose variable'
'nodes.humanInputV2.recipients.confirm': 'Confirm'
+ 'nodes.humanInputV2.recipients.contactInfo': 'Contact details for {{name}}'
'nodes.humanInputV2.recipients.contactSource.all': 'All'
'nodes.humanInputV2.recipients.contactSource.external': 'External'
'nodes.humanInputV2.recipients.contactSource.organization': 'Organization'
@@ -6234,8 +6162,11 @@ export default interface Resources {
'nodes.humanInputV2.recipients.noResults': 'No contacts found'
'nodes.humanInputV2.recipients.placeholder': 'Search contacts or add emails'
'nodes.humanInputV2.recipients.remove': 'Remove {{recipient}}'
+ 'nodes.humanInputV2.recipients.removeHint': 'Press Backspace or Delete to remove.'
+ 'nodes.humanInputV2.recipients.resultCount': '{{count}} matching recipients'
'nodes.humanInputV2.recipients.search': 'Search contacts'
'nodes.humanInputV2.recipients.searchPlaceholder': 'Search by name or email'
+ 'nodes.humanInputV2.recipients.selectionHint': '{{count}} recipients selected. At the start of the input, press Left Arrow to focus them.'
'nodes.humanInputV2.recipients.title': 'Recipients'
'nodes.humanInputV2.recipients.type.all_workspace_contacts': 'All workspace contacts'
'nodes.humanInputV2.recipients.type.contact': 'Contact'
diff --git a/web/service/__tests__/human-input-submission.spec.ts b/web/service/__tests__/human-input-submission.spec.ts
new file mode 100644
index 00000000000..9e30fa100fa
--- /dev/null
+++ b/web/service/__tests__/human-input-submission.spec.ts
@@ -0,0 +1,26 @@
+import {
+ HumanInputSubmissionPreparationError,
+ prepareHumanInputFormSubmission,
+} from '../human-input-submission'
+
+afterEach(() => vi.useRealTimers())
+
+it('reports a disposed or failed reconnect instead of treating it as a successful submission', async () => {
+ await expect(
+ prepareHumanInputFormSubmission(() => Promise.resolve(false)),
+ ).rejects.toBeInstanceOf(HumanInputSubmissionPreparationError)
+})
+
+it('times out when workflow readiness never arrives', async () => {
+ vi.useFakeTimers()
+ const pending = prepareHumanInputFormSubmission(() => new Promise<boolean>(() => {}))
+ const assertion = expect(pending).rejects.toBeInstanceOf(HumanInputSubmissionPreparationError)
+ await vi.advanceTimersByTimeAsync(15_000)
+ await assertion
+})
+
+it('clears its timeout after readiness succeeds', async () => {
+ vi.useFakeTimers()
+ await prepareHumanInputFormSubmission(() => Promise.resolve(true))
+ expect(vi.getTimerCount()).toBe(0)
+})
diff --git a/web/service/__tests__/share-human-input-submit.spec.ts b/web/service/__tests__/share-human-input-submit.spec.ts
index a94925d57b1..efa31907e52 100644
--- a/web/service/__tests__/share-human-input-submit.spec.ts
+++ b/web/service/__tests__/share-human-input-submit.spec.ts
@@ -63,6 +63,23 @@ describe('Web App human input submission', () => {
},
)
+ it.each([401, 403, 404, 409, 410, 500])(
+ 'propagates V2 HTTP %i without retrying the legacy endpoint',
+ async (status) => {
+ mocks.fetch.mockResolvedValue(
+ new Response(JSON.stringify({ code: 'not_found' }), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ )
+ await expect(
+ submitHumanInputForm('v2-token', { inputs: {}, action: 'approve' }, '2'),
+ ).rejects.toBeDefined()
+ expect(mocks.legacyPost).not.toHaveBeenCalled()
+ expect(mocks.fetch.mock.calls.length).toBeGreaterThanOrEqual(1)
+ },
+ )
+
it('uses the environment app API prefix when submitting its v2 form', async () => {
mocks.address.mockReturnValue({ kind: 'environment', code: 'environment-code' })
diff --git a/web/service/__tests__/webapp-human-input-submit.spec.ts b/web/service/__tests__/webapp-human-input-submit.spec.ts
deleted file mode 100644
index fcd99ee9e4c..00000000000
--- a/web/service/__tests__/webapp-human-input-submit.spec.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { createHttpError } from '../http-error'
-import { submitWebAppHumanInputForm } from '../webapp-human-input'
-
-const mocks = vi.hoisted(() => ({ request: vi.fn(), legacySubmit: vi.fn() }))
-vi.mock('../base', () => ({ request: mocks.request }))
-vi.mock('../share', () => ({ submitHumanInputForm: mocks.legacySubmit }))
-vi.mock('@/config', () => ({ PUBLIC_API_PREFIX: 'https://webapp.example/api' }))
-
-const data = { action: 'approve', inputs: { ReviewNote: 'Approved', choices: ['one', 'two'] } }
-
-describe('Webapp human input submission', () => {
- beforeEach(() => {
- mocks.request.mockReset()
- mocks.legacySubmit.mockReset()
- window.history.replaceState({}, '', '/chat/app-code')
- })
-
- it.each(['1', undefined] as const)(
- 'submits version %s through V1 without probing V2',
- async (formVersion) => {
- const result = { result: 'success' }
- mocks.legacySubmit.mockResolvedValueOnce(result)
- mocks.request.mockRejectedValueOnce(
- createHttpError(new Response(null, { status: 404 }), { code: 'not_found' }),
- )
-
- await expect(submitWebAppHumanInputForm('legacy-token', data, formVersion)).resolves.toBe(
- result,
- )
-
- expect(mocks.legacySubmit).toHaveBeenCalledExactlyOnceWith('legacy-token', data)
- expect(mocks.request).not.toHaveBeenCalled()
- },
- )
-
- it.each([
- ['/chat/app-code', 'https://webapp.example/api/form/human-input/v2/opaque-token'],
- [
- '/environment/chat/environment-code',
- 'https://webapp.example/api/environment/environment-code/form/human-input/v2/opaque-token',
- ],
- ])('submits V2 once in the passport scope for %s', async (path, expectedUrl) => {
- window.history.replaceState({}, '', path)
- mocks.request.mockResolvedValueOnce(Response.json({}))
-
- await submitWebAppHumanInputForm('opaque-token', data, '2')
-
- expect(mocks.legacySubmit).not.toHaveBeenCalled()
- expect(mocks.request).toHaveBeenCalledTimes(1)
- const postCall = mocks.request.mock.calls[0]
- if (!postCall) throw new Error('Expected the V2 submission request')
- const [postUrl, , postOptions] = postCall
- expect(postUrl).toBe(expectedUrl)
- expect(postOptions).toMatchObject({ isPublicAPI: true, fetchCompat: true })
- expect(postOptions.request.url).toBe(expectedUrl)
- expect(postOptions.request.method).toBe('POST')
- expect(await postOptions.request.json()).toEqual(data)
- })
-
- it.each([401, 403, 404, 409, 410, 500])(
- 'propagates a V2 HTTP %i error without retrying through V1',
- async (status) => {
- const error = createHttpError(new Response(null, { status }), {
- code: 'not_found',
- message: 'Form unavailable',
- })
- mocks.request.mockRejectedValueOnce(error)
-
- await expect(submitWebAppHumanInputForm('opaque-token', data, '2')).rejects.toBe(error)
-
- expect(mocks.legacySubmit).not.toHaveBeenCalled()
- expect(mocks.request).toHaveBeenCalledTimes(1)
- expect(mocks.request.mock.calls[0]?.[2].request.method).toBe('POST')
- },
- )
-
- it('propagates a V2 network failure without retrying through V1', async () => {
- const error = new TypeError('Network unavailable')
- mocks.request.mockRejectedValueOnce(error)
-
- await expect(submitWebAppHumanInputForm('opaque-token', data, '2')).rejects.toBe(error)
-
- expect(mocks.legacySubmit).not.toHaveBeenCalled()
- expect(mocks.request).toHaveBeenCalledTimes(1)
- expect(mocks.request.mock.calls[0]?.[2].request.method).toBe('POST')
- })
-})
diff --git a/web/service/__tests__/workflow-human-input-submit.spec.ts b/web/service/__tests__/workflow-human-input-submit.spec.ts
index 989f66b1ced..8c0e22ed934 100644
--- a/web/service/__tests__/workflow-human-input-submit.spec.ts
+++ b/web/service/__tests__/workflow-human-input-submit.spec.ts
@@ -1,3 +1,4 @@
+import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'
import { submitHumanInputForm } from '../workflow'
const mocks = vi.hoisted(() => ({ legacyPost: vi.fn(), approveV2: vi.fn() }))
@@ -19,20 +20,48 @@ describe('Console human input submission', () => {
it('uses the authenticated v2 contract for v2 nodes', async () => {
const data = { action: 'approve', inputs: { note: 'Approved' } }
await submitHumanInputForm('opaque-token', data, '2')
- expect(mocks.approveV2).toHaveBeenCalledWith({
- params: { form_token: 'opaque-token' },
- body: data,
- })
+ expect(mocks.approveV2).toHaveBeenCalledWith(
+ { params: { form_token: 'opaque-token' }, body: data },
+ { context: undefined },
+ )
+ expect(mocks.legacyPost).not.toHaveBeenCalled()
+ })
+
+ it('keeps workflow preview routing metadata out of the v2 request body', async () => {
+ const data: HumanInputFormSubmitData = {
+ action: 'approve',
+ inputs: { note: 'Approved' },
+ form_version: '2',
+ }
+
+ await submitHumanInputForm('opaque-token', data, data.form_version)
+
+ expect(mocks.approveV2).toHaveBeenCalledWith(
+ {
+ params: { form_token: 'opaque-token' },
+ body: { action: 'approve', inputs: { note: 'Approved' } },
+ },
+ { context: undefined },
+ )
+ expect(data.form_version).toBe('2')
expect(mocks.legacyPost).not.toHaveBeenCalled()
})
+ it('passes the caller context so surfaces with inline errors can skip the transport toast', async () => {
+ const data = { action: 'approve', inputs: { note: 'Approved' } }
+ await submitHumanInputForm('opaque-token', data, '2', { silent: true })
+ expect(mocks.approveV2).toHaveBeenCalledWith(expect.anything(), {
+ context: { silent: true },
+ })
+ })
+
it('preserves legacy node submission', async () => {
const data = { action: 'approve', inputs: { note: 'Approved' } }
await submitHumanInputForm('legacy-token', data)
- expect(mocks.legacyPost).toHaveBeenCalledWith({
- params: { form_token: 'legacy-token' },
- body: data,
- })
+ expect(mocks.legacyPost).toHaveBeenCalledWith(
+ { params: { form_token: 'legacy-token' }, body: data },
+ { context: undefined },
+ )
expect(mocks.approveV2).not.toHaveBeenCalled()
})
})
diff --git a/web/service/console/index.ts b/web/service/console/index.ts
index 5eae2c9e7a4..107f6731bed 100644
--- a/web/service/console/index.ts
+++ b/web/service/console/index.ts
@@ -3,14 +3,9 @@ import type { ClientLink } from '@orpc/client'
import type { ContractRouterClient } from '@orpc/contract'
import type { JsonifiedClient } from '@orpc/openapi-client'
import type { TanstackQueryOperationContext } from '@orpc/tanstack-query'
-import type { QueryClient } from '@tanstack/react-query'
import { createORPCClient, DynamicLink } from '@orpc/client'
import { consoleBrowserLink } from './browser'
-import {
- createConsoleQuery,
- invalidateHumanInputChannelQueries as invalidateChannelQueries,
- invalidateHumanInputContactQueries as invalidateContactQueries,
-} from './query-policies'
+import { createConsoleQuery } from './query-policies'
export type ConsoleClientContext = TanstackQueryOperationContext & {
keepalive?: boolean
@@ -39,11 +34,3 @@ const consoleLink = new DynamicLink<ConsoleClientContext>(() => {
export const consoleClient: ConsoleClient = createORPCClient(consoleLink)
export const consoleQuery = createConsoleQuery(consoleClient)
-
-export function invalidateHumanInputContactQueries(client: QueryClient, workspaceId?: string) {
- return invalidateContactQueries(consoleQuery, client, workspaceId)
-}
-
-export function invalidateHumanInputChannelQueries(client: QueryClient, workspaceId?: string) {
- return invalidateChannelQueries(consoleQuery, client, workspaceId)
-}
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index bf8ba1bdbee..0f00024c400 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -359,7 +359,7 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
platform: {
post: {
mutationOptions: {
- onSuccess: (_data, _variables, _onMutateResult, context) =>
+ onSettled: (_data, _error, _variables, _onMutateResult, context) =>
invalidateHumanInputContactQueries(consoleQuery, context.client),
},
},
@@ -419,6 +419,22 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
},
+ imSyncRuns: {
+ post: {
+ mutationOptions: {
+ onSuccess: (data, _variables, _onMutateResult, context) => {
+ context.client.setQueryData(
+ consoleQuery.workspaces.current.humanInput.v2.imSyncRuns.latest.get.queryKey(),
+ data,
+ )
+ return context.client.resetQueries({
+ queryKey:
+ consoleQuery.workspaces.current.humanInput.v2.imSyncRuns.latest.results.key(),
+ })
+ },
+ },
+ },
+ },
channels: {
email: {
post: {
@@ -430,13 +446,13 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
byChannelId: {
put: {
mutationOptions: {
- onSuccess: (_data, _variables, _onMutateResult, context) =>
+ onSettled: (_data, _error, _variables, _onMutateResult, context) =>
invalidateHumanInputChannelQueries(consoleQuery, context.client),
},
},
delete: {
mutationOptions: {
- onSuccess: (_data, _variables, _onMutateResult, context) =>
+ onSettled: (_data, _error, _variables, _onMutateResult, context) =>
invalidateHumanInputChannelQueries(consoleQuery, context.client),
},
},
@@ -452,20 +468,20 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
byChannelId: {
put: {
mutationOptions: {
- onSuccess: (_data, _variables, _onMutateResult, context) =>
+ onSettled: (_data, _error, _variables, _onMutateResult, context) =>
invalidateHumanInputChannelQueries(consoleQuery, context.client),
},
},
delete: {
mutationOptions: {
- onSuccess: (_data, _variables, _onMutateResult, context) =>
+ onSettled: (_data, _error, _variables, _onMutateResult, context) =>
invalidateHumanInputChannelQueries(consoleQuery, context.client),
},
},
replacement: {
post: {
mutationOptions: {
- onSuccess: (_data, _variables, _onMutateResult, context) =>
+ onSettled: (_data, _error, _variables, _onMutateResult, context) =>
invalidateHumanInputChannelQueries(consoleQuery, context.client),
},
},
@@ -2997,13 +3013,11 @@ function invalidateAgentAccessQueries(
])
}
-export function invalidateHumanInputContactQueries(
+function invalidateHumanInputContactQueries(
query: RouterUtils<ConsoleClient>,
client: QueryClient,
- workspaceId?: string,
) {
return invalidateQueryKeys(client, [
- workspaceId ? ['contacts-management', workspaceId] : ['contacts-management'],
query.workspaces.current.humanInput.v2.contacts.key(),
query.workspaces.current.humanInput.v2.contactOptions.key(),
query.workspaces.current.humanInput.v2.imIdentities.key(),
@@ -3011,15 +3025,13 @@ export function invalidateHumanInputContactQueries(
])
}
-export function invalidateHumanInputChannelQueries(
+function invalidateHumanInputChannelQueries(
query: RouterUtils<ConsoleClient>,
client: QueryClient,
- workspaceId?: string,
) {
return Promise.all([
- invalidateHumanInputContactQueries(query, client, workspaceId),
+ invalidateHumanInputContactQueries(query, client),
invalidateQueryKeys(client, [
- workspaceId ? ['contacts', 'im-platform', `api:${workspaceId}`] : ['contacts', 'im-platform'],
query.workspaces.current.humanInput.v2.channels.key(),
query.workspaces.current.humanInput.v2.imIdentities.key(),
query.workspaces.current.humanInput.v2.imSyncRuns.key(),
diff --git a/web/service/human-input-submission.ts b/web/service/human-input-submission.ts
new file mode 100644
index 00000000000..b1908a9ee1c
--- /dev/null
+++ b/web/service/human-input-submission.ts
@@ -0,0 +1,21 @@
+export class HumanInputSubmissionPreparationError extends Error {
+ constructor() {
+ super('Human Input submission could not establish the workflow connection')
+ this.name = 'HumanInputSubmissionPreparationError'
+ }
+}
+
+export const prepareHumanInputFormSubmission = async (prepare: () => Promise<boolean>) => {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ const ready = await Promise.race([
+ prepare(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new HumanInputSubmissionPreparationError()), 15_000)
+ }),
+ ])
+ if (!ready) throw new HumanInputSubmissionPreparationError()
+ } finally {
+ clearTimeout(timer)
+ }
+}
diff --git a/web/service/share.ts b/web/service/share.ts
index b5393342f5e..260e981f76c 100644
--- a/web/service/share.ts
+++ b/web/service/share.ts
@@ -11,6 +11,7 @@ import type { AccessMode } from '@/models/access-control'
import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'
import type { HumanInputFormData as WorkflowHumanInputFormData } from '@/types/workflow'
import { form as webFormContract } from '@dify/contracts/api/web/orpc.gen'
+import { zWebAppHumanInputV2SubmitPayload } from '@dify/contracts/api/web/zod.gen'
import { createORPCClient } from '@orpc/client'
import { OpenAPILink } from '@orpc/openapi-client/fetch'
import { PUBLIC_API_PREFIX, WEB_APP_SHARE_CODE_HEADER_NAME } from '@/config'
@@ -783,8 +784,8 @@ export const submitHumanInputForm = (
if (formVersion === '2') {
return webAppHumanInputFormClient.submit({
params: { form_token: token },
- body: data,
+ body: zWebAppHumanInputV2SubmitPayload.parse(data),
})
}
- return post(`/form/human_input/${token}`, { body: data })
+ return post(`/form/human_input/${token}`, { body: { inputs: data.inputs, action: data.action } })
}
diff --git a/web/service/webapp-human-input.ts b/web/service/webapp-human-input.ts
deleted file mode 100644
index 1e732422a6a..00000000000
--- a/web/service/webapp-human-input.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { ContractRouterClient } from '@orpc/contract'
-import type { JsonifiedClient } from '@orpc/openapi-client'
-import { v2 as webAppHumanInputV2Contract } from '@dify/contracts/api/web/orpc.gen'
-import { zWebAppHumanInputV2SubmitPayload } from '@dify/contracts/api/web/zod.gen'
-import { createORPCClient } from '@orpc/client'
-import { OpenAPILink } from '@orpc/openapi-client/fetch'
-import { PUBLIC_API_PREFIX } from '@/config'
-// oxlint-disable-next-line no-restricted-imports -- Preserve Webapp passport, authorization recovery, and request error handling in the generated transport.
-import { request } from './base'
-import { submitHumanInputForm } from './share'
-import { getWebAppPublicApiPath, resolveWebAppAddress } from './webapp-address'
-
-const formContract = webAppHumanInputV2Contract.byFormToken
-const formClient: JsonifiedClient<ContractRouterClient<typeof formContract>> = createORPCClient(
- new OpenAPILink(formContract, {
- url: () => new URL(PUBLIC_API_PREFIX, window.location.origin),
- fetch: (input, init) => {
- const url = new URL(input.url)
- const prefix = new URL(PUBLIC_API_PREFIX, window.location.origin).pathname.replace(/\/$/, '')
- const path = url.pathname.slice(prefix.length)
- url.pathname = prefix + getWebAppPublicApiPath(resolveWebAppAddress(), path)
- const normalizedRequest = url.href === input.url ? input : new Request(url, input)
- // oxlint-disable-next-line typescript/no-deprecated -- The generated public form client needs the Web App transport's passport scope and authorization recovery.
- return request<Response>(url.href, init, {
- fetchCompat: true,
- request: normalizedRequest,
- isPublicAPI: true,
- })
- },
- }),
-)
-
-export async function submitWebAppHumanInputForm(
- formToken: string,
- data: Parameters<typeof submitHumanInputForm>[1],
- formVersion?: Parameters<typeof submitHumanInputForm>[2],
-) {
- if (formVersion !== '2') return submitHumanInputForm(formToken, data)
-
- return formClient.post({
- params: { form_token: formToken },
- body: zWebAppHumanInputV2SubmitPayload.parse(data),
- })
-}
diff --git a/web/service/workflow.ts b/web/service/workflow.ts
index 192326e7823..9b4c8adae29 100644
--- a/web/service/workflow.ts
+++ b/web/service/workflow.ts
@@ -10,6 +10,7 @@ import type {
} from '@/app/components/workflow/types'
import type { ConsoleClientContext } from '@/service/console'
import type { FetchWorkflowDraftResponse, HumanInputFormData, VarInInspect } from '@/types/workflow'
+import { zConsoleHumanInputV2SubmitPayload } from '@dify/contracts/api/console/form/zod.gen'
import { consoleClient } from '@/service/console'
import { get } from './base'
@@ -179,15 +180,22 @@ export const submitHumanInputForm = (
action: string
},
formVersion?: HumanInputFormData['form_version'],
+ context?: ConsoleClientContext,
) => {
if (formVersion === '2') {
- return consoleClient.form.humanInput.v2.byFormToken.post({
+ return consoleClient.form.humanInput.v2.byFormToken.post(
+ {
+ params: { form_token: token },
+ body: zConsoleHumanInputV2SubmitPayload.parse(data),
+ },
+ { context },
+ )
+ }
+ return consoleClient.form.humanInput.byFormToken.post(
+ {
params: { form_token: token },
body: data,
- })
- }
- return consoleClient.form.humanInput.byFormToken.post({
- params: { form_token: token },
- body: data,
- })
+ },
+ { context },
+ )
}
diff --git a/web/types/workflow.ts b/web/types/workflow.ts
index 1140fe7591e..f36cdf34dd8 100644
--- a/web/types/workflow.ts
+++ b/web/types/workflow.ts
@@ -345,7 +345,6 @@ export type AgentLogResponse = {
}
export type HumanInputFormData = {
- // Older conversation history predates the versioned form event contract.
form_version?: '1' | '2'
form_id: string
node_id: string
diff --git a/web/utils/__tests__/marketplace-site-track.spec.ts b/web/utils/__tests__/marketplace-site-track.spec.ts
index 56fe21af190..b24108302d4 100644
--- a/web/utils/__tests__/marketplace-site-track.spec.ts
+++ b/web/utils/__tests__/marketplace-site-track.spec.ts
@@ -3,11 +3,15 @@ import { trackMarketplaceSiteCardClick, trackMarketplaceSiteEvent } from '../mar
describe('marketplace site track bridge', () => {
afterEach(() => {
- document.body.removeAttribute('data-is-marketplace')
+ document.documentElement.removeAttribute('data-is-marketplace')
delete window.__marketplaceTracking__
})
- it('does not forward events outside the standalone marketplace', () => {
+ it.each([
+ ['without the host marker', undefined],
+ ['on the Dify console runtime dataset', 'false'],
+ ])('does not forward events %s', (_label, marker) => {
+ if (marker !== undefined) document.documentElement.setAttribute('data-is-marketplace', marker)
const track = vi.fn()
window.__marketplaceTracking__ = {
track,
@@ -26,7 +30,7 @@ describe('marketplace site track bridge', () => {
it('forwards events and card clicks on the standalone marketplace', () => {
const track = vi.fn()
const rememberReferrer = vi.fn()
- document.body.setAttribute('data-is-marketplace', '')
+ document.documentElement.setAttribute('data-is-marketplace', '')
window.__marketplaceTracking__ = {
track,
rememberReferrer,
diff --git a/web/utils/marketplace-site-track.ts b/web/utils/marketplace-site-track.ts
index 56c7b7f6a22..08e49ffe3fb 100644
--- a/web/utils/marketplace-site-track.ts
+++ b/web/utils/marketplace-site-track.ts
@@ -1,10 +1,10 @@
/**
* Standalone Marketplace host contract.
*
- * The Dify console never stamps `data-is-marketplace` or assigns
+ * The Dify console stamps `data-is-marketplace="false"` and never assigns
* `window.__marketplaceTracking__`, so every helper here is a no-op in a Dify
* build. The standalone marketplace (dify-marketplace) owns the producer: it
- * sets `data-is-marketplace` on `<body>` and injects `__marketplaceTracking__`
+ * sets `data-is-marketplace` on `<html>` and injects `__marketplaceTracking__`
* from its analytics runtime. Shared Marketplace UI calls these helpers; the
* host implements the bridge.
*/
@@ -17,9 +17,11 @@ type MarketplaceSiteFilter = {
selected_values: string[]
}
-const isMarketplaceSite = () =>
- typeof globalThis.document !== 'undefined' &&
- globalThis.document.body?.hasAttribute('data-is-marketplace')
+const isMarketplaceSite = () => {
+ if (typeof globalThis.document === 'undefined') return false
+ const value = globalThis.document.documentElement.dataset.isMarketplace
+ return value !== undefined && value !== 'false'
+}
const marketplaceTracking = () => globalThis.window.__marketplaceTracking__