chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+38
@@ -0,0 +1,38 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import ChatVariableButton from '../chat-variable-button'
|
||||
|
||||
describe('ChatVariableButton', () => {
|
||||
it('opens the chat variable panel and closes the other workflow panels', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<ChatVariableButton disabled={false} />, {
|
||||
initialStoreState: {
|
||||
showEnvPanel: true,
|
||||
showGlobalVariablePanel: true,
|
||||
showDebugAndPreviewPanel: true,
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.chatVariable.panelTitle' }))
|
||||
|
||||
expect(store.getState().showChatVariablePanel).toBe(true)
|
||||
expect(store.getState().showEnvPanel).toBe(false)
|
||||
expect(store.getState().showGlobalVariablePanel).toBe(false)
|
||||
expect(store.getState().showDebugAndPreviewPanel).toBe(false)
|
||||
})
|
||||
|
||||
it('stays disabled without mutating panel state', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<ChatVariableButton disabled />, {
|
||||
initialStoreState: {
|
||||
showChatVariablePanel: false,
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.chatVariable.panelTitle' }))
|
||||
|
||||
expect(screen.getByRole('button')).toBeDisabled()
|
||||
expect(store.getState().showChatVariablePanel).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { screen, within } from '@testing-library/react'
|
||||
import { createAccountProfileQueryClient } from '@/test/console/account-profile'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import EditingTitle from '../editing-title'
|
||||
|
||||
describe('EditingTitle', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime(new Date('2024-03-09T19:00:00.000Z'))
|
||||
})
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('should render autosave, published time, and syncing status when the draft has metadata', () => {
|
||||
renderWorkflowComponent(<EditingTitle />, {
|
||||
queryClient: createAccountProfileQueryClient({ timezone: 'UTC' }),
|
||||
initialStoreState: {
|
||||
draftUpdatedAt: 1_710_000_000_000,
|
||||
publishedAt: 1_710_003_600_000,
|
||||
isSyncingWorkflowDraft: true,
|
||||
},
|
||||
})
|
||||
|
||||
const saveStatus = screen.getByRole('status', {
|
||||
name: 'workflow.common.workflowSaveStatus',
|
||||
})
|
||||
const statusContent = within(saveStatus)
|
||||
|
||||
expect(statusContent.getByText('workflow.common.autoSaved')).toBeInTheDocument()
|
||||
expect(statusContent.getByText('workflow.common.published')).toBeInTheDocument()
|
||||
expect(statusContent.getByText('workflow.common.syncingData')).toBeInTheDocument()
|
||||
|
||||
const draftUpdatedTime = statusContent.getByText('16:00:00')
|
||||
const publishedTime = statusContent.getByText('2 hours ago')
|
||||
expect(draftUpdatedTime).toHaveAttribute('datetime', '2024-03-09T16:00:00.000Z')
|
||||
expect(publishedTime).toHaveAttribute('datetime', '2024-03-09T17:00:00.000Z')
|
||||
})
|
||||
|
||||
it('should expose autosave time separately from the unpublished status', () => {
|
||||
renderWorkflowComponent(<EditingTitle />, {
|
||||
queryClient: createAccountProfileQueryClient({ timezone: 'UTC' }),
|
||||
initialStoreState: {
|
||||
draftUpdatedAt: 1_710_000_000_000,
|
||||
publishedAt: 0,
|
||||
isSyncingWorkflowDraft: false,
|
||||
},
|
||||
})
|
||||
|
||||
const saveStatus = screen.getByRole('status', {
|
||||
name: 'workflow.common.workflowSaveStatus',
|
||||
})
|
||||
const statusContent = within(saveStatus)
|
||||
|
||||
expect(statusContent.getByText('workflow.common.autoSaved')).toBeInTheDocument()
|
||||
expect(statusContent.getByText('workflow.common.unpublished')).toBeInTheDocument()
|
||||
expect(statusContent.queryByText('workflow.common.syncingData')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createRagPipelineSliceSlice } from '@/app/components/rag-pipeline/store'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import EnvButton from '../env-button'
|
||||
|
||||
describe('EnvButton', () => {
|
||||
it('should open the environment panel and close the other panels when clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<EnvButton disabled={false} />, {
|
||||
injectWorkflowStoreSliceFn: createRagPipelineSliceSlice,
|
||||
initialStoreState: {
|
||||
showInputFieldPanel: true,
|
||||
showInputFieldPreviewPanel: true,
|
||||
inputFieldEditPanelProps: { onSubmit: () => {}, onClose: () => {} },
|
||||
showChatVariablePanel: true,
|
||||
showGlobalVariablePanel: true,
|
||||
showDebugAndPreviewPanel: true,
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.env.envPanelTitle' }))
|
||||
|
||||
expect(store.getState().showEnvPanel).toBe(true)
|
||||
expect(store.getState().showChatVariablePanel).toBe(false)
|
||||
expect(store.getState().showGlobalVariablePanel).toBe(false)
|
||||
expect(store.getState().showDebugAndPreviewPanel).toBe(false)
|
||||
expect(store.getState()).toMatchObject({
|
||||
showInputFieldPanel: false,
|
||||
showInputFieldPreviewPanel: false,
|
||||
inputFieldEditPanelProps: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('should keep the button disabled when the disabled prop is true', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<EnvButton disabled />, {
|
||||
injectWorkflowStoreSliceFn: createRagPipelineSliceSlice,
|
||||
initialStoreState: {
|
||||
showInputFieldPanel: true,
|
||||
showInputFieldPreviewPanel: true,
|
||||
inputFieldEditPanelProps: { onSubmit: () => {}, onClose: () => {} },
|
||||
showEnvPanel: false,
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.env.envPanelTitle' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'workflow.env.envPanelTitle' })).toBeDisabled()
|
||||
expect(store.getState().showEnvPanel).toBe(false)
|
||||
expect(store.getState()).toMatchObject({
|
||||
showInputFieldPanel: true,
|
||||
showInputFieldPreviewPanel: true,
|
||||
inputFieldEditPanelProps: expect.objectContaining({ onSubmit: expect.any(Function) }),
|
||||
})
|
||||
})
|
||||
})
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createRagPipelineSliceSlice } from '@/app/components/rag-pipeline/store'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import GlobalVariableButton from '../global-variable-button'
|
||||
|
||||
describe('GlobalVariableButton', () => {
|
||||
it('should open the global variable panel and close the other panels when clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<GlobalVariableButton disabled={false} />, {
|
||||
injectWorkflowStoreSliceFn: createRagPipelineSliceSlice,
|
||||
initialStoreState: {
|
||||
showInputFieldPanel: true,
|
||||
showInputFieldPreviewPanel: true,
|
||||
inputFieldEditPanelProps: { onSubmit: () => {}, onClose: () => {} },
|
||||
showEnvPanel: true,
|
||||
showChatVariablePanel: true,
|
||||
showDebugAndPreviewPanel: true,
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.globalVar.title' }))
|
||||
|
||||
expect(store.getState().showGlobalVariablePanel).toBe(true)
|
||||
expect(store.getState().showEnvPanel).toBe(false)
|
||||
expect(store.getState().showChatVariablePanel).toBe(false)
|
||||
expect(store.getState().showDebugAndPreviewPanel).toBe(false)
|
||||
expect(store.getState()).toMatchObject({
|
||||
showInputFieldPanel: false,
|
||||
showInputFieldPreviewPanel: false,
|
||||
inputFieldEditPanelProps: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('should keep the button disabled when the disabled prop is true', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<GlobalVariableButton disabled />, {
|
||||
injectWorkflowStoreSliceFn: createRagPipelineSliceSlice,
|
||||
initialStoreState: {
|
||||
showInputFieldPanel: true,
|
||||
showInputFieldPreviewPanel: true,
|
||||
inputFieldEditPanelProps: { onSubmit: () => {}, onClose: () => {} },
|
||||
showGlobalVariablePanel: false,
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.globalVar.title' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'workflow.globalVar.title' })).toBeDisabled()
|
||||
expect(store.getState().showGlobalVariablePanel).toBe(false)
|
||||
expect(store.getState()).toMatchObject({
|
||||
showInputFieldPanel: true,
|
||||
showInputFieldPreviewPanel: true,
|
||||
inputFieldEditPanelProps: expect.objectContaining({ onSubmit: expect.any(Function) }),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,432 @@
|
||||
import type { Shape } from '../../store/workflow'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { createAccountProfileQueryClient } from '@/test/console/account-profile'
|
||||
import { seedModelProviderQueries } from '@/test/console/model-provider'
|
||||
import {
|
||||
createConsoleQueryWrapper,
|
||||
seedAppDslVersion,
|
||||
seedSystemFeatures,
|
||||
} from '@/test/console/query-data'
|
||||
import { seedToolProviders } from '@/test/console/tool-providers'
|
||||
import { createWorkflowResponseFixture } from '@/test/fixtures/workflow-response'
|
||||
import { createStartNode } from '../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { collaborationManager } from '../../collaboration/core/collaboration-manager'
|
||||
import DatasetsDetailProvider from '../../datasets-detail-store/provider'
|
||||
import { WorkflowVersion } from '../../types'
|
||||
import HeaderInNormal from '../header-in-normal'
|
||||
import HeaderInRestoring from '../header-in-restoring'
|
||||
import HeaderInHistory from '../header-in-view-history'
|
||||
|
||||
const mockHandleBackupDraft = vi.fn()
|
||||
const mockHandleLoadBackupDraft = vi.fn()
|
||||
const mockHandleRefreshWorkflowDraft = vi.fn()
|
||||
const mockRestoreWorkflow = vi.fn()
|
||||
const mockNotify = vi.fn()
|
||||
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'apps.byAppId.workflows.byWorkflowId.restore.post': (input) =>
|
||||
mockRestoreWorkflow('app', input),
|
||||
'rag.pipelines.byPipelineId.workflows.byWorkflowId.restore.post': (input) =>
|
||||
mockRestoreWorkflow('pipeline', input),
|
||||
'snippets.bySnippetId.workflows.byWorkflowId.restore.post': (input) =>
|
||||
mockRestoreWorkflow('snippet', input),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/app/notifications', () => ({
|
||||
toast: {
|
||||
success: (message: string) => mockNotify({ type: 'success', message }),
|
||||
error: (message: string) => mockNotify({ type: 'error', message }),
|
||||
warning: (message: string) => mockNotify({ type: 'warning', message }),
|
||||
info: (message: string) => mockNotify({ type: 'info', message }),
|
||||
},
|
||||
}))
|
||||
|
||||
const createBackupDraft = (): NonNullable<Shape['backupDraft']> => ({
|
||||
nodes: [],
|
||||
edges: [],
|
||||
viewport: { x: 0, y: 0, zoom: 1 },
|
||||
environmentVariables: [],
|
||||
})
|
||||
|
||||
const createCurrentVersion = (): NonNullable<Shape['currentVersion']> => ({
|
||||
id: 'version-1',
|
||||
graph: {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
viewport: { x: 0, y: 0, zoom: 1 },
|
||||
},
|
||||
created_at: 0,
|
||||
created_by: {
|
||||
id: 'user-1',
|
||||
name: 'Tester',
|
||||
email: 'tester@example.com',
|
||||
},
|
||||
hash: 'hash-1',
|
||||
updated_at: 0,
|
||||
updated_by: {
|
||||
id: 'user-1',
|
||||
name: 'Tester',
|
||||
email: 'tester@example.com',
|
||||
},
|
||||
tool_published: false,
|
||||
environment_variables: [],
|
||||
version: WorkflowVersion.Latest,
|
||||
version_number: 5,
|
||||
marked_name: '',
|
||||
marked_comment: '',
|
||||
})
|
||||
|
||||
describe('Header layout components', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.spyOn(collaborationManager, 'emitRestoreIntent').mockImplementation(() => {})
|
||||
vi.spyOn(collaborationManager, 'emitRestoreComplete').mockImplementation(() => {})
|
||||
vi.spyOn(collaborationManager, 'emitWorkflowUpdate').mockImplementation(() => {})
|
||||
mockRestoreWorkflow.mockReset().mockResolvedValue(createWorkflowResponseFixture())
|
||||
})
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
describe('HeaderInNormal', () => {
|
||||
it('opens version history, backs up the draft, and closes editing panels', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
const { store } = renderWorkflowComponent(<HeaderInNormal />, {
|
||||
nodes: [createStartNode({ id: 'node-selected', data: { selected: true } })],
|
||||
initialStoreState: {
|
||||
showEnvPanel: true,
|
||||
showDebugAndPreviewPanel: true,
|
||||
showVariableInspectPanel: true,
|
||||
showChatVariablePanel: true,
|
||||
showGlobalVariablePanel: true,
|
||||
},
|
||||
})
|
||||
|
||||
expect(
|
||||
screen.getByRole('status', { name: 'workflow.common.workflowSaveStatus' }),
|
||||
).toBeVisible()
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'workflow.panel.scrollToSelectedNode' }),
|
||||
).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'workflow.env.envPanelTitle' })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: 'workflow.globalVar.title' })).toBeEnabled()
|
||||
expect(screen.getByRole('button', { name: 'workflow.common.viewRunHistory' })).toBeVisible()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.versionHistory' }))
|
||||
|
||||
expect(mockHandleBackupDraft).toHaveBeenCalledTimes(1)
|
||||
expect(store.getState().isRestoring).toBe(true)
|
||||
expect(store.getState().showWorkflowVersionHistoryPanel).toBe(true)
|
||||
expect(screen.getByRole('button', { name: 'workflow.env.envPanelTitle' })).toHaveAttribute(
|
||||
'aria-expanded',
|
||||
'false',
|
||||
)
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.panel.scrollToSelectedNode' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(store.getState().showDebugAndPreviewPanel).toBe(false)
|
||||
expect(store.getState().showVariableInspectPanel).toBe(false)
|
||||
expect(store.getState().showChatVariablePanel).toBe(false)
|
||||
expect(screen.getByRole('button', { name: 'workflow.globalVar.title' })).toHaveAttribute(
|
||||
'aria-expanded',
|
||||
'false',
|
||||
)
|
||||
})
|
||||
|
||||
it('disables variable editing on a read-only canvas', () => {
|
||||
renderWorkflowComponent(<HeaderInNormal />, { initialStoreState: { canvasReadOnly: true } })
|
||||
expect(screen.getByRole('button', { name: 'workflow.env.envPanelTitle' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'workflow.globalVar.title' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('should hide env and global variable buttons when the controls are disabled', () => {
|
||||
renderWorkflowComponent(
|
||||
<HeaderInNormal
|
||||
controls={{
|
||||
showEnvButton: false,
|
||||
showGlobalVariableButton: false,
|
||||
}}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.env.envPanelTitle' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.globalVar.title' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('HeaderInRestoring', () => {
|
||||
it('disables restoring an unpublished draft', () => {
|
||||
renderWorkflowComponent(<HeaderInRestoring />, {
|
||||
initialStoreState: {
|
||||
currentVersion: { ...createCurrentVersion(), version: WorkflowVersion.Draft },
|
||||
},
|
||||
})
|
||||
expect(screen.getByRole('button', { name: 'workflow.common.restore' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('opens the upgrade dialog without restoring for a Cloud sandbox workspace', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { queryClient } = createConsoleQueryWrapper({
|
||||
systemFeatures: { deployment_edition: 'CLOUD' },
|
||||
features: { billing: { subscription: { plan: 'sandbox' } } },
|
||||
})
|
||||
renderWorkflowComponent(<HeaderInRestoring />, {
|
||||
queryClient,
|
||||
initialStoreState: { currentVersion: createCurrentVersion() },
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
|
||||
expect(
|
||||
await screen.findByRole('dialog', { name: 'billing.upgrade.workflowRestore.title' }),
|
||||
).toBeVisible()
|
||||
expect(mockRestoreWorkflow).not.toHaveBeenCalled()
|
||||
expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should cancel restoring mode and reopen the editor state', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(<HeaderInRestoring />, {
|
||||
initialStoreState: {
|
||||
isRestoring: true,
|
||||
showWorkflowVersionHistoryPanel: true,
|
||||
},
|
||||
resource: { kind: 'app' as const, appId: 'flow-1', mode: 'workflow' as const },
|
||||
hooksStoreProps: {
|
||||
fileSettings: {},
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.exitVersions' }))
|
||||
|
||||
expect(mockHandleLoadBackupDraft).toHaveBeenCalledTimes(1)
|
||||
expect(store.getState().isRestoring).toBe(false)
|
||||
expect(store.getState().showWorkflowVersionHistoryPanel).toBe(false)
|
||||
})
|
||||
|
||||
it('should restore the selected version, clear backup state, and forward lifecycle callbacks', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onRestoreSettled = vi.fn()
|
||||
const deleteAllInspectVars = vi.fn()
|
||||
const currentVersion = createCurrentVersion()
|
||||
const currentUser = { id: 'user-1', name: 'Alice' }
|
||||
const queryClient = createAccountProfileQueryClient(currentUser)
|
||||
seedSystemFeatures(queryClient)
|
||||
|
||||
const { store } = renderWorkflowComponent(
|
||||
<HeaderInRestoring onRestoreSettled={onRestoreSettled} />,
|
||||
{
|
||||
initialStoreState: {
|
||||
isRestoring: true,
|
||||
showWorkflowVersionHistoryPanel: true,
|
||||
backupDraft: createBackupDraft(),
|
||||
currentVersion,
|
||||
deleteAllInspectVars,
|
||||
},
|
||||
resource: { kind: 'app' as const, appId: 'flow-1', mode: 'workflow' as const },
|
||||
hooksStoreProps: {
|
||||
fileSettings: {},
|
||||
},
|
||||
queryClient,
|
||||
},
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRestoreWorkflow).toHaveBeenCalledWith('app', {
|
||||
params: { app_id: 'flow-1', workflow_id: 'version-1' },
|
||||
})
|
||||
expect(store.getState().showWorkflowVersionHistoryPanel).toBe(false)
|
||||
expect(store.getState().isRestoring).toBe(false)
|
||||
expect(store.getState().backupDraft).toBeUndefined()
|
||||
expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(1)
|
||||
expect(deleteAllInspectVars).toHaveBeenCalledTimes(1)
|
||||
expect(mockNotify).toHaveBeenCalledWith({
|
||||
type: 'success',
|
||||
message: 'workflowHistory.versionHistory.action.restoreSuccess',
|
||||
})
|
||||
})
|
||||
expect(collaborationManager.emitRestoreIntent).toHaveBeenCalledWith({
|
||||
versionId: currentVersion.id,
|
||||
versionName: '# 5',
|
||||
initiatorUserId: currentUser.id,
|
||||
initiatorName: currentUser.name,
|
||||
})
|
||||
expect(collaborationManager.emitRestoreComplete).toHaveBeenCalledWith({
|
||||
versionId: currentVersion.id,
|
||||
success: true,
|
||||
})
|
||||
expect(collaborationManager.emitWorkflowUpdate).toHaveBeenCalledWith('flow-1')
|
||||
expect(onRestoreSettled).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the draft recoverable and reports failure when restoration is rejected', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockRestoreWorkflow.mockRejectedValueOnce(new Error('Restore failed'))
|
||||
const backupDraft = createBackupDraft()
|
||||
const onRestoreSettled = vi.fn()
|
||||
const { store } = renderWorkflowComponent(
|
||||
<HeaderInRestoring onRestoreSettled={onRestoreSettled} />,
|
||||
{
|
||||
initialStoreState: {
|
||||
isRestoring: true,
|
||||
backupDraft,
|
||||
currentVersion: createCurrentVersion(),
|
||||
},
|
||||
resource: { kind: 'app', appId: 'flow-1', mode: 'workflow' },
|
||||
},
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
|
||||
|
||||
await waitFor(() => expect(onRestoreSettled).toHaveBeenCalledTimes(1))
|
||||
expect(store.getState().isRestoring).toBe(true)
|
||||
expect(store.getState().backupDraft).toEqual(backupDraft)
|
||||
expect(mockHandleRefreshWorkflowDraft).not.toHaveBeenCalled()
|
||||
expect(collaborationManager.emitWorkflowUpdate).not.toHaveBeenCalled()
|
||||
expect(collaborationManager.emitRestoreComplete).toHaveBeenCalledWith({
|
||||
versionId: 'version-1',
|
||||
success: false,
|
||||
error: 'restore failed',
|
||||
})
|
||||
expect(mockNotify).toHaveBeenCalledWith({
|
||||
type: 'error',
|
||||
message: 'workflowHistory.versionHistory.action.restoreFailure',
|
||||
})
|
||||
})
|
||||
|
||||
it('should restore rag pipeline versions without emitting collaboration events', async () => {
|
||||
const user = userEvent.setup()
|
||||
const currentVersion = createCurrentVersion()
|
||||
|
||||
renderWorkflowComponent(<HeaderInRestoring />, {
|
||||
initialStoreState: {
|
||||
isRestoring: true,
|
||||
showWorkflowVersionHistoryPanel: true,
|
||||
backupDraft: createBackupDraft(),
|
||||
currentVersion,
|
||||
},
|
||||
resource: { kind: 'knowledge-pipeline' as const, pipelineId: 'pipeline-1' },
|
||||
hooksStoreProps: {
|
||||
fileSettings: {},
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRestoreWorkflow).toHaveBeenCalledWith('pipeline', {
|
||||
params: { pipeline_id: 'pipeline-1', workflow_id: 'version-1' },
|
||||
})
|
||||
expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(collaborationManager.emitRestoreIntent).not.toHaveBeenCalled()
|
||||
expect(collaborationManager.emitRestoreComplete).not.toHaveBeenCalled()
|
||||
expect(collaborationManager.emitWorkflowUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should restore snippet versions through snippet routes without emitting collaboration events', async () => {
|
||||
const user = userEvent.setup()
|
||||
const currentVersion = createCurrentVersion()
|
||||
|
||||
renderWorkflowComponent(<HeaderInRestoring />, {
|
||||
initialStoreState: {
|
||||
isRestoring: true,
|
||||
showWorkflowVersionHistoryPanel: true,
|
||||
backupDraft: createBackupDraft(),
|
||||
currentVersion,
|
||||
},
|
||||
resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },
|
||||
hooksStoreProps: {
|
||||
fileSettings: {},
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.restore' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockRestoreWorkflow).toHaveBeenCalledWith('snippet', {
|
||||
params: { snippet_id: 'snippet-1', workflow_id: 'version-1' },
|
||||
})
|
||||
expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(collaborationManager.emitRestoreIntent).not.toHaveBeenCalled()
|
||||
expect(collaborationManager.emitRestoreComplete).not.toHaveBeenCalled()
|
||||
expect(collaborationManager.emitWorkflowUpdate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('HeaderInHistory', () => {
|
||||
it('exits run history and restores the backup draft', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { store } = renderWorkflowComponent(
|
||||
<HeaderInHistory viewHistoryProps={{ historyUrl: '/history' }} />,
|
||||
{
|
||||
initialStoreState: {
|
||||
historyWorkflowData: {
|
||||
id: 'history-1',
|
||||
status: 'succeeded',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(screen.getByText('workflow.common.viewOnly')).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'workflow.common.showRunHistory' })).toBeVisible()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.goBackToEdit' }))
|
||||
|
||||
expect(mockHandleLoadBackupDraft).toHaveBeenCalledTimes(1)
|
||||
expect(store.getState().historyWorkflowData).toBeUndefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function renderWorkflowComponent(
|
||||
ui: Parameters<typeof renderWorkflowFlowComponent>[0],
|
||||
options: Parameters<typeof renderWorkflowFlowComponent>[1] = {},
|
||||
) {
|
||||
const { queryClient } = createConsoleQueryWrapper({ queryClient: options.queryClient })
|
||||
seedAppDslVersion(queryClient)
|
||||
queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
|
||||
seedModelProviderQueries(queryClient)
|
||||
seedToolProviders(queryClient, {
|
||||
builtInTools: [],
|
||||
customTools: [],
|
||||
workflowTools: [],
|
||||
mcpTools: [],
|
||||
})
|
||||
queryClient.setQueryData(consoleQuery.workspaces.current.agentProviders.get.queryKey(), [])
|
||||
queryClient.setQueryData(consoleQuery.workspaces.current.triggers.get.queryKey({ input: {} }), [])
|
||||
const nodes = options.nodes ?? []
|
||||
return renderWorkflowFlowComponent(
|
||||
<NuqsTestingAdapter>
|
||||
<DatasetsDetailProvider nodes={nodes}>{ui}</DatasetsDetailProvider>
|
||||
</NuqsTestingAdapter>,
|
||||
{
|
||||
...options,
|
||||
queryClient,
|
||||
nodes,
|
||||
hooksStoreProps: {
|
||||
handleBackupDraft: mockHandleBackupDraft,
|
||||
handleLoadBackupDraft: mockHandleLoadBackupDraft,
|
||||
handleRefreshWorkflowDraft: mockHandleRefreshWorkflowDraft,
|
||||
...options.hooksStoreProps,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import { ReactFlowProvider } from 'reactflow'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import Record from '../../panel/record'
|
||||
import RunningTitle from '../running-title'
|
||||
|
||||
vi.mock('../../hooks/use-workflow', () => ({
|
||||
useIsChatMode: () => false,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/workflow/run', () => ({
|
||||
default: () => null,
|
||||
}))
|
||||
|
||||
describe('Paused workflow history titles', () => {
|
||||
it.each([
|
||||
{ name: 'history header', Component: RunningTitle },
|
||||
{ name: 'run detail panel', Component: Record },
|
||||
])('shows the persisted paused state in the $name', ({ Component }) => {
|
||||
renderWorkflowComponent(
|
||||
<ReactFlowProvider>
|
||||
<Component />
|
||||
</ReactFlowProvider>,
|
||||
{
|
||||
initialStoreState: {
|
||||
historyWorkflowData: { id: 'paused-run', status: 'paused' },
|
||||
},
|
||||
hooksStoreProps: {
|
||||
getWorkflowRunAndTraceUrl: () => ({
|
||||
runUrl: '/runs/paused-run',
|
||||
traceUrl: '/runs/paused-run/trace',
|
||||
}),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
expect(screen.getByText('Test Run (Paused)')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Test Run (Running)')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { WorkflowVersion } from '../../types'
|
||||
import RestoringTitle from '../restoring-title'
|
||||
|
||||
const mockFormatTime = vi.fn()
|
||||
const mockFormatTimeFromNow = vi.fn()
|
||||
|
||||
vi.mock('@/hooks/use-timestamp', () => ({
|
||||
default: () => ({
|
||||
formatTime: mockFormatTime,
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/use-format-time-from-now', () => ({
|
||||
useFormatTimeFromNow: () => ({
|
||||
formatTimeFromNow: mockFormatTimeFromNow,
|
||||
}),
|
||||
}))
|
||||
|
||||
const createVersion = (
|
||||
overrides: Partial<FetchWorkflowDraftResponse> = {},
|
||||
): FetchWorkflowDraftResponse => ({
|
||||
id: 'version-1',
|
||||
graph: {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
},
|
||||
created_at: 1_700_000_000,
|
||||
created_by: {
|
||||
id: 'user-1',
|
||||
name: 'Alice',
|
||||
email: 'alice@example.com',
|
||||
},
|
||||
hash: 'hash-1',
|
||||
updated_at: 1_700_000_100,
|
||||
updated_by: {
|
||||
id: 'user-2',
|
||||
name: 'Bob',
|
||||
email: 'bob@example.com',
|
||||
},
|
||||
tool_published: false,
|
||||
version: 'v1',
|
||||
marked_name: 'Release 1',
|
||||
marked_comment: '',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('RestoringTitle', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockFormatTime.mockReturnValue('09:30:00')
|
||||
mockFormatTimeFromNow.mockReturnValue('3 hours ago')
|
||||
})
|
||||
|
||||
it('should render draft metadata when the current version is a draft', () => {
|
||||
const currentVersion = createVersion({
|
||||
version: WorkflowVersion.Draft,
|
||||
})
|
||||
|
||||
const { container } = renderWorkflowComponent(<RestoringTitle />, {
|
||||
initialStoreState: {
|
||||
currentVersion,
|
||||
},
|
||||
})
|
||||
|
||||
expect(mockFormatTimeFromNow).toHaveBeenCalledWith(currentVersion.updated_at * 1000)
|
||||
expect(mockFormatTime).toHaveBeenCalledWith(currentVersion.created_at, 'HH:mm:ss')
|
||||
expect(container).toHaveTextContent('workflowHistory.versionHistory.currentDraft')
|
||||
expect(container).toHaveTextContent('workflow.common.viewOnly')
|
||||
expect(container).toHaveTextContent('workflow.common.unpublished')
|
||||
expect(container).toHaveTextContent('3 hours ago 09:30:00')
|
||||
expect(container).toHaveTextContent('Alice')
|
||||
})
|
||||
|
||||
it('should render published metadata and fallback version name when the marked name is empty', () => {
|
||||
const currentVersion = createVersion({
|
||||
marked_name: '',
|
||||
})
|
||||
|
||||
const { container } = renderWorkflowComponent(<RestoringTitle />, {
|
||||
initialStoreState: {
|
||||
currentVersion,
|
||||
},
|
||||
})
|
||||
|
||||
expect(mockFormatTimeFromNow).toHaveBeenCalledWith(currentVersion.created_at * 1000)
|
||||
expect(container).toHaveTextContent('workflowHistory.versionHistory.defaultName')
|
||||
expect(container).toHaveTextContent('workflow.common.published')
|
||||
expect(container).toHaveTextContent('Alice')
|
||||
})
|
||||
|
||||
it('should render the version number when the marked name is empty', () => {
|
||||
const currentVersion = createVersion({
|
||||
marked_name: '',
|
||||
version_number: 5,
|
||||
})
|
||||
|
||||
const { container } = renderWorkflowComponent(<RestoringTitle />, {
|
||||
initialStoreState: {
|
||||
currentVersion,
|
||||
},
|
||||
})
|
||||
|
||||
expect(container).toHaveTextContent('# 5')
|
||||
expect(container).not.toHaveTextContent('workflowHistory.versionHistory.defaultName')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { fullWorkflowAccessControl } from '../../hooks-store/store'
|
||||
import RunAndHistory from '../run-and-history'
|
||||
|
||||
vi.mock('../view-history', () => ({ default: () => null }))
|
||||
vi.mock('../checklist', () => ({ default: () => null }))
|
||||
|
||||
it('passes denied run permission to a custom run control', async () => {
|
||||
const user = userEvent.setup()
|
||||
const startRun = vi.fn()
|
||||
const CustomRunMode = ({ text, disabled }: { text?: string; disabled?: boolean }) => (
|
||||
<button type="button" disabled={disabled} onClick={startRun}>
|
||||
{text}
|
||||
</button>
|
||||
)
|
||||
renderWorkflowComponent(
|
||||
<RunAndHistory
|
||||
showRunButton
|
||||
runButtonText="Test Run"
|
||||
components={{ RunMode: CustomRunMode }}
|
||||
/>,
|
||||
{
|
||||
hooksStoreProps: { accessControl: { ...fullWorkflowAccessControl, canRun: false } },
|
||||
},
|
||||
)
|
||||
|
||||
const run = screen.getByRole('button', { name: 'Test Run' })
|
||||
expect(run).toBeDisabled()
|
||||
await user.click(run)
|
||||
expect(startRun).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps preview visible but prevents starting it when run permission is denied', async () => {
|
||||
const user = userEvent.setup()
|
||||
const startPreview = vi.fn()
|
||||
renderWorkflowComponent(<RunAndHistory showPreviewButton />, {
|
||||
hooksStoreProps: {
|
||||
accessControl: { ...fullWorkflowAccessControl, canRun: false },
|
||||
handleWorkflowStartRunInChatflow: startPreview,
|
||||
},
|
||||
})
|
||||
|
||||
const preview = screen.getByRole('button', { name: 'workflow.common.debugAndPreview' })
|
||||
expect(preview).toBeDisabled()
|
||||
await user.click(preview)
|
||||
expect(startPreview).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { TestRunOptions } from '../test-run-menu'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { trackEvent } from '@/app/components/base/amplitude'
|
||||
import { toast } from '@/app/notifications'
|
||||
import {
|
||||
baseRunningData,
|
||||
renderWorkflowComponent as renderWithStores,
|
||||
} from '../../__tests__/workflow-test-env'
|
||||
import { fullWorkflowAccessControl } from '../../hooks-store/store'
|
||||
import RunMode from '../run-mode'
|
||||
import { TriggerType } from '../test-run-menu'
|
||||
|
||||
const mockHandleWorkflowStartRunInWorkflow = vi.fn()
|
||||
const mockHandleWorkflowTriggerScheduleRunInWorkflow = vi.fn()
|
||||
const mockHandleWorkflowTriggerWebhookRunInWorkflow = vi.fn()
|
||||
const mockHandleWorkflowTriggerPluginRunInWorkflow = vi.fn()
|
||||
const mockHandleWorkflowRunAllTriggersInWorkflow = vi.fn()
|
||||
const mockHandleStopRun = vi.fn()
|
||||
let mockWarningNodes: Array<{ id: string }> = []
|
||||
let mockDynamicOptions: TestRunOptions
|
||||
|
||||
vi.mock('../../hooks/use-checklist', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../hooks/use-checklist')>()
|
||||
|
||||
return {
|
||||
...actual,
|
||||
useWorkflowRunValidation: () => ({
|
||||
warningNodes: mockWarningNodes,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
// Start and stop handlers reach RunMode through the hooks store, exactly as the app wires them.
|
||||
const renderWorkflowComponent = (...[ui, options]: Parameters<typeof renderWithStores>) =>
|
||||
renderWithStores(ui, {
|
||||
...options,
|
||||
hooksStoreProps: {
|
||||
handleWorkflowStartRunInWorkflow: mockHandleWorkflowStartRunInWorkflow,
|
||||
handleWorkflowTriggerScheduleRunInWorkflow: mockHandleWorkflowTriggerScheduleRunInWorkflow,
|
||||
handleWorkflowTriggerWebhookRunInWorkflow: mockHandleWorkflowTriggerWebhookRunInWorkflow,
|
||||
handleWorkflowTriggerPluginRunInWorkflow: mockHandleWorkflowTriggerPluginRunInWorkflow,
|
||||
handleWorkflowRunAllTriggersInWorkflow: mockHandleWorkflowRunAllTriggersInWorkflow,
|
||||
handleStopRun: mockHandleStopRun,
|
||||
...options?.hooksStoreProps,
|
||||
},
|
||||
})
|
||||
|
||||
// Checklist validation and trigger discovery derive from the graph and have their own suites.
|
||||
vi.mock('../../hooks/use-dynamic-test-run-options', () => ({
|
||||
useDynamicTestRunOptions: () => mockDynamicOptions,
|
||||
}))
|
||||
vi.mock('@/app/components/base/amplitude', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/app/components/base/amplitude')>()),
|
||||
trackEvent: vi.fn(),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockWarningNodes = []
|
||||
mockDynamicOptions = {
|
||||
userInput: {
|
||||
id: 'start',
|
||||
type: TriggerType.UserInput,
|
||||
name: 'User input',
|
||||
nodeId: 'start-node',
|
||||
icon: null,
|
||||
enabled: true,
|
||||
},
|
||||
triggers: [],
|
||||
}
|
||||
})
|
||||
|
||||
it('starts the sole user-input option from the real run button', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWorkflowComponent(<RunMode />)
|
||||
await user.click(screen.getByRole('button', { name: /workflow.common.run/ }))
|
||||
expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledOnce()
|
||||
expect(trackEvent).toHaveBeenCalledWith('app_start_action_time', { action_type: 'user_input' })
|
||||
})
|
||||
|
||||
it('reports checklist warnings without starting the selected trigger', async () => {
|
||||
const user = userEvent.setup()
|
||||
const error = vi.spyOn(toast, 'error')
|
||||
mockWarningNodes = [{ id: 'start-node' }]
|
||||
renderWorkflowComponent(<RunMode />)
|
||||
await user.click(screen.getByRole('button', { name: /workflow.common.run/ }))
|
||||
expect(error).toHaveBeenCalledWith('workflow.panel.checklistTip')
|
||||
expect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([false, true])('stops the active task while listening=%s', async (isListening) => {
|
||||
const user = userEvent.setup()
|
||||
renderWorkflowComponent(<RunMode />, {
|
||||
initialStoreState: { workflowRunningData: baseRunningData(), isListening },
|
||||
})
|
||||
expect(screen.getByRole('button', { name: isListening ? /listening/ : /running/ })).toBeDisabled()
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'workflowDebug.debug.variableInspect.trigger.stop' }),
|
||||
)
|
||||
expect(mockHandleStopRun).toHaveBeenCalledExactlyOnceWith('task-1')
|
||||
})
|
||||
|
||||
it('opens the real menu with the page shortcut, ignores repeats and inputs, and runs the chosen trigger', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockDynamicOptions.triggers = [
|
||||
{
|
||||
id: 'schedule',
|
||||
type: TriggerType.Schedule,
|
||||
name: 'Daily schedule',
|
||||
nodeId: 'schedule-node',
|
||||
icon: null,
|
||||
enabled: true,
|
||||
},
|
||||
]
|
||||
const { rerender } = renderWorkflowComponent(
|
||||
<>
|
||||
<RunMode />
|
||||
<input aria-label="Prompt" />
|
||||
<button onKeyDown={(event) => event.preventDefault()}>Local control</button>
|
||||
</>,
|
||||
)
|
||||
await user.keyboard('{Alt>}{r>3/}{/Alt}')
|
||||
expect(screen.getByRole('menu')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('menuitem', { name: /Daily schedule/ }))
|
||||
expect(mockHandleWorkflowTriggerScheduleRunInWorkflow).toHaveBeenCalledExactlyOnceWith(
|
||||
'schedule-node',
|
||||
)
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('textbox', { name: 'Prompt' }))
|
||||
await user.keyboard('{Alt>}r{/Alt}')
|
||||
await user.click(screen.getByRole('button', { name: 'Local control' }))
|
||||
await user.keyboard('{Alt>}r{/Alt}')
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
rerender(<RunMode disabled />)
|
||||
await user.keyboard('{Alt>}r{/Alt}')
|
||||
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('blocks clicks and shortcuts when run permission is denied, including during an active run', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWorkflowComponent(<RunMode />, {
|
||||
initialStoreState: { workflowRunningData: baseRunningData() },
|
||||
hooksStoreProps: { accessControl: { ...fullWorkflowAccessControl, canRun: false } },
|
||||
})
|
||||
const run = screen.getByRole('button', { name: /workflow.common.run/ })
|
||||
expect(run).toBeDisabled()
|
||||
await user.click(run)
|
||||
await user.keyboard('{Alt>}r{/Alt}')
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflowDebug.debug.variableInspect.trigger.stop' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()
|
||||
expect(mockHandleStopRun).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import RunningTitle from '../running-title'
|
||||
|
||||
describe('RunningTitle', () => {
|
||||
it('shows the completed run time in the read-only workflow header', () => {
|
||||
const finishedAt = new Date(2026, 0, 15, 14, 30, 25).getTime() / 1000
|
||||
renderWorkflowComponent(<RunningTitle />, {
|
||||
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
|
||||
initialStoreState: {
|
||||
historyWorkflowData: { id: 'history-1', status: 'succeeded', finished_at: finishedAt },
|
||||
},
|
||||
})
|
||||
|
||||
expect(screen.getByText(/Test Run \((14|02):30:25( PM)?\)/)).toBeInTheDocument()
|
||||
expect(screen.getByText('workflow.common.viewOnly')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('identifies an unfinished chat run without inventing a completion time', () => {
|
||||
renderWorkflowComponent(<RunningTitle />, {
|
||||
resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' },
|
||||
initialStoreState: { historyWorkflowData: { id: 'history-2', status: 'running' } },
|
||||
})
|
||||
|
||||
expect(screen.getByText('Test Chat (Running)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each(['workflow', 'advanced-chat'] as const)(
|
||||
'shows paused history in %s mode without a completion time',
|
||||
(mode) => {
|
||||
renderWorkflowComponent(<RunningTitle />, {
|
||||
resource: { kind: 'app', appId: 'app-1', mode },
|
||||
initialStoreState: { historyWorkflowData: { id: 'history-paused', status: 'paused' } },
|
||||
})
|
||||
|
||||
expect(
|
||||
screen.getByText(`Test ${mode === 'advanced-chat' ? 'Chat' : 'Run'} (Paused)`),
|
||||
).toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
})
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createNode } from '../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
|
||||
import ScrollToSelectedNodeButton from '../scroll-to-selected-node-button'
|
||||
|
||||
it('hides the navigation action when no node is selected', () => {
|
||||
renderWorkflowFlowComponent(<ScrollToSelectedNodeButton />, {
|
||||
nodes: [createNode({ id: 'node-1', data: { selected: false } })],
|
||||
})
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.panel.scrollToSelectedNode' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('dispatches a scroll request for the selected node', async () => {
|
||||
const user = userEvent.setup()
|
||||
const scroll = vi.fn()
|
||||
document.addEventListener('workflow:scroll-to-node', scroll)
|
||||
try {
|
||||
renderWorkflowFlowComponent(<ScrollToSelectedNodeButton />, {
|
||||
nodes: [
|
||||
createNode({ id: 'node-1', data: { selected: false } }),
|
||||
createNode({ id: 'node-2', data: { selected: true } }),
|
||||
],
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.panel.scrollToSelectedNode' }))
|
||||
expect(scroll).toHaveBeenCalledOnce()
|
||||
expect(scroll.mock.calls[0]![0].detail).toEqual({ nodeId: 'node-2' })
|
||||
} finally {
|
||||
document.removeEventListener('workflow:scroll-to-node', scroll)
|
||||
}
|
||||
})
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { getNormalizedShortcutKey, SingleOptionTrigger } from '../test-run-menu-helpers'
|
||||
|
||||
describe('test-run-menu helpers', () => {
|
||||
it('should normalize shortcut keys', () => {
|
||||
expect(getNormalizedShortcutKey(new KeyboardEvent('keydown', { key: '`' }))).toBe('~')
|
||||
expect(getNormalizedShortcutKey(new KeyboardEvent('keydown', { key: '1' }))).toBe('1')
|
||||
})
|
||||
|
||||
it('should run single options for element and non-element children unless the click is prevented', async () => {
|
||||
const user = userEvent.setup()
|
||||
const runSoleOption = vi.fn()
|
||||
const originalOnClick = vi.fn()
|
||||
|
||||
const { rerender } = render(
|
||||
<SingleOptionTrigger runSoleOption={runSoleOption}>Open directly</SingleOptionTrigger>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Open directly'))
|
||||
expect(runSoleOption).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender(
|
||||
<SingleOptionTrigger runSoleOption={runSoleOption}>
|
||||
<button onClick={originalOnClick}>Child trigger</button>
|
||||
</SingleOptionTrigger>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Child trigger' }))
|
||||
expect(originalOnClick).toHaveBeenCalledTimes(1)
|
||||
expect(runSoleOption).toHaveBeenCalledTimes(2)
|
||||
|
||||
rerender(
|
||||
<SingleOptionTrigger runSoleOption={runSoleOption}>
|
||||
<button
|
||||
onClick={(event) => {
|
||||
event.preventDefault()
|
||||
originalOnClick()
|
||||
}}
|
||||
>
|
||||
Prevented child
|
||||
</button>
|
||||
</SingleOptionTrigger>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Prevented child' }))
|
||||
|
||||
expect(originalOnClick).toHaveBeenCalledTimes(2)
|
||||
expect(runSoleOption).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { TestRunMenuRef, TriggerOption } from '../test-run-menu'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import * as React from 'react'
|
||||
import TestRunMenu, { TriggerType } from '../test-run-menu'
|
||||
|
||||
const createOption = (overrides: Partial<TriggerOption> = {}): TriggerOption => ({
|
||||
id: 'user-input',
|
||||
type: TriggerType.UserInput,
|
||||
name: 'User Input',
|
||||
icon: <span>icon</span>,
|
||||
enabled: true,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('TestRunMenu', () => {
|
||||
it('should run the only enabled option directly and preserve the child click handler', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelect = vi.fn()
|
||||
const originalOnClick = vi.fn()
|
||||
|
||||
render(
|
||||
<TestRunMenu
|
||||
options={{
|
||||
userInput: createOption(),
|
||||
triggers: [],
|
||||
}}
|
||||
onSelect={onSelect}
|
||||
>
|
||||
<button onClick={originalOnClick}>Run now</button>
|
||||
</TestRunMenu>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Run now' }))
|
||||
|
||||
expect(originalOnClick).toHaveBeenCalledTimes(1)
|
||||
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'user-input' }))
|
||||
})
|
||||
|
||||
it('selects Run All through the public toggle and menu shortcut', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelect = vi.fn()
|
||||
|
||||
const Harness = () => {
|
||||
const ref = React.useRef<TestRunMenuRef>(null)
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => ref.current?.toggle()}>Toggle via ref</button>
|
||||
<TestRunMenu
|
||||
ref={ref}
|
||||
options={{
|
||||
userInput: createOption(),
|
||||
runAll: createOption({ id: 'run-all', type: TriggerType.All, name: 'Run All' }),
|
||||
triggers: [
|
||||
createOption({
|
||||
id: 'trigger-1',
|
||||
type: TriggerType.Webhook,
|
||||
name: 'Webhook Trigger',
|
||||
}),
|
||||
],
|
||||
}}
|
||||
onSelect={onSelect}
|
||||
>
|
||||
<button>Open menu</button>
|
||||
</TestRunMenu>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(<Harness />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Toggle via ref' }))
|
||||
expect(screen.getByRole('menu')).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(screen.getByRole('menu'), { key: '0' })
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'run-all' }))
|
||||
})
|
||||
|
||||
it('keeps menu accelerators local and ignores composition and modified keys', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelect = vi.fn()
|
||||
render(
|
||||
<TestRunMenu
|
||||
options={{
|
||||
userInput: createOption(),
|
||||
triggers: [createOption({ id: 'trigger', name: 'Webhook', type: TriggerType.Webhook })],
|
||||
}}
|
||||
onSelect={onSelect}
|
||||
>
|
||||
<button>Open menu</button>
|
||||
</TestRunMenu>,
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Open menu' }))
|
||||
const menu = screen.getByRole('menu')
|
||||
fireEvent.keyDown(document.body, { key: '0' })
|
||||
fireEvent.keyDown(menu, { key: '0', isComposing: true })
|
||||
fireEvent.keyDown(menu, { key: '0', ctrlKey: true })
|
||||
fireEvent.keyDown(menu, { key: '0', repeat: true })
|
||||
expect(onSelect).not.toHaveBeenCalled()
|
||||
fireEvent.keyDown(menu, { key: '0' })
|
||||
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'trigger' }))
|
||||
})
|
||||
|
||||
it('should ignore disabled options in the rendered menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<TestRunMenu
|
||||
options={{
|
||||
userInput: createOption({ enabled: false }),
|
||||
runAll: createOption({ id: 'run-all', type: TriggerType.All, name: 'Run All' }),
|
||||
triggers: [
|
||||
createOption({ id: 'trigger-1', type: TriggerType.Webhook, name: 'Webhook Trigger' }),
|
||||
],
|
||||
}}
|
||||
onSelect={vi.fn()}
|
||||
>
|
||||
<button>Open menu</button>
|
||||
</TestRunMenu>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Open menu' }))
|
||||
|
||||
expect(screen.queryByText('User Input')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Webhook Trigger')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { act, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createNode } from '../../__tests__/fixtures'
|
||||
import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
|
||||
import UndoRedo from '../undo-redo'
|
||||
|
||||
// The separate workflow-version picker does not own local undo/redo availability.
|
||||
vi.mock('@/app/components/workflow/header/view-workflow-history', () => ({ default: () => null }))
|
||||
|
||||
it('follows real history through edit, undo and redo', async () => {
|
||||
const user = userEvent.setup()
|
||||
const handleUndo = vi.fn()
|
||||
const handleRedo = vi.fn()
|
||||
const { store } = renderWorkflowComponent(
|
||||
<UndoRedo handleUndo={handleUndo} handleRedo={handleRedo} />,
|
||||
{ historyStore: {} },
|
||||
)
|
||||
handleUndo.mockImplementation(() => store.temporal.getState().undo())
|
||||
handleRedo.mockImplementation(() => store.temporal.getState().redo())
|
||||
const undo = screen.getByRole('button', { name: 'workflow.common.undo' })
|
||||
const redo = screen.getByRole('button', { name: 'workflow.common.redo' })
|
||||
expect(undo).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(redo).toHaveAttribute('aria-disabled', 'true')
|
||||
act(() =>
|
||||
store.getState().setWorkflowHistory({
|
||||
nodes: [createNode({ id: 'added' })],
|
||||
edges: [],
|
||||
workflowHistoryEvent: undefined,
|
||||
}),
|
||||
)
|
||||
expect(undo).not.toHaveAttribute('aria-disabled', 'true')
|
||||
expect(redo).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(undo)
|
||||
expect(store.getState().workflowHistory.nodes).toEqual([])
|
||||
expect(undo).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(redo).not.toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(redo)
|
||||
expect(store.getState().workflowHistory.nodes.map((node) => node.id)).toEqual(['added'])
|
||||
expect(handleUndo).toHaveBeenCalledOnce()
|
||||
expect(handleRedo).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps unavailable actions focusable without activating them', async () => {
|
||||
const user = userEvent.setup()
|
||||
const handleUndo = vi.fn()
|
||||
const handleRedo = vi.fn()
|
||||
renderWorkflowComponent(<UndoRedo handleUndo={handleUndo} handleRedo={handleRedo} />, {
|
||||
historyStore: {},
|
||||
})
|
||||
await user.tab()
|
||||
expect(screen.getByRole('button', { name: 'workflow.common.undo' })).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
await user.tab()
|
||||
expect(screen.getByRole('button', { name: 'workflow.common.redo' })).toHaveFocus()
|
||||
await user.keyboard(' ')
|
||||
expect(handleUndo).not.toHaveBeenCalled()
|
||||
expect(handleRedo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks available history actions when the canvas becomes read only', async () => {
|
||||
const user = userEvent.setup()
|
||||
const handleUndo = vi.fn()
|
||||
const handleRedo = vi.fn()
|
||||
const { store } = renderWorkflowComponent(
|
||||
<UndoRedo handleUndo={handleUndo} handleRedo={handleRedo} />,
|
||||
{ historyStore: {} },
|
||||
)
|
||||
act(() => {
|
||||
store.getState().setWorkflowHistory({
|
||||
nodes: [createNode({ id: 'first' })],
|
||||
edges: [],
|
||||
workflowHistoryEvent: undefined,
|
||||
})
|
||||
store.getState().setWorkflowHistory({
|
||||
nodes: [createNode({ id: 'second' })],
|
||||
edges: [],
|
||||
workflowHistoryEvent: undefined,
|
||||
})
|
||||
store.temporal.getState().undo()
|
||||
store.setState({ canvasReadOnly: true })
|
||||
})
|
||||
for (const name of ['workflow.common.undo', 'workflow.common.redo']) {
|
||||
const action = screen.getByRole('button', { name })
|
||||
expect(action).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(action)
|
||||
}
|
||||
expect(handleUndo).not.toHaveBeenCalled()
|
||||
expect(handleRedo).not.toHaveBeenCalled()
|
||||
})
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { HotkeysProvider } from '@tanstack/react-hotkeys'
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { VersionHistoryButton } from '../version-history-button'
|
||||
|
||||
describe('VersionHistoryButton', () => {
|
||||
it('opens history once per press from the page and respects editable and handled keys', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onClick = vi.fn()
|
||||
render(
|
||||
<HotkeysProvider defaultOptions={{ hotkey: { platform: 'windows' } }}>
|
||||
<VersionHistoryButton onClick={onClick} />
|
||||
<input aria-label="Prompt" />
|
||||
<button onKeyDown={(event) => event.preventDefault()}>Local control</button>
|
||||
</HotkeysProvider>,
|
||||
)
|
||||
for (const repeat of [false, true, true]) {
|
||||
const event = new KeyboardEvent('keydown', {
|
||||
key: 'h',
|
||||
ctrlKey: true,
|
||||
shiftKey: true,
|
||||
repeat,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
})
|
||||
fireEvent(document.body, event)
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
}
|
||||
fireEvent.keyUp(document.body, { key: 'h', ctrlKey: true, shiftKey: true })
|
||||
expect(onClick).toHaveBeenCalledTimes(1)
|
||||
await user.click(screen.getByRole('textbox', { name: 'Prompt' }))
|
||||
await user.keyboard('{Control>}{Shift>}h{/Shift}{/Control}')
|
||||
await user.click(screen.getByRole('button', { name: 'Local control' }))
|
||||
await user.keyboard('{Control>}{Shift>}h{/Shift}{/Control}')
|
||||
expect(onClick).toHaveBeenCalledTimes(1)
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.versionHistory' }))
|
||||
expect(onClick).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import type { ReactElement } from 'react'
|
||||
import type { WorkflowRunHistory, WorkflowRunHistoryResponse } from '@/types/workflow'
|
||||
import { act, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { seedModelProviderQueries } from '@/test/console/model-provider'
|
||||
import { createConsoleQueryWrapper, seedAppDslVersion } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createStartNode } from '../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
|
||||
import { ControlMode, WorkflowRunningStatus } from '../../types'
|
||||
import ScrollToSelectedNodeButton from '../scroll-to-selected-node-button'
|
||||
import ViewHistory from '../view-history'
|
||||
|
||||
const fetchHistory = vi.hoisted(() => vi.fn<() => Promise<WorkflowRunHistoryResponse>>())
|
||||
vi.mock('@/service/base', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/base')>()),
|
||||
get: fetchHistory,
|
||||
}))
|
||||
|
||||
const createHistoryItem = (overrides: Partial<WorkflowRunHistory> = {}): WorkflowRunHistory => ({
|
||||
id: 'run-1',
|
||||
version: 'v1',
|
||||
graph: {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
},
|
||||
inputs: {},
|
||||
status: WorkflowRunningStatus.Succeeded,
|
||||
outputs: {},
|
||||
elapsed_time: 1,
|
||||
total_tokens: 2,
|
||||
total_steps: 3,
|
||||
created_at: 100,
|
||||
finished_at: 120,
|
||||
created_by_account: {
|
||||
id: 'user-1',
|
||||
name: 'Alice',
|
||||
email: 'alice@example.com',
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
function renderHistory(
|
||||
ui: ReactElement,
|
||||
options: Parameters<typeof renderWorkflowFlowComponent>[1] = {},
|
||||
) {
|
||||
const { queryClient } = createConsoleQueryWrapper()
|
||||
seedAppDslVersion(queryClient)
|
||||
seedModelProviderQueries(queryClient)
|
||||
return renderWorkflowFlowComponent(ui, { queryClient, ...options })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
fetchHistory.mockReset().mockResolvedValue({ data: [] })
|
||||
})
|
||||
|
||||
it('fetches only after opening history and clears log modals when closing it', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clearModals = vi.fn()
|
||||
renderHistory(
|
||||
<ViewHistory historyUrl="/history" withText onClearLogAndMessageModal={clearModals} />,
|
||||
)
|
||||
expect(fetchHistory).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.showRunHistory' }))
|
||||
expect(await screen.findByText('workflow.common.notRunning')).toBeVisible()
|
||||
expect(fetchHistory).toHaveBeenCalledExactlyOnceWith('/history')
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
|
||||
expect(clearModals).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByText('workflow.common.runHistory')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears log modals on the icon trigger and displays loading until history arrives', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clearModals = vi.fn()
|
||||
const response = createDeferred<WorkflowRunHistoryResponse>()
|
||||
fetchHistory.mockReturnValueOnce(response.promise)
|
||||
renderHistory(<ViewHistory historyUrl="/history" onClearLogAndMessageModal={clearModals} />)
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.viewRunHistory' }))
|
||||
expect(clearModals).toHaveBeenCalledOnce()
|
||||
expect(screen.getByRole('progressbar', { name: 'common.loading' })).toBeVisible()
|
||||
await act(async () => response.resolve({ data: [createHistoryItem()] }))
|
||||
expect(await screen.findByText(/^Test Run \(/)).toBeVisible()
|
||||
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('backs up the draft, clears node selection and editing panels, and selects the historical run', async () => {
|
||||
const user = userEvent.setup()
|
||||
const backupDraft = vi.fn()
|
||||
const run = createHistoryItem({
|
||||
id: 'run-paused',
|
||||
status: WorkflowRunningStatus.Paused,
|
||||
finished_at: 0,
|
||||
})
|
||||
fetchHistory.mockResolvedValue({ data: [run] })
|
||||
const { store } = renderHistory(
|
||||
<>
|
||||
<ViewHistory historyUrl="/history" withText />
|
||||
<ScrollToSelectedNodeButton />
|
||||
</>,
|
||||
{
|
||||
nodes: [createStartNode({ data: { selected: true } })],
|
||||
hooksStoreProps: { handleBackupDraft: backupDraft },
|
||||
initialStoreState: {
|
||||
showInputsPanel: true,
|
||||
showEnvPanel: true,
|
||||
showDebugAndPreviewPanel: true,
|
||||
controlMode: ControlMode.Pointer,
|
||||
},
|
||||
},
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'workflow.panel.scrollToSelectedNode' })).toBeVisible()
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.showRunHistory' }))
|
||||
await user.click(await screen.findByText('Test Run (Paused)'))
|
||||
expect(store.getState()).toMatchObject({
|
||||
historyWorkflowData: run,
|
||||
showInputsPanel: false,
|
||||
showEnvPanel: false,
|
||||
showDebugAndPreviewPanel: false,
|
||||
controlMode: ControlMode.Hand,
|
||||
})
|
||||
expect(backupDraft).toHaveBeenCalledOnce()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'workflow.panel.scrollToSelectedNode' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('identifies chatflow history as chat sessions', async () => {
|
||||
const user = userEvent.setup()
|
||||
fetchHistory.mockResolvedValue({ data: [createHistoryItem()] })
|
||||
renderHistory(<ViewHistory historyUrl="/history" withText />, {
|
||||
resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' },
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: 'workflow.common.showRunHistory' }))
|
||||
expect(await screen.findByText(/^Test Chat \(/)).toBeVisible()
|
||||
})
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { act, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
|
||||
import ViewWorkflowHistory from '../view-workflow-history'
|
||||
|
||||
describe('ViewWorkflowHistory log session', () => {
|
||||
it('clears the selected message when history opens and closes with Escape', async () => {
|
||||
const user = userEvent.setup()
|
||||
const messageLogItem = {
|
||||
id: 'message-1',
|
||||
content: 'Answer',
|
||||
isAnswer: true,
|
||||
workflow_run_id: 'run-1',
|
||||
}
|
||||
const { store } = renderWorkflowFlowComponent(<ViewWorkflowHistory />, {
|
||||
nodes: [],
|
||||
edges: [],
|
||||
initialStoreState: { messageLogItem },
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'workflowHistory.changeHistory.title' }))
|
||||
expect(store.getState().messageLogItem).toBeUndefined()
|
||||
act(() => store.getState().setMessageLogItem(messageLogItem))
|
||||
await user.keyboard('{Escape}')
|
||||
expect(store.getState().messageLogItem).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
|
||||
const ChatVariableButton = ({ disabled }: { disabled: boolean }) => {
|
||||
const { theme } = useTheme()
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const showChatVariablePanel = useStore((s) => s.showChatVariablePanel)
|
||||
const setShowChatVariablePanel = useStore((s) => s.setShowChatVariablePanel)
|
||||
const setShowEnvPanel = useStore((s) => s.setShowEnvPanel)
|
||||
const setShowGlobalVariablePanel = useStore((s) => s.setShowGlobalVariablePanel)
|
||||
const setShowDebugAndPreviewPanel = useStore((s) => s.setShowDebugAndPreviewPanel)
|
||||
|
||||
const handleClick = () => {
|
||||
setShowChatVariablePanel(true)
|
||||
setShowEnvPanel(false)
|
||||
setShowGlobalVariablePanel(false)
|
||||
setShowDebugAndPreviewPanel(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={t(($) => $['chatVariable.panelTitle'], {
|
||||
ns: 'workflow',
|
||||
})}
|
||||
aria-expanded={showChatVariablePanel}
|
||||
size="lg"
|
||||
className={cn(
|
||||
'border border-transparent',
|
||||
theme === 'dark' &&
|
||||
showChatVariablePanel &&
|
||||
'border-black/5 bg-white/10 backdrop-blur-xs',
|
||||
)}
|
||||
disabled={disabled}
|
||||
onClick={handleClick}
|
||||
variant="ghost"
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-others-bubble-x size-4 text-components-button-secondary-text"
|
||||
/>
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
|
||||
<TooltipContent>
|
||||
{t(($) => $['chatVariable.panelTitle'], {
|
||||
ns: 'workflow',
|
||||
})}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ChatVariableButton)
|
||||
@@ -0,0 +1,229 @@
|
||||
import type { AgentSoulDifyToolConfig } from '@dify/contracts/api/console/apps/types.gen'
|
||||
import type { Edge, Node } from '../../../types'
|
||||
import { zWorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/zod.gen'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { CollectionType } from '@/app/components/tools/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 {
|
||||
CANVAS_NODES_STATUS_NAME,
|
||||
CanvasNodesCatalogProbe,
|
||||
} from '../../../__tests__/canvas-nodes-catalog-probe'
|
||||
import { createEdge, createNode, createStartNode } from '../../../__tests__/fixtures'
|
||||
import { renderWorkflowFlowComponent as render } from '../../../__tests__/workflow-test-env'
|
||||
import DatasetsDetailProvider from '../../../datasets-detail-store/provider'
|
||||
import llmDefault from '../../../nodes/llm/default'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import WorkflowChecklist from '../index'
|
||||
|
||||
vi.mock('@/service/base', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/base')>()),
|
||||
postMarketplace: vi.fn().mockResolvedValue({ data: { list: [] } }),
|
||||
}))
|
||||
|
||||
function createChecklistQueryClient() {
|
||||
const { queryClient } = createConsoleQueryWrapper({ appDslVersion: '0.6.0' })
|
||||
seedModelProviderQueries(queryClient)
|
||||
seedToolProviders(queryClient, {
|
||||
builtInTools: [],
|
||||
customTools: [],
|
||||
workflowTools: [],
|
||||
mcpTools: [],
|
||||
})
|
||||
queryClient.setQueryData(consoleQuery.workspaces.current.agentProviders.get.queryKey(), [])
|
||||
queryClient.setQueryData(consoleQuery.workspaces.current.triggers.get.queryKey({ input: {} }), [])
|
||||
queryClient.setQueryData(consoleQuery.spec.schemaDefinitions.get.queryKey(), [])
|
||||
return queryClient
|
||||
}
|
||||
|
||||
function createWarningGraph() {
|
||||
const start = createStartNode({
|
||||
id: 'start',
|
||||
width: 240,
|
||||
height: 80,
|
||||
data: { variables: [] },
|
||||
})
|
||||
const missingPlugin = createNode({
|
||||
id: 'missing-plugin',
|
||||
width: 240,
|
||||
height: 80,
|
||||
data: {
|
||||
type: BlockEnum.Tool,
|
||||
title: 'Missing Plugin',
|
||||
tool_parameters: {},
|
||||
provider_type: CollectionType.builtIn,
|
||||
provider_id: 'missing-provider',
|
||||
plugin_unique_identifier: 'plugin/tool@0.0.1',
|
||||
},
|
||||
})
|
||||
const invalidNode = createNode({
|
||||
id: 'invalid-node',
|
||||
width: 240,
|
||||
height: 80,
|
||||
data: { ...llmDefault.defaultValue, type: BlockEnum.LLM, title: 'Broken Node' },
|
||||
})
|
||||
return {
|
||||
nodes: [start, missingPlugin, invalidNode],
|
||||
edges: [
|
||||
createEdge({ source: start.id, target: missingPlugin.id }),
|
||||
createEdge({ source: start.id, target: invalidNode.id }),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function createInlineAgentGraph() {
|
||||
const queryClient = createChecklistQueryClient()
|
||||
const nodeId = 'inline-agent'
|
||||
queryClient.setQueryData(
|
||||
consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
|
||||
input: { params: { app_id: 'app-1', node_id: nodeId } },
|
||||
}),
|
||||
zWorkflowAgentComposerResponse.parse({
|
||||
agent_soul: {
|
||||
config_files: [],
|
||||
config_skills: [],
|
||||
tools: { dify_tools: [] satisfies AgentSoulDifyToolConfig[] },
|
||||
},
|
||||
node_job: {},
|
||||
save_options: [],
|
||||
soul_lock: { locked: false },
|
||||
variant: 'workflow',
|
||||
}),
|
||||
)
|
||||
const start = createStartNode({
|
||||
id: 'start',
|
||||
width: 240,
|
||||
height: 80,
|
||||
data: { variables: [] },
|
||||
})
|
||||
const agent = createNode({
|
||||
id: nodeId,
|
||||
width: 240,
|
||||
height: 80,
|
||||
data: {
|
||||
type: BlockEnum.AgentV2,
|
||||
title: 'Inline Agent',
|
||||
agent_node_kind: 'dify_agent',
|
||||
version: '2',
|
||||
agent_binding: {
|
||||
binding_type: 'inline_agent',
|
||||
agent_id: 'agent-1',
|
||||
current_snapshot_id: 'snapshot-1',
|
||||
},
|
||||
},
|
||||
})
|
||||
return {
|
||||
nodes: [start, agent],
|
||||
edges: [createEdge({ source: start.id, target: agent.id })],
|
||||
queryClient,
|
||||
}
|
||||
}
|
||||
|
||||
function renderChecklist(
|
||||
nodes: Node[],
|
||||
edges: Edge[],
|
||||
options: {
|
||||
disabled?: boolean
|
||||
onItemClick?: Parameters<typeof WorkflowChecklist>[0]['onItemClick']
|
||||
queryClient?: ReturnType<typeof createChecklistQueryClient>
|
||||
} = {},
|
||||
) {
|
||||
return render(
|
||||
<DatasetsDetailProvider nodes={nodes}>
|
||||
<WorkflowChecklist disabled={options.disabled ?? false} onItemClick={options.onItemClick} />
|
||||
<CanvasNodesCatalogProbe />
|
||||
</DatasetsDetailProvider>,
|
||||
{
|
||||
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
|
||||
initialStoreState: { nodes },
|
||||
nodes,
|
||||
edges,
|
||||
queryClient: options.queryClient ?? createChecklistQueryClient(),
|
||||
reactFlowProps: { fitView: false },
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
function selectedCanvasNodeIds() {
|
||||
return (
|
||||
screen.getByRole('status', { name: CANVAS_NODES_STATUS_NAME }).textContent?.split(',') ?? []
|
||||
).filter((node) => node.endsWith('*'))
|
||||
}
|
||||
|
||||
describe('WorkflowChecklist', () => {
|
||||
it('groups real missing-plugin and invalid-node warnings, then selects the invalid node', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { nodes, edges } = createWarningGraph()
|
||||
renderChecklist(nodes, edges)
|
||||
|
||||
const trigger = await screen.findByRole('button', { name: 'workflow.panel.checklist 2' })
|
||||
expect(trigger).toHaveTextContent('2')
|
||||
await user.click(trigger)
|
||||
expect(screen.getByText(/pluginsNotInstalled/)).toBeInTheDocument()
|
||||
expect(screen.getByText('Missing Plugin')).toBeInTheDocument()
|
||||
expect(screen.getByText('Broken Node')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /workflow\.errorMsg\.fieldRequired/ }))
|
||||
|
||||
await waitFor(() => expect(selectedCanvasNodeIds()).toEqual(['invalid-node*']))
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /workflow\.errorMsg\.fieldRequired/ }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the caller item-click boundary without changing canvas selection', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onItemClick = vi.fn()
|
||||
const { nodes, edges } = createWarningGraph()
|
||||
renderChecklist(nodes, edges, { onItemClick })
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'workflow.panel.checklist 2' }))
|
||||
await user.click(screen.getByRole('button', { name: /workflow\.errorMsg\.fieldRequired/ }))
|
||||
|
||||
expect(onItemClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'invalid-node' }))
|
||||
expect(selectedCanvasNodeIds()).toEqual([])
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /workflow\.errorMsg\.fieldRequired/ }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('selects an inline agent warning and opens its editor panel', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { nodes, edges, queryClient } = createInlineAgentGraph()
|
||||
const { store } = renderChecklist(nodes, edges, { queryClient })
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'workflow.panel.checklist 1' }))
|
||||
await user.click(await screen.findByRole('button', { name: /model/i }))
|
||||
|
||||
await waitFor(() => expect(selectedCanvasNodeIds()).toEqual(['inline-agent*']))
|
||||
expect(store.getState().openInlineAgentPanelNodeId).toBe('inline-agent')
|
||||
expect(screen.queryByRole('button', { name: /model/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the resolved state for a valid graph', async () => {
|
||||
const user = userEvent.setup()
|
||||
const nodes = [
|
||||
createStartNode({
|
||||
id: 'start',
|
||||
width: 240,
|
||||
height: 80,
|
||||
data: { variables: [] },
|
||||
}),
|
||||
]
|
||||
renderChecklist(nodes, [])
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'workflow.panel.checklist' }))
|
||||
expect(screen.getByText(/checklistResolved/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not open when disabled', async () => {
|
||||
const { nodes, edges } = createWarningGraph()
|
||||
renderChecklist(nodes, edges, { disabled: true })
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'workflow.panel.checklist 2' })).toBeDisabled()
|
||||
expect(screen.queryByText('Broken Node')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import type { ChecklistItem } from '../../../hooks/use-checklist'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import { ChecklistNodeGroup } from '../node-group'
|
||||
|
||||
const createItem = (overrides: Partial<ChecklistItem> = {}): ChecklistItem => ({
|
||||
id: 'node-1',
|
||||
type: BlockEnum.LLM,
|
||||
title: 'Broken Node',
|
||||
errorMessages: ['Needs configuration'],
|
||||
canNavigate: true,
|
||||
disableGoTo: false,
|
||||
unConnected: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('ChecklistNodeGroup', () => {
|
||||
it('should render errors and the connection warning, and allow navigation when go-to is enabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onItemClick = vi.fn()
|
||||
|
||||
render(
|
||||
<ChecklistNodeGroup
|
||||
item={createItem({ unConnected: true })}
|
||||
showGoTo={true}
|
||||
onItemClick={onItemClick}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Needs configuration')).toBeInTheDocument()
|
||||
expect(screen.getByText(/needConnectTip/i)).toBeInTheDocument()
|
||||
expect(screen.getAllByText(/goToFix/i)).toHaveLength(2)
|
||||
expect(screen.getByRole('button', { name: /Needs configuration/i })).toHaveAttribute(
|
||||
'title',
|
||||
'Needs configuration',
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Needs configuration'))
|
||||
|
||||
expect(onItemClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'node-1' }))
|
||||
})
|
||||
|
||||
it('should not allow navigation when go-to is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onItemClick = vi.fn()
|
||||
|
||||
render(
|
||||
<ChecklistNodeGroup
|
||||
item={createItem({ disableGoTo: true })}
|
||||
showGoTo={true}
|
||||
onItemClick={onItemClick}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('Needs configuration'))
|
||||
|
||||
expect(onItemClick).not.toHaveBeenCalled()
|
||||
expect(screen.queryByText(/goToFix/i)).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /Needs configuration/i })).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Needs configuration').parentElement).toHaveAttribute(
|
||||
'title',
|
||||
'Needs configuration',
|
||||
)
|
||||
})
|
||||
})
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import type { ChecklistItem } from '../../../hooks/use-checklist'
|
||||
import { Popover, PopoverContent } from '@langgenius/dify-ui/popover'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it } from 'vite-plus/test'
|
||||
import { useStore as usePluginDependencyStore } from '../../../plugin-dependency/store'
|
||||
import { BlockEnum } from '../../../types'
|
||||
import { ChecklistPluginGroup } from '../plugin-group'
|
||||
|
||||
const createChecklistItem = (overrides: Partial<ChecklistItem> = {}): ChecklistItem => ({
|
||||
id: 'node-1',
|
||||
type: BlockEnum.Tool,
|
||||
title: 'Tool Node',
|
||||
errorMessages: [],
|
||||
canNavigate: false,
|
||||
isPluginMissing: true,
|
||||
pluginUniqueIdentifier: 'langgenius/test-plugin:1.0.0@sha256',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('ChecklistPluginGroup', () => {
|
||||
const getInstallButton = () =>
|
||||
screen.getByRole('button', { name: 'workflowAgent.nodes.agent.pluginInstaller.install' })
|
||||
|
||||
const renderInPopover = (items: ChecklistItem[]) => {
|
||||
return render(
|
||||
<Popover open>
|
||||
<PopoverContent>
|
||||
<ChecklistPluginGroup items={items} />
|
||||
</PopoverContent>
|
||||
</Popover>,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
usePluginDependencyStore.setState({ dependencies: [] })
|
||||
})
|
||||
|
||||
it('should set marketplace dependencies when install button is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const items: ChecklistItem[] = [
|
||||
createChecklistItem({
|
||||
id: 'node-1',
|
||||
pluginUniqueIdentifier: 'langgenius/test-plugin:1.0.0@sha256',
|
||||
}),
|
||||
createChecklistItem({
|
||||
id: 'node-2',
|
||||
pluginUniqueIdentifier: 'langgenius/test-plugin:1.0.0@sha256',
|
||||
}),
|
||||
createChecklistItem({
|
||||
id: 'node-3',
|
||||
pluginUniqueIdentifier: 'langgenius/another-plugin:2.0.0@sha256',
|
||||
}),
|
||||
]
|
||||
|
||||
renderInPopover(items)
|
||||
|
||||
await user.click(getInstallButton())
|
||||
|
||||
expect(usePluginDependencyStore.getState().dependencies).toEqual([
|
||||
{
|
||||
type: 'marketplace',
|
||||
value: {
|
||||
marketplace_plugin_unique_identifier: 'langgenius/test-plugin:1.0.0@sha256',
|
||||
plugin_unique_identifier: 'langgenius/test-plugin:1.0.0@sha256',
|
||||
version: '1.0.0',
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'marketplace',
|
||||
value: {
|
||||
marketplace_plugin_unique_identifier: 'langgenius/another-plugin:2.0.0@sha256',
|
||||
plugin_unique_identifier: 'langgenius/another-plugin:2.0.0@sha256',
|
||||
version: '2.0.0',
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('should keep install button disabled when no identifier is available', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInPopover([createChecklistItem({ pluginUniqueIdentifier: undefined })])
|
||||
|
||||
const installButton = getInstallButton()
|
||||
expect(installButton).toBeDisabled()
|
||||
|
||||
await user.click(installButton)
|
||||
expect(usePluginDependencyStore.getState().dependencies).toEqual([])
|
||||
})
|
||||
|
||||
it('should omit the version when the marketplace identifier does not include one', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInPopover([
|
||||
createChecklistItem({ pluginUniqueIdentifier: 'langgenius/test-plugin@sha256' }),
|
||||
])
|
||||
|
||||
await user.click(getInstallButton())
|
||||
|
||||
expect(usePluginDependencyStore.getState().dependencies).toEqual([
|
||||
{
|
||||
type: 'marketplace',
|
||||
value: {
|
||||
marketplace_plugin_unique_identifier: 'langgenius/test-plugin@sha256',
|
||||
plugin_unique_identifier: 'langgenius/test-plugin@sha256',
|
||||
version: undefined,
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { ChecklistItem } from '../../hooks/use-checklist'
|
||||
import type { CommonEdgeType } from '../../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import {
|
||||
Popover,
|
||||
PopoverClose,
|
||||
PopoverContent,
|
||||
PopoverDescription,
|
||||
PopoverTitle,
|
||||
PopoverTrigger,
|
||||
} from '@langgenius/dify-ui/popover'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { memo, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useEdges } from 'reactflow'
|
||||
import useNodes from '@/app/components/workflow/store/workflow/use-nodes'
|
||||
import { useChecklist } from '../../hooks/use-checklist'
|
||||
import { useNodesInteractions } from '../../hooks/use-nodes-interactions'
|
||||
import { useStore } from '../../store'
|
||||
import { ChecklistNodeGroup } from './node-group'
|
||||
import { ChecklistPluginGroup } from './plugin-group'
|
||||
|
||||
type WorkflowChecklistProps = {
|
||||
disabled: boolean
|
||||
showGoTo?: boolean
|
||||
onItemClick?: (item: ChecklistItem) => void
|
||||
}
|
||||
|
||||
const WorkflowChecklist = ({ disabled, showGoTo = true, onItemClick }: WorkflowChecklistProps) => {
|
||||
const { t } = useTranslation(['common', 'workflow'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const edges = useEdges<CommonEdgeType>()
|
||||
const nodes = useNodes()
|
||||
const needWarningNodes = useChecklist(nodes, edges)
|
||||
const { handleNodeSelect } = useNodesInteractions()
|
||||
const setOpenInlineAgentPanelNodeId = useStore((state) => state.setOpenInlineAgentPanelNodeId)
|
||||
const checklistLabel = t(($) => $['panel.checklist'], { ns: 'workflow' })
|
||||
|
||||
const { pluginItems, nodeItems } = useMemo(() => {
|
||||
const plugins: ChecklistItem[] = []
|
||||
const regular: ChecklistItem[] = []
|
||||
for (const item of needWarningNodes) {
|
||||
if (item.isPluginMissing) plugins.push(item)
|
||||
else regular.push(item)
|
||||
}
|
||||
return { pluginItems: plugins, nodeItems: regular }
|
||||
}, [needWarningNodes])
|
||||
|
||||
const handleItemClick = (item: ChecklistItem) => {
|
||||
if (onItemClick) onItemClick(item)
|
||||
else {
|
||||
handleNodeSelect(item.id)
|
||||
if (item.openInlineAgentPanel) setOpenInlineAgentPanelNodeId(item.id)
|
||||
}
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={(newOpen) => !disabled && setOpen(newOpen)}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<PopoverTrigger
|
||||
disabled={disabled}
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'group relative ml-0.5 flex size-7 items-center justify-center rounded-md border-none bg-transparent p-0',
|
||||
'data-disabled:cursor-not-allowed data-disabled:opacity-50',
|
||||
)}
|
||||
disabled={disabled || undefined}
|
||||
>
|
||||
<span className="sr-only">{checklistLabel}</span>
|
||||
<span className="flex size-full items-center justify-center rounded-md group-data-popup-open:bg-state-accent-hover hover:bg-state-accent-hover">
|
||||
<span
|
||||
className="i-ri-list-check-3 size-4 text-components-button-ghost-text group-hover:text-components-button-secondary-accent-text group-data-popup-open:text-components-button-secondary-accent-text"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</span>
|
||||
{!!needWarningNodes.length && (
|
||||
<span className="absolute -top-1.5 -right-1.5 flex h-4.5 min-w-4.5 items-center justify-center rounded-full border border-gray-100 bg-text-warning-secondary text-[11px] font-semibold text-white">
|
||||
{needWarningNodes.length}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{checklistLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
sideOffset={12}
|
||||
alignOffset={-30}
|
||||
className="w-105 rounded-2xl bg-background-default-subtle"
|
||||
>
|
||||
<div className="overflow-y-auto" style={{ maxHeight: 'calc(2 / 3 * 100vh)' }}>
|
||||
<div className="flex flex-col gap-0.5 px-3 pt-3.5 pb-1">
|
||||
<div className="flex items-start px-1">
|
||||
<div className="min-w-0 grow pr-8">
|
||||
<PopoverTitle className="text-base/6 font-semibold text-text-primary">
|
||||
{checklistLabel}
|
||||
{needWarningNodes.length > 0 && `(${needWarningNodes.length})`}
|
||||
</PopoverTitle>
|
||||
</div>
|
||||
<PopoverClose
|
||||
render={
|
||||
<IconButton
|
||||
size="lg"
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
className="-mt-1 -mr-1 shrink-0"
|
||||
>
|
||||
<span className="i-ri-close-line size-4" aria-hidden="true" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{needWarningNodes.length > 0 && (
|
||||
<PopoverDescription className="px-1 text-xs/4 text-text-tertiary">
|
||||
{t(($) => $['panel.checklistDescription'], { ns: 'workflow' })}
|
||||
</PopoverDescription>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{needWarningNodes.length > 0 ? (
|
||||
<div className="flex flex-col gap-1 px-4 pt-1 pb-4">
|
||||
{pluginItems.length > 0 && <ChecklistPluginGroup items={pluginItems} />}
|
||||
{nodeItems.map((item) => (
|
||||
<ChecklistNodeGroup
|
||||
key={item.id}
|
||||
item={item}
|
||||
showGoTo={showGoTo}
|
||||
onItemClick={handleItemClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-4 mb-3 rounded-lg py-4 text-center text-xs text-text-tertiary">
|
||||
<span className="mx-auto mb-1.25 i-custom-vender-line-general-checklist-square block h-8 w-8 text-text-quaternary" />
|
||||
{t(($) => $['panel.checklistResolved'], { ns: 'workflow' })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(WorkflowChecklist)
|
||||
@@ -0,0 +1,21 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
|
||||
type ItemIndicatorProps = {
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const ItemIndicator = ({ className }: ItemIndicatorProps) => {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
height="24"
|
||||
viewBox="0 0 20 24"
|
||||
fill="none"
|
||||
className={cn('shrink-0', className)}
|
||||
>
|
||||
<path d="M9.5 0H10.5V24H9.5V0Z" fill="currentColor" className="text-divider-regular" />
|
||||
<circle cx="10" cy="12" r="3.25" fill="#F79009" stroke="white" strokeWidth="1.5" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { ChecklistItem } from '../../hooks/use-checklist'
|
||||
import type { BlockEnum } from '../../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import BlockIcon from '../../block-icon'
|
||||
import { ItemIndicator } from './item-indicator'
|
||||
|
||||
type ChecklistSubItem = {
|
||||
key: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export const ChecklistNodeGroup = memo(
|
||||
({
|
||||
item,
|
||||
showGoTo,
|
||||
onItemClick,
|
||||
}: {
|
||||
item: ChecklistItem
|
||||
showGoTo: boolean
|
||||
onItemClick: (item: ChecklistItem) => void
|
||||
}) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const goToEnabled = showGoTo && item.canNavigate && !item.disableGoTo
|
||||
|
||||
const subItems = useMemo(() => {
|
||||
const items: ChecklistSubItem[] = []
|
||||
for (let i = 0; i < item.errorMessages.length; i++)
|
||||
items.push({ key: `error-${i}`, message: item.errorMessages[i]! })
|
||||
if (item.unConnected)
|
||||
items.push({
|
||||
key: 'unconnected',
|
||||
message: t(($) => $['common.needConnectTip'], { ns: 'workflow' }),
|
||||
})
|
||||
return items
|
||||
}, [item.errorMessages, item.unConnected, t])
|
||||
|
||||
return (
|
||||
<div className="overflow-clip rounded-[10px] bg-components-panel-on-panel-item-bg">
|
||||
<div className="flex items-center gap-2 px-2 pt-2">
|
||||
<BlockIcon type={item.type as BlockEnum} size="sm" toolIcon={item.toolIcon} />
|
||||
<span className="min-w-0 grow truncate text-sm/5 font-medium text-text-primary">
|
||||
{item.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="p-1">
|
||||
{subItems.map((sub) => {
|
||||
const content = (
|
||||
<>
|
||||
<ItemIndicator />
|
||||
<span className="min-w-0 grow truncate text-xs/4 text-text-warning">
|
||||
{sub.message}
|
||||
</span>
|
||||
{goToEnabled && (
|
||||
<div className="flex shrink-0 items-center gap-0.5 pr-0.5 opacity-0 transition-opacity duration-150 group-hover/item:opacity-100">
|
||||
<span className="text-xs/4 font-medium whitespace-nowrap text-text-accent">
|
||||
{t(($) => $['panel.goToFix'], { ns: 'workflow' })}
|
||||
</span>
|
||||
<span
|
||||
className="i-ri-arrow-right-line size-3.5 text-text-accent"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
const className = cn(
|
||||
'group/item flex w-full items-center gap-2 rounded-lg px-1 text-left',
|
||||
goToEnabled && 'cursor-pointer hover:bg-state-base-hover',
|
||||
)
|
||||
|
||||
if (goToEnabled) {
|
||||
return (
|
||||
<button
|
||||
key={sub.key}
|
||||
type="button"
|
||||
className={cn(className, 'border-none bg-transparent')}
|
||||
title={sub.message}
|
||||
onClick={() => onItemClick(item)}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={sub.key} className={className} title={sub.message}>
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
ChecklistNodeGroup.displayName = 'ChecklistNodeGroup'
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { ChecklistItem } from '../../hooks/use-checklist'
|
||||
import type { BlockEnum } from '../../types'
|
||||
import type { Dependency } from '@/app/components/plugins/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { PopoverClose } from '@langgenius/dify-ui/popover'
|
||||
import { memo, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import BlockIcon from '../../block-icon'
|
||||
import { useStore as usePluginDependencyStore } from '../../plugin-dependency/store'
|
||||
import { ItemIndicator } from './item-indicator'
|
||||
|
||||
function getVersionFromMarketplaceIdentifier(identifier: string): string | undefined {
|
||||
const withoutHash = identifier.split('@')[0]
|
||||
const [, version] = withoutHash!.split(':')
|
||||
return version || undefined
|
||||
}
|
||||
|
||||
export const ChecklistPluginGroup = memo(({ items }: { items: ChecklistItem[] }) => {
|
||||
const { t } = useTranslation(['workflow', 'workflowAgent'])
|
||||
|
||||
const identifiers = useMemo(
|
||||
() =>
|
||||
Array.from(
|
||||
new Set(
|
||||
items.map((i) => i.pluginUniqueIdentifier).filter((id): id is string => Boolean(id)),
|
||||
),
|
||||
),
|
||||
[items],
|
||||
)
|
||||
|
||||
const dependencies = useMemo<Dependency[]>(() => {
|
||||
return identifiers.map((identifier) => {
|
||||
return {
|
||||
type: 'marketplace',
|
||||
value: {
|
||||
marketplace_plugin_unique_identifier: identifier,
|
||||
plugin_unique_identifier: identifier,
|
||||
version: getVersionFromMarketplaceIdentifier(identifier),
|
||||
},
|
||||
}
|
||||
})
|
||||
}, [identifiers])
|
||||
|
||||
const handleInstallAll = () => {
|
||||
if (dependencies.length === 0) return
|
||||
const { setDependencies } = usePluginDependencyStore.getState()
|
||||
setDependencies(dependencies)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-clip rounded-[10px] bg-components-panel-on-panel-item-bg">
|
||||
<div className="flex items-center gap-2 px-2 pt-2">
|
||||
<div className="flex size-5 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-components-icon-bg-midnight-solid shadow-xs">
|
||||
<span className="i-ri-download-line size-3.5 text-white" />
|
||||
</div>
|
||||
<span className="min-w-0 grow truncate text-sm/5 font-medium text-text-primary">
|
||||
{t(($) => $['nodes.common.pluginsNotInstalled'], { ns: 'workflow', count: items.length })}
|
||||
</span>
|
||||
<PopoverClose
|
||||
render={
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={handleInstallAll}
|
||||
disabled={dependencies.length === 0}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{t(($) => $['nodes.agent.pluginInstaller.install'], { ns: 'workflowAgent' })}
|
||||
</PopoverClose>
|
||||
</div>
|
||||
<div className="p-1">
|
||||
{items.map((item) => (
|
||||
<div key={item.id} className="flex items-center gap-2 rounded-lg px-1">
|
||||
<ItemIndicator />
|
||||
<BlockIcon type={item.type as BlockEnum} size="xs" toolIcon={item.toolIcon} />
|
||||
<span className="min-w-0 grow truncate text-xs/4 text-text-warning">{item.title}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
ChecklistPluginGroup.displayName = 'ChecklistPluginGroup'
|
||||
@@ -0,0 +1,54 @@
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
|
||||
import useTimestamp from '@/hooks/use-timestamp'
|
||||
|
||||
function EditingTitle() {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const { formatTime } = useTimestamp()
|
||||
const { formatTimeFromNow } = useFormatTimeFromNow()
|
||||
const draftUpdatedAt = useStore((state) => state.draftUpdatedAt)
|
||||
const publishedAt = useStore((state) => state.publishedAt)
|
||||
const isSyncingWorkflowDraft = useStore((s) => s.isSyncingWorkflowDraft)
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-label={t(($) => $['common.workflowSaveStatus'], { ns: 'workflow' })}
|
||||
className="flex h-4.5 min-w-75 items-center system-xs-regular whitespace-nowrap text-text-tertiary"
|
||||
>
|
||||
{!!draftUpdatedAt && (
|
||||
<span className="flex items-center gap-1">
|
||||
<span>{t(($) => $['common.autoSaved'], { ns: 'workflow' })}</span>
|
||||
<time dateTime={new Date(draftUpdatedAt).toISOString()}>
|
||||
{formatTime(draftUpdatedAt / 1000, 'HH:mm:ss')}
|
||||
</time>
|
||||
</span>
|
||||
)}
|
||||
<span aria-hidden="true" className="mx-1 flex items-center">
|
||||
·
|
||||
</span>
|
||||
{publishedAt ? (
|
||||
<span className="flex items-center gap-1">
|
||||
<span>{t(($) => $['common.published'], { ns: 'workflow' })}</span>
|
||||
<time dateTime={new Date(publishedAt).toISOString()}>
|
||||
{formatTimeFromNow(publishedAt)}
|
||||
</time>
|
||||
</span>
|
||||
) : (
|
||||
<span>{t(($) => $['common.unpublished'], { ns: 'workflow' })}</span>
|
||||
)}
|
||||
{isSyncingWorkflowDraft && (
|
||||
<>
|
||||
<span aria-hidden="true" className="mx-1 flex items-center">
|
||||
·
|
||||
</span>
|
||||
<span>{t(($) => $['common.syncingData'], { ns: 'workflow' })}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(EditingTitle)
|
||||
@@ -0,0 +1,56 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks/use-input-field-panel'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
|
||||
const EnvButton = ({ disabled }: { disabled: boolean }) => {
|
||||
const { theme } = useTheme()
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const setShowChatVariablePanel = useStore((s) => s.setShowChatVariablePanel)
|
||||
const showEnvPanel = useStore((s) => s.showEnvPanel)
|
||||
const setShowEnvPanel = useStore((s) => s.setShowEnvPanel)
|
||||
const setShowGlobalVariablePanel = useStore((s) => s.setShowGlobalVariablePanel)
|
||||
const setShowDebugAndPreviewPanel = useStore((s) => s.setShowDebugAndPreviewPanel)
|
||||
const { closeAllInputFieldPanels } = useInputFieldPanel()
|
||||
|
||||
const handleClick = () => {
|
||||
setShowEnvPanel(true)
|
||||
setShowChatVariablePanel(false)
|
||||
setShowGlobalVariablePanel(false)
|
||||
setShowDebugAndPreviewPanel(false)
|
||||
closeAllInputFieldPanels()
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={t(($) => $['env.envPanelTitle'], { ns: 'workflow' })}
|
||||
aria-expanded={showEnvPanel}
|
||||
size="lg"
|
||||
className={cn(
|
||||
'border border-transparent',
|
||||
theme === 'dark' && showEnvPanel && 'border-black/5 bg-white/10 backdrop-blur-xs',
|
||||
)}
|
||||
variant="ghost"
|
||||
disabled={disabled}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-others-env size-4 text-components-button-secondary-text"
|
||||
/>
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{t(($) => $['env.envPanelTitle'], { ns: 'workflow' })}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(EnvButton)
|
||||
@@ -0,0 +1,58 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks/use-input-field-panel'
|
||||
import { useStore } from '@/app/components/workflow/store'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
|
||||
const GlobalVariableButton = ({ disabled }: { disabled: boolean }) => {
|
||||
const { theme } = useTheme()
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const showGlobalVariablePanel = useStore((s) => s.showGlobalVariablePanel)
|
||||
const setShowGlobalVariablePanel = useStore((s) => s.setShowGlobalVariablePanel)
|
||||
const setShowEnvPanel = useStore((s) => s.setShowEnvPanel)
|
||||
const setShowChatVariablePanel = useStore((s) => s.setShowChatVariablePanel)
|
||||
const setShowDebugAndPreviewPanel = useStore((s) => s.setShowDebugAndPreviewPanel)
|
||||
const { closeAllInputFieldPanels } = useInputFieldPanel()
|
||||
|
||||
const handleClick = () => {
|
||||
setShowGlobalVariablePanel(true)
|
||||
setShowEnvPanel(false)
|
||||
setShowChatVariablePanel(false)
|
||||
setShowDebugAndPreviewPanel(false)
|
||||
closeAllInputFieldPanels()
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={t(($) => $['globalVar.title'], { ns: 'workflow' })}
|
||||
aria-expanded={showGlobalVariablePanel}
|
||||
size="lg"
|
||||
className={cn(
|
||||
'border border-transparent',
|
||||
theme === 'dark' &&
|
||||
showGlobalVariablePanel &&
|
||||
'border-black/5 bg-white/10 backdrop-blur-xs',
|
||||
)}
|
||||
disabled={disabled}
|
||||
onClick={handleClick}
|
||||
variant="ghost"
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-others-global-variable size-4 text-components-button-secondary-text"
|
||||
/>
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{t(($) => $['globalVar.title'], { ns: 'workflow' })}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(GlobalVariableButton)
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { StartNodeType } from '../nodes/start/types'
|
||||
import type { RunAndHistoryProps } from './run-and-history'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { useCallback } from 'react'
|
||||
import { useNodes } from 'reactflow'
|
||||
import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks/use-input-field-panel'
|
||||
import { useHooksStore } from '../hooks-store'
|
||||
import { useNodesInteractions } from '../hooks/use-nodes-interactions'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import { useWorkflowRun } from '../hooks/use-workflow-run'
|
||||
import { useStore, useWorkflowStore } from '../store'
|
||||
import EditingTitle from './editing-title'
|
||||
import EnvButton from './env-button'
|
||||
import GlobalVariableButton from './global-variable-button'
|
||||
import OnlineUsers from './online-users'
|
||||
import RunAndHistory from './run-and-history'
|
||||
import ScrollToSelectedNodeButton from './scroll-to-selected-node-button'
|
||||
import { VersionHistoryButton } from './version-history-button'
|
||||
|
||||
export type HeaderInNormalProps = {
|
||||
components?: {
|
||||
title?: React.ReactNode
|
||||
left?: React.ReactNode
|
||||
middle?: React.ReactNode
|
||||
chatVariableTrigger?: React.ReactNode
|
||||
}
|
||||
controls?: {
|
||||
showEnvButton?: boolean
|
||||
showGlobalVariableButton?: boolean
|
||||
}
|
||||
runAndHistoryProps?: RunAndHistoryProps
|
||||
}
|
||||
const HeaderInNormal = ({ components, controls, runAndHistoryProps }: HeaderInNormalProps) => {
|
||||
const workflowStore = useWorkflowStore()
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const canReleaseAndVersion = useHooksStore((s) => s.accessControl.canReleaseAndVersion)
|
||||
const { handleNodeSelect } = useNodesInteractions()
|
||||
const setShowWorkflowVersionHistoryPanel = useStore((s) => s.setShowWorkflowVersionHistoryPanel)
|
||||
const setShowEnvPanel = useStore((s) => s.setShowEnvPanel)
|
||||
const setShowDebugAndPreviewPanel = useStore((s) => s.setShowDebugAndPreviewPanel)
|
||||
const setShowVariableInspectPanel = useStore((s) => s.setShowVariableInspectPanel)
|
||||
const setShowChatVariablePanel = useStore((s) => s.setShowChatVariablePanel)
|
||||
const setShowGlobalVariablePanel = useStore((s) => s.setShowGlobalVariablePanel)
|
||||
const nodes = useNodes<StartNodeType>()
|
||||
const selectedNode = nodes.find((node) => node.data.selected)
|
||||
const { handleBackupDraft } = useWorkflowRun()
|
||||
const { closeAllInputFieldPanels } = useInputFieldPanel()
|
||||
const showEnvButton = controls?.showEnvButton !== false
|
||||
const showGlobalVariableButton = controls?.showGlobalVariableButton !== false
|
||||
const showContextButtons =
|
||||
!!components?.chatVariableTrigger || showEnvButton || showGlobalVariableButton
|
||||
|
||||
const onStartRestoring = useCallback(() => {
|
||||
workflowStore.setState({ isRestoring: true })
|
||||
handleBackupDraft()
|
||||
// clear right panel
|
||||
if (selectedNode) handleNodeSelect(selectedNode.id, true)
|
||||
setShowWorkflowVersionHistoryPanel(true)
|
||||
setShowEnvPanel(false)
|
||||
setShowDebugAndPreviewPanel(false)
|
||||
setShowVariableInspectPanel(false)
|
||||
setShowChatVariablePanel(false)
|
||||
setShowGlobalVariablePanel(false)
|
||||
closeAllInputFieldPanels()
|
||||
}, [
|
||||
workflowStore,
|
||||
handleBackupDraft,
|
||||
selectedNode,
|
||||
handleNodeSelect,
|
||||
setShowWorkflowVersionHistoryPanel,
|
||||
setShowEnvPanel,
|
||||
setShowDebugAndPreviewPanel,
|
||||
setShowVariableInspectPanel,
|
||||
setShowChatVariablePanel,
|
||||
setShowGlobalVariablePanel,
|
||||
closeAllInputFieldPanels,
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div>{components?.title ?? <EditingTitle />}</div>
|
||||
<div>
|
||||
<ScrollToSelectedNodeButton />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<OnlineUsers />
|
||||
{components?.left}
|
||||
<Separator decorative orientation="vertical" className="mx-auto h-3.5" />
|
||||
<RunAndHistory {...runAndHistoryProps} />
|
||||
{showContextButtons && (
|
||||
<div className="shrink-0 cursor-pointer rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg shadow-xs backdrop-blur-[10px]">
|
||||
{components?.chatVariableTrigger}
|
||||
{showEnvButton && <EnvButton disabled={nodesReadOnly} />}
|
||||
{showGlobalVariableButton && <GlobalVariableButton disabled={nodesReadOnly} />}
|
||||
</div>
|
||||
)}
|
||||
{components?.middle}
|
||||
{canReleaseAndVersion && <VersionHistoryButton onClick={onStartRestoring} />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default HeaderInNormal
|
||||
@@ -0,0 +1,204 @@
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RiHistoryLine } from '@remixicon/react'
|
||||
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal'
|
||||
import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'
|
||||
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
|
||||
import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { deploymentEditionAtom } from '@/features/system-features/state'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
useInvalidateAllLastRun,
|
||||
useResetWorkflowVersionHistory,
|
||||
useRestoreWorkflow,
|
||||
} from '@/service/use-workflow'
|
||||
import { useWorkflowRefreshDraft } from '../hooks/use-workflow-refresh-draft'
|
||||
import { useWorkflowRun } from '../hooks/use-workflow-run'
|
||||
import { useStore, useWorkflowStore } from '../store'
|
||||
import { WorkflowVersion } from '../types'
|
||||
import RestoringTitle from './restoring-title'
|
||||
|
||||
export type HeaderInRestoringProps = {
|
||||
onRestoreSettled?: () => void
|
||||
}
|
||||
const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {
|
||||
const { t } = useTranslation(['billing', 'workflow', 'workflowHistory'])
|
||||
const { theme } = useTheme()
|
||||
const [isRestorePlanUpgradeModalOpen, setIsRestorePlanUpgradeModalOpen] = useState(false)
|
||||
const deploymentEdition = useAtomValue(deploymentEditionAtom)
|
||||
const { data: plan } = useQuery(
|
||||
consoleQuery.features.get.queryOptions({
|
||||
enabled: deploymentEdition === 'CLOUD',
|
||||
select: (data) => data.billing.subscription.plan,
|
||||
}),
|
||||
)
|
||||
const workflowStore = useWorkflowStore()
|
||||
const { data: userProfile } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.profile,
|
||||
})
|
||||
const resource = useAtomValue(editorResourceAtom)
|
||||
const resourceId = getEditorResourceId(resource)
|
||||
const invalidAllLastRun = useInvalidateAllLastRun(resource)
|
||||
const { deleteAllInspectVars } = workflowStore.getState()
|
||||
const currentVersion = useStore((s) => s.currentVersion)
|
||||
const setShowWorkflowVersionHistoryPanel = useStore((s) => s.setShowWorkflowVersionHistoryPanel)
|
||||
|
||||
const { handleLoadBackupDraft } = useWorkflowRun()
|
||||
const { handleRefreshWorkflowDraft } = useWorkflowRefreshDraft()
|
||||
const { mutateAsync: restoreWorkflow } = useRestoreWorkflow(resource)
|
||||
const resetWorkflowVersionHistory = useResetWorkflowVersionHistory()
|
||||
const canRestore =
|
||||
!!currentVersion?.id && !!resourceId && currentVersion.version !== WorkflowVersion.Draft
|
||||
const isPlanUnavailable = deploymentEdition === 'CLOUD' && plan === undefined
|
||||
const canEmitCollaborationEvents = resource.kind === 'app'
|
||||
|
||||
const handleCancelRestore = useCallback(() => {
|
||||
handleLoadBackupDraft()
|
||||
workflowStore.setState({ isRestoring: false })
|
||||
setShowWorkflowVersionHistoryPanel(false)
|
||||
}, [workflowStore, handleLoadBackupDraft, setShowWorkflowVersionHistoryPanel])
|
||||
|
||||
const emitRestoreIntent = useCallback(async () => {
|
||||
if (!currentVersion || !canEmitCollaborationEvents) return
|
||||
try {
|
||||
const { collaborationManager } = await import('../collaboration/core/collaboration-manager')
|
||||
collaborationManager.emitRestoreIntent({
|
||||
versionId: currentVersion.id,
|
||||
versionName: getWorkflowVersionName(
|
||||
currentVersion,
|
||||
t(($) => $['versionHistory.defaultName'], { ns: 'workflowHistory' }),
|
||||
),
|
||||
initiatorUserId: userProfile.id,
|
||||
initiatorName: userProfile.name,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to emit restore intent:', error)
|
||||
}
|
||||
}, [canEmitCollaborationEvents, currentVersion, t, userProfile.id, userProfile.name])
|
||||
|
||||
const emitRestoreComplete = useCallback(
|
||||
async (success: boolean, errorMessage?: string) => {
|
||||
if (!currentVersion || !canEmitCollaborationEvents) return
|
||||
try {
|
||||
const { collaborationManager } = await import('../collaboration/core/collaboration-manager')
|
||||
collaborationManager.emitRestoreComplete({
|
||||
versionId: currentVersion.id,
|
||||
success,
|
||||
...(errorMessage ? { error: errorMessage } : {}),
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to emit restore complete:', error)
|
||||
}
|
||||
},
|
||||
[canEmitCollaborationEvents, currentVersion],
|
||||
)
|
||||
|
||||
const emitWorkflowUpdate = useCallback(async () => {
|
||||
if (!resourceId || !canEmitCollaborationEvents) return
|
||||
try {
|
||||
const { collaborationManager } = await import('../collaboration/core/collaboration-manager')
|
||||
collaborationManager.emitWorkflowUpdate(resourceId)
|
||||
} catch (error) {
|
||||
console.error('Failed to emit workflow update:', error)
|
||||
}
|
||||
}, [canEmitCollaborationEvents, resourceId])
|
||||
|
||||
const handleRestore = useCallback(async () => {
|
||||
if (isPlanUnavailable || !canRestore || !currentVersion) return
|
||||
|
||||
if (deploymentEdition === 'CLOUD' && plan === 'sandbox') {
|
||||
setIsRestorePlanUpgradeModalOpen(true)
|
||||
return
|
||||
}
|
||||
|
||||
setShowWorkflowVersionHistoryPanel(false)
|
||||
await emitRestoreIntent()
|
||||
|
||||
try {
|
||||
await restoreWorkflow(currentVersion.id)
|
||||
workflowStore.setState({ isRestoring: false })
|
||||
workflowStore.setState({ backupDraft: undefined })
|
||||
handleRefreshWorkflowDraft()
|
||||
toast.success(t(($) => $['versionHistory.action.restoreSuccess'], { ns: 'workflowHistory' }))
|
||||
deleteAllInspectVars()
|
||||
invalidAllLastRun()
|
||||
await emitRestoreComplete(true)
|
||||
await emitWorkflowUpdate()
|
||||
} catch {
|
||||
toast.error(t(($) => $['versionHistory.action.restoreFailure'], { ns: 'workflowHistory' }))
|
||||
await emitRestoreComplete(false, 'restore failed')
|
||||
} finally {
|
||||
resetWorkflowVersionHistory()
|
||||
onRestoreSettled?.()
|
||||
}
|
||||
}, [
|
||||
isPlanUnavailable,
|
||||
canRestore,
|
||||
currentVersion,
|
||||
deploymentEdition,
|
||||
plan,
|
||||
setShowWorkflowVersionHistoryPanel,
|
||||
emitRestoreIntent,
|
||||
restoreWorkflow,
|
||||
workflowStore,
|
||||
handleRefreshWorkflowDraft,
|
||||
t,
|
||||
deleteAllInspectVars,
|
||||
invalidAllLastRun,
|
||||
emitRestoreComplete,
|
||||
emitWorkflowUpdate,
|
||||
resetWorkflowVersionHistory,
|
||||
onRestoreSettled,
|
||||
])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<RestoringTitle />
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-x-2">
|
||||
<Button
|
||||
onClick={handleRestore}
|
||||
disabled={isPlanUnavailable || !canRestore}
|
||||
variant="primary"
|
||||
className={cn(
|
||||
'rounded-lg inset-ring-1 inset-ring-transparent',
|
||||
theme === 'dark' && 'bg-white/10 inset-ring-black/5 backdrop-blur-xs',
|
||||
)}
|
||||
>
|
||||
{t(($) => $['common.restore'], { ns: 'workflow' })}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleCancelRestore}
|
||||
className={cn(
|
||||
'rounded-lg text-components-button-secondary-accent-text inset-ring-1 inset-ring-transparent',
|
||||
theme === 'dark' && 'bg-white/10 inset-ring-black/5 backdrop-blur-xs',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-x-0.5">
|
||||
<RiHistoryLine className="size-4" />
|
||||
<span className="px-0.5">{t(($) => $['common.exitVersions'], { ns: 'workflow' })}</span>
|
||||
</div>
|
||||
</Button>
|
||||
</div>
|
||||
{isRestorePlanUpgradeModalOpen && (
|
||||
<PlanUpgradeModal
|
||||
show
|
||||
onClose={() => setIsRestorePlanUpgradeModalOpen(false)}
|
||||
title={t(($) => $['upgrade.workflowRestore.title'], { ns: 'billing' })!}
|
||||
description={t(($) => $['upgrade.workflowRestore.description'], { ns: 'billing' })!}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default HeaderInRestoring
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { ViewHistoryProps } from './view-history'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useWorkflowRun } from '../hooks/use-workflow-run'
|
||||
import { useWorkflowStore } from '../store'
|
||||
import RunningTitle from './running-title'
|
||||
import ViewHistory from './view-history'
|
||||
|
||||
export type HeaderInHistoryProps = {
|
||||
viewHistoryProps?: ViewHistoryProps
|
||||
}
|
||||
const HeaderInHistory = ({ viewHistoryProps }: HeaderInHistoryProps) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const workflowStore = useWorkflowStore()
|
||||
|
||||
const { handleLoadBackupDraft } = useWorkflowRun()
|
||||
|
||||
const handleGoBackToEdit = useCallback(() => {
|
||||
handleLoadBackupDraft()
|
||||
workflowStore.setState({ historyWorkflowData: undefined })
|
||||
}, [workflowStore, handleLoadBackupDraft])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<RunningTitle />
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<ViewHistory {...viewHistoryProps} withText />
|
||||
<Separator decorative orientation="vertical" className="mx-auto h-3.5" />
|
||||
<Button variant="primary" onClick={handleGoBackToEdit}>
|
||||
<span aria-hidden className="i-custom-vender-line-arrows-arrow-narrow-left size-4" />
|
||||
{t(($) => $['common.goBackToEdit'], { ns: 'workflow' })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default HeaderInHistory
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { HeaderInNormalProps } from './header-in-normal'
|
||||
import type { HeaderInRestoringProps } from './header-in-restoring'
|
||||
import type { HeaderInHistoryProps } from './header-in-view-history'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { useWorkflowMode } from '../hooks/use-workflow-mode'
|
||||
import HeaderInNormal from './header-in-normal'
|
||||
|
||||
const HeaderInHistory = dynamic(() => import('./header-in-view-history'), {
|
||||
ssr: false,
|
||||
})
|
||||
const HeaderInRestoring = dynamic(() => import('./header-in-restoring'), {
|
||||
ssr: false,
|
||||
})
|
||||
|
||||
export type HeaderProps = {
|
||||
normal?: HeaderInNormalProps
|
||||
viewHistory?: HeaderInHistoryProps
|
||||
restoring?: HeaderInRestoringProps
|
||||
}
|
||||
const Header = ({
|
||||
normal: normalProps,
|
||||
viewHistory: viewHistoryProps,
|
||||
restoring: restoringProps,
|
||||
}: HeaderProps) => {
|
||||
const { normal, restoring, viewHistory } = useWorkflowMode()
|
||||
|
||||
return (
|
||||
<div className="absolute top-7 left-0 z-10 flex h-0 w-full items-center justify-between bg-mask-top2bottom-gray-50-to-transparent px-3">
|
||||
{normal && <HeaderInNormal {...normalProps} />}
|
||||
{viewHistory && <HeaderInHistory {...viewHistoryProps} />}
|
||||
{restoring && <HeaderInRestoring {...restoringProps} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Header
|
||||
@@ -0,0 +1,248 @@
|
||||
'use client'
|
||||
|
||||
import type { OnlineUser } from '../collaboration/types/collaboration'
|
||||
import { ChevronDownIcon } from '@heroicons/react/20/solid'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useReactFlow } from 'reactflow'
|
||||
import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { getAvatar } from '@/service/common'
|
||||
import { getAvatarInitial } from '@/utils/avatar'
|
||||
import { useCollaboration } from '../collaboration/hooks/use-collaboration'
|
||||
import { getUserColor } from '../collaboration/utils/user-color'
|
||||
import { useHooksStore } from '../hooks-store'
|
||||
|
||||
const useAvatarUrls = (users: OnlineUser[]) => {
|
||||
const [avatarUrls, setAvatarUrls] = useState<Record<string, string>>({})
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAvatars = async () => {
|
||||
const newAvatarUrls: Record<string, string> = {}
|
||||
|
||||
await Promise.all(
|
||||
users.map(async (user) => {
|
||||
if (user.avatar) {
|
||||
try {
|
||||
const response = await getAvatar({ avatar: user.avatar })
|
||||
newAvatarUrls[user.sid] = response.avatar_url
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch avatar:', error)
|
||||
newAvatarUrls[user.sid] = user.avatar
|
||||
}
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
setAvatarUrls(newAvatarUrls)
|
||||
}
|
||||
|
||||
if (users.length > 0) fetchAvatars()
|
||||
}, [users])
|
||||
|
||||
return avatarUrls
|
||||
}
|
||||
|
||||
const OnlineUsers = () => {
|
||||
const { t } = useTranslation(['workspaceMembers', 'workflowComments'])
|
||||
const appId = useAtomValue(editorAppIdAtom)
|
||||
const canEdit = useHooksStore((s) => s.accessControl.canEdit)
|
||||
const {
|
||||
onlineUsers,
|
||||
cursors,
|
||||
isEnabled: isCollaborationEnabled,
|
||||
} = useCollaboration(appId, canEdit)
|
||||
const { data: currentUserId } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.profile.id,
|
||||
})
|
||||
const reactFlow = useReactFlow()
|
||||
const [dropdownOpen, setDropdownOpen] = useState(false)
|
||||
const avatarUrls = useAvatarUrls(onlineUsers || [])
|
||||
|
||||
const fallbackUsername = t(($) => $['comments.fallback.user'], { ns: 'workflowComments' })
|
||||
const currentUserSuffix = t(($) => $['members.you'], { ns: 'workspaceMembers' })
|
||||
|
||||
const renderDisplayName = (user: OnlineUser, baseClassName: string, suffixClassName: string) => {
|
||||
const baseName = user.username || fallbackUsername
|
||||
const isCurrentUser = user.user_id === currentUserId
|
||||
|
||||
return (
|
||||
<span className={cn('inline-flex min-w-0 items-center gap-1', baseClassName)}>
|
||||
<span className="truncate">{baseName}</span>
|
||||
{isCurrentUser && (
|
||||
<span className={cn('shrink-0', suffixClassName)}>{currentUserSuffix}</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// Function to jump to user's cursor position
|
||||
const jumpToUserCursor = (userId: string) => {
|
||||
const cursor = cursors[userId]
|
||||
if (!cursor) return
|
||||
|
||||
// Convert world coordinates to center the view on the cursor
|
||||
reactFlow.setCenter(cursor.x, cursor.y, { zoom: 1, duration: 800 })
|
||||
}
|
||||
|
||||
if (!isCollaborationEnabled || !onlineUsers || onlineUsers.length === 0) return null
|
||||
|
||||
// Display logic:
|
||||
// 1-3 users: show all avatars
|
||||
// 4+ users: show 2 avatars + count + arrow
|
||||
const shouldShowCount = onlineUsers.length >= 4
|
||||
const maxVisible = shouldShowCount ? 2 : 3
|
||||
const visibleUsers = onlineUsers.slice(0, maxVisible)
|
||||
const remainingCount = onlineUsers.length - maxVisible
|
||||
|
||||
const getAvatarUrl = (user: OnlineUser) => {
|
||||
return avatarUrls[user.sid] || user.avatar
|
||||
}
|
||||
|
||||
const hasCounter = remainingCount > 0
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-8 items-center rounded-full border-[0.5px] border-components-panel-border',
|
||||
'bg-components-panel-bg py-1 shadow-xs shadow-shadow-shadow-3 backdrop-blur-[10px]',
|
||||
hasCounter ? 'min-w-21.75 gap-px pr-1.5 pl-1' : 'gap-1 px-1.5',
|
||||
)}
|
||||
>
|
||||
<div className="flex h-6 items-center">
|
||||
<div className="flex items-center">
|
||||
{visibleUsers.map((user, index) => {
|
||||
const isCurrentUser = user.user_id === currentUserId
|
||||
const userColor = isCurrentUser ? undefined : getUserColor(user.user_id)
|
||||
const avatarUrl = getAvatarUrl(user)
|
||||
const displayName = user.username || fallbackUsername
|
||||
const avatar = (
|
||||
<Avatar size="sm" aria-hidden="true" className="ring-1 ring-components-panel-bg">
|
||||
<AvatarFallback style={userColor ? { backgroundColor: userColor } : undefined}>
|
||||
{getAvatarInitial(displayName)}
|
||||
</AvatarFallback>
|
||||
<AvatarImage src={avatarUrl || undefined} alt="" />
|
||||
</Avatar>
|
||||
)
|
||||
const triggerClassName = cn(
|
||||
'relative flex size-6 items-center justify-center',
|
||||
index > 0 && '-ml-1.5',
|
||||
!isCurrentUser && 'cursor-pointer transition-transform hover:scale-110',
|
||||
)
|
||||
const triggerStyle = { zIndex: visibleUsers.length - index }
|
||||
return (
|
||||
<Tooltip key={user.sid}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
isCurrentUser ? (
|
||||
<div
|
||||
role="img"
|
||||
aria-label={displayName}
|
||||
className={triggerClassName}
|
||||
style={triggerStyle}
|
||||
>
|
||||
{avatar}
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={displayName}
|
||||
className={triggerClassName}
|
||||
style={triggerStyle}
|
||||
onClick={() => jumpToUserCursor(user.user_id)}
|
||||
>
|
||||
{avatar}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<TooltipContent side="bottom" sideOffset={4} className="max-w-55">
|
||||
{displayName}
|
||||
{isCurrentUser && (
|
||||
<span className="ml-1 text-text-quaternary">{currentUserSuffix}</span>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
{remainingCount > 0 && (
|
||||
<Popover open={dropdownOpen} onOpenChange={setDropdownOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<div className="flex items-center gap-1">
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-6 w-6 cursor-pointer items-center justify-center rounded-full bg-components-icon-bg-midnight-solid text-2xs leading-3 font-semibold text-white uppercase ring-1 ring-components-panel-bg select-none',
|
||||
visibleUsers.length > 0 && '-ml-1',
|
||||
)}
|
||||
>
|
||||
+{remainingCount}
|
||||
</div>
|
||||
<ChevronDownIcon className="size-3 cursor-pointer text-gray-500" />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
alignOffset={-48}
|
||||
className={cn(
|
||||
'mt-1.5 flex max-h-50 w-60 flex-col overflow-y-auto',
|
||||
'rounded-xl border-[0.5px] border-components-panel-border',
|
||||
'bg-components-panel-bg-blur p-1 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[10px]',
|
||||
)}
|
||||
>
|
||||
{onlineUsers.map((user) => {
|
||||
const isCurrentUser = user.user_id === currentUserId
|
||||
const userColor = isCurrentUser ? undefined : getUserColor(user.user_id)
|
||||
const avatarUrl = getAvatarUrl(user)
|
||||
const displayName = user.username || fallbackUsername
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={user.sid}
|
||||
disabled={isCurrentUser}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-left',
|
||||
!isCurrentUser &&
|
||||
'cursor-pointer hover:bg-components-panel-on-panel-item-bg-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
jumpToUserCursor(user.user_id)
|
||||
setDropdownOpen(false)
|
||||
}}
|
||||
>
|
||||
<div className="relative">
|
||||
<Avatar size="sm" aria-hidden="true">
|
||||
<AvatarFallback
|
||||
style={userColor ? { backgroundColor: userColor } : undefined}
|
||||
>
|
||||
{getAvatarInitial(displayName)}
|
||||
</AvatarFallback>
|
||||
<AvatarImage src={avatarUrl || undefined} alt="" />
|
||||
</Avatar>
|
||||
</div>
|
||||
{renderDisplayName(
|
||||
user,
|
||||
'system-xs-medium text-text-secondary',
|
||||
'text-text-tertiary',
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default OnlineUsers
|
||||
@@ -0,0 +1,49 @@
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'
|
||||
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
|
||||
import useTimestamp from '@/hooks/use-timestamp'
|
||||
import { useStore } from '../store'
|
||||
import { WorkflowVersion } from '../types'
|
||||
|
||||
const RestoringTitle = () => {
|
||||
const { t } = useTranslation(['workflow', 'workflowHistory'])
|
||||
const { formatTimeFromNow } = useFormatTimeFromNow()
|
||||
const { formatTime } = useTimestamp()
|
||||
const currentVersion = useStore((state) => state.currentVersion)
|
||||
const isDraft = currentVersion?.version === WorkflowVersion.Draft
|
||||
const publishStatus = isDraft
|
||||
? t(($) => $['common.unpublished'], { ns: 'workflow' })
|
||||
: t(($) => $['common.published'], { ns: 'workflow' })
|
||||
|
||||
const versionName = isDraft
|
||||
? t(($) => $['versionHistory.currentDraft'], { ns: 'workflowHistory' })
|
||||
: getWorkflowVersionName(
|
||||
currentVersion,
|
||||
t(($) => $['versionHistory.defaultName'], { ns: 'workflowHistory' }),
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-y-0.5">
|
||||
<div className="flex items-center gap-x-1">
|
||||
<span className="system-sm-semibold text-text-primary">{versionName}</span>
|
||||
<span className="rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-accent-secondary">
|
||||
{t(($) => $['common.viewOnly'], { ns: 'workflow' })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex h-4 items-center gap-x-1 system-xs-regular text-text-tertiary">
|
||||
{currentVersion && (
|
||||
<>
|
||||
<span>{publishStatus}</span>
|
||||
<span>·</span>
|
||||
<span>{`${formatTimeFromNow((isDraft ? currentVersion.updated_at : currentVersion.created_at) * 1000)} ${formatTime(currentVersion.created_at, 'HH:mm:ss')}`}</span>
|
||||
<span>·</span>
|
||||
<span>{currentVersion?.created_by?.name || ''}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(RestoringTitle)
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { ViewHistoryProps } from './view-history'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useHooksStore } from '../hooks-store'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import { useWorkflowStartRun } from '../hooks/use-workflow-start-run'
|
||||
import Checklist from './checklist'
|
||||
import RunMode from './run-mode'
|
||||
import ViewHistory from './view-history'
|
||||
|
||||
const PreviewMode = memo(({ disabled = false }: { disabled?: boolean }) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const { handleWorkflowStartRunInChatflow } = useWorkflowStartRun()
|
||||
const canRun = useHooksStore((s) => s.accessControl.canRun)
|
||||
const isDisabled = disabled || !canRun
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isDisabled}
|
||||
className={cn(
|
||||
'flex h-7 items-center rounded-md px-2.5 text-[13px] font-medium text-components-button-secondary-accent-text',
|
||||
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:bg-state-accent-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (!isDisabled) handleWorkflowStartRunInChatflow()
|
||||
}}
|
||||
>
|
||||
<span aria-hidden className="mr-1 i-ri-play-large-line size-4" />
|
||||
{t(($) => $['common.debugAndPreview'], { ns: 'workflow' })}
|
||||
</button>
|
||||
)
|
||||
})
|
||||
|
||||
export type RunAndHistoryProps = {
|
||||
showRunButton?: boolean
|
||||
runButtonText?: string
|
||||
isRunning?: boolean
|
||||
showPreviewButton?: boolean
|
||||
viewHistoryProps?: ViewHistoryProps
|
||||
components?: {
|
||||
RunMode?: React.ComponentType<{
|
||||
text?: string
|
||||
disabled?: boolean
|
||||
}>
|
||||
}
|
||||
}
|
||||
const RunAndHistory = ({
|
||||
showRunButton,
|
||||
runButtonText,
|
||||
showPreviewButton,
|
||||
viewHistoryProps,
|
||||
components,
|
||||
}: RunAndHistoryProps) => {
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const canRun = useHooksStore((s) => s.accessControl.canRun)
|
||||
const { RunMode: CustomRunMode } = components || {}
|
||||
|
||||
return (
|
||||
<div className="flex h-8 items-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-0.5 shadow-xs">
|
||||
{showRunButton &&
|
||||
(CustomRunMode ? (
|
||||
<CustomRunMode text={runButtonText} disabled={!canRun} />
|
||||
) : (
|
||||
<RunMode text={runButtonText} disabled={!canRun} />
|
||||
))}
|
||||
{showPreviewButton && <PreviewMode disabled={!canRun} />}
|
||||
<div className="mx-0.5 h-3.5 w-px bg-divider-regular"></div>
|
||||
<ViewHistory {...viewHistoryProps} />
|
||||
<Checklist disabled={nodesReadOnly} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(RunAndHistory)
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { TestRunMenuRef, TriggerOption } from './test-run-menu'
|
||||
import type { EventEmitterValue } from '@/context/event-emitter'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useHotkey } from '@tanstack/react-hotkeys'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { trackEvent } from '@/app/components/base/amplitude'
|
||||
import { useHooksStore } from '@/app/components/workflow/hooks-store'
|
||||
import { ShortcutKbd } from '@/app/components/workflow/shortcuts/shortcut-kbd'
|
||||
import { useStore } from '@/app/components/workflow/store/workflow'
|
||||
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
|
||||
import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { useEventEmitterContextContext } from '@/context/event-emitter'
|
||||
import { useWorkflowRunValidation } from '../hooks/use-checklist'
|
||||
import { useDynamicTestRunOptions } from '../hooks/use-dynamic-test-run-options'
|
||||
import { useWorkflowRun } from '../hooks/use-workflow-run'
|
||||
import { useWorkflowStartRun } from '../hooks/use-workflow-start-run'
|
||||
import { TEST_RUN_MENU_HOTKEY } from '../hotkeys'
|
||||
import TestRunMenu, { TriggerType } from './test-run-menu'
|
||||
|
||||
type RunModeProps = {
|
||||
text?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const isWorkflowStopEvent = (value: EventEmitterValue) =>
|
||||
typeof value !== 'string' && value.type === EVENT_WORKFLOW_STOP
|
||||
|
||||
const RunMode = ({ text, disabled = false }: RunModeProps) => {
|
||||
const { t } = useTranslation(['workflow', 'workflowDebug'])
|
||||
const {
|
||||
handleWorkflowStartRunInWorkflow,
|
||||
handleWorkflowTriggerScheduleRunInWorkflow,
|
||||
handleWorkflowTriggerWebhookRunInWorkflow,
|
||||
handleWorkflowTriggerPluginRunInWorkflow,
|
||||
handleWorkflowRunAllTriggersInWorkflow,
|
||||
} = useWorkflowStartRun()
|
||||
const { handleStopRun } = useWorkflowRun()
|
||||
const { warningNodes } = useWorkflowRunValidation()
|
||||
const workflowRunningData = useStore((s) => s.workflowRunningData)
|
||||
const isListening = useStore((s) => s.isListening)
|
||||
const canRun = useHooksStore((s) => s.accessControl.canRun)
|
||||
const isRunDisabled = disabled || !canRun
|
||||
|
||||
const status = workflowRunningData?.result.status
|
||||
const isRunning = status === WorkflowRunningStatus.Running || isListening
|
||||
|
||||
const dynamicOptions = useDynamicTestRunOptions()
|
||||
const testRunMenuRef = useRef<TestRunMenuRef>(null)
|
||||
|
||||
const handleToggleTestRunMenu = useCallback(() => {
|
||||
if (isRunDisabled) return
|
||||
|
||||
testRunMenuRef.current?.toggle()
|
||||
}, [isRunDisabled])
|
||||
|
||||
useHotkey(
|
||||
TEST_RUN_MENU_HOTKEY,
|
||||
(event) => {
|
||||
if (event.defaultPrevented) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
if (event.repeat) return
|
||||
handleToggleTestRunMenu()
|
||||
},
|
||||
{
|
||||
enabled: !isRunDisabled,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
ignoreInputs: true,
|
||||
},
|
||||
)
|
||||
|
||||
const handleStop = useCallback(() => {
|
||||
handleStopRun(workflowRunningData?.task_id || '')
|
||||
}, [handleStopRun, workflowRunningData?.task_id])
|
||||
|
||||
const handleTriggerSelect = useCallback(
|
||||
(option: TriggerOption) => {
|
||||
if (isRunDisabled) return
|
||||
|
||||
// Validate checklist before running any workflow
|
||||
let isValid: boolean = true
|
||||
warningNodes.forEach((node) => {
|
||||
if (node.id === option.nodeId) isValid = false
|
||||
})
|
||||
if (!isValid) {
|
||||
toast.error(t(($) => $['panel.checklistTip'], { ns: 'workflow' }))
|
||||
return
|
||||
}
|
||||
|
||||
if (option.type === TriggerType.UserInput) {
|
||||
handleWorkflowStartRunInWorkflow()
|
||||
trackEvent('app_start_action_time', { action_type: 'user_input' })
|
||||
} else if (option.type === TriggerType.Schedule) {
|
||||
handleWorkflowTriggerScheduleRunInWorkflow(option.nodeId)
|
||||
trackEvent('app_start_action_time', { action_type: 'schedule' })
|
||||
} else if (option.type === TriggerType.Webhook) {
|
||||
if (option.nodeId) handleWorkflowTriggerWebhookRunInWorkflow({ nodeId: option.nodeId })
|
||||
trackEvent('app_start_action_time', { action_type: 'webhook' })
|
||||
} else if (option.type === TriggerType.Plugin) {
|
||||
if (option.nodeId) handleWorkflowTriggerPluginRunInWorkflow(option.nodeId)
|
||||
trackEvent('app_start_action_time', { action_type: 'plugin' })
|
||||
} else if (option.type === TriggerType.All) {
|
||||
const targetNodeIds = option.relatedNodeIds?.filter(Boolean)
|
||||
if (targetNodeIds && targetNodeIds.length > 0)
|
||||
handleWorkflowRunAllTriggersInWorkflow(targetNodeIds)
|
||||
trackEvent('app_start_action_time', { action_type: 'all' })
|
||||
}
|
||||
},
|
||||
[
|
||||
isRunDisabled,
|
||||
warningNodes,
|
||||
t,
|
||||
handleWorkflowStartRunInWorkflow,
|
||||
handleWorkflowTriggerScheduleRunInWorkflow,
|
||||
handleWorkflowTriggerWebhookRunInWorkflow,
|
||||
handleWorkflowTriggerPluginRunInWorkflow,
|
||||
handleWorkflowRunAllTriggersInWorkflow,
|
||||
],
|
||||
)
|
||||
|
||||
const { eventEmitter } = useEventEmitterContextContext()
|
||||
eventEmitter?.useSubscription((v: EventEmitterValue) => {
|
||||
if (isWorkflowStopEvent(v)) handleStop()
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-x-px">
|
||||
{isRunDisabled ? (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex h-7 cursor-not-allowed items-center gap-x-1 rounded-md px-1.5 system-xs-medium text-text-accent opacity-50',
|
||||
)}
|
||||
disabled
|
||||
style={{ userSelect: 'none' }}
|
||||
>
|
||||
<span aria-hidden className="mr-1 i-ri-play-large-line size-4" />
|
||||
{text ?? t(($) => $['common.run'], { ns: 'workflow' })}
|
||||
<ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} textColor="secondary" />
|
||||
</button>
|
||||
) : isRunning ? (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex h-7 cursor-not-allowed items-center gap-x-1 rounded-l-md bg-state-accent-hover px-1.5 system-xs-medium text-text-accent',
|
||||
)}
|
||||
disabled={true}
|
||||
>
|
||||
<span className="mr-1 i-ri-loader-2-line size-4 animate-spin" />
|
||||
{isListening
|
||||
? t(($) => $['common.listening'], { ns: 'workflow' })
|
||||
: t(($) => $['common.running'], { ns: 'workflow' })}
|
||||
</button>
|
||||
) : (
|
||||
<TestRunMenu ref={testRunMenuRef} options={dynamicOptions} onSelect={handleTriggerSelect}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex h-7 cursor-pointer items-center gap-x-1 rounded-md px-1.5 system-xs-medium text-text-accent hover:bg-state-accent-hover',
|
||||
)}
|
||||
style={{ userSelect: 'none' }}
|
||||
>
|
||||
<span aria-hidden className="mr-1 i-ri-play-large-line size-4" />
|
||||
{text ?? t(($) => $['common.run'], { ns: 'workflow' })}
|
||||
<ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} textColor="secondary" />
|
||||
</button>
|
||||
</TestRunMenu>
|
||||
)}
|
||||
{isRunning && !isRunDisabled && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['debug.variableInspect.trigger.stop'], { ns: 'workflowDebug' })}
|
||||
className={cn(
|
||||
'flex size-7 items-center justify-center rounded-r-md bg-state-accent-active',
|
||||
)}
|
||||
onClick={handleStop}
|
||||
>
|
||||
<span aria-hidden className="i-ri-stop-circle-line size-4 text-text-accent" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(RunMode)
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { memo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'
|
||||
import { useStore } from '../store'
|
||||
import { formatWorkflowRunIdentifier } from '../utils'
|
||||
|
||||
const RunningTitle = () => {
|
||||
const { t } = useTranslation(['workflow'] as const)
|
||||
const isChatflow = useAtomValue(isChatflowAtom)
|
||||
const historyWorkflowData = useStore((s) => s.historyWorkflowData)
|
||||
|
||||
return (
|
||||
<div className="flex h-4.5 items-center text-xs text-gray-500">
|
||||
<span
|
||||
aria-hidden
|
||||
className="me-1 i-custom-vender-line-time-clock-play size-3 text-gray-500"
|
||||
/>
|
||||
<span>
|
||||
{isChatflow
|
||||
? `Test Chat${formatWorkflowRunIdentifier(historyWorkflowData?.finished_at, historyWorkflowData?.status)}`
|
||||
: `Test Run${formatWorkflowRunIdentifier(historyWorkflowData?.finished_at, historyWorkflowData?.status)}`}
|
||||
</span>
|
||||
<span className="mx-1">·</span>
|
||||
<span className="ms-1 flex h-4.5 items-center rounded-[5px] border border-indigo-300 bg-white/48 px-1 text-2xs font-semibold text-indigo-600 uppercase">
|
||||
{t(($) => $['common.viewOnly'], { ns: 'workflow' })}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(RunningTitle)
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { FC } from 'react'
|
||||
import type { CommonNodeType } from '../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useNodes } from 'reactflow'
|
||||
import { scrollToWorkflowNode } from '../utils/node-navigation'
|
||||
|
||||
const ScrollToSelectedNodeButton: FC = () => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const nodes = useNodes<CommonNodeType>()
|
||||
const selectedNode = nodes.find((node) => node.data.selected)
|
||||
|
||||
if (!selectedNode) return null
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex h-6 cursor-pointer appearance-none items-center justify-center rounded-md border-[0.5px] border-effects-highlight bg-components-actionbar-bg px-3 system-xs-medium whitespace-nowrap text-text-tertiary shadow-lg backdrop-blur-xs transition-colors duration-200 hover:text-text-accent focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
|
||||
)}
|
||||
onClick={() => scrollToWorkflowNode(selectedNode.id)}
|
||||
>
|
||||
{t(($) => $['panel.scrollToSelectedNode'], { ns: 'workflow' })}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default ScrollToSelectedNodeButton
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { KeyboardEvent, MouseEvent, MouseEventHandler, ReactElement } from 'react'
|
||||
import type { TriggerOption } from './test-run-menu'
|
||||
import { cloneElement, isValidElement } from 'react'
|
||||
|
||||
export type ShortcutMapping = {
|
||||
option: TriggerOption
|
||||
shortcutKey: string
|
||||
}
|
||||
|
||||
export const getNormalizedShortcutKey = (event: Pick<KeyboardEvent, 'key'>) => {
|
||||
return event.key === '`' ? '~' : event.key
|
||||
}
|
||||
|
||||
export function handleShortcutMenuKeyDown(
|
||||
event: KeyboardEvent,
|
||||
shortcutMappings: ShortcutMapping[],
|
||||
onSelect: (option: TriggerOption) => void,
|
||||
) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.nativeEvent.isComposing ||
|
||||
event.repeat ||
|
||||
event.altKey ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey
|
||||
)
|
||||
return
|
||||
|
||||
const normalizedKey = getNormalizedShortcutKey(event)
|
||||
const mapping = shortcutMappings.find(({ shortcutKey }) => shortcutKey === normalizedKey)
|
||||
if (!mapping) return
|
||||
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
onSelect(mapping.option)
|
||||
}
|
||||
|
||||
export const SingleOptionTrigger = ({
|
||||
children,
|
||||
runSoleOption,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
runSoleOption: () => void
|
||||
}) => {
|
||||
const handleRunClick = (event?: MouseEvent<HTMLElement>) => {
|
||||
if (event?.defaultPrevented) return
|
||||
|
||||
runSoleOption()
|
||||
}
|
||||
|
||||
if (isValidElement(children)) {
|
||||
const childElement = children as ReactElement<{ onClick?: MouseEventHandler<HTMLElement> }>
|
||||
const originalOnClick = childElement.props?.onClick
|
||||
|
||||
// oxlint-disable-next-line react/no-clone-element
|
||||
return cloneElement(childElement, {
|
||||
onClick: (event: MouseEvent<HTMLElement>) => {
|
||||
if (typeof originalOnClick === 'function') originalOnClick(event)
|
||||
|
||||
if (event?.defaultPrevented) return
|
||||
|
||||
runSoleOption()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<button type="button" onClick={handleRunClick}>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import type { ShortcutMapping } from './test-run-menu-helpers'
|
||||
import {
|
||||
Menu,
|
||||
MenuContent,
|
||||
MenuGroup,
|
||||
MenuGroupLabel,
|
||||
MenuItem,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import {
|
||||
forwardRef,
|
||||
isValidElement,
|
||||
useCallback,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ShortcutKbd } from '../shortcuts/shortcut-kbd'
|
||||
import { handleShortcutMenuKeyDown, SingleOptionTrigger } from './test-run-menu-helpers'
|
||||
|
||||
export const TriggerType = {
|
||||
UserInput: 'user_input',
|
||||
Schedule: 'schedule',
|
||||
Webhook: 'webhook',
|
||||
Plugin: 'plugin',
|
||||
All: 'all',
|
||||
} as const
|
||||
|
||||
export type TriggerType = (typeof TriggerType)[keyof typeof TriggerType]
|
||||
|
||||
export type TriggerOption = {
|
||||
id: string
|
||||
type: TriggerType
|
||||
name: string
|
||||
icon: React.ReactNode
|
||||
nodeId?: string
|
||||
relatedNodeIds?: string[]
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export type TestRunOptions = {
|
||||
userInput?: TriggerOption
|
||||
triggers: TriggerOption[]
|
||||
runAll?: TriggerOption
|
||||
}
|
||||
|
||||
type TestRunMenuProps = {
|
||||
options: TestRunOptions
|
||||
onSelect: (option: TriggerOption) => void
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export type TestRunMenuRef = {
|
||||
toggle: () => void
|
||||
}
|
||||
|
||||
const OptionRow = ({
|
||||
option,
|
||||
shortcutKey,
|
||||
onSelect,
|
||||
}: {
|
||||
option: TriggerOption
|
||||
shortcutKey?: string
|
||||
onSelect: (option: TriggerOption) => void
|
||||
}) => {
|
||||
return (
|
||||
<MenuItem
|
||||
className="h-auto gap-3 px-3 py-1.5 system-md-regular"
|
||||
onClick={() => onSelect(option)}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex size-6 shrink-0 items-center justify-center">{option.icon}</div>
|
||||
<span className="truncate">{option.name}</span>
|
||||
</div>
|
||||
{shortcutKey && <ShortcutKbd displayKey={shortcutKey} textColor="secondary" />}
|
||||
</MenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
const getEnabledOptions = (options: TestRunOptions) => {
|
||||
const flattened: TriggerOption[] = []
|
||||
|
||||
if (options.userInput) flattened.push(options.userInput)
|
||||
if (options.runAll) flattened.push(options.runAll)
|
||||
flattened.push(...options.triggers)
|
||||
|
||||
return flattened.filter((option) => option.enabled !== false)
|
||||
}
|
||||
|
||||
const getMenuVisibility = (options: TestRunOptions) => {
|
||||
return {
|
||||
hasUserInput: Boolean(options.userInput?.enabled !== false && options.userInput),
|
||||
hasTriggers: options.triggers.some((trigger) => trigger.enabled !== false),
|
||||
hasRunAll: Boolean(options.runAll?.enabled !== false && options.runAll),
|
||||
}
|
||||
}
|
||||
|
||||
const buildShortcutMappings = (options: TestRunOptions): ShortcutMapping[] => {
|
||||
const mappings: ShortcutMapping[] = []
|
||||
|
||||
if (options.userInput && options.userInput.enabled !== false)
|
||||
mappings.push({ option: options.userInput, shortcutKey: '~' })
|
||||
|
||||
let numericShortcut = 0
|
||||
|
||||
if (options.runAll && options.runAll.enabled !== false)
|
||||
mappings.push({ option: options.runAll, shortcutKey: String(numericShortcut++) })
|
||||
|
||||
options.triggers.forEach((trigger) => {
|
||||
if (trigger.enabled !== false && numericShortcut < 10)
|
||||
mappings.push({ option: trigger, shortcutKey: String(numericShortcut++) })
|
||||
})
|
||||
|
||||
return mappings
|
||||
}
|
||||
|
||||
// oxlint-disable-next-line eslint-react/no-forward-ref
|
||||
const TestRunMenu = forwardRef<TestRunMenuRef, TestRunMenuProps>(
|
||||
({ options, onSelect, children }, ref) => {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const shortcutMappings = useMemo(() => buildShortcutMappings(options), [options])
|
||||
const shortcutKeyById = useMemo(() => {
|
||||
const map = new Map<string, string>()
|
||||
shortcutMappings.forEach(({ option, shortcutKey }) => {
|
||||
map.set(option.id, shortcutKey)
|
||||
})
|
||||
return map
|
||||
}, [shortcutMappings])
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(option: TriggerOption) => {
|
||||
onSelect(option)
|
||||
setOpen(false)
|
||||
},
|
||||
[onSelect],
|
||||
)
|
||||
|
||||
const enabledOptions = useMemo(() => getEnabledOptions(options), [options])
|
||||
|
||||
const hasSingleEnabledOption = enabledOptions.length === 1
|
||||
const soleEnabledOption = hasSingleEnabledOption ? enabledOptions[0] : undefined
|
||||
|
||||
const runSoleOption = useCallback(() => {
|
||||
if (soleEnabledOption) handleSelect(soleEnabledOption)
|
||||
}, [handleSelect, soleEnabledOption])
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
toggle: () => {
|
||||
if (hasSingleEnabledOption) {
|
||||
runSoleOption()
|
||||
return
|
||||
}
|
||||
|
||||
setOpen((prev) => !prev)
|
||||
},
|
||||
}),
|
||||
[hasSingleEnabledOption, runSoleOption],
|
||||
)
|
||||
|
||||
const renderOption = (option: TriggerOption) => {
|
||||
return (
|
||||
<OptionRow
|
||||
key={option.id}
|
||||
option={option}
|
||||
shortcutKey={shortcutKeyById.get(option.id)}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const { hasUserInput, hasTriggers, hasRunAll } = useMemo(
|
||||
() => getMenuVisibility(options),
|
||||
[options],
|
||||
)
|
||||
|
||||
if (hasSingleEnabledOption && soleEnabledOption) {
|
||||
return <SingleOptionTrigger runSoleOption={runSoleOption}>{children}</SingleOptionTrigger>
|
||||
}
|
||||
|
||||
return (
|
||||
<Menu open={open} onOpenChange={setOpen}>
|
||||
{isValidElement(children) ? (
|
||||
<MenuTrigger render={children} style={{ userSelect: 'none' }} />
|
||||
) : (
|
||||
<MenuTrigger style={{ userSelect: 'none' }}>{children}</MenuTrigger>
|
||||
)}
|
||||
<MenuContent
|
||||
onKeyDown={(event) => handleShortcutMenuKeyDown(event, shortcutMappings, handleSelect)}
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
alignOffset={-4}
|
||||
className="w-71"
|
||||
>
|
||||
<MenuGroup className="flex flex-col gap-1">
|
||||
<MenuGroupLabel className="pt-2 text-sm font-medium text-text-primary">
|
||||
{t(($) => $['common.chooseStartNodeToRun'], { ns: 'workflow' })}
|
||||
</MenuGroupLabel>
|
||||
<div>
|
||||
{hasUserInput && renderOption(options.userInput!)}
|
||||
|
||||
{(hasTriggers || hasRunAll) && hasUserInput && <MenuSeparator className="mx-3" />}
|
||||
|
||||
{hasRunAll && renderOption(options.runAll!)}
|
||||
|
||||
{hasTriggers &&
|
||||
options.triggers
|
||||
.filter((trigger) => trigger.enabled !== false)
|
||||
.map((trigger) => renderOption(trigger))}
|
||||
</div>
|
||||
</MenuGroup>
|
||||
</MenuContent>
|
||||
</Menu>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
TestRunMenu.displayName = 'TestRunMenu'
|
||||
|
||||
export default TestRunMenu
|
||||
@@ -0,0 +1,62 @@
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ViewWorkflowHistory from '@/app/components/workflow/header/view-workflow-history'
|
||||
import { useWorkflowHistoryStore } from '@/app/components/workflow/workflow-history-store'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import TipPopup from '../operator/tip-popup'
|
||||
|
||||
type UndoRedoProps = { handleUndo: () => void; handleRedo: () => void }
|
||||
function UndoRedo({ handleUndo, handleRedo }: UndoRedoProps) {
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const { store } = useWorkflowHistoryStore()
|
||||
const [buttonsDisabled, setButtonsDisabled] = useState({ undo: true, redo: true })
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = store.temporal.subscribe((state) => {
|
||||
setButtonsDisabled({
|
||||
undo: state.pastStates.length === 0,
|
||||
redo: state.futureStates.length === 0,
|
||||
})
|
||||
})
|
||||
return () => unsubscribe()
|
||||
}, [store])
|
||||
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-0.5 rounded-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-lg backdrop-blur-[5px]">
|
||||
<TipPopup title={t(($) => $['common.undo'], { ns: 'workflow' })!} shortcut="workflow.undo">
|
||||
<IconButton
|
||||
size="lg"
|
||||
className="rounded-md"
|
||||
aria-label={t(($) => $['common.undo'], { ns: 'workflow' })!}
|
||||
data-tooltip-id="workflow.undo"
|
||||
disabled={nodesReadOnly || buttonsDisabled.undo}
|
||||
focusableWhenDisabled
|
||||
onClick={handleUndo}
|
||||
>
|
||||
<span aria-hidden className="i-ri-arrow-go-back-line size-4" />
|
||||
</IconButton>
|
||||
</TipPopup>
|
||||
<TipPopup title={t(($) => $['common.redo'], { ns: 'workflow' })!} shortcut="workflow.redo">
|
||||
<IconButton
|
||||
size="lg"
|
||||
className="rounded-md"
|
||||
aria-label={t(($) => $['common.redo'], { ns: 'workflow' })!}
|
||||
data-tooltip-id="workflow.redo"
|
||||
disabled={nodesReadOnly || buttonsDisabled.redo}
|
||||
focusableWhenDisabled
|
||||
onClick={handleRedo}
|
||||
>
|
||||
<span aria-hidden className="i-ri-arrow-go-forward-fill size-4" />
|
||||
</IconButton>
|
||||
</TipPopup>
|
||||
<Separator orientation="vertical" className="mx-0.5 h-3.5" />
|
||||
<ViewWorkflowHistory />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(UndoRedo)
|
||||
@@ -0,0 +1,67 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { useHotkey } from '@tanstack/react-hotkeys'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
import { VERSION_HISTORY_HOTKEY } from '../hotkeys'
|
||||
import { ShortcutKbd } from '../shortcuts/shortcut-kbd'
|
||||
|
||||
type VersionHistoryButtonProps = {
|
||||
onClick: () => Promise<unknown> | unknown
|
||||
}
|
||||
|
||||
export function VersionHistoryButton({ onClick }: VersionHistoryButtonProps) {
|
||||
const { theme } = useTheme()
|
||||
const { t } = useTranslation(['workflow'])
|
||||
const label = t(($) => $['common.versionHistory'], { ns: 'workflow' })
|
||||
|
||||
useHotkey(
|
||||
VERSION_HISTORY_HOTKEY,
|
||||
(event) => {
|
||||
if (event.defaultPrevented) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
if (event.repeat) return
|
||||
void onClick()
|
||||
},
|
||||
{
|
||||
ignoreInputs: true,
|
||||
preventDefault: false,
|
||||
stopPropagation: false,
|
||||
},
|
||||
)
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={label}
|
||||
variant="secondary"
|
||||
size="lg"
|
||||
className={cn(
|
||||
'inset-ring-1 inset-ring-transparent',
|
||||
theme === 'dark' && 'bg-white/10 inset-ring-black/5 backdrop-blur-xs',
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-history-line size-4 text-components-button-secondary-text"
|
||||
/>
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
<TooltipContent className="flex items-center gap-1">
|
||||
<span className="px-0.5">{label}</span>
|
||||
<ShortcutKbd
|
||||
hotkey={VERSION_HISTORY_HOTKEY}
|
||||
|
||||
bgColor="gray"
|
||||
textColor="secondary"
|
||||
/>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { memo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
|
||||
import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks/use-input-field-panel'
|
||||
import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'
|
||||
import { useStore, useWorkflowStore } from '@/app/components/workflow/store'
|
||||
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
|
||||
import { useWorkflowRunHistory } from '@/service/use-workflow'
|
||||
import { useNodesInteractions } from '../hooks/use-nodes-interactions'
|
||||
import { useWorkflowInteractions } from '../hooks/use-workflow-panel-interactions'
|
||||
import { useWorkflowRun } from '../hooks/use-workflow-run'
|
||||
import { ControlMode, WorkflowRunningStatus } from '../types'
|
||||
import { formatWorkflowRunIdentifier } from '../utils'
|
||||
|
||||
export type ViewHistoryProps = {
|
||||
withText?: boolean
|
||||
onClearLogAndMessageModal?: () => void
|
||||
historyUrl?: string
|
||||
}
|
||||
const ViewHistory = ({ withText, onClearLogAndMessageModal, historyUrl }: ViewHistoryProps) => {
|
||||
const { t } = useTranslation(['common', 'workflow'])
|
||||
const isChatflow = useAtomValue(isChatflowAtom)
|
||||
const [open, setOpen] = useState(false)
|
||||
const { formatTimeFromNow } = useFormatTimeFromNow()
|
||||
const { handleNodesCancelSelected } = useNodesInteractions()
|
||||
const { handleCancelDebugAndPreviewPanel } = useWorkflowInteractions()
|
||||
const workflowStore = useWorkflowStore()
|
||||
const setControlMode = useStore((s) => s.setControlMode)
|
||||
const historyWorkflowData = useStore((s) => s.historyWorkflowData)
|
||||
const { handleBackupDraft } = useWorkflowRun()
|
||||
const { closeAllInputFieldPanels } = useInputFieldPanel()
|
||||
|
||||
const shouldFetchHistory = open && !!historyUrl
|
||||
const { data, isLoading } = useWorkflowRunHistory(historyUrl, shouldFetchHistory)
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
{withText ? (
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'flex h-8 items-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 shadow-xs',
|
||||
'cursor-pointer text-[13px] font-medium text-components-button-secondary-text hover:bg-components-button-secondary-bg-hover',
|
||||
'data-popup-open:bg-components-button-secondary-bg-hover',
|
||||
)}
|
||||
>
|
||||
<span className="mr-1 i-custom-vender-line-time-clock-play size-4" />
|
||||
{t(($) => $['common.showRunHistory'], { ns: 'workflow' })}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={<div className="flex" />}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['common.viewRunHistory'], { ns: 'workflow' })}
|
||||
className="group flex size-7 cursor-pointer items-center justify-center rounded-md hover:bg-state-accent-hover data-popup-open:bg-state-accent-hover"
|
||||
onClick={() => {
|
||||
onClearLogAndMessageModal?.()
|
||||
}}
|
||||
>
|
||||
<span className="i-custom-vender-line-time-clock-play size-4 text-components-button-ghost-text group-hover:text-components-button-secondary-accent-text group-data-popup-open:text-components-button-secondary-accent-text" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{t(($) => $['common.viewRunHistory'], { ns: 'workflow' })}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<PopoverContent
|
||||
align={withText ? 'start' : 'end'}
|
||||
sideOffset={4}
|
||||
alignOffset={withText ? -8 : 10}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<div
|
||||
className="ml-2 flex w-60 flex-col overflow-y-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl"
|
||||
style={{
|
||||
maxHeight: 'calc(2 / 3 * 100vh)',
|
||||
}}
|
||||
>
|
||||
<div className="sticky top-0 flex items-center justify-between bg-components-panel-bg px-4 pt-3 text-base font-semibold text-text-primary">
|
||||
<div className="grow">{t(($) => $['common.runHistory'], { ns: 'workflow' })}</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
className="flex size-6 shrink-0 cursor-pointer items-center justify-center"
|
||||
onClick={() => {
|
||||
onClearLogAndMessageModal?.()
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<span className="i-ri-close-line size-4 text-text-tertiary" />
|
||||
</button>
|
||||
</div>
|
||||
{isLoading && (
|
||||
<div className="flex h-10 items-center justify-center">
|
||||
<LoadingPlaceholder />
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && (
|
||||
<div className="p-2">
|
||||
{!data?.data.length && (
|
||||
<div className="py-12">
|
||||
<span className="mx-auto mb-2 i-custom-vender-line-time-clock-play-slim size-8 text-text-quaternary" />
|
||||
<div className="text-center text-[13px] text-text-quaternary">
|
||||
{t(($) => $['common.notRunning'], { ns: 'workflow' })}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{data?.data.map((item) => {
|
||||
const interruptedStatuses: readonly WorkflowRunningStatus[] = [
|
||||
WorkflowRunningStatus.Stopped,
|
||||
WorkflowRunningStatus.Paused,
|
||||
]
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={cn(
|
||||
'mb-0.5 flex cursor-pointer rounded-lg px-2 py-1.75 hover:bg-state-base-hover',
|
||||
item.id === historyWorkflowData?.id &&
|
||||
'bg-state-accent-hover hover:bg-state-accent-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
workflowStore.setState({
|
||||
historyWorkflowData: item,
|
||||
showInputsPanel: false,
|
||||
showEnvPanel: false,
|
||||
})
|
||||
closeAllInputFieldPanels()
|
||||
handleBackupDraft()
|
||||
setOpen(false)
|
||||
handleNodesCancelSelected()
|
||||
handleCancelDebugAndPreviewPanel()
|
||||
setControlMode(ControlMode.Hand)
|
||||
}}
|
||||
>
|
||||
{!isChatflow && interruptedStatuses.includes(item.status) && (
|
||||
<span className="mt-0.5 mr-1.5 i-custom-vender-line-alertsAndFeedback-alert-triangle h-3.5 w-3.5 text-[#F79009]" />
|
||||
)}
|
||||
{!isChatflow && item.status === WorkflowRunningStatus.Failed && (
|
||||
<span className="mt-0.5 mr-1.5 i-ri-error-warning-line h-3.5 w-3.5 text-[#F04438]" />
|
||||
)}
|
||||
{!isChatflow && item.status === WorkflowRunningStatus.Succeeded && (
|
||||
<span className="mt-0.5 mr-1.5 i-ri-checkbox-circle-line h-3.5 w-3.5 text-[#12B76A]" />
|
||||
)}
|
||||
<div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center text-[13px] leading-4.5 font-medium text-text-primary',
|
||||
item.id === historyWorkflowData?.id && 'text-text-accent',
|
||||
)}
|
||||
>
|
||||
{`Test ${isChatflow ? 'Chat' : 'Run'}${formatWorkflowRunIdentifier(item.finished_at, item.status)}`}
|
||||
</div>
|
||||
<div className="flex items-center text-xs leading-4.5 text-text-tertiary">
|
||||
{item.created_by_account?.name} ·
|
||||
{formatTimeFromNow((item.finished_at || item.created_at) * 1000)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ViewHistory)
|
||||
@@ -0,0 +1,301 @@
|
||||
import type { WorkflowHistoryState } from '../store/workflow/history-slice'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { Separator } from '@langgenius/dify-ui/separator'
|
||||
import { memo, useCallback, useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { collaborationManager } from '../collaboration/core/collaboration-manager'
|
||||
import { useCollaborativeWorkflow } from '../hooks/use-collaborative-workflow'
|
||||
import { useNodesReadOnly } from '../hooks/use-workflow'
|
||||
import { useWorkflowHistory } from '../hooks/use-workflow-history'
|
||||
import TipPopup from '../operator/tip-popup'
|
||||
import { useStore } from '../store'
|
||||
|
||||
type ChangeHistoryEntry = {
|
||||
label: string
|
||||
index: number
|
||||
state: Partial<WorkflowHistoryState>
|
||||
}
|
||||
|
||||
type ChangeHistoryList = {
|
||||
pastStates: ChangeHistoryEntry[]
|
||||
futureStates: ChangeHistoryEntry[]
|
||||
statesCount: number
|
||||
}
|
||||
|
||||
const ViewWorkflowHistory = () => {
|
||||
const { t } = useTranslation(['common', 'workflow', 'workflowHistory'])
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const { nodesReadOnly } = useNodesReadOnly()
|
||||
const setMessageLogItem = useStore((state) => state.setMessageLogItem)
|
||||
const collaborativeWorkflow = useCollaborativeWorkflow()
|
||||
const { store, getHistoryLabel } = useWorkflowHistory()
|
||||
|
||||
const { pastStates, futureStates, undo, redo, clear } = store.temporal.getState()
|
||||
const [currentHistoryStateIndex, setCurrentHistoryStateIndex] = useState<number>(0)
|
||||
|
||||
const handleClearHistory = useCallback(() => {
|
||||
clear()
|
||||
setCurrentHistoryStateIndex(0)
|
||||
}, [clear])
|
||||
|
||||
const handleSetState = useCallback(
|
||||
({ index }: ChangeHistoryEntry) => {
|
||||
const diff = currentHistoryStateIndex + index
|
||||
if (diff === 0) return
|
||||
|
||||
if (diff < 0) undo(diff * -1)
|
||||
else redo(diff)
|
||||
|
||||
const { edges, nodes } = store.getState()
|
||||
if (edges.length === 0 && nodes.length === 0) return
|
||||
|
||||
const shouldBroadcast = collaborationManager.isConnected()
|
||||
const { setEdges, setNodes } = collaborativeWorkflow.getState()
|
||||
setEdges(edges, shouldBroadcast)
|
||||
setNodes(nodes, shouldBroadcast, 'history:jump')
|
||||
if (collaborationManager.isConnected()) collaborationManager.emitHistoryAction('jump')
|
||||
},
|
||||
[collaborativeWorkflow, currentHistoryStateIndex, redo, store, undo],
|
||||
)
|
||||
|
||||
const calculateStepLabel = useCallback(
|
||||
(index: number) => {
|
||||
if (!index) return
|
||||
|
||||
const count = index < 0 ? index * -1 : index
|
||||
return `${index > 0 ? t(($) => $['changeHistory.stepForward'], { ns: 'workflowHistory', count }) : t(($) => $['changeHistory.stepBackward'], { ns: 'workflowHistory', count })}`
|
||||
},
|
||||
[t],
|
||||
)
|
||||
|
||||
const calculateChangeList: ChangeHistoryList = useMemo(() => {
|
||||
const filterList = (
|
||||
list: Array<Partial<WorkflowHistoryState> | undefined>,
|
||||
startIndex = 0,
|
||||
reverse = false,
|
||||
) =>
|
||||
list.flatMap((state, index) => {
|
||||
if (!state) return []
|
||||
|
||||
const nodes = state.nodes || store.getState().nodes || []
|
||||
const nodeId = state.workflowHistoryEventMeta?.nodeId
|
||||
const targetTitle = nodes.find((n) => n.id === nodeId)?.data?.title ?? ''
|
||||
|
||||
return [
|
||||
{
|
||||
label: state.workflowHistoryEvent ? getHistoryLabel(state.workflowHistoryEvent) : '',
|
||||
index: reverse ? list.length - 1 - index - startIndex : index - startIndex,
|
||||
state: {
|
||||
...state,
|
||||
workflowHistoryEventMeta: state.workflowHistoryEventMeta
|
||||
? {
|
||||
...state.workflowHistoryEventMeta,
|
||||
nodeTitle: state.workflowHistoryEventMeta.nodeTitle || targetTitle,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
const historyData = {
|
||||
pastStates: filterList(pastStates, pastStates.length).reverse(),
|
||||
futureStates: filterList(
|
||||
[
|
||||
...futureStates,
|
||||
!pastStates.length && !futureStates.length ? undefined : store.getState(),
|
||||
].filter(Boolean),
|
||||
0,
|
||||
true,
|
||||
),
|
||||
statesCount: 0,
|
||||
}
|
||||
|
||||
historyData.statesCount = pastStates.length + futureStates.length
|
||||
|
||||
return {
|
||||
...historyData,
|
||||
statesCount: pastStates.length + futureStates.length,
|
||||
}
|
||||
}, [futureStates, getHistoryLabel, pastStates, store])
|
||||
|
||||
const composeHistoryItemLabel = useCallback(
|
||||
(nodeTitle: string | undefined, baseLabel: string) => {
|
||||
if (!nodeTitle) return baseLabel
|
||||
return `${nodeTitle} ${baseLabel}`
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
return (
|
||||
<Popover
|
||||
modal="trap-focus"
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nodesReadOnly) return
|
||||
setMessageLogItem(undefined)
|
||||
setOpen(nextOpen)
|
||||
}}
|
||||
>
|
||||
<TipPopup title={t(($) => $['changeHistory.title'], { ns: 'workflowHistory' })}>
|
||||
{/* Tooltip and Popover share data-popup-open on this button, so read Popover state directly. */}
|
||||
<PopoverTrigger
|
||||
className={({ open: popoverOpen }) =>
|
||||
cn(
|
||||
popoverOpen &&
|
||||
'bg-state-accent-active text-text-accent hover:bg-state-accent-active hover:text-text-accent',
|
||||
)
|
||||
}
|
||||
render={
|
||||
<IconButton
|
||||
size="lg"
|
||||
disabled={nodesReadOnly}
|
||||
focusableWhenDisabled
|
||||
aria-label={t(($) => $['changeHistory.title'], { ns: 'workflowHistory' })}
|
||||
className="rounded-md"
|
||||
>
|
||||
<span aria-hidden className="i-ri-history-line size-4 shrink-0" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</TipPopup>
|
||||
<PopoverContent align="end" className="border-none bg-transparent shadow-none">
|
||||
<div className="flex max-w-90 min-w-60 flex-col overflow-y-auto rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-xl backdrop-blur-[5px]">
|
||||
<div className="sticky top-0 flex items-center justify-between px-4 pt-3">
|
||||
<div className="grow text-text-secondary">
|
||||
{t(($) => $['changeHistory.title'], { ns: 'workflowHistory' })}
|
||||
</div>
|
||||
<PopoverClose
|
||||
render={
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="md"
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
className="shrink-0 text-text-secondary hover:bg-state-base-hover"
|
||||
>
|
||||
<span aria-hidden className="i-ri-close-line size-4 text-text-secondary" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className="overflow-y-auto p-2"
|
||||
style={{
|
||||
maxHeight: 'calc(1 / 2 * 100vh)',
|
||||
}}
|
||||
>
|
||||
{!calculateChangeList.statesCount && (
|
||||
<div className="py-12">
|
||||
<span
|
||||
aria-hidden
|
||||
className="mx-auto mb-2 i-ri-history-line block size-8 text-text-tertiary"
|
||||
/>
|
||||
<div className="text-center text-[13px] text-text-tertiary">
|
||||
{t(($) => $['changeHistory.placeholder'], { ns: 'workflowHistory' })}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col">
|
||||
{calculateChangeList.futureStates.map((item: ChangeHistoryEntry) => (
|
||||
<button
|
||||
type="button"
|
||||
key={item?.index}
|
||||
className={cn(
|
||||
'mb-0.5 flex w-full cursor-pointer rounded-lg px-2 py-1.75 text-left text-text-secondary hover:bg-state-base-hover',
|
||||
item?.index === currentHistoryStateIndex && 'bg-state-base-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
handleSetState(item)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center text-[13px] leading-4.5 font-medium text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{composeHistoryItemLabel(
|
||||
item?.state?.workflowHistoryEventMeta?.nodeTitle,
|
||||
item?.label ||
|
||||
t(($) => $['changeHistory.sessionStart'], { ns: 'workflowHistory' }),
|
||||
)}{' '}
|
||||
({calculateStepLabel(item?.index)}
|
||||
{item?.index === currentHistoryStateIndex &&
|
||||
t(($) => $['changeHistory.currentState'], { ns: 'workflowHistory' })}
|
||||
)
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
{calculateChangeList.pastStates.map((item: ChangeHistoryEntry) => (
|
||||
<button
|
||||
type="button"
|
||||
key={item?.index}
|
||||
className={cn(
|
||||
'mb-0.5 flex w-full cursor-pointer rounded-lg px-2 py-1.75 text-left hover:bg-state-base-hover',
|
||||
item?.index === calculateChangeList.statesCount - 1 && 'bg-state-base-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
handleSetState(item)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center text-[13px] leading-4.5 font-medium text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{composeHistoryItemLabel(
|
||||
item?.state?.workflowHistoryEventMeta?.nodeTitle,
|
||||
item?.label ||
|
||||
t(($) => $['changeHistory.sessionStart'], { ns: 'workflowHistory' }),
|
||||
)}{' '}
|
||||
({calculateStepLabel(item?.index)})
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{!!calculateChangeList.statesCount && (
|
||||
<div className="px-0.5">
|
||||
<Separator className="m-0 h-[0.5px]" />
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
'my-0.5 flex w-full cursor-pointer rounded-lg px-2 py-1.75 text-left text-text-secondary',
|
||||
'hover:bg-state-base-hover',
|
||||
)}
|
||||
onClick={() => {
|
||||
handleClearHistory()
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div className={cn('flex items-center text-[13px] leading-4.5 font-medium')}>
|
||||
{t(($) => $['changeHistory.clearHistory'], { ns: 'workflowHistory' })}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="w-60 px-3 py-2 text-xs text-text-tertiary">
|
||||
<div className="mb-1 flex h-5.5 items-center font-medium uppercase">
|
||||
{t(($) => $['changeHistory.hint'], { ns: 'workflowHistory' })}
|
||||
</div>
|
||||
<div className="mb-1 leading-4.5 text-text-tertiary">
|
||||
{t(($) => $['changeHistory.hintText'], { ns: 'workflowHistory' })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ViewWorkflowHistory)
|
||||
Reference in new issue
Block a user