Skip to content

armgit / dify

Public Imported from GitHub
0

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

chore: fit the app canvas when create from DSL and preview (#42073)

Joel9e6c0c20d298
diff --git a/api/services/app_dsl_service.py b/api/services/app_dsl_service.py
index c312e6a8c2b..4c9f10729a0 100644
--- a/api/services/app_dsl_service.py
+++ b/api/services/app_dsl_service.py
@@ -645,6 +645,11 @@ class AppDslService:
else:
unique_hash = None
graph = workflow_data.get("graph", {})
+ if not isinstance(graph, dict):
+ raise ValueError("Workflow graph must be a mapping")
+ # The source canvas position should not determine the imported app's initial view.
+ graph = graph.copy()
+ graph.pop("viewport", None)
for node in graph.get("nodes", []):
if node.get("data", {}).get("type", "") == BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL:
dataset_ids = node["data"].get("dataset_ids", [])
diff --git a/api/services/rag_pipeline/rag_pipeline_dsl_service.py b/api/services/rag_pipeline/rag_pipeline_dsl_service.py
index 6ee64efc9d5..1e655e510db 100644
--- a/api/services/rag_pipeline/rag_pipeline_dsl_service.py
+++ b/api/services/rag_pipeline/rag_pipeline_dsl_service.py
@@ -562,6 +562,11 @@ class RagPipelineDslService:
rag_pipeline_variables_list = workflow_data.get("rag_pipeline_variables", [])
graph = workflow_data.get("graph", {})
+ if not isinstance(graph, dict):
+ raise ValueError("Workflow graph must be a mapping")
+ # The source canvas position should not determine the imported pipeline's initial view.
+ graph = graph.copy()
+ graph.pop("viewport", None)
for node in graph.get("nodes", []):
if node.get("data", {}).get("type", "") == BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL:
dataset_ids = node["data"].get("dataset_ids", [])
diff --git a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py
index 75a45c8436c..44859fb7e2d 100644
--- a/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py
+++ b/api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline_dsl_service.py
@@ -788,6 +788,30 @@ def test_create_or_update_pipeline_flushes_caller_transaction_and_updates_existi
assert workflow.graph_dict["nodes"] == [{"id": "node"}]
+def test_create_or_update_pipeline_removes_imported_workflow_viewport(
+ service: RagPipelineDslService, sqlite_session: Session
+) -> None:
+ imported_graph: dict[str, Any] = {
+ "nodes": [],
+ "edges": [],
+ "viewport": {"x": 100, "y": 200, "zoom": 1.5},
+ }
+
+ pipeline = service._create_or_update_pipeline(
+ pipeline=None,
+ data={
+ "rag_pipeline": {"name": "Pipeline"},
+ "workflow": {"graph": imported_graph},
+ },
+ account=_account(),
+ )
+
+ workflow = sqlite_session.get(Workflow, pipeline.workflow_id)
+ assert workflow is not None
+ assert workflow.graph_dict == {"nodes": [], "edges": []}
+ assert imported_graph["viewport"] == {"x": 100, "y": 200, "zoom": 1.5}
+
+
def test_create_pipeline_flush_failure_is_rolled_back_by_caller(
service: RagPipelineDslService, sqlite_session: Session, sqlite_engine: Engine
) -> None:
diff --git a/api/tests/unit_tests/services/test_app_dsl_service.py b/api/tests/unit_tests/services/test_app_dsl_service.py
index b4cbd5cfb46..86a410c665e 100644
--- a/api/tests/unit_tests/services/test_app_dsl_service.py
+++ b/api/tests/unit_tests/services/test_app_dsl_service.py
@@ -594,6 +594,45 @@ def test_create_or_update_app_flushes_new_model_config_before_signal(
assert sqlite_session.in_transaction()
+def test_create_or_update_app_removes_imported_workflow_viewport(monkeypatch: pytest.MonkeyPatch) -> None:
+ session = cast(Session, SimpleNamespace(add=Mock(), flush=Mock(), get=Mock()))
+ service = AppDslService(session=session)
+ app = SimpleNamespace(
+ id="app-1",
+ tenant_id="tenant-1",
+ name="Workflow",
+ description="",
+ icon_type=IconType.EMOJI,
+ icon="robot",
+ icon_background="#FFFFFF",
+ )
+ workflow_service = SimpleNamespace(
+ get_draft_workflow=Mock(return_value=None),
+ sync_draft_workflow=Mock(return_value=SimpleNamespace(id="workflow-1")),
+ )
+ monkeypatch.setattr("services.app_dsl_service.WorkflowService", Mock(return_value=workflow_service))
+ imported_graph: dict[str, object] = {
+ "nodes": [],
+ "edges": [],
+ "viewport": {"x": 100, "y": 200, "zoom": 1.5},
+ }
+
+ service._create_or_update_app(
+ app=cast(App, app),
+ data={
+ "app": {"mode": AppMode.WORKFLOW.value},
+ "workflow": {"graph": imported_graph},
+ },
+ account=Mock(id="account-1"),
+ )
+
+ assert workflow_service.sync_draft_workflow.call_args.kwargs["graph"] == {
+ "nodes": [],
+ "edges": [],
+ }
+ assert imported_graph["viewport"] == {"x": 100, "y": 200, "zoom": 1.5}
+
+
def test_create_or_update_app_forwards_imported_agent_purge_ids(monkeypatch: pytest.MonkeyPatch) -> None:
session = cast(Session, SimpleNamespace(add=Mock(), flush=Mock(), commit=Mock(), get=Mock()))
service = AppDslService(session=session)
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
index 6e73a2aff14..216c7e0e24e 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
@@ -142,6 +142,22 @@ describe('useWorkflowInit', () => {
mockSyncWorkflowDraft.mockReset()
})
+ it.each([undefined, { x: 120, y: -80, zoom: 0.75 }])(
+ 'should preserve the initial draft viewport as %j',
+ async (viewport) => {
+ mockFetchWorkflowDraft.mockReset().mockResolvedValue({
+ ...draftResponse,
+ graph: { ...draftResponse.graph, viewport },
+ })
+
+ const { result } = renderHook(() => useWorkflowInit())
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false))
+
+ expect(result.current.data?.graph.viewport).toEqual(viewport)
+ },
+ )
+
it('should create an empty backend draft and restore a local start placeholder when the workflow draft does not exist', async () => {
mockFetchWorkflowDraft
.mockReset()
@@ -252,6 +268,7 @@ describe('useWorkflowInit', () => {
}),
)
expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('')
+ expect(result.current.data?.graph.viewport).toBeUndefined()
})
it('should restore a local start placeholder when an existing workflow draft has an empty graph', async () => {
diff --git a/web/app/components/workflow-app/hooks/use-workflow-init.ts b/web/app/components/workflow-app/hooks/use-workflow-init.ts
index 177c1877a6d..2625cc33765 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-init.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-init.ts
@@ -96,9 +96,13 @@ export const useWorkflowInit = () => {
const res = await fetchWorkflowDraft(`/apps/${appDetail.id}/workflows/draft`)
const initialData = {
...res,
- graph: getWorkflowDraftGraphForCanvas(res.graph, {
- localStartPlaceholderNodes: nodesTemplate,
- }),
+ graph: {
+ ...getWorkflowDraftGraphForCanvas(res.graph, {
+ localStartPlaceholderNodes: nodesTemplate,
+ }),
+ // Let the canvas fit the nodes when no saved viewport exists.
+ viewport: res.graph.viewport,
+ },
}
setData(initialData)
@@ -147,6 +151,7 @@ export const useWorkflowInit = () => {
...getWorkflowDraftGraphForCanvas(initialGraph, {
localStartPlaceholderNodes: nodesTemplate,
}),
+ viewport: undefined,
})
setData(initialData)
workflowStore.setState({
diff --git a/web/app/components/workflow/index.tsx b/web/app/components/workflow/index.tsx
index f754330386f..3d99f3db45f 100644
--- a/web/app/components/workflow/index.tsx
+++ b/web/app/components/workflow/index.tsx
@@ -793,6 +793,7 @@ export const Workflow: FC<WorkflowProps> = memo(
onSelectionContextMenu={handleSelectionContextMenu}
connectionLineComponent={CustomConnectionLine}
defaultViewport={viewport}
+ fitView={!viewport}
multiSelectionKeyCode={null}
deleteKeyCode={null}
nodesDraggable={!nodesReadOnly && controlMode !== ControlMode.Comment}
diff --git a/web/app/components/workflow/workflow-preview/index.tsx b/web/app/components/workflow/workflow-preview/index.tsx
index 8b5cd398269..8589aac2708 100644
--- a/web/app/components/workflow/workflow-preview/index.tsx
+++ b/web/app/components/workflow/workflow-preview/index.tsx
@@ -94,6 +94,7 @@ const WorkflowPreview = ({
onEdgesChange={onEdgesChange}
connectionLineComponent={CustomConnectionLine}
defaultViewport={viewport}
+ fitView
multiSelectionKeyCode={null}
deleteKeyCode={null}
nodesDraggable={false}