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.

7.0 KB
Raw Blame
import type { WorkflowResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { GeneratedGraph, WorkflowGeneratorMode } from './types'
import type { WorkflowAppMode } from '@/app/components/apps/app-type'
import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'
import { consoleClient } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'

const MODE_TO_APP_MODE = {
  workflow: 'workflow',
  'advanced-chat': 'advanced-chat',
} as const satisfies Record<WorkflowGeneratorMode, WorkflowAppMode>

/**
 * Thrown by ``applyToCurrentApp`` when the backend rejects the sync because
 * the draft's ``unique_hash`` doesn't match — typically another tab edited
 * the draft after we fetched it. The caller maps this to a dedicated
 * "Workspace was edited elsewhere" toast with a Reload affordance instead
 * of a generic "Apply failed".
 *
 * Backend surfaces this as HTTP 409 with ``error_code:
 * "draft_workflow_not_sync"`` (see
 * ``api/controllers/console/app/error.py::DraftWorkflowNotSync``).
 */
export class WorkflowApplyHashCollisionError extends Error {
  constructor() {
    super('Workflow draft was modified in another tab; reload required.')
    this.name = 'WorkflowApplyHashCollisionError'
  }
}

/**
 * Thrown by ``applyToNewApp`` when the freshly-created app's draft sync
 * failed AND we couldn't roll back by deleting the new app. The caller
 * routes the user to ``/apps`` so the orphan is at least discoverable and
 * surfaces a localised toast — without this an unrecoverable orphan would
 * silently sit in the app list with no graph.
 */
export class WorkflowApplyOrphanError extends Error {
  readonly orphanAppId: string

  constructor(orphanAppId: string, cause?: unknown) {
    // ES2022 Error supports ``cause`` natively via the options bag — far
    // cleaner than reassigning a typed-cast property after construction.
    super(`Failed to apply graph; new app ${orphanAppId} may be orphaned.`, { cause })
    this.name = 'WorkflowApplyOrphanError'
    this.orphanAppId = orphanAppId
  }
}

// Derive a sane App name from the user's instruction: trim, cap at 40 chars,
// strip trailing punctuation.
const deriveAppName = (instruction: string): string => {
  const trimmed = instruction.trim().slice(0, 40)
  const name = trimmed.replace(/[.,!?;:。,!?;:]+$/, '').trim()
  if (!name) throw new Error('Cannot create a generated app without an instruction.')
  return name
}

type ApplyToNewAppParams = {
  mode: WorkflowGeneratorMode
  graph: GeneratedGraph
  instruction: string
  /**
   * Planner-picked product-style name (e.g. "URL Summarizer"). When empty,
   * we fall back to ``deriveAppName(instruction)`` so the apps list never
   * shows an empty title.
   */
  appName?: string
  /**
   * Planner-picked emoji (e.g. "📰"). When empty, we fall back to 🤖
   * which is the historical default.
   */
  icon?: string
}

/**
 * Apply path A — create a brand-new Workflow / Chatflow app and write the
 * generated graph into its draft. Returns the created app id so the caller
 * can route to ``/app/{id}/workflow``.
 */
export const applyToNewApp = async ({
  mode,
  graph,
  instruction,
  appName,
  icon,
}: ApplyToNewAppParams): Promise<{
  appId: string
  appMode: WorkflowAppMode
  permissionKeys?: string[]
}> => {
  const appMode = MODE_TO_APP_MODE[mode]
  const name = (appName ?? '').trim() || deriveAppName(instruction)
  const appIcon = (icon ?? '').trim() || '🤖'
  const app = await consoleClient.apps.post(
    {
      body: {
        name,
        mode: appMode,
        icon_type: 'emoji',
        icon: appIcon,
        icon_background: '#FFEAD5',
        description: instruction.trim().slice(0, 200),
      },
    },
    { context: { silent: true } },
  )

  // Sync the generated graph into the brand-new app's draft. ``createApp``
  // already succeeded so the app exists; if the sync fails (network blip,
  // backend rejection of the graph) we MUST roll the createApp back so the
  // user isn't left with a discoverable-but-empty app sitting at the top
  // of their /apps list. ``deleteApp`` is best-effort — if that also fails
  // (it usually won't, it's a simple DELETE) we surface ``WorkflowApplyOrphanError``
  // so the caller can route to /apps where the orphan is still recoverable
  // by hand.
  try {
    await consoleClient.apps.byAppId.workflows.draft.post(
      {
        params: { app_id: app.id },
        body: {
          graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },
          features: {},
          conversation_variables: [],
        },
      },
      { context: { silent: true } },
    )
  } catch (syncErr) {
    try {
      await consoleClient.apps.byAppId.delete(
        { params: { app_id: app.id } },
        { context: { silent: true } },
      )
    } catch (deleteErr) {
      throw new WorkflowApplyOrphanError(app.id, deleteErr)
    }
    throw syncErr
  }

  return { appId: app.id, appMode, permissionKeys: app.permission_keys }
}

type ApplyToCurrentAppParams = {
  appId: string
  appMode?: WorkflowAppMode
  graph: GeneratedGraph
}

/**
 * Apply path B — overwrite the current Workflow Studio's draft graph.
 *
 * The backend's ``sync_draft_workflow`` rejects writes whose ``hash`` doesn't
 * match the existing draft's ``unique_hash`` (WorkflowHashNotEqualError), so we
 * must read the current draft first to grab its hash. We also preserve the
 * existing ``features`` and ``conversation_variables``. Environment variables
 * are preserved by omitting them from the draft-sync payload, so only nodes /
 * edges / viewport (the ``graph`` field) get replaced by the generated graph.
 *
 * Caller is responsible for showing the overwrite confirmation dialog before
 * invoking this.
 */
export const applyToCurrentApp = async ({
  appId,
  appMode,
  graph,
}: ApplyToCurrentAppParams): Promise<void> => {
  // First sync may have no existing draft (workflow apps can exist before Studio
  // has created/saved a draft). Preserve the existing fallback: treat a fetch
  // failure as "no existing draft" and sync without a hash.
  let existing: WorkflowResponse | null = null
  try {
    existing = await consoleClient.apps.byAppId.workflows.draft.get(
      { params: { app_id: appId } },
      { context: { silent: true } },
    )
  } catch {
    existing = null
  }

  try {
    await consoleClient.apps.byAppId.workflows.draft.post(
      {
        params: { app_id: appId },
        body: {
          graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },
          features: existing?.features ?? {},
          conversation_variables: existing?.conversation_variables ?? [],
          ...(existing?.hash ? { hash: existing.hash } : {}),
        },
      },
      { context: { silent: true } },
    )
  } catch (e) {
    // 409 → draft was edited in another tab between our fetch and sync.
    // Translate the HTTP error into a domain error so the caller
    // can show a Reload affordance instead of a generic "apply failed" toast.
    if (getHttpErrorStatus(e) === 409) throw new WorkflowApplyHashCollisionError()
    throw e
  }
}