Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix(web): preserve inline agent layout and clarify configure ownership (#44534)
yyh7e29f20494ca
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsxindex d0ca58bf8b9..a0aa096aa8d 100644--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx@@ -650,14 +650,16 @@ describe('Inline Agent configure workspace', () => {await receive(0, 'preview-conversation', 'Preview answer')await complete()await user.click(restartButton())- await waitFor(() =>- expect(api.refreshConversation).toHaveBeenCalledExactlyOnceWith({- params: { agent_id: 'agent-1' },- body: { draft_type: 'draft' },- }),- )+ expect(api.refreshConversation).not.toHaveBeenCalled()await waitFor(() => expect(screen.queryByText('Preview answer')).not.toBeInTheDocument())expect(api.deleteBuildDraft).not.toHaveBeenCalled()+ await sendPreview(user)+ await waitFor(() => expect(ssePost).toHaveBeenCalledTimes(2))+ expect(ssePost.mock.calls[1]?.[1].body).toEqual(+ expect.objectContaining({ conversation_id: '', parent_message_id: null }),+ )+ await receive(1, 'new-preview-conversation', 'New preview answer')+ await complete(1)await changeMode(user, 'build')expect(await screen.findByText('Build history')).toBeVisible()})diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsxindex 8490f7734cf..aaf7f90a42f 100644--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx@@ -1,6 +1,7 @@-import { screen } from '@testing-library/react'+import { screen, waitForElementToBeRemoved, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useRef } from 'react'+import { AgentPreviewHeader } from '@/features/agent-v2/agent-detail/configure/components/preview/header'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { AgentRosterField } from '../agent-roster-field'@@ -35,6 +36,70 @@ function renderDetailRosterField(}describe('AgentRosterField', () => {+ it('keeps inline mode controls independent from the roster field label and identity', async () => {+ const user = userEvent.setup()+ render(+ <AgentRosterField+ agent={{ id: 'inline-agent', name: 'Inline Agent' }}+ isInlineSetup+ portalContainerRef={{ current: null }}+ onChange={vi.fn()}+ panelBody={+ <AgentPreviewHeader+ mode="build"+ previewEnabled+ onModeChange={vi.fn()}+ onOpenWorkingDirectory={vi.fn()}+ onRefresh={vi.fn()}+ />+ }+ />,+ )+ await user.click(+ screen.getByRole('button', {+ name: /^workflowAgent\.nodes\.agent\.roster\.openPanel/,+ }),+ )+ const dialog = within(await screen.findByRole('dialog', { name: 'Inline Agent' }))+ const modes = within(+ dialog.getByRole('radiogroup', {+ name: 'agentV2.agentDetail.configure.rightPanel.modeLabel',+ }),+ )+ const build = modes.getByRole('radio', {+ name: 'agentV2.agentDetail.configure.rightPanel.build',+ })+ const preview = modes.getByRole('radio', {+ name: 'agentV2.agentDetail.configure.rightPanel.preview',+ })+ expect(build.id).not.toBe(preview.id)+ })++ it('keeps the inline dialog close control available before its workspace loads', async () => {+ const user = userEvent.setup()+ function Harness() {+ const portalContainerRef = useRef<HTMLDivElement>(null)+ return (+ <div ref={portalContainerRef}>+ <AgentRosterField+ agent={{ id: 'inline-agent', name: 'Inline Agent' }}+ isInlineSetup+ portalContainerRef={portalContainerRef}+ onChange={vi.fn()}+ />+ </div>+ )+ }+ render(<Harness />)+ await user.click(+ screen.getByRole('button', { name: /^workflowAgent\.nodes\.agent\.roster\.openPanel/ }),+ )+ const dialog = await screen.findByRole('dialog', { name: 'Inline Agent' })+ const closed = waitForElementToBeRemoved(dialog)+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))+ await closed+ })+it('copies the roster agent from its detail panel', async () => {const user = userEvent.setup()const { onMakeCopy } = renderDetailRosterField()diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsxindex 1ac4565c976..437382348ac 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx@@ -41,15 +41,13 @@ import { AgentOrchestratePanel } from '@/features/agent-v2/agent-detail/configurimport { AgentBuildDraftBar } from '@/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar'import { AgentBuildPanelBackground } from '@/features/agent-v2/agent-detail/configure/components/preview/build-background'import { AgentPreviewHeader } from '@/features/agent-v2/agent-detail/configure/components/preview/header'-import {- invalidateAgentWorkingDirectoryFiles,- useAgentWorkingDirectoryPanel,-} from '@/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel'import { AgentConfigureRightPanelChat } from '@/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat'import {+ AgentConfigurePreviewBody,AgentConfigurePreviewSurface,- AgentConfigureWorkspace,-} from '@/features/agent-v2/agent-detail/configure/components/workspace'+} from '@/features/agent-v2/agent-detail/configure/components/preview/surface'+import { invalidateAgentWorkingDirectoryFiles } from '@/features/agent-v2/agent-detail/configure/components/preview/working-directory-cache'+import { AgentWorkingDirectoryPanel } from '@/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel'import {agentConfigureConversationIdsAtom,agentConfigureRightPanelModeAtom,@@ -58,16 +56,14 @@ import {setAgentConfigureConversationIdAtom,workflowInlineAgentConfigureScopedAtoms,} from '@/features/agent-v2/agent-detail/configure/state'-import {- useAgentConfigureBuildDraftActions,- useAgentConfigureBuildDraftData,-} from '@/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft'+import { useAgentConfigureBuildDraftData } from '@/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft'import { useAgentConfigureSessionController } from '@/features/agent-v2/agent-detail/configure/use-agent-configure-session-controller'import {trackAgentBuildModeRun,trackAgentPreviewModeRun,useInlineAgentScope,} from '@/features/agent-v2/analytics'+import { useAgentBuildDraftRefresh } from '@/features/agent-v2/build-draft-refresh'import { useCanCreateAgents } from '@/features/agent-v2/permissions'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/console'@@ -85,7 +81,6 @@ type WorkflowInlineAgentConfigureWorkspaceProps = {resource?: Extract<EditorResource, { kind: 'app' | 'snippet' }>inlineComposerState?: WorkflowAgentComposerResponsenodeId: string- onClose?: () => voidonSaved?: (binding: AgentComposerBindingResponse) => voidonSaveInlineToRoster?: () => voidopen: boolean@@ -135,7 +130,6 @@ export function WorkflowRosterAgentOrchestratePanelContent(><WorkflowRosterAgentOrchestratePanelContentInneragentId={agentId}- agentSoulConfig={initialAgentSoulConfig}composerState={composerState}/></AgentComposerProvider>@@ -144,11 +138,9 @@ export function WorkflowRosterAgentOrchestratePanelContent(function WorkflowRosterAgentOrchestratePanelContentInner({agentId,- agentSoulConfig,composerState,}: {agentId: string- agentSoulConfig: AgentSoulConfigcomposerState?: {agent?: {name?: string | null@@ -160,7 +152,6 @@ function WorkflowRosterAgentOrchestratePanelContentInner({return (<AgentOrchestratePanelagentId={agentId}- agentSoulConfig={agentSoulConfig}agentName={composerState?.agent?.name}currentModel={currentModel}readOnly@@ -168,7 +159,6 @@ function WorkflowRosterAgentOrchestratePanelContentInner({showPublishBar={false}className="h-full max-w-none min-w-0 flex-none rounded-none border-0"onSelectModel={setConfigureModel}- onOpenVersions={() => undefined}/>)}@@ -273,7 +263,6 @@ function WorkflowInlineAgentConfigureWorkspaceContent({resource,inlineComposerState,nodeId,- onClose,onSaved,onSaveInlineToRoster,open,@@ -299,14 +288,8 @@ function WorkflowInlineAgentConfigureWorkspaceContent({const conversationIds = useAtomValue(agentConfigureConversationIdsAtom)const [rightPanelMode, setRightPanelMode] = useAtom(agentConfigureRightPanelModeAtom)const previewEnabled = systemFeatures?.deployment_edition !== 'COMMUNITY'- const workingDirectoryPanel = useAgentWorkingDirectoryPanel({- type: 'agent',- agentId,- caller: {- type: 'build_draft',- id: buildDraft.id,- },- })+ const [showWorkingDirectory, setShowWorkingDirectory] = useState(false)+const resetConversation = useSetAtom(resetAgentConfigureConversationAtom)const setConversationId = useSetAtom(setAgentConfigureConversationIdAtom)const rebaseComposerDraft = useSetAtom(rebaseAgentComposerDraftAtom)@@ -405,33 +388,10 @@ function WorkflowInlineAgentConfigureWorkspaceContent({mutateAsync: refreshDebugConversationRequestAsync,isPending: isRefreshingBuildConversation,} = refreshDebugConversationMutation- const { mutate: refreshPreviewConversationRequest, isPending: isRefreshingPreviewConversation } =- useMutation(consoleQuery.agent.byAgentId.debugConversation.refresh.post.mutationOptions())- const refreshDebugConversationInput = useCallback(- () => ({- params: {- agent_id: agentId,- },- }),- [agentId],+ const refreshDebugConversationAsync = useCallback(+ () => refreshDebugConversationRequestAsync({ params: { agent_id: agentId } }),+ [agentId, refreshDebugConversationRequestAsync],)- const refreshDebugConversationAsync = useCallback(() => {- return refreshDebugConversationRequestAsync(refreshDebugConversationInput())- }, [refreshDebugConversationInput, refreshDebugConversationRequestAsync])- const refreshPreviewConversationInput = useCallback(- () => ({- params: {- agent_id: agentId,- },- body: {- draft_type: 'draft' as const,- },- }),- [agentId],- )- const refreshPreviewConversation = useCallback(() => {- refreshPreviewConversationRequest(refreshPreviewConversationInput())- }, [refreshPreviewConversationInput, refreshPreviewConversationRequest])const resetBuildChatState = useCallback(async () => {await refreshDebugConversationAsync().catch(() => undefined)setCompletedBuildConversationId(null)@@ -471,26 +431,10 @@ function WorkflowInlineAgentConfigureWorkspaceContent({() => resetSessionController(resetBuildChatState),[resetBuildChatState, resetSessionController],)- const buildDraftActions = useAgentConfigureBuildDraftActions({- agentId,- buildDraftAgentSoulConfig: buildDraft.agentSoulConfig,- isActive: buildDraft.isActive,- normalAgentSoulConfig: agentSoulConfig,- rebaseComposerDraft: rebaseComposerDraftFromSoulConfig,+ const { cancelBuildDraftRefresh, refreshBuildDraftAfterBuildChat } = useAgentBuildDraftRefresh({refetchBuildDraft: buildDraft.refetch,- refetchComposer: async () => ({- data: {- agent_soul: agentSoulConfig,- },- }),- resetBuildChatSession: resetBuildSession,- saveDraft: async () => {- await waitForPendingPreviewDraftSave()- await saveDraft()- },- setSoulSourceOverride: buildDraft.setSoulSourceOverride,+ rebaseComposerDraft: rebaseComposerDraftFromSoulConfig,})- const { cancelBuildDraftRefresh } = buildDraftActionsconst buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({input: {params: {@@ -637,8 +581,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({buildDraftActionsDisabled ||isApplyingInlineBuildDraft ||isDiscardingBuildDraft ||- isRefreshingBuildConversation ||- isRefreshingPreviewConversation+ isRefreshingBuildConversationconst buildConversationHasAgentResponse =!!conversationIds.build &&(conversationIds.build === completedBuildConversationId ||@@ -655,20 +598,53 @@ function WorkflowInlineAgentConfigureWorkspaceContent({}if (rightPanelMode === 'build') void refreshDebugConversationAsync().catch(() => undefined)- else refreshPreviewConversation()resetConversation(rightPanelMode)setClearPreviewChat(true)}+ const handleConversationComplete = (+ mode: 'build' | 'preview',+ completedConversationId: string,+ ) => {+ if (mode !== 'build' || !isBuildCallbackCurrent(buildCallbackGeneration)) return++ setCompletedBuildConversationId(completedConversationId)+ invalidateAgentWorkingDirectoryFiles({+ conversationId: completedConversationId,+ queryClient,+ })+ refreshBuildDraftAfterBuildChat(() => finishBuildAction(buildCallbackGeneration))+ }+ const handleConversationIdChange = (mode: 'build' | 'preview', conversationId: string) => {+ if (mode === 'build' && !isBuildCallbackCurrent(buildCallbackGeneration)) return+ setConversationId({ mode, conversationId })+ }+ const saveDraftBeforeChatRun =+ rightPanelMode === 'build'+ ? async () => {+ const preparedBuildDraft = await runBuildPreparation({+ generation: buildCallbackGeneration,+ markBuildChatStarted: true,+ prepare: prepareInlineBuildDraftBeforeRun,+ })+ trackAgentBuildModeRun(agentScope)+ return preparedBuildDraft+ }+ : async () => {+ await saveDraft()+ trackAgentPreviewModeRun(agentScope)+ }+ const handleSendInterrupted = () => {+ finishBuildAction(buildCallbackGeneration)+ }+return (- <AgentConfigureWorkspace- className="rounded-[inherit]"- leftPanel={+ <>+ <section className="flex h-full min-w-0 flex-1 gap-1 overflow-hidden rounded-[inherit] bg-background-body p-1"><AgentOrchestratePanelagentId={agentId}appId={appId}nodeId={nodeId}- agentSoulConfig={buildDraft.agentSoulConfig}agentName={composerState?.agent?.name}currentModel={currentModel}readOnly={buildDraft.isActive}@@ -697,39 +673,21 @@ function WorkflowInlineAgentConfigureWorkspaceContent({<WorkflowInlineAgentConfigureMoreAction onSaveInlineToRoster={onSaveInlineToRoster} />) : undefined}- className="min-w-90"+ className="max-w-140 min-w-0 flex-[0_0_min(41.08280255%,560px)]"onSelectModel={setConfigureModel}- onOpenVersions={() => undefined}/>- }- rightPanel={- <AgentConfigurePreviewSurface- background={<AgentBuildPanelBackground visible={rightPanelMode === 'build'} />}- header={- <AgentPreviewHeader- mode={rightPanelMode}- previewEnabled={previewEnabled}- isChatFeaturesOpen={false}- onModeChange={changeRightPanelMode}- onToggleChatFeatures={() => undefined}- onOpenWorkingDirectory={workingDirectoryPanel.openWorkingDirectory}- onRefresh={restartCurrentChat}- refreshDisabled={isRestartCurrentChatDisabled}- showWorkingDirectoryAction={showWorkingDirectoryAction}- showChatFeaturesAction={false}- trailingAction={- <button- type="button"- onClick={onClose}- className="flex size-8 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"- aria-label={t(($) => $['operation.close'])}- >- <span aria-hidden className="i-ri-close-line size-4" />- </button>- }- />- }- chat={+ <AgentConfigurePreviewSurface className="min-w-0 flex-1">+ <AgentBuildPanelBackground visible={rightPanelMode === 'build'} />+ <AgentPreviewHeader+ mode={rightPanelMode}+ previewEnabled={previewEnabled}+ onModeChange={changeRightPanelMode}+ onOpenWorkingDirectory={() => setShowWorkingDirectory(true)}+ onRefresh={restartCurrentChat}+ refreshDisabled={isRestartCurrentChatDisabled}+ showWorkingDirectoryAction={showWorkingDirectoryAction}+ />+ <AgentConfigurePreviewBody><AgentConfigureRightPanelChatagentId={agentId}answerActionPosition="below"@@ -740,57 +698,28 @@ function WorkflowInlineAgentConfigureWorkspaceContent({conversationIds={conversationIds}mode={rightPanelMode}onClearChatListChange={setClearPreviewChat}- onConversationComplete={(mode, completedConversationId) => {- if (mode !== 'build' || !isBuildCallbackCurrent(buildCallbackGeneration)) return-- setCompletedBuildConversationId(completedConversationId)- invalidateAgentWorkingDirectoryFiles({- conversationId: completedConversationId,- queryClient,- })- buildDraftActions.refreshBuildDraftAfterBuildChat(() =>- finishBuildAction(buildCallbackGeneration),- )- }}- onConversationIdChange={(mode, conversationId) => {- if (mode === 'build' && !isBuildCallbackCurrent(buildCallbackGeneration)) return- setConversationId({ mode, conversationId })- }}- onSaveDraftBeforeRun={- rightPanelMode === 'build'- ? async () => {- const preparedBuildDraft = await runBuildPreparation({- generation: buildCallbackGeneration,- markBuildChatStarted: true,- prepare: prepareInlineBuildDraftBeforeRun,- })- trackAgentBuildModeRun(agentScope)- return preparedBuildDraft- }- : async () => {- await saveDraft()- trackAgentPreviewModeRun(agentScope)- }- }- onSendInterrupted={() => {- finishBuildAction(buildCallbackGeneration)- }}+ onConversationComplete={handleConversationComplete}+ onConversationIdChange={handleConversationIdChange}+ onSaveDraftBeforeRun={saveDraftBeforeChatRun}+ onSendInterrupted={handleSendInterrupted}/>- }+ </AgentConfigurePreviewBody>+ </AgentConfigurePreviewSurface>+ </section>+ {buildDraft.id && (+ <AgentWorkingDirectoryPanel+ source={{ type: 'agent', agentId, callerType: 'build_draft', callerId: buildDraft.id }}+ open={showWorkingDirectory}+ onOpenChange={setShowWorkingDirectory}/>- }- sidePanels={- <>- {workingDirectoryPanel.panel}- <AgentConfigureClearSessionConfirmDialog- open={showSwitchToPreviewConfirm}- title={tAgent(($) => $['agentDetail.configure.switchToPreviewConfirm.title'])}- onOpenChange={setShowSwitchToPreviewConfirm}- onConfirm={confirmSwitchToPreview}- />- </>- }- />+ )}+ <AgentConfigureClearSessionConfirmDialog+ open={showSwitchToPreviewConfirm}+ title={tAgent(($) => $['agentDetail.configure.switchToPreviewConfirm.title'])}+ onOpenChange={setShowSwitchToPreviewConfirm}+ onConfirm={confirmSwitchToPreview}+ />+ </>)}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsxindex 2d19ecab758..ccfc7c9830b 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx@@ -4,6 +4,7 @@ import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import {Dialog,+ DialogClose,DialogContent,DialogDescription,DialogTitle,@@ -24,9 +25,8 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'-import { Field, FieldLabel } from '@langgenius/dify-ui/field'import { IconButton } from '@langgenius/dify-ui/icon-button'-import { Suspense, useState } from 'react'+import { Suspense, useId, useState } from 'react'import { useTranslation } from 'react-i18next'import AppIcon from '@/app/components/base/app-icon'import {@@ -301,7 +301,7 @@ function AgentRosterInlineConfigureDialog({trigger: ReactElementonOpenChange: (open: boolean) => void}) {- const { t } = useTranslation(['workflow', 'workflowAgent'])+ const { t } = useTranslation(['workflow', 'workflowAgent', 'common'])return (<Dialog open={open} onOpenChange={onOpenChange} disablePointerDismissal>@@ -311,9 +311,21 @@ function AgentRosterInlineConfigureDialog({<DialogDescription className="sr-only">{t(($) => $[`${i18nPrefix}.roster.inlineSetup.description`], { ns: 'workflowAgent' })}</DialogDescription>- <Suspense fallback={<InlineAgentLoading />}>- {children ?? <div className="h-full min-h-80 bg-components-panel-bg" />}- </Suspense>+ <div className="contents [--agent-preview-header-end:4.625rem] max-sm:[--agent-preview-header-end:3.5rem]">+ <Suspense fallback={<InlineAgentLoading />}>+ {children ?? <div className="h-full min-h-80 bg-components-panel-bg" />}+ </Suspense>+ <div className="absolute top-3 right-5 flex items-center max-sm:right-3">+ <span aria-hidden className="mx-3 h-3.5 w-px bg-divider-regular max-sm:hidden" />+ <DialogClose+ render={+ <IconButton size="lg" aria-label={t(($) => $['operation.close'], { ns: 'common' })}>+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ </div>+ </div></DialogContent></Dialog>)@@ -363,6 +375,7 @@ export function AgentRosterField({onStartFromScratch?: () => void}) {const { t } = useTranslation(['common', 'workflow', 'workflowAgent', 'agentRoster'])+ const labelId = useId()const [localPanelOpen, setLocalPanelOpen] = useState(false)const panelOpen = isPanelOpen ?? localPanelOpenconst setPanelOpen = onPanelOpenChange ?? setLocalPanelOpen@@ -414,11 +427,14 @@ export function AgentRosterField({)return (- <Field name="agent_binding" className="gap-1 px-4 py-2">+ <div role="group" aria-labelledby={labelId} className="grid min-w-0 gap-1 px-4 py-2"><div className="flex h-6 items-center gap-2">- <FieldLabel className="min-w-0 flex-1 py-1 system-sm-semibold-uppercase! text-text-secondary">+ <span+ id={labelId}+ className="min-w-0 flex-1 py-1 system-sm-semibold-uppercase text-text-secondary"+ >{t(($) => $['nodes.agent.roster.label'], { ns: 'workflow' })}- </FieldLabel>+ </span><AgentSelectorMenu><AgentSelectorMenuTriggerrender={@@ -516,6 +532,6 @@ export function AgentRosterField({</span></div>)}- </Field>+ </div>)}diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsxindex 92da97a8236..06620729d07 100644--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx@@ -684,7 +684,6 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {resource={inlineAgentResource ?? undefined}inlineComposerState={inlineComposerStateForPanel}nodeId={id}- onClose={() => handleAgentPanelOpenChange(false)}onSaved={handleInlineAgentSaved}onSaveInlineToRoster={canSaveInlineToRoster ? handleSaveInlineToRosterOpen : undefineddiff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsxindex 344363960c3..f2ac7239843 100644--- a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx@@ -164,6 +164,17 @@ describe('Configure page loading and access', () => {})describe('Configure chat sessions', () => {+ it('keeps keyboard focus on the mode control when entering Preview', async () => {+ const user = userEvent.setup()+ createEnvironment({ conversationId: null }).render()+ await screen.findByRole('textbox', { name: `${prefix}.prompt.label` })+ await user.click(modeButton('build'))+ await user.keyboard('{ArrowRight}')+ await waitFor(() => expect(modeButton('preview')).toBeChecked())+ await waitFor(() => expect(chatInput('preview')).toBeVisible())+ expect(modeButton('preview')).toHaveFocus()+ })+it('runs and restarts Preview through its own conversation without creating a build draft', async () => {const user = userEvent.setup()createEnvironment().render('?mode=preview')@@ -184,11 +195,15 @@ describe('Configure chat sessions', () => {expect(api.checkout).not.toHaveBeenCalled()await user.click(restartButton())await waitFor(() => expect(screen.queryByText('Preview answer')).not.toBeInTheDocument())- expect(api.refresh).toHaveBeenCalledWith({- params: { agent_id: 'agent-1' },- body: { draft_type: 'draft' },- })+ expect(api.refresh).not.toHaveBeenCalled()expect(restartButton()).toBeDisabled()+ await send(user, 'preview')+ await waitFor(() => expect(ssePost).toHaveBeenCalledTimes(2))+ expect(ssePost.mock.calls[1]?.[1].body).toEqual(+ expect.objectContaining({ conversation_id: '', parent_message_id: null }),+ )+ await receive(1, 'preview-2', 'New preview answer')+ await complete(1)await changeMode(user, 'build')await waitFor(() => expect(modeButton('build')).toBeChecked())expect(api.refresh).toHaveBeenLastCalledWith({ params: { agent_id: 'agent-1' } })diff --git a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsxindex e046bbb4370..480518f2dfa 100644--- a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx@@ -45,13 +45,11 @@ import { AgentConfigurePageLoading } from './page-loading'import { AgentBuildPanelBackground } from './preview/build-background'import { AgentChatFeaturesPanel } from './preview/chat-features-panel'import { AgentPreviewHeader } from './preview/header'-import {- invalidateAgentWorkingDirectoryFiles,- useAgentWorkingDirectoryPanel,-} from './preview/hook/use-working-directory-panel'import { AgentConfigureRightPanelChat } from './preview/right-panel-chat'+import { AgentConfigurePreviewBody, AgentConfigurePreviewSurface } from './preview/surface'import { AgentPreviewVersionsPanel } from './preview/versions-panel'-import { AgentConfigurePreviewSurface, AgentConfigureWorkspace } from './workspace'+import { invalidateAgentWorkingDirectoryFiles } from './preview/working-directory-cache'+import { AgentWorkingDirectoryPanel } from './preview/working-directory-panel'export function AgentConfigureComposerScope({agentId,@@ -179,36 +177,13 @@ function AgentConfigurePageComposerSession({mutateAsync: refreshDebugConversationRequestAsync,isPending: isRefreshingBuildConversation,} = refreshDebugConversationMutation- const { mutate: refreshPreviewConversationRequest, isPending: isRefreshingPreviewConversation } =- useMutation(consoleQuery.agent.byAgentId.debugConversation.refresh.post.mutationOptions())- const refreshDebugConversationInput = useCallback(- () => ({- params: {- agent_id: agentId,- },- }),- [agentId],- )- const refreshDebugConversation = useCallback(() => {- refreshDebugConversationRequest(refreshDebugConversationInput())- }, [refreshDebugConversationInput, refreshDebugConversationRequest])- const refreshDebugConversationAsync = useCallback(() => {- return refreshDebugConversationRequestAsync(refreshDebugConversationInput())- }, [refreshDebugConversationInput, refreshDebugConversationRequestAsync])- const refreshPreviewConversationInput = useCallback(- () => ({- params: {- agent_id: agentId,- },- body: {- draft_type: 'draft' as const,- },- }),- [agentId],+ const refreshDebugConversation = () => {+ refreshDebugConversationRequest({ params: { agent_id: agentId } })+ }+ const refreshDebugConversationAsync = useCallback(+ () => refreshDebugConversationRequestAsync({ params: { agent_id: agentId } }),+ [agentId, refreshDebugConversationRequestAsync],)- const refreshPreviewConversation = useCallback(() => {- refreshPreviewConversationRequest(refreshPreviewConversationInput())- }, [refreshPreviewConversationInput, refreshPreviewConversationRequest])return (<ScopeProvider@@ -231,9 +206,7 @@ function AgentConfigurePageComposerSession({agentId={agentId}buildDraft={buildDraft}configureData={configureData}- isRefreshingDebugConversation={- isRefreshingBuildConversation || isRefreshingPreviewConversation- }+ isRefreshingDebugConversation={isRefreshingBuildConversation}isViewingVersion={isViewingVersion}previewEnabled={previewEnabled}rightPanelMode={rightPanelMode}@@ -241,7 +214,6 @@ function AgentConfigurePageComposerSession({onComposerRebase={onComposerRebase}onRefreshDebugConversation={refreshDebugConversation}onRefreshDebugConversationAsync={refreshDebugConversationAsync}- onRefreshPreviewConversation={refreshPreviewConversation}onSelectVersion={onSelectVersion}/></AgentComposerProvider>@@ -261,7 +233,6 @@ function AgentConfigurePageComposerContent({onComposerRebase,onRefreshDebugConversation,onRefreshDebugConversationAsync,- onRefreshPreviewConversation,onSelectVersion,}: {agentId: string@@ -275,7 +246,6 @@ function AgentConfigurePageComposerContent({onComposerRebase: () => voidonRefreshDebugConversation: () => voidonRefreshDebugConversationAsync: () => Promise<unknown>- onRefreshPreviewConversation: () => voidonSelectVersion: (versionId: string | null) => void}) {const {@@ -302,25 +272,10 @@ function AgentConfigurePageComposerContent({const rightPanelChatControllerRef = useRef<AgentPreviewChatController>(null)const conversationIds = useAtomValue(agentConfigureConversationIdsAtom)const rightPanelChatMode = rightPanelMode- const workingDirectoryPanel = useAgentWorkingDirectoryPanel(- rightPanelChatMode === 'build'- ? {- type: 'agent',- agentId,- caller: {- type: 'build_draft',- id: buildDraft.id,- },- }- : {- type: 'agent',- agentId,- caller: {- type: 'conversation',- id: conversationIds.preview,- },- },- )+ const [showWorkingDirectory, setShowWorkingDirectory] = useState(false)+ const workingDirectoryCallerId =+ rightPanelChatMode === 'build' ? buildDraft.id : conversationIds.preview+const showChatFeatures = useAtomValue(agentConfigureShowChatFeaturesAtom)const showPreviewVersions = useAtomValue(agentConfigureShowPreviewVersionsAtom)const resetConversation = useSetAtom(resetAgentConfigureConversationAtom)@@ -460,22 +415,68 @@ function AgentConfigurePageComposerContent({if (rightPanelChatMode === 'build') {resetBuildSessionState()onRefreshDebugConversation()- } else {- onRefreshPreviewConversation()}resetConversation(rightPanelChatMode)setClearChatByMode((current) => ({ ...current, [rightPanelChatMode]: true }))}+ const handleConversationComplete = (+ mode: 'build' | 'preview',+ completedConversationId: string,+ ) => {+ if (mode !== 'build' || !isBuildCallbackCurrent(buildCallbackGeneration)) return++ setCompletedBuildConversationId(completedConversationId)+ invalidateAgentWorkingDirectoryFiles({+ conversationId: completedConversationId,+ queryClient,+ })+ buildDraftActions.refreshBuildDraftAfterBuildChat(() =>+ finishBuildAction(buildCallbackGeneration),+ )+ }+ const handleConversationIdChange = (mode: 'build' | 'preview', conversationId: string) => {+ if (mode === 'build' && !isBuildCallbackCurrent(buildCallbackGeneration)) return+ setConversationId({ mode, conversationId })+ }+ const saveDraftBeforeChatRun =+ rightPanelChatMode === 'build'+ ? async () => {+ if (!currentModel?.provider || !currentModel.model) {+ toast.error(+ tCommon(($) => $['modelProvider.selectModel'], {+ ns: 'modelProvider',+ }),+ )+ throw new Error('Agent model is required.')+ }++ const preparedBuildDraft = await runBuildPreparation({+ generation: buildCallbackGeneration,+ markBuildChatStarted: true,+ prepare: buildDraftActions.prepareBuildDraftBeforeRun,+ })+ trackAgentBuildModeRun(AgentScope.Global)+ return preparedBuildDraft+ }+ : async () => {+ await saveDraft()+ trackAgentPreviewModeRun(AgentScope.Global)+ }+ const handleSendInterrupted = () => {+ if (rightPanelChatMode === 'build') finishBuildAction(buildCallbackGeneration)+ }+return (- <AgentConfigureWorkspace- aria-busy={agentQuery.isFetching || isEnteringBuildMode}- leftPanel={+ <>+ <section+ aria-busy={agentQuery.isFetching || isEnteringBuildMode}+ className="flex h-full min-w-0 flex-1 gap-1 overflow-hidden bg-background-body p-1 max-xl:flex-col max-xl:overflow-y-auto"+ ><AgentOrchestratePanel- className="max-xl:h-100 max-xl:w-full max-xl:max-w-none max-xl:min-w-0 max-xl:flex-none"+ className="max-w-140 min-w-90 flex-[0_0_min(41.08280255%,560px)] max-xl:h-100 max-xl:w-full max-xl:max-w-none max-xl:min-w-0 max-xl:flex-none"agentId={agentId}- agentSoulConfig={buildDraft.agentSoulConfig}agentName={agentQuery.data?.name}currentModel={currentModel}isPublishing={isPublishing}@@ -510,7 +511,7 @@ function AgentConfigurePageComposerContent({onSelectModel={setConfigureModel}onPublish={publishDraft}onOpenVersions={() => {- workingDirectoryPanel.closeWorkingDirectory()+ setShowWorkingDirectory(false)setShowPreviewVersions(true)}}onExitVersions={() => selectVersion(null)}@@ -519,105 +520,66 @@ function AgentConfigurePageComposerContent({onComposerRebase()}}/>- }- rightPanel={- <AgentConfigurePreviewSurface- background={<AgentBuildPanelBackground visible={rightPanelChatMode === 'build'} />}- header={+ <div className="flex min-w-105 flex-1 gap-1 overflow-hidden max-xl:w-full max-xl:min-w-0 max-xl:flex-none max-xl:flex-col max-xl:overflow-visible">+ <AgentConfigurePreviewSurface className="min-w-105 flex-1 max-xl:h-100 max-xl:w-full max-xl:min-w-0 max-xl:flex-none">+ <AgentBuildPanelBackground visible={rightPanelChatMode === 'build'} /><AgentPreviewHeadermode={rightPanelChatMode}previewEnabled={previewEnabled}buildEnabled={capabilities.canBuild}- showChatFeaturesAction={capabilities.canEdit}- isChatFeaturesOpen={showChatFeatures}+ chatFeatures={+ capabilities.canEdit+ ? {+ open: showChatFeatures,+ onToggle: () => setShowChatFeatures((open) => !open),+ }+ : undefined+ }onModeChange={changeRightPanelMode}- onToggleChatFeatures={() => setShowChatFeatures((open) => !open)}onOpenWorkingDirectory={() => {setShowPreviewVersions(false)- workingDirectoryPanel.openWorkingDirectory()+ setShowWorkingDirectory(true)}}onRefresh={restartCurrentChat}refreshDisabled={isRestartCurrentChatDisabled}showWorkingDirectoryAction={capabilities.canBuild && showWorkingDirectoryAction}/>- }- chat={- !(rightPanelMode === 'build'- ? capabilities.canBuild- : previewEnabled) ? null : buildDraft.isPending ? (- <LoadingPlaceholder className="h-full" />- ) : (- <AgentConfigureRightPanelChat- agentId={agentId}- answerActionPosition="below"- agentName={agentQuery.data?.name}- agentSoulConfig={buildDraft.agentSoulConfig}- clearChatList={clearChatByMode[rightPanelChatMode]}- controllerRef={rightPanelChatControllerRef}- conversationIds={conversationIds}- disabled={isEnteringBuildMode}- mode={rightPanelChatMode}- speechToTextDraftType={- rightPanelChatMode === 'build' && buildDraft.isActive ? 'debug_build' : 'draft'- }- onClearChatListChange={(clearChatList) => {- setClearChatByMode((current) => ({- ...current,- [rightPanelChatMode]: clearChatList,- }))- }}- onConversationComplete={(mode, completedConversationId) => {- if (mode !== 'build' || !isBuildCallbackCurrent(buildCallbackGeneration)) return-- setCompletedBuildConversationId(completedConversationId)- invalidateAgentWorkingDirectoryFiles({- conversationId: completedConversationId,- queryClient,- })- buildDraftActions.refreshBuildDraftAfterBuildChat(() =>- finishBuildAction(buildCallbackGeneration),- )- }}- onConversationIdChange={(mode, conversationId) => {- if (mode === 'build' && !isBuildCallbackCurrent(buildCallbackGeneration)) return- setConversationId({ mode, conversationId })- }}- onBeforeSpeechToText={- rightPanelChatMode === 'build' ? saveDraftBeforeBuildRun : saveDraft- }- onSaveDraftBeforeRun={- rightPanelChatMode === 'build'- ? async () => {- if (!currentModel?.provider || !currentModel.model) {- toast.error(- tCommon(($) => $['modelProvider.selectModel'], { ns: 'modelProvider' }),- )- throw new Error('Agent model is required.')- }-- const preparedBuildDraft = await runBuildPreparation({- generation: buildCallbackGeneration,- markBuildChatStarted: true,- prepare: buildDraftActions.prepareBuildDraftBeforeRun,- })- trackAgentBuildModeRun(AgentScope.Global)- return preparedBuildDraft- }- : async () => {- await saveDraft()- trackAgentPreviewModeRun(AgentScope.Global)- }- }- onSendInterrupted={() => {- if (rightPanelChatMode === 'build') finishBuildAction(buildCallbackGeneration)- }}- />- )- }- />- }- sidePanels={- <>+ <AgentConfigurePreviewBody>+ {!(rightPanelMode === 'build'+ ? capabilities.canBuild+ : previewEnabled) ? null : buildDraft.isPending ? (+ <LoadingPlaceholder className="h-full" />+ ) : (+ <AgentConfigureRightPanelChat+ agentId={agentId}+ answerActionPosition="below"+ agentName={agentQuery.data?.name}+ agentSoulConfig={buildDraft.agentSoulConfig}+ clearChatList={clearChatByMode[rightPanelChatMode]}+ controllerRef={rightPanelChatControllerRef}+ conversationIds={conversationIds}+ disabled={isEnteringBuildMode}+ mode={rightPanelChatMode}+ speechToTextDraftType={+ rightPanelChatMode === 'build' && buildDraft.isActive ? 'debug_build' : 'draft'+ }+ onClearChatListChange={(clearChatList) => {+ setClearChatByMode((current) => ({+ ...current,+ [rightPanelChatMode]: clearChatList,+ }))+ }}+ onConversationComplete={handleConversationComplete}+ onConversationIdChange={handleConversationIdChange}+ onBeforeSpeechToText={+ rightPanelChatMode === 'build' ? saveDraftBeforeBuildRun : saveDraft+ }+ onSaveDraftBeforeRun={saveDraftBeforeChatRun}+ onSendInterrupted={handleSendInterrupted}+ />+ )}+ </AgentConfigurePreviewBody>+ </AgentConfigurePreviewSurface>{capabilities.canReleaseAndVersion && showPreviewVersions && (<AgentPreviewVersionsPanelagentId={agentId}@@ -642,21 +604,32 @@ function AgentConfigurePageComposerContent({onClose={() => setShowPreviewVersions(false)}/>)}- {capabilities.canBuild && workingDirectoryPanel.panel}- <AgentChatFeaturesPanel- show={capabilities.canEdit && showChatFeatures}- appFeatures={buildDraft.agentSoulConfig?.app_features}- disabled={isChatFeaturesReadOnly}- onClose={() => setShowChatFeatures(false)}- />- <AgentConfigureClearSessionConfirmDialog- open={capabilities.canBuild && showSwitchToPreviewConfirm}- title={t(($) => $['agentDetail.configure.switchToPreviewConfirm.title'])}- onOpenChange={setShowSwitchToPreviewConfirm}- onConfirm={confirmSwitchToPreview}- />- </>- }- />+ </div>+ </section>+ {capabilities.canBuild && workingDirectoryCallerId && (+ <AgentWorkingDirectoryPanel+ source={{+ type: 'agent',+ agentId,+ callerType: rightPanelChatMode === 'build' ? 'build_draft' : 'conversation',+ callerId: workingDirectoryCallerId,+ }}+ open={showWorkingDirectory}+ onOpenChange={setShowWorkingDirectory}+ />+ )}+ <AgentChatFeaturesPanel+ show={capabilities.canEdit && showChatFeatures}+ appFeatures={buildDraft.agentSoulConfig?.app_features}+ disabled={isChatFeaturesReadOnly}+ onClose={() => setShowChatFeatures(false)}+ />+ <AgentConfigureClearSessionConfirmDialog+ open={capabilities.canBuild && showSwitchToPreviewConfirm}+ title={t(($) => $['agentDetail.configure.switchToPreviewConfirm.title'])}+ onOpenChange={setShowSwitchToPreviewConfirm}+ onConfirm={confirmSwitchToPreview}+ />+ </>)}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsxindex 38df49edf68..999935ed9fc 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx@@ -1,9 +1,6 @@'use client'-import type {- AgentConfigSnapshotDetailResponse,- AgentConfigSnapshotSummaryResponse,-} from '@dify/contracts/api/console/agent/types.gen'+import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'import type { ReactNode } from 'react'import type { AgentConfigurePublishResult } from '../../use-agent-configure-sync'import type { AgentBuildDraftChangedKey } from './build-draft-changes-context'@@ -16,7 +13,7 @@ import {ScrollAreaThumb,ScrollAreaViewport,} from '@langgenius/dify-ui/scroll-area'-import { useMemo } from 'react'+import { useId, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { ENABLE_AGENT_KNOWLEDGE_RETRIEVAL } from '@/features/agent-v2/agent-detail/configure/feature-flags'import { AgentOrchestrateAddActionsProvider } from './add-actions'@@ -43,7 +40,6 @@ type AgentOrchestratePanelProps = {agentId: stringappId?: stringnodeId?: string- agentSoulConfig?: AgentConfigSnapshotDetailResponse['config_snapshot']agentName?: string | nullcurrentModel?: AgentComposerModelisPublishing?: boolean@@ -69,7 +65,6 @@ export function AgentOrchestratePanel({agentId,appId,nodeId,- agentSoulConfig: _agentSoulConfig,agentName,currentModel,isPublishing,@@ -92,7 +87,7 @@ export function AgentOrchestratePanel({}: AgentOrchestratePanelProps) {const { t } = useTranslation(['agentV2'])const isTemplatePreview = !!trialAppId- const orchestrateHeadingId = 'agent-configure-orchestrate-heading'+ const orchestrateHeadingId = useId()const orchestrateLabel = t(($) => $['agentDetail.configure.title'])const orchestrateBottomAction =bottomAction ??@@ -133,7 +128,7 @@ export function AgentOrchestratePanel({return (<divclassName={cn(- 'relative flex max-w-140 min-w-90 flex-[0_0_min(41.08280255%,560px)] flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg',+ 'relative flex flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg',className,)}>diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsxindex b8173c34364..dccd1afe9ee 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx@@ -61,6 +61,7 @@ export function AgentModelField({ currentModel, onSelect }: AgentModelFieldProps</div>) : (<ModelParameterModal+ triggerContainerClassName="min-w-0"isAdvancedModemodelId={currentModel?.model ?? ''}provider={currentModel?.provider ?? ''}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsxindex 3a8c1730c38..848b99c6154 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx@@ -342,6 +342,23 @@ export function AgentSkillDetailDialog({}: {skillName: stringdetail: AgentSkillDetail+}) {+ return (+ <DialogContent+ backdropProps={{ forceRender: true, className: 'fixed' }}+ className="h-[min(720px,calc(100dvh-2rem))] w-[min(960px,calc(100vw-2rem))] overflow-hidden"+ >+ <AgentSkillDetailBody skillName={skillName} detail={detail} />+ </DialogContent>+ )+}++export function AgentSkillDetailBody({+ skillName,+ detail,+}: {+ skillName: string+ detail: AgentSkillDetail}) {const { t: tCommon } = useTranslation(['common'])const dialogTitleId = useId()@@ -349,10 +366,7 @@ export function AgentSkillDetailDialog({const isHeaderDownloadLoading = detail.filePreview?.downloadActionLoadingTarget === 'header'return (- <DialogContent- backdropProps={{ forceRender: true, className: 'fixed' }}- className="h-[min(720px,calc(100dvh-2rem))] w-[min(960px,calc(100vw-2rem))] overflow-hidden"- >+ <><div className="flex min-h-0 flex-1"><divclassName={cn(@@ -465,6 +479,6 @@ export function AgentSkillDetailDialog({</ScrollArea></div></div>- </DialogContent>+ </>)}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsxindex ef8bec273b5..5c019256d6c 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx@@ -26,9 +26,8 @@ function renderHeader({<AgentPreviewHeadermode={mode}previewEnabled={previewEnabled}- isChatFeaturesOpen={false}onModeChange={onModeChange}- onToggleChatFeatures={onToggleChatFeatures}+ chatFeatures={{ open: false, onToggle: onToggleChatFeatures }}onOpenWorkingDirectory={onOpenWorkingDirectory}onRefresh={onRefresh}refreshDisabled={refreshDisabled}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/working-directory-panel.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/working-directory-panel.spec.tsxindex db410e50220..1b6588520bb 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/working-directory-panel.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/working-directory-panel.spec.tsx@@ -363,6 +363,31 @@ describe('AgentWorkingDirectoryPanel', () => {)})+ it('loads files only while mounted and starts a fresh directory selection after reopening', async () => {+ const user = userEvent.setup()+ const view = renderWorkingDirectoryPanel({ open: false })+ expect(mocks.sandboxFilesQueryOptions).not.toHaveBeenCalled()+ view.rerenderPanel({ open: true, source: agentSource })+ await user.click(+ await screen.findByRole('tab', {+ name: 'agentV2.agentDetail.configure.workingDirectory.temporaryFiles',+ }),+ )+ expect(+ screen.getByRole('tab', {+ name: 'agentV2.agentDetail.configure.workingDirectory.temporaryFiles',+ }),+ ).toHaveAttribute('aria-selected', 'true')+ view.rerenderPanel({ open: false, source: agentSource })+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ view.rerenderPanel({ open: true, source: agentSource })+ expect(+ await screen.findByRole('tab', {+ name: 'agentV2.agentDetail.configure.workingDirectory.persistentFiles',+ }),+ ).toHaveAttribute('aria-selected', 'true')+ })+it('lets keyboard users expand and enter a folder with separate controls', async () => {const user = userEvent.setup()mocks.sandboxFilesQueryOptions.mockImplementation(({ input }: QueryOptionsInput) => {diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsxindex 994a8e72422..0ca53d5413b 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx@@ -111,29 +111,23 @@ function PreviewModeItem({export function AgentPreviewHeader({mode,previewEnabled,- isChatFeaturesOpen,+ chatFeatures,buildEnabled = true,onModeChange,- onToggleChatFeatures,onOpenWorkingDirectory,onRefresh,refreshDisabled,showWorkingDirectoryAction = false,- showChatFeaturesAction = true,- trailingAction,}: {mode: AgentConfigureRightPanelModepreviewEnabled: boolean- isChatFeaturesOpen: boolean+ chatFeatures?: { open: boolean; onToggle: () => void }buildEnabled?: booleanonModeChange: (mode: AgentConfigureRightPanelMode) => void- onToggleChatFeatures: () => voidonOpenWorkingDirectory: () => voidonRefresh: () => voidrefreshDisabled?: booleanshowWorkingDirectoryAction?: boolean- showChatFeaturesAction?: boolean- trailingAction?: ReactNode}) {const { t } = useTranslation(['agentV2'])const docLink = useDocLink()@@ -158,7 +152,7 @@ export function AgentPreviewHeader({)return (- <div className="relative z-1 flex h-12 shrink-0 items-center justify-between gap-3 px-4 py-2 max-sm:h-auto max-sm:flex-wrap max-sm:gap-1 max-sm:px-2">+ <div className="relative z-1 flex h-12 shrink-0 items-center justify-between gap-3 px-4 py-2 pr-(--agent-preview-header-end,1rem) max-sm:h-auto max-sm:flex-wrap max-sm:gap-1 max-sm:px-2 max-sm:pr-(--agent-preview-header-end,0.5rem)"><div className="flex min-w-0 flex-1 items-center gap-2 max-sm:w-full max-sm:flex-none"><SegmentedControl<AgentConfigureRightPanelMode>value={mode}@@ -242,16 +236,16 @@ export function AgentPreviewHeader({</button>)}</div>- {showChatFeaturesAction && (+ {chatFeatures && (<><SegmentedControlDivider className="mx-3 max-sm:hidden" /><buttontype="button"- aria-expanded={isChatFeaturesOpen}- onClick={onToggleChatFeatures}+ aria-expanded={chatFeatures.open}+ onClick={chatFeatures.onToggle}className={cn('flex h-8 items-center justify-center gap-1 rounded-lg px-2 py-2 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',- isChatFeaturesOpen && 'bg-state-base-hover text-text-secondary',+ chatFeatures.open && 'bg-state-base-hover text-text-secondary',)}><span aria-hidden className="i-ri-chat-settings-line size-4" />@@ -261,12 +255,6 @@ export function AgentPreviewHeader({</button></>)}- {trailingAction != null && (- <>- <SegmentedControlDivider className="mx-3 max-sm:hidden" />- {trailingAction}- </>- )}</div></div>)diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel.tsxdeleted file mode 100644index e4a0bc1b4c2..00000000000--- a/web/features/agent-v2/agent-detail/configure/components/preview/hook/use-working-directory-panel.tsx+++ /dev/null@@ -1,99 +0,0 @@-'use client'--import type { QueryClient } from '@tanstack/react-query'-import type { ReactNode } from 'react'-import type { AgentWorkingDirectorySource } from '../working-directory-panel'-import { useState } from 'react'-import { consoleQuery } from '@/service/console'-import { AgentWorkingDirectoryPanel } from '../working-directory-panel'--export function invalidateAgentWorkingDirectoryFiles({- appId,- conversationId,- nodeId,- queryClient,-}: {- appId?: string- conversationId?: string | null- nodeId?: string- queryClient: QueryClient-}) {- if (appId && nodeId) {- void queryClient.invalidateQueries({- queryKey:- consoleQuery.apps.byAppId.workflowRuns.byWorkflowRunId.agentNodes.byNodeId.sandbox.files.get.key(- { type: 'query' },- ),- })- return- }-- if (!conversationId) return-- void queryClient.invalidateQueries({- queryKey: consoleQuery.agent.byAgentId.sandbox.files.get.key({ type: 'query' }),- })-}--type AgentWorkingDirectoryPanelInput =- | {- type: 'agent'- agentId: string- caller:- | {- type: 'build_draft'- id?: string- }- | {- type: 'conversation'- id?: string | null- }- }- | {- type: 'workflow-node'- appId?: string- nodeId: string- nodeExecutionId?: string- workflowRunId?: string | null- }--export function useAgentWorkingDirectoryPanel(input: AgentWorkingDirectoryPanelInput): {- closeWorkingDirectory: () => void- openWorkingDirectory: () => void- panel: ReactNode-} {- const [open, setOpen] = useState(false)- let source: AgentWorkingDirectorySource | undefined- if (input.type === 'workflow-node') {- const { appId, nodeExecutionId, nodeId, workflowRunId } = input- source =- appId && nodeExecutionId && workflowRunId- ? {- type: 'workflow-node',- appId,- nodeId,- nodeExecutionId,- workflowRunId,- }- : undefined- } else {- const callerId = input.caller.id- source = callerId- ? {- type: 'agent',- agentId: input.agentId,- callerType: input.caller.type,- callerId,- }- : undefined- }-- return {- closeWorkingDirectory: () => setOpen(false),- openWorkingDirectory: () => setOpen(true),- panel:- open && source ? (- <AgentWorkingDirectoryPanel source={source} open={open} onOpenChange={setOpen} />- ) : null,- }-}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsxindex 52db74013f5..926a68916cf 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx@@ -47,6 +47,7 @@ export function AgentConfigureRightPanelChat({) : (<AgentPreviewChat{...props}+ inputAutoFocus={false}conversationId={conversationId}agentSoulConfig={previewAgentSoulConfig}onConversationComplete={handleConversationComplete}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/surface.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/surface.tsxnew file mode 100644index 00000000000..59ccc692958--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/surface.tsx@@ -0,0 +1,29 @@+'use client'++import type { ReactNode } from 'react'+import { cn } from '@langgenius/dify-ui/cn'++type AgentConfigurePreviewSurfaceProps = {+ children: ReactNode+ className?: string+}++export function AgentConfigurePreviewSurface({+ children,+ className,+}: AgentConfigurePreviewSurfaceProps) {+ return (+ <div+ className={cn(+ 'relative isolate flex flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-linear-to-b from-background-gradient-bg-fill-chat-bg-1 to-background-gradient-bg-fill-chat-bg-2 shadow-xl shadow-shadow-shadow-5',+ className,+ )}+ >+ {children}+ </div>+ )+}++export function AgentConfigurePreviewBody({ children }: { children: ReactNode }) {+ return <div className="relative z-1 min-h-0 flex-1">{children}</div>+}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-cache.ts b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-cache.tsnew file mode 100644index 00000000000..511563a845e--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-cache.ts@@ -0,0 +1,30 @@+import type { QueryClient } from '@tanstack/react-query'+import { consoleQuery } from '@/service/console'++export function invalidateAgentWorkingDirectoryFiles({+ appId,+ conversationId,+ nodeId,+ queryClient,+}: {+ appId?: string+ conversationId?: string | null+ nodeId?: string+ queryClient: QueryClient+}) {+ if (appId && nodeId) {+ void queryClient.invalidateQueries({+ queryKey:+ consoleQuery.apps.byAppId.workflowRuns.byWorkflowRunId.agentNodes.byNodeId.sandbox.files.get.key(+ { type: 'query' },+ ),+ })+ return+ }++ if (!conversationId) return++ void queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.byAgentId.sandbox.files.get.key({ type: 'query' }),+ })+}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsxindex 511a59e9bfd..9dcca80527d 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx@@ -10,7 +10,7 @@ import type {AgentWorkingDirectoryRootPath,} from './working-directory-breadcrumb'import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'-import { Dialog } from '@langgenius/dify-ui/dialog'+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'import { Tabs, TabsIndicator, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'import { isDefinedError } from '@orpc/client'@@ -22,7 +22,7 @@ import { getFileIconType } from '@/features/agent-v2/file-icon'import { consoleClient, consoleQuery } from '@/service/console'import { isNotFoundError } from '@/service/http-error'import { downloadUrl } from '@/utils/download'-import { AgentSkillDetailDialog } from '../orchestrate/skills/detail-dialog'+import { AgentSkillDetailBody } from '../orchestrate/skills/detail-dialog'import {AGENT_SAVED_FILES_ROOT_PATH,AGENT_TEMPORARY_FILES_ROOT_PATH,@@ -228,6 +228,22 @@ export function AgentWorkingDirectoryPanel({onOpenChange,open,}: AgentWorkingDirectoryPanelProps) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ backdropProps={{ forceRender: true, className: 'fixed' }}+ className="h-[min(720px,calc(100dvh-2rem))] w-[min(960px,calc(100vw-2rem))] overflow-hidden"+ >+ <AgentWorkingDirectoryContent source={source} open={open} />+ </DialogContent>+ </Dialog>+ )+}++function AgentWorkingDirectoryContent({+ source,+ open,+}: Pick<AgentWorkingDirectoryPanelProps, 'source' | 'open'>) {const temporaryFilesLabelId = useId()const persistentFilesLabelId = useId()@@ -507,147 +523,143 @@ export function AgentWorkingDirectoryPanel({)return (- <Dialog open={open} onOpenChange={onOpenChange}>- <AgentSkillDetailDialog- skillName={t(($) => $['agentDetail.configure.workingDirectory.title'])}- detail={{- description: t(($) => $['agentDetail.configure.workingDirectory.description']),- fileCount: countReadableFiles(workingDirectoryFiles),- fileListHeader: (- <div className="flex shrink-0 flex-col">- <h3- id="agent-skill-detail-files-heading"- className="px-4 pt-3.5 pb-2 system-xl-semibold text-text-primary"- >- {t(($) => $['agentDetail.configure.workingDirectory.fileSystem'])}- </h3>- <Tabs- value={selectedRootPath}- onValueChange={(path) =>- handleDirectoryPathChange(path as AgentWorkingDirectoryPath)- }- >- <TabsList className="relative h-9 gap-4 border-b-[0.5px] border-divider-regular px-4">- <div className="flex h-full items-center gap-0.5">- <TabsTab- value={AGENT_SAVED_FILES_ROOT_PATH}- className="h-full min-w-0 pt-0 pb-0 system-sm-semibold data-active:border-transparent"- >- <span id={persistentFilesLabelId}>- {t(($) => $['agentDetail.configure.workingDirectory.persistentFiles'])}- </span>- </TabsTab>- <Infotip>- <InfotipTrigger- aria-labelledby={persistentFilesLabelId}- iconVariant="information"- />- <InfotipContent aria-labelledby={persistentFilesLabelId} className="w-64">- {persistentFilesTooltip}- </InfotipContent>- </Infotip>- </div>- <div className="flex h-full items-center gap-0.5">- <TabsTab- value={AGENT_TEMPORARY_FILES_ROOT_PATH}- className="h-full min-w-0 pt-0 pb-0 system-sm-semibold data-active:border-transparent"- >- <span id={temporaryFilesLabelId}>- {t(($) => $['agentDetail.configure.workingDirectory.temporaryFiles'])}- </span>- </TabsTab>- <Infotip>- <InfotipTrigger- aria-labelledby={temporaryFilesLabelId}- iconVariant="information"- />- <InfotipContent aria-labelledby={temporaryFilesLabelId} className="w-64">- {temporaryFilesTooltip}- </InfotipContent>- </Infotip>- </div>- <TabsIndicator- className="pointer-events-none absolute bottom-0 left-0 h-0 border-b-2 border-components-tab-active transition-[translate,width] duration-150 ease-in-out motion-reduce:transition-none"- style={{- translate: 'var(--active-tab-left)',- width: 'var(--active-tab-width)',- }}- />- </TabsList>- <TabsPanel value={AGENT_SAVED_FILES_ROOT_PATH} tabIndex={-1}>- <AgentWorkingDirectoryBreadcrumb- path={directoryPath}- onPathChange={handleDirectoryPathChange}- />- </TabsPanel>- <TabsPanel value={AGENT_TEMPORARY_FILES_ROOT_PATH} tabIndex={-1}>- <AgentWorkingDirectoryBreadcrumb- path={directoryPath}- onPathChange={handleDirectoryPathChange}- />- </TabsPanel>- </Tabs>- </div>- ),- fileListPanelClassName: 'w-[360px]',- fileListTreeClassName: 'px-0',- fileListTreeListClassName: 'px-1',- fileListTitle: t(($) => $['agentDetail.configure.workingDirectory.title']),- files: workingDirectoryFiles,- filePreview: {- binary: fileReadQuery.data?.binary,- content: fileReadQuery.data?.text ?? undefined,- downloadActionLoadingTarget,- downloadUrl: imagePreviewQuery.data?.url,- fileName: isFileListLoading ? '' : selectedWorkingDirectoryFile?.name,- isDownloadError: imagePreviewQuery.isError,- isDownloadLoading: !!isImagePreviewFile && imagePreviewQuery.isPending,- isError: (fileListQuery.isError && !hasNoActiveBinding) || fileReadQuery.isError,- isImage: isImagePreviewFile,- isLoading: isFileListLoading || isFileReadLoading,- },- onDownloadFile: selectedWorkingDirectoryFile ? handleDownloadFile : undefined,- folderOpenState: ({ file }) => {- const queryIndex = loadedFolderPathIndexes.get(file.id)- const folderLoaded = queryIndex !== undefined && expandedFolders[queryIndex]?.isLoaded-- return (- openFolderPaths.includes(file.id) ||- (pendingOpenFolderPaths.includes(file.id) && !!folderLoaded)- )- },- onFolderOpenChange: ({ file, open }) => {- if (loadingFolderPaths.has(file.id)) return-- if (open && !loadedFolderPaths.includes(file.id)) {- setLoadedFolderPaths((paths) => [...paths, file.id])- setPendingOpenFolderPaths((paths) =>- paths.includes(file.id) ? paths : [...paths, file.id],- )- return- }-- setPendingOpenFolderPaths((paths) => paths.filter((path) => path !== file.id))- setOpenFolderPaths((paths) =>- open- ? paths.includes(file.id)- ? paths- : [...paths, file.id]- : paths.filter((path) => path !== file.id),+ <AgentSkillDetailBody+ skillName={t(($) => $['agentDetail.configure.workingDirectory.title'])}+ detail={{+ description: t(($) => $['agentDetail.configure.workingDirectory.description']),+ fileCount: countReadableFiles(workingDirectoryFiles),+ fileListHeader: (+ <div className="flex shrink-0 flex-col">+ <h3+ id="agent-skill-detail-files-heading"+ className="px-4 pt-3.5 pb-2 system-xl-semibold text-text-primary"+ >+ {t(($) => $['agentDetail.configure.workingDirectory.fileSystem'])}+ </h3>+ <Tabs+ value={selectedRootPath}+ onValueChange={(path) => handleDirectoryPathChange(path as AgentWorkingDirectoryPath)}+ >+ <TabsList className="relative h-9 gap-4 border-b-[0.5px] border-divider-regular px-4">+ <div className="flex h-full items-center gap-0.5">+ <TabsTab+ value={AGENT_SAVED_FILES_ROOT_PATH}+ className="h-full min-w-0 pt-0 pb-0 system-sm-semibold data-active:border-transparent"+ >+ <span id={persistentFilesLabelId}>+ {t(($) => $['agentDetail.configure.workingDirectory.persistentFiles'])}+ </span>+ </TabsTab>+ <Infotip>+ <InfotipTrigger+ aria-labelledby={persistentFilesLabelId}+ iconVariant="information"+ />+ <InfotipContent aria-labelledby={persistentFilesLabelId} className="w-64">+ {persistentFilesTooltip}+ </InfotipContent>+ </Infotip>+ </div>+ <div className="flex h-full items-center gap-0.5">+ <TabsTab+ value={AGENT_TEMPORARY_FILES_ROOT_PATH}+ className="h-full min-w-0 pt-0 pb-0 system-sm-semibold data-active:border-transparent"+ >+ <span id={temporaryFilesLabelId}>+ {t(($) => $['agentDetail.configure.workingDirectory.temporaryFiles'])}+ </span>+ </TabsTab>+ <Infotip>+ <InfotipTrigger+ aria-labelledby={temporaryFilesLabelId}+ iconVariant="information"+ />+ <InfotipContent aria-labelledby={temporaryFilesLabelId} className="w-64">+ {temporaryFilesTooltip}+ </InfotipContent>+ </Infotip>+ </div>+ <TabsIndicator+ className="pointer-events-none absolute bottom-0 left-0 h-0 border-b-2 border-components-tab-active transition-[translate,width] duration-150 ease-in-out motion-reduce:transition-none"+ style={{+ translate: 'var(--active-tab-left)',+ width: 'var(--active-tab-width)',+ }}+ />+ </TabsList>+ <TabsPanel value={AGENT_SAVED_FILES_ROOT_PATH} tabIndex={-1}>+ <AgentWorkingDirectoryBreadcrumb+ path={directoryPath}+ onPathChange={handleDirectoryPathChange}+ />+ </TabsPanel>+ <TabsPanel value={AGENT_TEMPORARY_FILES_ROOT_PATH} tabIndex={-1}>+ <AgentWorkingDirectoryBreadcrumb+ path={directoryPath}+ onPathChange={handleDirectoryPathChange}+ />+ </TabsPanel>+ </Tabs>+ </div>+ ),+ fileListPanelClassName: 'w-[360px]',+ fileListTreeClassName: 'px-0',+ fileListTreeListClassName: 'px-1',+ fileListTitle: t(($) => $['agentDetail.configure.workingDirectory.title']),+ files: workingDirectoryFiles,+ filePreview: {+ binary: fileReadQuery.data?.binary,+ content: fileReadQuery.data?.text ?? undefined,+ downloadActionLoadingTarget,+ downloadUrl: imagePreviewQuery.data?.url,+ fileName: isFileListLoading ? '' : selectedWorkingDirectoryFile?.name,+ isDownloadError: imagePreviewQuery.isError,+ isDownloadLoading: !!isImagePreviewFile && imagePreviewQuery.isPending,+ isError: (fileListQuery.isError && !hasNoActiveBinding) || fileReadQuery.isError,+ isImage: isImagePreviewFile,+ isLoading: isFileListLoading || isFileReadLoading,+ },+ onDownloadFile: selectedWorkingDirectoryFile ? handleDownloadFile : undefined,+ folderOpenState: ({ file }) => {+ const queryIndex = loadedFolderPathIndexes.get(file.id)+ const folderLoaded = queryIndex !== undefined && expandedFolders[queryIndex]?.isLoaded++ return (+ openFolderPaths.includes(file.id) ||+ (pendingOpenFolderPaths.includes(file.id) && !!folderLoaded)+ )+ },+ onFolderOpenChange: ({ file, open }) => {+ if (loadingFolderPaths.has(file.id)) return++ if (open && !loadedFolderPaths.includes(file.id)) {+ setLoadedFolderPaths((paths) => [...paths, file.id])+ setPendingOpenFolderPaths((paths) =>+ paths.includes(file.id) ? paths : [...paths, file.id],)- },- onFolderEnter: ({ file }) => handleDirectoryPathChange(file.id),- onSelectFile: (selectedFile) => setSelectedFileId(selectedFile.id),- renderFolderSuffix: ({ file }) =>- loadingFolderPaths.has(file.id) ? (- <span className="ms-auto i-ri-loader-4-line size-4 shrink-0 animate-spin text-text-tertiary">- <span className="sr-only">{tCommon(($) => $.loading)}</span>- </span>- ) : null,- selectedFileId: selectedWorkingDirectoryFile?.id,- sections: [],- }}- />- </Dialog>+ return+ }++ setPendingOpenFolderPaths((paths) => paths.filter((path) => path !== file.id))+ setOpenFolderPaths((paths) =>+ open+ ? paths.includes(file.id)+ ? paths+ : [...paths, file.id]+ : paths.filter((path) => path !== file.id),+ )+ },+ onFolderEnter: ({ file }) => handleDirectoryPathChange(file.id),+ onSelectFile: (selectedFile) => setSelectedFileId(selectedFile.id),+ renderFolderSuffix: ({ file }) =>+ loadingFolderPaths.has(file.id) ? (+ <span className="ms-auto i-ri-loader-4-line size-4 shrink-0 animate-spin text-text-tertiary">+ <span className="sr-only">{tCommon(($) => $.loading)}</span>+ </span>+ ) : null,+ selectedFileId: selectedWorkingDirectoryFile?.id,+ sections: [],+ }}+ />)}diff --git a/web/features/agent-v2/agent-detail/configure/components/workspace.tsx b/web/features/agent-v2/agent-detail/configure/components/workspace.tsxdeleted file mode 100644index df59a7388ad..00000000000--- a/web/features/agent-v2/agent-detail/configure/components/workspace.tsx+++ /dev/null@@ -1,56 +0,0 @@-'use client'--import type { ReactNode } from 'react'-import { cn } from '@langgenius/dify-ui/cn'--type AgentConfigureWorkspaceProps = {- 'aria-busy'?: boolean- className?: string- leftPanel: ReactNode- rightPanel: ReactNode- sidePanels?: ReactNode-}--export function AgentConfigureWorkspace({- 'aria-busy': ariaBusy,- className,- leftPanel,- rightPanel,- sidePanels,-}: AgentConfigureWorkspaceProps) {- return (- <section- aria-busy={ariaBusy}- className={cn(- 'flex h-full min-w-0 flex-1 gap-1 overflow-hidden bg-background-body p-1 max-xl:flex-col max-xl:overflow-y-auto',- className,- )}- >- {leftPanel}- <div className="flex min-w-105 flex-1 gap-1 overflow-hidden max-xl:w-full max-xl:min-w-0 max-xl:flex-none max-xl:flex-col max-xl:overflow-visible">- {rightPanel}- {sidePanels}- </div>- </section>- )-}--type AgentConfigurePreviewSurfaceProps = {- background?: ReactNode- chat: ReactNode- header: ReactNode-}--export function AgentConfigurePreviewSurface({- background,- chat,- header,-}: AgentConfigurePreviewSurfaceProps) {- return (- <div className="relative isolate flex min-w-105 flex-1 flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-linear-to-b from-background-gradient-bg-fill-chat-bg-1 to-background-gradient-bg-fill-chat-bg-2 shadow-xl shadow-shadow-shadow-5 max-xl:h-100 max-xl:w-full max-xl:min-w-0 max-xl:flex-none">- {background}- {header}- <div className="relative z-1 min-h-0 flex-1">{chat}</div>- </div>- )-}diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.tsindex 05e82d6a28d..cef073780e6 100644--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts@@ -13,10 +13,11 @@ import type {} from '@/features/agent-v2/agent-composer/form-state'import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import isEqual from 'fast-deep-equal'-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useCallback, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { toast } from '@/app/notifications'import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'+import { useAgentBuildDraftRefresh } from '@/features/agent-v2/build-draft-refresh'import { consoleQuery } from '@/service/console'import { isNotFoundError } from '@/service/http-error'import { usePrepareAgentBuildDraftBeforeRun } from './use-agent-build-draft-run'@@ -24,9 +25,6 @@ import { usePrepareAgentBuildDraftBeforeRun } from './use-agent-build-draft-run'const BUILD_NOTE_FILE_ID = '__agent_config_build_note__'const BUILD_NOTE_FILE_NAME = 'build_note.md'-const getAgentSoulConfigFromRefetchResult = (result: unknown) => {- return (result as { data?: { agent_soul?: AgentSoulConfig } } | undefined)?.data?.agent_soul-}const flattenFileNodes = (files: AgentFileNode[]): AgentFileNode[] =>files.flatMap((file) =>file.children?.length ? [file, ...flattenFileNodes(file.children)] : [file],@@ -157,14 +155,9 @@ export function useAgentConfigureBuildDraftData({soulSourceOverride: AgentConfigureSoulSource | null}) {const { t } = useTranslation(['common'])- const buildDraftQueryInput = {- params: {- agent_id: agentId,- },- }const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({input: {- params: buildDraftQueryInput.params,+ params: { agent_id: agentId },},context: {silent: true,@@ -206,7 +199,7 @@ export function useAgentConfigureBuildDraftData({const hasActiveBuildDraft = resolvedSoulSource === 'build-draft'const soulSource = !isBuildMode && hasActiveBuildDraft ? 'draft' : resolvedSoulSourceconst isBuildDraftActive = soulSource === 'build-draft'- const buildDraftAgentSoulConfig = buildDraftData?.agent_soul as AgentSoulConfig | undefined+ const buildDraftAgentSoulConfig = buildDraftData?.agent_soulconst visibleAgentSoulConfig = isBuildDraftActive? buildDraftAgentSoulConfig: normalAgentSoulConfig@@ -277,8 +270,8 @@ export function useAgentConfigureBuildDraftActions({isActive: booleannormalAgentSoulConfig?: AgentSoulConfigrebaseComposerDraft: (agentSoulConfig?: AgentSoulConfig) => void- refetchBuildDraft: () => Promise<unknown>- refetchComposer: () => Promise<unknown>+ refetchBuildDraft: () => Promise<{ data?: { agent_soul?: AgentSoulConfig } }>+ refetchComposer: () => Promise<{ data?: { agent_soul?: AgentSoulConfig } }>resetBuildChatSession: () => Promise<void>saveDraft: () => Promise<void>onComposerRebased?: () => void@@ -286,8 +279,6 @@ export function useAgentConfigureBuildDraftActions({}) {const { t: tCommon } = useTranslation(['common'])const queryClient = useQueryClient()- const buildDraftRefreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)- const buildDraftRefreshGenerationRef = useRef(0)const forceCheckoutBeforeNextBuildRunRef = useRef(false)const [isApplyingBuildDraftWorkflow, setIsApplyingBuildDraftWorkflow] = useState(false)const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({@@ -309,10 +300,8 @@ export function useAgentConfigureBuildDraftActions({const discardBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions(),)- const { mutateAsync: finalizeBuildChatRequest, isPending: isFinalizingBuildChat } =- finalizeBuildChatMutation- const { mutateAsync: applyBuildDraftRequest, isPending: isApplyingBuildDraftRequest } =- applyBuildDraftMutation+ const { mutateAsync: finalizeBuildChatRequest } = finalizeBuildChatMutation+ const { mutateAsync: applyBuildDraftRequest } = applyBuildDraftMutationconst { mutateAsync: discardBuildDraftRequest, isPending: isDiscardingBuildDraft } =discardBuildDraftMutationconst { forceCheckoutBuildDraft, prepareBuildDraftBeforeRun } =@@ -325,13 +314,10 @@ export function useAgentConfigureBuildDraftActions({setSoulSourceOverride,})- const cancelBuildDraftRefresh = useCallback(() => {- buildDraftRefreshGenerationRef.current += 1- if (!buildDraftRefreshTimerRef.current) return-- clearTimeout(buildDraftRefreshTimerRef.current)- buildDraftRefreshTimerRef.current = null- }, [])+ const { cancelBuildDraftRefresh, refreshBuildDraftAfterBuildChat } = useAgentBuildDraftRefresh({+ refetchBuildDraft,+ rebaseComposerDraft,+ })const prepareBuildDraftRun = useCallback(async () => {cancelBuildDraftRefresh()@@ -367,28 +353,6 @@ export function useAgentConfigureBuildDraftActions({}}, [cancelBuildDraftRefresh, resetBuildChatSession, setSoulSourceOverride, tCommon])- const refreshBuildDraftAfterBuildChat = useCallback(- (onRefreshed?: () => void) => {- cancelBuildDraftRefresh()- const refreshGeneration = buildDraftRefreshGenerationRef.current-- buildDraftRefreshTimerRef.current = setTimeout(async () => {- buildDraftRefreshTimerRef.current = null- try {- const result = await refetchBuildDraft()- if (refreshGeneration !== buildDraftRefreshGenerationRef.current) return-- const agentSoulConfig = getAgentSoulConfigFromRefetchResult(result)- if (agentSoulConfig) rebaseComposerDraft(agentSoulConfig)- } catch {- } finally {- if (refreshGeneration === buildDraftRefreshGenerationRef.current) onRefreshed?.()- }- }, 1000)- },- [cancelBuildDraftRefresh, rebaseComposerDraft, refetchBuildDraft],- )-const exitBuildDraftMode = useCallback(async (shouldRefetchComposer: boolean) => {cancelBuildDraftRefresh()@@ -396,7 +360,7 @@ export function useAgentConfigureBuildDraftActions({let nextAgentSoulConfig = normalAgentSoulConfigif (shouldRefetchComposer) {const result = await refetchComposer()- nextAgentSoulConfig = getAgentSoulConfigFromRefetchResult(result) ?? normalAgentSoulConfig+ nextAgentSoulConfig = result.data?.agent_soul ?? normalAgentSoulConfig}setSoulSourceOverride('draft')queryClient.removeQueries({@@ -462,18 +426,11 @@ export function useAgentConfigureBuildDraftActions({}}- useEffect(() => {- return () => {- cancelBuildDraftRefresh()- }- }, [cancelBuildDraftRefresh])-return {applyBuildDraft,cancelBuildDraftRefresh,discardBuildDraft,- isApplyingBuildDraft:- isApplyingBuildDraftWorkflow || isFinalizingBuildChat || isApplyingBuildDraftRequest,+ isApplyingBuildDraft: isApplyingBuildDraftWorkflow,isDiscardingBuildDraft,prepareBuildDraftBeforeRun: prepareBuildDraftRun,refreshBuildDraftAfterBuildChat,diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-session-controller.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-session-controller.tsindex 2a29e712ca3..88d50df845e 100644--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-session-controller.ts+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-session-controller.ts@@ -23,7 +23,7 @@ export function useAgentConfigureSessionController({}) {const [buildCallbackRevision, setBuildCallbackRevision] = useState(0)const [buildDraftActionsDisabled, setBuildDraftActionsDisabled] = useState(false)- const [hasStartedBuildChat, setHasStartedBuildChat] = useState(false)+ const hasStartedBuildChatRef = useRef(false)const [isEnteringBuildMode, setIsEnteringBuildMode] = useState(false)const [showSwitchToPreviewConfirm, setShowSwitchToPreviewConfirm] = useState(false)const buildCallbackGeneration = useMemo(@@ -104,7 +104,7 @@ export function useAgentConfigureSessionController({throw new Error('The Build session is no longer active.')if (markBuildChatStarted) {- setHasStartedBuildChat(true)+ hasStartedBuildChatRef.current = truesetBuildDraftActionsDisabled(true)}@@ -121,7 +121,7 @@ export function useAgentConfigureSessionController({} catch (error) {if (markBuildChatStarted && isBuildCallbackCurrent(generation)) {setBuildDraftActionsDisabled(false)- setHasStartedBuildChat(false)+ hasStartedBuildChatRef.current = false}throw error} finally {@@ -145,7 +145,7 @@ export function useAgentConfigureSessionController({buildCallbacksEnabledRef.current && modeRef.current === 'build'rotateBuildCallbackGeneration(keepBuildCallbacksEnabled)setBuildDraftActionsDisabled(false)- setHasStartedBuildChat(false)+ hasStartedBuildChatRef.current = false}, [rotateBuildCallbackGeneration])const resetBuildSession = useCallback(@@ -197,7 +197,7 @@ export function useAgentConfigureSessionController({if (nextMode === modeRef.current) returnconst isLeavingBuildMode = modeRef.current === 'build' && nextMode === 'preview'- if (isLeavingBuildMode && (hasActiveBuildDraft || hasStartedBuildChat)) {+ if (isLeavingBuildMode && (hasActiveBuildDraft || hasStartedBuildChatRef.current)) {setShowSwitchToPreviewConfirm(true)return}@@ -259,7 +259,6 @@ export function useAgentConfigureSessionController({buildDraftAgentSoulConfig,discardBuildDraftAndSwitchToPreview,hasActiveBuildDraft,- hasStartedBuildChat,isBuildDraftActive,normalAgentSoulConfig,onModeChange,diff --git a/web/features/agent-v2/build-draft-refresh.ts b/web/features/agent-v2/build-draft-refresh.tsnew file mode 100644index 00000000000..a581c400e6c--- /dev/null+++ b/web/features/agent-v2/build-draft-refresh.ts@@ -0,0 +1,44 @@+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import { useCallback, useEffect, useRef } from 'react'++export function useAgentBuildDraftRefresh({+ refetchBuildDraft,+ rebaseComposerDraft,+}: {+ refetchBuildDraft: () => Promise<{ data?: { agent_soul?: AgentSoulConfig } }>+ rebaseComposerDraft: (agentSoulConfig: AgentSoulConfig) => void+}) {+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const generationRef = useRef(0)++ const cancelBuildDraftRefresh = useCallback(() => {+ generationRef.current += 1+ if (!timerRef.current) return+ clearTimeout(timerRef.current)+ timerRef.current = null+ }, [])++ const refreshBuildDraftAfterBuildChat = useCallback(+ (onRefreshed?: () => void) => {+ cancelBuildDraftRefresh()+ const generation = generationRef.current+ timerRef.current = setTimeout(async () => {+ timerRef.current = null+ try {+ const result = await refetchBuildDraft()+ if (generation !== generationRef.current) return+ const config = result.data?.agent_soul+ if (config) rebaseComposerDraft(config)+ } catch {+ } finally {+ if (generation === generationRef.current) onRefreshed?.()+ }+ }, 1000)+ },+ [cancelBuildDraftRefresh, rebaseComposerDraft, refetchBuildDraft],+ )++ useEffect(() => cancelBuildDraftRefresh, [cancelBuildDraftRefresh])++ return { cancelBuildDraftRefresh, refreshBuildDraftAfterBuildChat }+}