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.

13.8 KB
Raw Blame
import type { currentVarType } from './panel'
import type { GenRes } from '@/service/debug'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton, iconButtonVariants } from '@langgenius/dify-ui/icon-button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useBoolean } from 'ahooks'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import GetAutomaticResModal from '@/app/components/app/configuration/config/automatic/get-automatic-res'
import Badge from '@/app/components/base/badge'
import { CopyFeedback } from '@/app/components/base/copy-feedback'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import BlockIcon from '@/app/components/workflow/block-icon'
import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
import { VariableIconWithColor } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { VarInInspectType } from '@/types/workflow'
import GetCodeGeneratorResModal from '../../app/configuration/config/code-generator/get-code-generator-res'
import { PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER } from '../../base/prompt-editor/plugins/update-block'
import useCurrentVars from '../hooks/use-inspect-vars-crud'
import { useNodesInteractions } from '../hooks/use-nodes-interactions'
import { useToolIcon } from '../hooks/use-tool-icon'
import useNodeCrud from '../nodes/_base/hooks/use-node-crud'
import useNodeInfo from '../nodes/_base/hooks/use-node-info'
import { CodeLanguage } from '../nodes/code/types'
import { useStore } from '../store'
import { BlockEnum } from '../types'
import Empty from './empty'
import ValueContent from './value-content'

type Props = Readonly<{
  nodeId: string
  currentNodeVar?: currentVarType
  handleOpenMenu: () => void
  isValueFetching?: boolean
}>

const Right = ({ nodeId, currentNodeVar, handleOpenMenu, isValueFetching }: Props) => {
  const { t } = useTranslation(['common', 'workflowDebug', 'appGeneration'])
  const bottomPanelWidth = useStore((s) => s.bottomPanelWidth)
  const setShowVariableInspectPanel = useStore((s) => s.setShowVariableInspectPanel)
  const setCurrentFocusNodeId = useStore((s) => s.setCurrentFocusNodeId)
  const toolIcon = useToolIcon(currentNodeVar?.nodeData)
  const isTruncated = currentNodeVar?.var.is_truncated
  const fullContent = currentNodeVar?.var.full_content

  const { resetConversationVar, resetToLastRunVar, editInspectVarValue } = useCurrentVars()

  const handleValueChange = (varId: string, value: any) => {
    if (!currentNodeVar) return
    editInspectVarValue(currentNodeVar.nodeId, varId, value)
  }

  const resetValue = () => {
    if (!currentNodeVar) return
    resetToLastRunVar(currentNodeVar.nodeId, currentNodeVar.var.id)
  }

  const handleClose = () => {
    setShowVariableInspectPanel(false)
    setCurrentFocusNodeId('')
  }

  const handleClear = () => {
    if (!currentNodeVar) return
    resetConversationVar(currentNodeVar.var.id)
  }

  const getCopyContent = () => {
    const value = currentNodeVar?.var.value
    if (value === null || value === undefined) return ''

    if (typeof value === 'object') return JSON.stringify(value)

    return String(value)
  }

  const resource = useAtomValue(editorResourceAtom)
  const resourceId = getEditorResourceId(resource)
  const { eventEmitter } = useEventEmitterContextContext()
  const { handleNodeSelect } = useNodesInteractions()
  const { node } = useNodeInfo(nodeId)
  const { setInputs } = useNodeCrud(nodeId, node?.data)
  const blockType = node?.data?.type
  const isCodeBlock = blockType === BlockEnum.Code
  const canShowPromptGenerator = [BlockEnum.LLM, BlockEnum.Code].includes(blockType)
  const currentPrompt = useMemo(() => {
    if (!canShowPromptGenerator) return ''
    if (blockType === BlockEnum.LLM)
      return node?.data?.prompt_template?.text || node?.data?.prompt_template?.[0].text

    if (blockType === BlockEnum.Code) return node?.data?.code
  }, [canShowPromptGenerator])

  const [
    isShowPromptGenerator,
    { setTrue: doShowPromptGenerator, setFalse: handleHidePromptGenerator },
  ] = useBoolean(false)
  const handleShowPromptGenerator = useCallback(() => {
    handleNodeSelect(nodeId)
    doShowPromptGenerator()
  }, [doShowPromptGenerator, handleNodeSelect, nodeId])

  const handleUpdatePrompt = useCallback(
    (res: GenRes) => {
      const newInputs = produce(node?.data, (draft: any) => {
        switch (blockType) {
          case BlockEnum.LLM:
            if (draft?.prompt_template) {
              if (Array.isArray(draft.prompt_template)) draft.prompt_template[0].text = res.modified
              else draft.prompt_template.text = res.modified
            }
            break

          case BlockEnum.Code:
            draft.code = res.modified
            break
        }
      })
      setInputs(newInputs)
      eventEmitter?.emit({
        type: PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER,
        instanceId: `${nodeId}-chat-workflow-llm-prompt-editor`,
        payload: res.modified,
      } as any)
      handleHidePromptGenerator()
    },
    [setInputs, blockType, nodeId, node?.data, handleHidePromptGenerator],
  )

  const displaySchemaType = currentNodeVar?.var.schemaType
    ? `(${currentNodeVar.var.schemaType})`
    : ''

  return (
    <div className={cn('flex h-full flex-col')}>
      {/* header */}
      <div className="flex shrink-0 items-center justify-between gap-1 px-2 pt-2">
        {bottomPanelWidth < 488 && (
          <IconButton
            aria-label={t(($) => $['debug.variableInspect.title'], { ns: 'workflowDebug' })}
            className="shrink-0"
            onClick={handleOpenMenu}
          >
            <span aria-hidden className="i-ri-menu-line size-4" />
          </IconButton>
        )}
        <div className="flex w-0 grow items-center gap-1">
          {currentNodeVar?.var && (
            <>
              {(
                [
                  VarInInspectType.environment,
                  VarInInspectType.conversation,
                  VarInInspectType.system,
                ] as VarInInspectType[]
              ).includes(currentNodeVar.nodeType as VarInInspectType) && (
                <VariableIconWithColor
                  variableCategory={currentNodeVar.nodeType as VarInInspectType}
                  className="size-4"
                />
              )}
              {currentNodeVar.nodeType !== VarInInspectType.environment &&
                currentNodeVar.nodeType !== VarInInspectType.conversation &&
                currentNodeVar.nodeType !== VarInInspectType.system && (
                  <>
                    <BlockIcon
                      className="shrink-0"
                      type={currentNodeVar.nodeType as BlockEnum}
                      size="xs"
                      toolIcon={toolIcon}
                    />
                    <div className="shrink-0 system-sm-regular text-text-secondary">
                      {currentNodeVar.title}
                    </div>
                    <div className="shrink-0 system-sm-regular text-text-quaternary">/</div>
                  </>
                )}
              <div
                title={currentNodeVar.var.name}
                className="truncate system-sm-semibold text-text-secondary"
              >
                {currentNodeVar.var.name}
              </div>
              <div className="ml-1 shrink-0 space-x-2 system-xs-medium text-text-tertiary">
                <span>{`${currentNodeVar.var.value_type}${displaySchemaType}`}</span>
                {isTruncated && (
                  <>
                    <span>·</span>
                    <span>
                      {((fullContent?.size_bytes || 0) / 1024 / 1024).toFixed(1)}
                      MB
                    </span>
                  </>
                )}
              </div>
            </>
          )}
        </div>
        <div className="flex shrink-0 items-center gap-1">
          {currentNodeVar && (
            <>
              {canShowPromptGenerator && (
                <Tooltip>
                  <TooltipTrigger
                    render={
                      <div
                        className="cursor-pointer rounded-md p-1 hover:bg-state-accent-active"
                        onClick={handleShowPromptGenerator}
                      >
                        <span
                          aria-hidden
                          className="i-ri-sparkling-fill size-4 text-components-input-border-active-prompt-1"
                        />
                      </div>
                    }
                  />
                  <TooltipContent>
                    {t(($) => $['generate.optimizePromptTooltip'], { ns: 'appGeneration' })}
                  </TooltipContent>
                </Tooltip>
              )}
              {isTruncated && (
                <Tooltip>
                  <TooltipTrigger
                    render={
                      <a
                        aria-label={t(($) => $['debug.variableInspect.exportToolTip'], {
                          ns: 'workflowDebug',
                        })}
                        href={fullContent?.download_url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className={iconButtonVariants({ size: 'md' })}
                      >
                        <span aria-hidden className="i-ri-file-download-fill size-4" />
                      </a>
                    }
                  />
                  <TooltipContent>
                    {t(($) => $['debug.variableInspect.exportToolTip'], { ns: 'workflowDebug' })}
                  </TooltipContent>
                </Tooltip>
              )}
              {!isTruncated && currentNodeVar.var.edited && (
                <Badge>
                  <span className="mr-[4.5px] ml-[2.5px] h-0.75 w-0.75 rounded-sm bg-text-accent-secondary"></span>
                  <span>
                    {t(($) => $['debug.variableInspect.edited'], { ns: 'workflowDebug' })}
                  </span>
                </Badge>
              )}
              {!isTruncated &&
                currentNodeVar.var.edited &&
                currentNodeVar.var.type !== VarInInspectType.conversation && (
                  <Tooltip>
                    <TooltipTrigger
                      render={
                        <IconButton
                          aria-label={t(($) => $['debug.variableInspect.reset'], {
                            ns: 'workflowDebug',
                          })}
                          onClick={resetValue}
                        >
                          <span aria-hidden className="i-ri-arrow-go-back-line size-4" />
                        </IconButton>
                      }
                    />
                    <TooltipContent>
                      {t(($) => $['debug.variableInspect.reset'], { ns: 'workflowDebug' })}
                    </TooltipContent>
                  </Tooltip>
                )}
              {!isTruncated &&
                currentNodeVar.var.edited &&
                currentNodeVar.var.type === VarInInspectType.conversation && (
                  <Tooltip>
                    <TooltipTrigger
                      render={
                        <IconButton
                          aria-label={t(($) => $['debug.variableInspect.resetConversationVar'], {
                            ns: 'workflowDebug',
                          })}
                          onClick={handleClear}
                        >
                          <span aria-hidden className="i-ri-arrow-go-back-line size-4" />
                        </IconButton>
                      }
                    />
                    <TooltipContent>
                      {t(($) => $['debug.variableInspect.resetConversationVar'], {
                        ns: 'workflowDebug',
                      })}
                    </TooltipContent>
                  </Tooltip>
                )}
              {currentNodeVar.var.value_type !== 'secret' && (
                <CopyFeedback content={getCopyContent()} />
              )}
            </>
          )}
          <IconButton
            aria-label={t(($) => $['operation.close'], { ns: 'common' })}
            onClick={handleClose}
          >
            <span aria-hidden className="i-ri-close-line size-4" />
          </IconButton>
        </div>
      </div>
      {/* content */}
      <div className="grow p-2">
        {!currentNodeVar?.var && <Empty />}
        {isValueFetching && (
          <div className="flex h-full items-center justify-center">
            <LoadingPlaceholder />
          </div>
        )}
        {currentNodeVar?.var && !isValueFetching && (
          <ValueContent
            key={`${currentNodeVar.nodeId}-${currentNodeVar.var.id}`}
            currentVar={currentNodeVar.var}
            handleValueChange={handleValueChange}
            isTruncated={!!isTruncated}
          />
        )}
      </div>
      {isShowPromptGenerator &&
        (isCodeBlock ? (
          <GetCodeGeneratorResModal
            isShow
            modelMode="chat"
            onClose={handleHidePromptGenerator}
            flowId={resourceId || ''}
            nodeId={nodeId}
            currentCode={currentPrompt}
            codeLanguages={node?.data?.code_languages || CodeLanguage.python3}
            onFinished={handleUpdatePrompt}
          />
        ) : (
          <GetAutomaticResModal
            modelMode="chat"
            isShow
            onClose={handleHidePromptGenerator}
            onFinished={handleUpdatePrompt}
            flowId={resourceId || ''}
            nodeId={nodeId}
            currentPrompt={currentPrompt}
          />
        ))}
    </div>
  )
}

export default Right