aiStreamSession.js 4.38 KB
import { DEMO_STREAM_MARKDOWN } from './demoStreamMarkdown.js'
import {
  USE_AI_STREAM_MOCK,
  STREAM_MOCK_CHARS_PER_TICK,
  STREAM_MOCK_INTERVAL_MS,
  STREAM_WAIT_TIMEOUT_MS
} from './constants.js'
import AiChatWsService from './AiChatWsService.js'

const STREAM_DELTA_TYPES = new Set([
  'text',
  'delta',
  'chunk',
  'markdown',
  'content',
  'message',
  'answer'
])
const STREAM_DONE_TYPES = new Set(['done', 'end', 'complete', 'finished', 'stop'])

function extractDelta(data) {
  if (!data || typeof data !== 'object') return ''
  if (STREAM_DONE_TYPES.has(data.type)) return null
  if (data.type === 'receiving' || data.type === 'processing') return ''
  if (STREAM_DELTA_TYPES.has(data.type)) {
    return data.content ?? data.text ?? data.delta ?? data.markdown ?? data.message ?? ''
  }
  if (typeof data.content === 'string' && data.type !== 'error') {
    return data.content
  }
  return ''
}

function isDoneMessage(data) {
  return data && STREAM_DONE_TYPES.has(data.type)
}

function isErrorMessage(data) {
  return data && (data.type === 'error' || data.error)
}

class AiStreamSession {
  constructor() {
    this._active = false
    this._markdown = ''
    this._callbacks = null
    this._prevOnMessage = null
    this._mockTimer = null
    this._timeoutTimer = null
    this._mockIndex = 0
    this._useMock = false
  }

  get isActive() {
    return this._active
  }

  get markdown() {
    return this._markdown
  }

  /**
   * @param {{ onUpdate?: Function, onDone?: Function, onError?: Function, useMock?: boolean }} callbacks
   */
  start(callbacks = {}) {
    this.cancel()
    this._active = true
    this._markdown = ''
    this._callbacks = callbacks
    this._useMock = callbacks.useMock ?? USE_AI_STREAM_MOCK

    if (this._useMock) {
      this._startMockStream(DEMO_STREAM_MARKDOWN)
    } else {
      this._bindWsListener()
      this._timeoutTimer = setTimeout(() => {
        if (this._active) {
          this._finish(new Error('等待 AI 回复超时'))
        }
      }, STREAM_WAIT_TIMEOUT_MS)
    }

    return this
  }

  cancel() {
    this._active = false
    this._unbindWsListener()
    this._clearTimers()
    this._callbacks = null
    this._mockIndex = 0
  }

  handleWsMessage(data) {
    if (!this._active) return

    if (isErrorMessage(data)) {
      const msg = data.message || data.content || data.error || 'AI 返回错误'
      this._finish(new Error(msg))
      return
    }

    if (isDoneMessage(data)) {
      this._finish()
      return
    }

    const delta = extractDelta(data)
    if (delta === null) {
      this._finish()
      return
    }
    if (delta) {
      this._append(delta)
    }
  }

  _append(chunk) {
    if (!chunk) return
    this._markdown += chunk
    this._callbacks?.onUpdate?.({
      markdown: this._markdown,
      delta: chunk
    })
  }

  _finish(err) {
    if (!this._active) return
    this._active = false
    this._clearTimers()
    this._unbindWsListener()
    if (err) {
      this._callbacks?.onError?.(err)
    } else {
      this._callbacks?.onDone?.({
        markdown: this._markdown
      })
    }
    this._callbacks = null
  }

  _bindWsListener() {
    const client = AiChatWsService.getInstance().getClient()
    this._prevOnMessage = client.onMessage
    client.onMessage = (data) => {
      this.handleWsMessage(data)
      this._prevOnMessage && this._prevOnMessage(data)
    }
  }

  _unbindWsListener() {
    const client = AiChatWsService.getInstance().getClient()
    if (client.onMessage && this._prevOnMessage !== undefined) {
      client.onMessage = this._prevOnMessage
    }
    this._prevOnMessage = null
  }

  _clearTimers() {
    if (this._mockTimer) {
      clearInterval(this._mockTimer)
      this._mockTimer = null
    }
    if (this._timeoutTimer) {
      clearTimeout(this._timeoutTimer)
      this._timeoutTimer = null
    }
  }

  _startMockStream(fullText) {
    this._mockIndex = 0
    this._mockTimer = setInterval(() => {
      if (!this._active) return
      if (this._mockIndex >= fullText.length) {
        this._finish()
        return
      }
      const chunk = fullText.slice(this._mockIndex, this._mockIndex + STREAM_MOCK_CHARS_PER_TICK)
      this._mockIndex += STREAM_MOCK_CHARS_PER_TICK
      this._append(chunk)
    }, STREAM_MOCK_INTERVAL_MS)
  }
}

let _instance = null

export function getAiStreamSession() {
  if (!_instance) {
    _instance = new AiStreamSession()
  }
  return _instance
}

export default AiStreamSession