chat-wrapper.tsx 4.88 KB
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: limin
 * @Date: 2025-04-16 18:17:38
 * @LastEditors: limin
 * @LastEditTime: 2025-07-28 17:41:15
 * @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx
 */

import { useEffect, FC, useCallback, useRef, useState } from 'react'
import Chat from '../chat'
import { useChat, useUrlParams } from './hooks'
import { InputMessageType } from '../types'
import {
  ChatContextProvider,
  ChatConfigProvider,
  ChatListProvider,
  ChatRespondingProvider,
} from '@/app/components/base/chat/chat-with-history/context'
import React from 'react'
import { useStore } from '@/app/components/app/store'

enum MessageListenerType {
  RESET_CHAT = 'reset_chat',
}
type MessageListenerProps = {
  payload: {
    tags?: string[]
    message?: string
  }
  type: MessageListenerType
}
const SEND_MESSAGE_KEY = 'sendMessage' // 使用 Symbol 避免命名冲突
const NEXT_SCENE_KEY = 'nextScene' // 下一场景全局方法键名
// 扩展 globalThis 类型
interface IGlobalThis {
  [SEND_MESSAGE_KEY]?: (data: MessageListenerProps) => void
  [NEXT_SCENE_KEY]?: () => void
}
type Props = {
  presuppositionQuestion?: string
  inputs?: Record<string, any>
  // isShowPracticeButton: boolean
}
const ChatWrapper: FC<Props> = React.memo(({ presuppositionQuestion, inputs }) => {
  const setScenarioSummaryIndex = useStore(state => state.setScenarioSummaryIndex)
  const setCustomerOriginal = useStore(state => state.setCustomerOriginal)
  const setScenarioSummary = useStore(state => state.setScenarioSummary)
  const setScenarioType = useStore(state => state.setScenarioType)
  const setReviewPassed = useStore(state => state.setReviewPassed)

  const [isAutoSend, setAutoSend] = useState<boolean>(true)
  const [autoSendQuestion, setAutoSendQuestion] = useState<string | undefined>(presuppositionQuestion)
  const {
    config,
    chatList,
    handleStop,
    sendMessage,
    doRegenerate,
    // appInfoError,
    isResponding,
    handleRestart,
    handleFeedback,
    // appInfoLoading,
    handleNewConversation,
    isManuallyStopped,
    taskId,
  } = useChat(inputs, useStore())
  useEffect(() => {
    if (autoSendQuestion && config.initial_message !== undefined && isAutoSend) {
      const timer = setTimeout(() => {
        sendMessage(autoSendQuestion, InputMessageType.BY_AUTO)
        setAutoSend(false)
      }, 0)
      return () => clearTimeout(timer)
    }
  }, [autoSendQuestion, config.initial_message, isAutoSend])

  const handleGlobalMessage = useCallback((data: MessageListenerProps) => {
    try {
      switch (data?.type) {
        case MessageListenerType.RESET_CHAT:
          handleNewConversation(undefined, false) // 重新开启一次会话
          const message = data?.payload?.message
          setAutoSendQuestion(message) //可能没有预设消息,但是也要更新 重置对话的时候也要保持没有预设消息
          message && setAutoSend(true) // 有预设消息才自动发送
          break
      }
    } catch (error) {
      console.error('send failed:', error)
    }
  }, [])

  const handleNextScene = useCallback((data: any) => {
    let sceneData = data
    try {
      setScenarioType(sceneData.type)
      setScenarioSummary(sceneData.scenario_summary)
      setCustomerOriginal(sceneData.customer_original)
      setScenarioSummaryIndex(sceneData.scenario_summary_index)
      setReviewPassed(false)
    } catch (error) {
      console.error('nextScene failed:', error)
    }
  }, [])

  useEffect(() => {
    Object.defineProperty(globalThis, SEND_MESSAGE_KEY, {
      value: handleGlobalMessage,
      writable: false,
      configurable: true,
      enumerable: false,
    })

    Object.defineProperty(globalThis, NEXT_SCENE_KEY, {
      value: handleNextScene,
      writable: false,
      configurable: true,
      enumerable: false,
    })

    return () => {
      if (SEND_MESSAGE_KEY in globalThis) {
        delete (globalThis as IGlobalThis)[SEND_MESSAGE_KEY]
      }
      if (NEXT_SCENE_KEY in globalThis) {
        delete (globalThis as IGlobalThis)[NEXT_SCENE_KEY]
      }
    }
  }, [handleGlobalMessage, handleNextScene])

  const onRestart = useCallback(() => {
    setAutoSend(true)
    handleRestart()
  }, [])
  if (config.initial_message === undefined) return null
  return (
    <div className="h-full overflow-hidden">
      <ChatConfigProvider config={config}>
        <ChatContextProvider
          onSend={sendMessage}
          onRegenerate={doRegenerate}
          onRestart={onRestart}
          onFeedback={handleFeedback}
          onStopResponding={handleStop}>
          <ChatRespondingProvider isResponding={isResponding} taskId={taskId}>
            <ChatListProvider chatList={chatList} isManuallyStopped={isManuallyStopped}>
              <Chat />
            </ChatListProvider>
          </ChatRespondingProvider>
        </ChatContextProvider>
      </ChatConfigProvider>
    </div>
  )
})

export default ChatWrapper