feat(embed): add widget, visitor chat, and management UI (#1657)

Add embed.html entrypoint, floating widget SDK, secure-mode snippets,
management panel with preview, visitor chat composables, citation rendering,
and integration docs for subdomain and server-side token exchange.
This commit is contained in:
wizardchen
2026-06-12 22:40:18 +08:00
committed by lyingbug
parent ed9802ff2b
commit 08852ab19d
41 changed files with 10186 additions and 745 deletions
@@ -0,0 +1,855 @@
import { markRaw, nextTick, type Ref } from 'vue'
import { useI18n } from 'vue-i18n'
export type ChatMessage = Record<string, unknown>
export interface UseChatStreamHandlerOptions {
messagesList: ChatMessage[]
loading: Ref<boolean>
isReplying: Ref<boolean>
currentAssistantMessageId: Ref<string>
fullContent: Ref<string>
isAgentStreamSession: () => boolean
scrollToBottom: (force?: boolean) => void
onReplyComplete?: (content: string) => void
onError?: (message: string) => void
/** Main chat: keep the last incomplete message reactive for continue-stream. */
preserveIncompleteStreamReactive?: boolean
isFirstEnter?: Ref<boolean>
scrollContainer?: Ref<HTMLElement | null>
onAfterMsgList?: () => void | Promise<void>
onAgentQuery?: (
data: ChatMessage,
existingMessage: ChatMessage | undefined,
created: boolean,
) => void
onMessageCreated?: (message: ChatMessage) => void
onMessageUpdated?: (message: ChatMessage, payload?: ChatMessage) => void
onAgentAnswerDone?: (message: ChatMessage) => void
onAgentChunkBound?: (message: ChatMessage, created: boolean) => void
debug?: boolean
}
export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
const { t } = useI18n()
const {
messagesList,
loading,
isReplying,
currentAssistantMessageId,
fullContent,
isAgentStreamSession,
scrollToBottom,
onReplyComplete,
onError,
preserveIncompleteStreamReactive = false,
isFirstEnter,
scrollContainer,
onAfterMsgList,
onAgentQuery,
onMessageCreated,
onMessageUpdated,
onAgentAnswerDone,
onAgentChunkBound,
debug = false,
} = options
const log = (...args: unknown[]) => {
if (debug) console.log(...args)
}
const findLastMessage = (predicate: (item: ChatMessage) => boolean) => {
for (let i = messagesList.length - 1; i >= 0; i--) {
const item = messagesList[i]
if (predicate(item)) return item
}
return undefined
}
const ensureAgentMessageShell = (message: ChatMessage, requestId?: string) => {
message.isAgentMode = true
if (!message.agentEventStream) message.agentEventStream = []
if (!message._eventMap) message._eventMap = new Map()
if (!message._pendingToolCalls) message._pendingToolCalls = new Map()
if (requestId) {
if (!message.id) message.id = requestId
if (!message.request_id) message.request_id = requestId
}
}
const shouldRenderAssistantMessage = (session: ChatMessage) => {
if (!session?.isAgentMode) return true
const stream = session.agentEventStream
return Array.isArray(stream) && stream.length > 0
}
const recomposeAgentAnswer = (message: ChatMessage) => {
const stream = message.agentEventStream as Array<{
type?: string
superseded?: boolean
content?: string
}> | undefined
if (!stream) return ''
let out = ''
for (const e of stream) {
if (e.type === 'answer' && !e.superseded && e.content) {
out += e.content
}
}
return out
}
const reconstructEventStreamFromSteps = (
agentSteps: unknown[],
messageContent: string,
isCompleted = false,
isFallback = false,
agentDurationMs = 0,
) => {
const events: ChatMessage[] = []
if (agentSteps && Array.isArray(agentSteps) && agentSteps.length > 0) {
agentSteps.forEach((step: ChatMessage) => {
const stepTimestamp = step.timestamp ? new Date(String(step.timestamp)).getTime() : 0
const toolCalls = step.tool_calls
const hasToolCalls = toolCalls && Array.isArray(toolCalls) && toolCalls.length > 0
const reasoningText =
step.reasoning_content && String(step.reasoning_content).trim()
? String(step.reasoning_content)
: ''
if (reasoningText) {
events.push({
type: 'thinking',
event_id: `step-${step.iteration}-thought`,
content: reasoningText,
done: true,
thinking: false,
timestamp: stepTimestamp || undefined,
duration_ms: step.duration || undefined,
})
}
const preambleText = step.thought && String(step.thought).trim() ? String(step.thought) : ''
if (preambleText && hasToolCalls) {
events.push({
type: 'answer',
event_id: `step-${step.iteration}-preamble`,
content: preambleText,
done: true,
superseded: true,
timestamp: stepTimestamp || undefined,
})
}
if (toolCalls && Array.isArray(toolCalls)) {
toolCalls.forEach((toolCall: ChatMessage) => {
if (toolCall.name === 'final_answer') return
const result = toolCall.result as ChatMessage | undefined
const resultData = result?.data as ChatMessage | undefined
events.push({
type: 'tool_call',
tool_call_id: toolCall.id,
tool_name: toolCall.name,
arguments: toolCall.args,
pending: false,
success: result?.success !== false,
output: result?.output || '',
error: result?.error || undefined,
timestamp: stepTimestamp || undefined,
duration: toolCall.duration,
duration_ms: toolCall.duration,
display_type: resultData?.display_type,
tool_data: result?.data,
})
})
}
})
}
if (agentDurationMs > 0) {
events.push({
type: 'agent_complete',
total_duration_ms: agentDurationMs,
})
}
if (messageContent && messageContent.trim()) {
const answerEvent: ChatMessage = {
type: 'answer',
content: messageContent,
done: true,
}
if (isFallback) answerEvent.is_fallback = true
events.push(answerEvent)
} else if (isCompleted) {
events.push({
type: 'stop',
timestamp: Date.now(),
reason: 'user_requested',
})
}
return events
}
const handleMsgList = async (
data: ChatMessage[],
isScrollType = false,
newScrollHeight?: number,
) => {
const chatlist = [...data]
const existingIds = new Set(messagesList.map((m) => m.id).filter(Boolean))
const processed: ChatMessage[] = []
for (const raw of chatlist) {
const item = preserveIncompleteStreamReactive ? raw : { ...raw }
if (item.id && existingIds.has(item.id)) continue
if (item.id) existingIds.add(item.id)
item.isAgentMode = false
const willContinueStream = preserveIncompleteStreamReactive && !item.is_completed
if (willContinueStream) {
item.agentEventStream = item.agentEventStream || []
item._eventMap = new Map()
item._pendingToolCalls = new Map()
} else {
item.agent_steps = item.agent_steps ? markRaw(item.agent_steps as object) : item.agent_steps
item.agentEventStream = markRaw((item.agentEventStream as unknown[]) || [])
item._eventMap = markRaw(new Map())
item._pendingToolCalls = markRaw(new Map())
}
if (item.agent_steps && Array.isArray(item.agent_steps) && item.agent_steps.length > 0) {
item.isAgentMode = true
item.agentEventStream = markRaw(
reconstructEventStreamFromSteps(
item.agent_steps as unknown[],
String(item.content || ''),
Boolean(item.is_completed),
Boolean(item.is_fallback),
Number(item.agent_duration_ms) || 0,
),
)
item.hideContent = true
}
if (item.content) {
const content = String(item.content)
const thinkCloseTag = '</think>'
if (!content.includes('<think>') && !content.includes(thinkCloseTag)) {
item.thinkContent = ''
item.showThink = false
item.thinking = false
} else if (content.includes(thinkCloseTag)) {
item.showThink = true
item.thinking = false
const index = content.trim().lastIndexOf(thinkCloseTag)
item.thinkContent = content.trim().substring(0, index).replace('<think>', '').trim()
item.content = content.trim().substring(index + thinkCloseTag.length)
} else if (content.includes('<think>')) {
item.showThink = true
item.thinking = true
item.thinkContent = content.replace('<think>', '').trim()
item.content = ''
}
}
processed.push(item)
}
if (processed.length > 0) {
if (isScrollType) {
for (let i = processed.length - 1; i >= 0; i--) {
messagesList.unshift(processed[i])
}
} else {
messagesList.push(...processed)
}
}
if (isFirstEnter?.value) {
scrollToBottom(true)
} else if (isScrollType && scrollContainer?.value && typeof newScrollHeight === 'number') {
nextTick(() => {
if (!scrollContainer.value) return
const { scrollHeight } = scrollContainer.value
scrollContainer.value.scrollTop = scrollHeight - newScrollHeight
})
}
if (onAfterMsgList) {
await onAfterMsgList()
}
}
const updateAssistantSession = (payload: ChatMessage) => {
const message = findLastMessage((item) => {
if (item.request_id === payload.id) return true
return item.id === payload.id
})
if (message) {
if (payload.id && !message.request_id) message.request_id = payload.id
message.content = payload.content
message.thinking = payload.thinking
message.thinkContent = payload.thinkContent
message.showThink = payload.showThink
if (!message.knowledge_references) {
message.knowledge_references = payload.knowledge_references
}
if (payload.is_fallback) message.is_fallback = true
if (payload.is_completed) message.is_completed = true
onMessageUpdated?.(message, payload)
} else {
const entry = { ...payload }
if (entry.id && !entry.request_id) entry.request_id = entry.id
messagesList.push(entry)
onMessageCreated?.(entry)
onMessageUpdated?.(entry, payload)
}
scrollToBottom()
}
const reportError = (errorMsg: string) => {
if (onError) {
onError(errorMsg)
}
}
const handleAgentChunk = (data: ChatMessage) => {
const dataId = data.id as string | undefined
let message = findLastMessage(
(item) => item.request_id === dataId || item.id === dataId,
)
let created = false
if (!message) {
const newMsg: ChatMessage = {
id: dataId,
request_id: dataId,
role: 'assistant',
content: '',
isAgentMode: true,
agentEventStream: [],
_eventMap: new Map(),
knowledge_references: [],
}
messagesList.push(newMsg)
onMessageCreated?.(newMsg)
loading.value = false
scrollToBottom(true)
message = newMsg
created = true
} else {
onAgentChunkBound?.(message, false)
}
if (created) {
onAgentChunkBound?.(message, true)
}
message.isAgentMode = true
if (
loading.value &&
(data.response_type === 'thinking' ||
data.response_type === 'answer' ||
data.response_type === 'tool_call' ||
data.response_type === 'tool_approval_required')
) {
log('[Agent Chunk] Closing loading for continued stream')
loading.value = false
}
const responseType = data.response_type as string
const dataPayload = data.data as ChatMessage | undefined
switch (responseType) {
case 'thinking': {
const eventId = dataPayload?.event_id as string | undefined
log('[Thinking Event]', {
event_id: eventId,
done: data.done,
content_length: (data.content as string | undefined)?.length || 0,
})
if (!message.agentEventStream) message.agentEventStream = []
if (!message._eventMap) message._eventMap = new Map()
const eventMap = message._eventMap as Map<string, ChatMessage>
const stream = message.agentEventStream as ChatMessage[]
if (!data.done) {
let thinkingEvent = eventMap.get(eventId || '')
if (!thinkingEvent) {
log('[Thinking] Creating new thinking event, event_id:', eventId)
thinkingEvent = {
type: 'thinking',
event_id: eventId,
content: '',
done: false,
startTime: Date.now(),
thinking: true,
}
stream.push(thinkingEvent)
if (eventId) eventMap.set(eventId, thinkingEvent)
}
if (data.content) {
thinkingEvent.content = String(thinkingEvent.content || '') + String(data.content)
log('[Thinking] Event', eventId, 'accumulated:', String(thinkingEvent.content).length, 'chars')
}
} else {
const thinkingEvent = eventMap.get(eventId || '')
if (thinkingEvent) {
thinkingEvent.done = true
thinkingEvent.thinking = false
thinkingEvent.duration_ms =
dataPayload?.duration_ms || Date.now() - Number(thinkingEvent.startTime || Date.now())
thinkingEvent.completed_at = dataPayload?.completed_at || Date.now()
log('[Thinking] Event completed, duration:', thinkingEvent.duration_ms, 'ms')
} else {
console.warn('[Thinking] Received done for unknown event_id:', eventId)
}
}
break
}
case 'tool_approval_required': {
if (!message.agentEventStream) message.agentEventStream = []
const d = dataPayload || {}
;(message.agentEventStream as ChatMessage[]).push({
type: 'tool_approval_required',
pending_id: d.pending_id,
service_name: d.service_name,
mcp_tool_name: d.mcp_tool_name,
description: d.description,
args_json: d.args_json,
timeout_seconds: d.timeout_seconds,
requested_at: d.requested_at,
tool_call_id: d.tool_call_id,
resolved: false,
})
break
}
case 'tool_approval_resolved': {
const d = dataPayload || {}
const pid = d.pending_id
const ev = (message.agentEventStream as ChatMessage[] | undefined)?.find(
(e) => e.type === 'tool_approval_required' && e.pending_id === pid,
)
if (ev) {
ev.resolved = true
ev.approved = d.approved
ev.resolve_reason = d.reason
ev.timed_out = d.timed_out
ev.canceled = d.canceled
}
break
}
case 'tool_call': {
if (dataPayload?.tool_name === 'final_answer') break
if (message.agentEventStream) {
let retracted = false
for (const ev of message.agentEventStream as ChatMessage[]) {
if (ev.type === 'answer' && !ev.superseded && ev.content && String(ev.content).trim()) {
ev.superseded = true
ev.done = true
retracted = true
}
}
if (retracted) {
message.content = recomposeAgentAnswer(message)
fullContent.value = String(message.content || '')
}
}
if (dataPayload && (dataPayload.tool_name || dataPayload.tool_call_id)) {
if (!message.agentEventStream) message.agentEventStream = []
if (!message._pendingToolCalls) message._pendingToolCalls = new Map()
const pending = message._pendingToolCalls as Map<string, ChatMessage>
const stream = message.agentEventStream as ChatMessage[]
const incomingToolName = dataPayload.tool_name as string | undefined
const incomingArguments = dataPayload.arguments
const toolCallId =
(dataPayload.tool_call_id as string) ||
(incomingToolName ? `${incomingToolName}_${Date.now()}` : null)
if (!toolCallId) {
console.warn('[Tool Call] Received event without identifiable tool_call_id:', dataPayload)
break
}
log('[Tool Call]', {
tool_call_id: toolCallId,
tool_name: incomingToolName,
has_arguments: Boolean(incomingArguments),
})
let toolCallEvent = pending.get(toolCallId)
if (!toolCallEvent) {
toolCallEvent = stream.find(
(event) => event.type === 'tool_call' && event.tool_call_id === toolCallId,
)
}
if (toolCallEvent) {
if (incomingToolName) toolCallEvent.tool_name = incomingToolName
if (incomingArguments) toolCallEvent.arguments = incomingArguments
toolCallEvent.pending = true
if (!toolCallEvent.timestamp) toolCallEvent.timestamp = Date.now()
pending.set(toolCallId, toolCallEvent)
} else {
const newToolCallEvent = {
type: 'tool_call',
tool_call_id: toolCallId,
tool_name: incomingToolName,
arguments: incomingArguments,
timestamp: Date.now(),
pending: true,
}
stream.push(newToolCallEvent)
pending.set(toolCallId, newToolCallEvent)
}
}
break
}
case 'tool_result':
case 'error': {
if (dataPayload) {
const toolCallId = dataPayload.tool_call_id as string | undefined
const toolName = dataPayload.tool_name as string | undefined
const success = responseType !== 'error' && dataPayload.success !== false
log('[Tool Result]', {
tool_call_id: toolCallId,
tool_name: toolName,
success,
})
let toolCallEvent: ChatMessage | undefined
const pending = message._pendingToolCalls as Map<string, ChatMessage> | undefined
if (pending) {
if (toolCallId && pending.has(toolCallId)) {
toolCallEvent = pending.get(toolCallId)
pending.delete(toolCallId)
} else {
Array.from(pending.entries()).some(([key, value]) => {
if (value.tool_name === toolName) {
toolCallEvent = value
pending.delete(key)
return true
}
return false
})
}
}
if (toolCallEvent) {
toolCallEvent.pending = false
toolCallEvent.success = success
toolCallEvent.output = success
? dataPayload.output || data.content
: dataPayload.error || data.content
toolCallEvent.error = !success ? dataPayload.error || data.content : undefined
const duration =
dataPayload.duration_ms !== undefined ? dataPayload.duration_ms : dataPayload.duration
toolCallEvent.duration = duration
toolCallEvent.duration_ms = duration
toolCallEvent.display_type = dataPayload.display_type
toolCallEvent.tool_data = dataPayload
log('[Tool Result] Updated event in stream')
} else {
console.warn('[Tool Result] No pending tool call found for', toolCallId || toolName)
}
if (responseType === 'error' && !toolName) {
const errorMsg = String(data.content || t('chat.processError'))
message.content = errorMsg
message.is_completed = true
isReplying.value = false
loading.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
reportError(errorMsg)
console.error('[Chat Error]', errorMsg)
}
} else if (responseType === 'error') {
const errorMsg = String(data.content || t('chat.processError'))
message.content = errorMsg
message.is_completed = true
isReplying.value = false
loading.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
reportError(errorMsg)
console.error('[Chat Error]', errorMsg)
}
break
}
case 'references': {
if (dataPayload?.references) {
message.knowledge_references = dataPayload.references
} else if (data.knowledge_references) {
message.knowledge_references = data.knowledge_references
}
break
}
case 'answer': {
message.thinking = false
const eventId = dataPayload?.event_id as string | undefined
if (!message.agentEventStream) message.agentEventStream = []
if (!message._eventMap) message._eventMap = new Map()
const eventMap = message._eventMap as Map<string, ChatMessage>
const stream = message.agentEventStream as ChatMessage[]
let answerEvent = eventId
? eventMap.get(eventId)
: stream.find((e) => e.type === 'answer' && !e.event_id)
if (!answerEvent) {
answerEvent = { type: 'answer', event_id: eventId, content: '', done: false }
stream.push(answerEvent)
if (eventId) eventMap.set(eventId, answerEvent)
}
if (!answerEvent.content && message.content && String(message.content).trim()) {
answerEvent.content = message.content
}
if (data.content) {
answerEvent.content = String(answerEvent.content || '') + String(data.content)
message.content = recomposeAgentAnswer(message)
fullContent.value = String(message.content || '')
}
if (dataPayload?.is_fallback) {
answerEvent.is_fallback = true
message.is_fallback = true
}
if (data.done && !answerEvent.done) {
answerEvent.done = true
onAgentAnswerDone?.(message)
loading.value = false
isReplying.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
}
break
}
case 'complete': {
log('[Agent] Complete event received')
loading.value = false
isReplying.value = false
message.is_completed = true
onReplyComplete?.(String(message.content || ''))
fullContent.value = ''
currentAssistantMessageId.value = ''
if (message.agentEventStream) {
;(message.agentEventStream as ChatMessage[]).push({
type: 'agent_complete',
total_duration_ms: dataPayload?.total_duration_ms || 0,
total_steps: dataPayload?.total_steps || 0,
})
}
break
}
case 'stop': {
log('[Agent] Stop event received')
if (!message.agentEventStream) message.agentEventStream = []
;(message.agentEventStream as ChatMessage[]).push({
type: 'stop',
timestamp: Date.now(),
reason: dataPayload?.reason || 'user_requested',
})
isReplying.value = false
fullContent.value = ''
break
}
}
scrollToBottom()
}
const processStreamChunk = (data: ChatMessage) => {
log('[Agent Event Received]', {
response_type: data.response_type,
id: data.id,
done: data.done,
content_length: (data.content as string | undefined)?.length || 0,
content_preview: data.content ? String(data.content).substring(0, 50) : '',
data: data.data,
session_id: data.session_id,
assistant_message_id: data.assistant_message_id,
})
if (data.response_type === 'agent_query') {
if (data.id) {
const earlyMsg = findLastMessage(
(item) => item.role === 'assistant' && !item.is_completed,
)
if (earlyMsg) earlyMsg.request_id = data.id
}
if (data.assistant_message_id) {
currentAssistantMessageId.value = data.assistant_message_id as string
log('[Agent Query] Saved assistant message ID:', data.assistant_message_id)
}
log('[Agent Query Event]', {
session_id: data.session_id || (data.data as ChatMessage | undefined)?.session_id,
assistant_message_id: data.assistant_message_id,
query: (data.data as ChatMessage | undefined)?.query,
request_id: (data.data as ChatMessage | undefined)?.request_id,
})
let existingMessage = findLastMessage(
(item) => item.id === data.id || item.request_id === data.id,
)
const created = !existingMessage
if (!existingMessage) {
existingMessage = {
id: data.id,
request_id: data.id,
role: 'assistant',
content: '',
isAgentMode: true,
is_completed: false,
agentEventStream: [],
_eventMap: new Map(),
_pendingToolCalls: new Map(),
knowledge_references: [],
}
messagesList.push(existingMessage)
onMessageCreated?.(existingMessage)
scrollToBottom(true)
log('[Agent Query] Created agent placeholder message')
} else {
ensureAgentMessageShell(existingMessage, data.id as string | undefined)
log('[Agent Query] Continuing stream for existing message')
}
onAgentQuery?.(data, existingMessage, created)
return
}
const isAgentOnlyResponse =
data.response_type === 'thinking' ||
data.response_type === 'tool_call' ||
data.response_type === 'tool_result' ||
data.response_type === 'reflection'
const lastMessage = messagesList[messagesList.length - 1]
const isCurrentlyAgentMode = lastMessage?.isAgentMode === true
const targetsActiveAgentRequest =
isAgentStreamSession() &&
!!data.id &&
(data.id === currentAssistantMessageId.value ||
lastMessage?.request_id === data.id ||
lastMessage?.id === data.id)
const isAgentAnswerChunk =
data.response_type === 'answer' && (isAgentStreamSession() || targetsActiveAgentRequest)
const isAgentCompleteChunk =
data.response_type === 'complete' && (isAgentStreamSession() || targetsActiveAgentRequest)
const shouldHandleAsAgent =
isAgentOnlyResponse ||
isCurrentlyAgentMode ||
isAgentAnswerChunk ||
isAgentCompleteChunk
if (data.response_type === 'references') {
if (isCurrentlyAgentMode) {
handleAgentChunk(data)
return
}
let existingMessage = findLastMessage(
(item) => item.request_id === data.id || item.id === data.id,
)
if (!existingMessage) {
existingMessage = {
id: data.id,
request_id: data.id,
role: 'assistant',
content: '',
showThink: false,
thinkContent: '',
thinking: false,
is_completed: false,
knowledge_references: [],
}
messagesList.push(existingMessage)
onMessageCreated?.(existingMessage)
loading.value = false
scrollToBottom(true)
}
const refs =
data.knowledge_references ||
(data.data as ChatMessage | undefined)?.references ||
[]
existingMessage.knowledge_references = refs
log('[References] Saved to message, count:', Array.isArray(refs) ? refs.length : 0)
return
}
if (shouldHandleAsAgent) {
handleAgentChunk(data)
if (data.response_type === 'stop') {
log('[Stop Event] Generation stopped')
loading.value = false
isReplying.value = false
currentAssistantMessageId.value = ''
}
return
}
if (data.response_type === 'stop') {
log('[Stop Event] Non-agent generation stopped')
const stoppedMessage = findLastMessage((item) => {
if (item.request_id === data.id) return true
return item.id === data.id
})
if (stoppedMessage) stoppedMessage.is_completed = true
loading.value = false
isReplying.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
return
}
const existingMessage = findLastMessage((item) => {
if (item.request_id === data.id) return true
return item.id === data.id
})
if (existingMessage?.is_completed && data.done && !data.content) {
log('[Non-Agent] Ignoring duplicate completion event for completed message')
return
}
fullContent.value += (data.content as string) || ''
const obj: ChatMessage = {
...data,
content: '',
role: 'assistant',
showThink: false,
is_completed: false,
}
if ((data.data as ChatMessage | undefined)?.is_fallback) obj.is_fallback = true
const thinkCloseTag = '</think>'
if (fullContent.value.includes('<think>') && !fullContent.value.includes(thinkCloseTag)) {
obj.thinking = true
obj.showThink = true
obj.content = ''
obj.thinkContent = fullContent.value.replace('<think>', '').trim()
} else if (fullContent.value.includes('<think>') && fullContent.value.includes(thinkCloseTag)) {
obj.thinking = false
obj.showThink = true
const index = fullContent.value.lastIndexOf(thinkCloseTag)
obj.thinkContent = fullContent.value.substring(0, index).replace('<think>', '').trim()
obj.content = fullContent.value.substring(index + thinkCloseTag.length).trim()
} else {
obj.content = fullContent.value
}
if (!existingMessage) loading.value = false
if (data.done) {
obj.is_completed = true
onReplyComplete?.(String(obj.content || ''))
isReplying.value = false
fullContent.value = ''
currentAssistantMessageId.value = ''
}
updateAssistantSession(obj)
}
return {
findLastMessage,
shouldRenderAssistantMessage,
handleMsgList,
processStreamChunk,
}
}
+253
View File
@@ -0,0 +1,253 @@
import { onMounted, onUnmounted, ref, type Ref } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import {
createEmbedSession,
exchangeEmbedSession,
getEmbedConfig,
getEmbedMessageList,
isEmbedSessionToken,
onEmbedHostContext,
onEmbedHostLocale,
onEmbedHostToken,
parseEmbedTokenFromLocation,
postEmbedBootstrapRequest,
postEmbedReady,
type EmbedChannelPublicConfig,
} from '@/api/embed'
import { applyEmbedLocale, readEmbedLocaleFromUrl, syncEmbedLocaleFromUrl } from '@/i18n/embed'
// Persist the chat session id per channel so a page refresh resumes the same
// conversation (and its history) instead of silently starting a new session.
const EMBED_SESSION_STORAGE_PREFIX = 'weknora-embed-session:'
const sessionStorageKey = (channelId: string) => `${EMBED_SESSION_STORAGE_PREFIX}${channelId}`
interface StoredSession {
id: string
sig: string
}
function readStoredSession(channelId: string): StoredSession | null {
try {
const raw = window.localStorage.getItem(sessionStorageKey(channelId))
if (!raw) return null
const parsed = JSON.parse(raw)
if (parsed && typeof parsed.id === 'string' && typeof parsed.sig === 'string' && parsed.id) {
return { id: parsed.id, sig: parsed.sig }
}
} catch {
// Malformed / legacy (plain-string) entry: ignore so a fresh signed
// session is created below.
}
return null
}
function writeStoredSession(channelId: string, session: StoredSession | null) {
try {
if (session?.id) {
window.localStorage.setItem(sessionStorageKey(channelId), JSON.stringify(session))
} else {
window.localStorage.removeItem(sessionStorageKey(channelId))
}
} catch {
// localStorage may be unavailable (private mode / disabled cookies).
// Persistence is best-effort; the session still works for this load.
}
}
// A stored session may have been deleted/expired server-side, or its signed
// handle invalidated by a channel token rotation. Probe it cheaply (limit=1)
// with the stored signature before reusing — the backend rejects stale/foreign
// ids and bad signatures with 4xx, which surfaces here as a thrown error.
async function isStoredSessionValid(
channelId: string,
apiToken: string,
session: StoredSession,
): Promise<boolean> {
try {
await getEmbedMessageList(channelId, apiToken, session.id, 1, undefined, session.sig)
return true
} catch {
return false
}
}
export function useEmbedBridge(channelId: Ref<string>) {
const { locale: activeLocale, t } = useI18n()
const route = useRoute()
const token = ref('')
const config = ref<EmbedChannelPublicConfig | null>(null)
const sessionId = ref('')
const sessionSig = ref('')
const loadError = ref('')
const awaitingToken = ref(false)
const bootstrapping = ref(false)
const hostContext = ref<Record<string, unknown>>({})
let removeHostListener: (() => void) | null = null
let removeLocaleListener: (() => void) | null = null
let removeTokenListener: (() => void) | null = null
let bootstrapped = false
let hostLocalePinned = false
if (typeof window !== 'undefined') {
hostLocalePinned = Boolean(readEmbedLocaleFromUrl())
if (hostLocalePinned) {
syncEmbedLocaleFromUrl(activeLocale)
}
}
const bootstrap = async (embedToken: string) => {
const id = channelId.value
if (!id || !embedToken || bootstrapped) return
bootstrapped = true
awaitingToken.value = false
bootstrapping.value = true
token.value = embedToken
try {
let apiToken = embedToken
// Secure mode: the host already handed us a short-lived session token
// (minted server-side from the publish token). Use it directly — the
// exchange endpoint only accepts publish tokens and would reject this.
if (!isEmbedSessionToken(embedToken)) {
try {
const exchangeRes = await exchangeEmbedSession(id, embedToken)
if (exchangeRes?.data?.session_token) {
apiToken = exchangeRes.data.session_token
} else if (!import.meta.env.DEV) {
// Fail closed in production: a missing session token must not silently
// fall back to the long-lived publish token.
throw new Error('embed session exchange returned no token')
}
} catch (exchangeErr) {
// In production we refuse to downgrade to the publish token; only the
// dev build keeps the convenience fallback for local testing.
if (!import.meta.env.DEV) {
throw exchangeErr
}
}
}
const res = await getEmbedConfig(id, apiToken)
if (!res?.success || !res.data) {
loadError.value = t('embedPublish.invalidChannel')
return
}
config.value = res.data
if (res.data.default_locale && !hostLocalePinned) {
applyEmbedLocale(res.data.default_locale, activeLocale)
}
// Resume a persisted session when still valid; otherwise create a fresh one.
let resolved: StoredSession | null = null
const stored = readStoredSession(id)
if (stored && (await isStoredSessionValid(id, apiToken, stored))) {
resolved = stored
} else {
const sessionRes = await createEmbedSession(id, apiToken)
const newId = sessionRes?.data?.id || ''
if (newId) resolved = { id: newId, sig: sessionRes?.data?.sig || '' }
}
if (!resolved) {
loadError.value = t('embedPublish.sessionFailed')
return
}
sessionId.value = resolved.id
sessionSig.value = resolved.sig
writeStoredSession(id, resolved)
token.value = apiToken
postEmbedReady(id)
} catch (e: unknown) {
bootstrapped = false
const msg = String((e as { message?: string })?.message || '')
if (msg.includes('disabled')) {
loadError.value = t('embedPublish.channelDisabled')
} else if (msg.includes('failed to create session')) {
loadError.value = t('embedPublish.sessionFailed')
} else {
loadError.value = msg || t('embedPublish.loadError')
}
} finally {
bootstrapping.value = false
}
}
// Discard the current conversation and start a fresh signed session. Backing
// the "新建对话" affordance — also the privacy escape hatch on shared devices.
const startNewSession = async () => {
const id = channelId.value
const apiToken = token.value
if (!id || !apiToken) return
try {
const sessionRes = await createEmbedSession(id, apiToken)
const newId = sessionRes?.data?.id || ''
if (!newId) return
const next: StoredSession = { id: newId, sig: sessionRes?.data?.sig || '' }
sessionSig.value = next.sig
sessionId.value = next.id
writeStoredSession(id, next)
} catch {
// Non-fatal: keep the current session if creating a new one fails.
}
}
const start = async () => {
removeHostListener = onEmbedHostContext((payload) => {
hostContext.value = { ...hostContext.value, ...payload }
})
removeLocaleListener = onEmbedHostLocale((locale) => {
hostLocalePinned = true
applyEmbedLocale(locale, activeLocale)
})
removeTokenListener = onEmbedHostToken((providedToken, providedChannelId) => {
if (providedChannelId && providedChannelId !== channelId.value) return
bootstrap(providedToken)
})
if (!channelId.value) {
loadError.value = t('embedPublish.missingChannel')
return
}
const initialToken = String(route.query.token || '') || parseEmbedTokenFromLocation()
if (initialToken) {
await bootstrap(initialToken)
return
}
if (window.parent !== window) {
awaitingToken.value = true
postEmbedBootstrapRequest(channelId.value)
return
}
loadError.value = t('embedPublish.missingChannel')
}
onMounted(() => {
start()
})
onUnmounted(() => {
removeHostListener?.()
removeLocaleListener?.()
removeTokenListener?.()
})
return {
token,
config,
sessionId,
sessionSig,
loadError,
awaitingToken,
bootstrapping,
hostContext,
startNewSession,
}
}
@@ -0,0 +1,369 @@
import {
ref,
reactive,
watch,
nextTick,
onMounted,
onUnmounted,
type Ref,
} from 'vue'
import { useStream } from '@/api/chat/streame'
import {
getEmbedMessageList,
postEmbedMessageSent,
postEmbedMessageReceived,
relayEmbedWebhookEvent,
stopEmbedSession,
} from '@/api/embed'
import { embedToast } from '@/utils/embedToast'
import { buildQueryWithHostContext } from '@/utils/embedContext'
import { fileToDataURI } from '@/utils/embedFile'
import { useI18n } from 'vue-i18n'
import { useChatStreamHandler } from '@/composables/useChatStreamHandler'
export function useEmbedChatSession(options: {
sessionId: Ref<string>
sessionSig: Ref<string>
channelId: string
token: string
agentId: string
kbIds: string[]
allowWebSearch?: boolean
allowFileUpload?: boolean
hostContext?: Ref<Record<string, unknown>>
onMessagesChange?: (has: boolean) => void
onSessionTitle?: (title: string) => void
}) {
const { t } = useI18n()
const { onChunk, error, startStream, stopStream } = useStream()
const isAgentStreamSession = () =>
!!(options.agentId && options.agentId !== 'builtin-quick-answer')
const limit = ref(20)
const messagesList = reactive<Record<string, unknown>[]>([])
watch(
() => messagesList.length,
(len) => options.onMessagesChange?.(len > 0),
{ immediate: true },
)
const isReplying = ref(false)
const currentAssistantMessageId = ref('')
const isFirstEnter = ref(true)
const loading = ref(false)
const historyLoading = ref(true)
const historyLoadingMore = ref(false)
const hasMoreHistory = ref(true)
const created_at = ref('')
const fullContent = ref('')
const scrollContainer = ref<HTMLElement | null>(null)
const userHasScrolledUp = ref(false)
const SCROLL_BOTTOM_THRESHOLD = 80
const isNearBottom = () => {
if (!scrollContainer.value) return true
const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value
return scrollHeight - scrollTop - clientHeight < SCROLL_BOTTOM_THRESHOLD
}
const getUserQuery = (index: number) => {
if (index <= 0) return ''
const previous = messagesList[index - 1]
if (previous && previous.role === 'user') {
return String(previous.content || '')
}
return ''
}
const scrollToBottom = (force = false) => {
if (!force && userHasScrolledUp.value) return
nextTick(() => {
if (scrollContainer.value) {
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
}
})
}
const onClickScrollToBottom = () => {
userHasScrolledUp.value = false
scrollToBottom(true)
}
const debounce = <T extends (...args: never[]) => void>(fn: T, delay: number) => {
let timer: ReturnType<typeof setTimeout>
return (...args: Parameters<T>) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), delay)
}
}
const notifyEmbedReceived = (content: string) => {
if (!content?.trim()) return
postEmbedMessageReceived(options.channelId, options.sessionId.value, content)
relayEmbedWebhookEvent(
options.channelId,
options.token,
options.sessionId.value,
options.sessionSig.value,
{ type: 'message_received', content },
)
}
const {
shouldRenderAssistantMessage,
handleMsgList,
processStreamChunk,
} = useChatStreamHandler({
messagesList,
loading,
isReplying,
currentAssistantMessageId,
fullContent,
isAgentStreamSession,
scrollToBottom,
onReplyComplete: notifyEmbedReceived,
onError: embedToast,
isFirstEnter,
scrollContainer,
})
const onChatScrollTop = () => {
if (historyLoadingMore.value || !hasMoreHistory.value) return
if (!scrollContainer.value) return
const { scrollTop, scrollHeight } = scrollContainer.value
isFirstEnter.value = false
if (scrollTop <= 0) {
getmsgList(
{
session_id: options.sessionId.value,
created_at: created_at.value,
limit: limit.value,
},
true,
scrollHeight,
)
}
}
const debouncedScrollTop = debounce(onChatScrollTop, 500)
const handleScroll = () => {
userHasScrolledUp.value = !isNearBottom()
debouncedScrollTop()
}
const getmsgList = (
data: { session_id: string; created_at?: string; limit: number },
isScrollType = false,
scrollHeight?: number,
) => {
if (isScrollType) {
if (historyLoadingMore.value || !hasMoreHistory.value) return
historyLoadingMore.value = true
}
getEmbedMessageList(
options.channelId,
options.token,
data.session_id,
data.limit,
data.created_at || undefined,
options.sessionSig.value,
)
.then(async (res) => {
const batch = res?.data as Record<string, unknown>[] | undefined
if (!batch?.length) {
// No (more) server history. Crucially this also covers the initial
// load of a brand-new session: leaving hasMoreHistory true here would
// let a later scroll-to-top re-fetch with an empty cursor (= "latest"),
// pulling back the just-sent messages and duplicating them.
hasMoreHistory.value = false
return
}
const nextCursor = String(batch[0].created_at)
if (isScrollType && created_at.value && nextCursor === created_at.value) {
hasMoreHistory.value = false
return
}
if (batch.length < limit.value) hasMoreHistory.value = false
created_at.value = nextCursor
await handleMsgList(batch, isScrollType, scrollHeight)
})
.catch((err) => {
console.error('Failed to load messages:', err)
if (isScrollType) hasMoreHistory.value = false
})
.finally(() => {
historyLoading.value = false
historyLoadingMore.value = false
})
}
const handleStopGeneration = () => {
stopStream()
const messageId = currentAssistantMessageId.value
if (messageId) {
stopEmbedSession(
options.channelId,
options.token,
options.sessionId.value,
messageId,
options.sessionSig.value,
).catch((err) => console.error('Failed to stop embed generation:', err))
}
loading.value = false
isReplying.value = false
}
const sendMsg = async (
value: string,
opts: { webSearchEnabled?: boolean; imageFiles?: File[]; attachmentFiles?: File[] } = {},
) => {
const outboundQuery = buildQueryWithHostContext(value, options.hostContext?.value)
const visitorWebSearchEnabled = opts.webSearchEnabled ?? false
const imageFiles = (options.allowFileUpload ? opts.imageFiles : undefined) || []
const attachmentFiles = (options.allowFileUpload ? opts.attachmentFiles : undefined) || []
isReplying.value = true
loading.value = true
const imageAttachments: Array<{ data: string }> = []
const displayImages: Array<{ url: string }> = []
const attachmentUploads: Array<{ data: string; file_name: string; file_size: number }> = []
const displayAttachments: Array<{ file_name: string; file_size: number }> = []
try {
for (const file of imageFiles) {
const dataURI = String(await fileToDataURI(file))
imageAttachments.push({ data: dataURI })
displayImages.push({ url: dataURI })
}
for (const file of attachmentFiles) {
const dataURI = String(await fileToDataURI(file))
attachmentUploads.push({ data: dataURI, file_name: file.name, file_size: file.size })
displayAttachments.push({ file_name: file.name, file_size: file.size })
}
} catch (err) {
console.error('Failed to read attachment:', err)
embedToast(t('chat.imageReadFailed'))
isReplying.value = false
loading.value = false
return
}
messagesList.push({
content: value,
role: 'user',
mentioned_items: [],
images: displayImages,
attachments: displayAttachments,
channel: 'embed',
})
postEmbedMessageSent(options.channelId, options.sessionId.value, value)
relayEmbedWebhookEvent(
options.channelId,
options.token,
options.sessionId.value,
options.sessionSig.value,
{ type: 'message_sent', query: value },
)
userHasScrolledUp.value = false
scrollToBottom(true)
const agentEnabled = isAgentStreamSession()
const endpoint = agentEnabled
? `/api/v1/embed/${options.channelId}/agent-chat`
: `/api/v1/embed/${options.channelId}/knowledge-chat`
await startStream({
session_id: options.sessionId.value,
knowledge_base_ids: options.kbIds,
knowledge_ids: [],
agent_enabled: agentEnabled,
agent_id: options.agentId,
web_search_enabled: (options.allowWebSearch ?? false) && visitorWebSearchEnabled,
enable_memory: false,
summary_model_id: '',
mcp_service_ids: [],
mentioned_items: [],
images: imageAttachments.length > 0 ? imageAttachments : undefined,
attachment_uploads: attachmentUploads.length > 0 ? attachmentUploads : undefined,
query: outboundQuery,
method: 'POST',
url: endpoint,
embed_token: options.token,
embed_session_sig: options.sessionSig.value,
})
}
watch(error, (newError) => {
if (newError) {
embedToast(newError)
isReplying.value = false
loading.value = false
currentAssistantMessageId.value = ''
}
})
onChunk((data) => {
if (data.response_type === 'session_title') {
const title = String(data.content || (data.data as { title?: string })?.title || '').trim()
if (title) {
options.onSessionTitle?.(title)
}
return
}
processStreamChunk(data)
})
const resetAndLoad = (sid: string) => {
messagesList.splice(0)
historyLoading.value = true
historyLoadingMore.value = false
hasMoreHistory.value = true
created_at.value = ''
loading.value = false
isReplying.value = false
currentAssistantMessageId.value = ''
userHasScrolledUp.value = false
isFirstEnter.value = true
fullContent.value = ''
if (!sid) {
historyLoading.value = false
return
}
getmsgList({ session_id: sid, created_at: '', limit: limit.value })
}
watch(
() => options.sessionId.value,
(sid) => resetAndLoad(sid),
{ immediate: true },
)
onMounted(() => {
loading.value = false
isReplying.value = false
})
onUnmounted(() => {
stopStream()
fullContent.value = ''
})
return {
messagesList,
loading,
isReplying,
historyLoading,
scrollContainer,
userHasScrolledUp,
isFirstEnter,
shouldRenderAssistantMessage,
getUserQuery,
handleScroll,
scrollToBottom,
onClickScrollToBottom,
sendMsg,
handleStopGeneration,
}
}
@@ -0,0 +1,168 @@
import { onBeforeUnmount, ref, unref, watch, type MaybeRef, type Ref } from 'vue'
import { getEmbedChunkById } from '@/api/embed'
type FloatState = {
visible: boolean
type: 'kb' | 'web'
top: number
left: number
title: string
content: string
url: string
loading: boolean
error: string
}
const chunkCache = new Map<string, { content: string; error?: string }>()
export function useEmbedCitationPopover(
rootRef: Ref<HTMLElement | null>,
channelId: MaybeRef<string>,
token: MaybeRef<string>,
) {
const float = ref<FloatState>({
visible: false,
type: 'kb',
top: 0,
left: 0,
title: '',
content: '',
url: '',
loading: false,
error: '',
})
let hoverTimer: number | null = null
let closeTimer: number | null = null
const positionFor = (el: HTMLElement, offsetY = 0) => {
const rect = el.getBoundingClientRect()
float.value.top = rect.bottom + window.scrollY + 6 + offsetY
float.value.left = Math.min(rect.left + window.scrollX, window.innerWidth - 320)
}
const openWeb = (el: HTMLElement) => {
const url = el.getAttribute('data-url') || ''
float.value.type = 'web'
float.value.url = url
float.value.title = el.querySelector('.tip-title')?.textContent || ''
float.value.content = ''
float.value.loading = false
float.value.error = ''
float.value.visible = true
positionFor(el)
}
const openKb = async (el: HTMLElement) => {
const chunkId = el.getAttribute('data-chunk-id') || ''
const title = el.getAttribute('data-doc') || ''
if (!chunkId) return
float.value.type = 'kb'
float.value.title = title
float.value.url = ''
float.value.visible = true
positionFor(el, 4)
const cached = chunkCache.get(chunkId)
if (cached) {
float.value.content = cached.content
float.value.error = cached.error || ''
float.value.loading = false
return
}
float.value.loading = true
float.value.error = ''
float.value.content = ''
try {
const res = await getEmbedChunkById(unref(channelId), unref(token), chunkId)
const content = String(res?.data?.content || '').trim()
chunkCache.set(chunkId, { content })
float.value.content = content
} catch {
const msg = 'Failed to load'
chunkCache.set(chunkId, { content: '', error: msg })
float.value.error = msg
} finally {
float.value.loading = false
}
}
const scheduleClose = () => {
if (closeTimer) window.clearTimeout(closeTimer)
closeTimer = window.setTimeout(() => {
float.value.visible = false
}, 120)
}
const onMouseOver = (e: Event) => {
const target = e.target as HTMLElement
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null
const webEl = target.closest?.('.citation-web') as HTMLElement | null
if (!kbEl && !webEl) return
if (closeTimer) {
window.clearTimeout(closeTimer)
closeTimer = null
}
if (hoverTimer) window.clearTimeout(hoverTimer)
hoverTimer = window.setTimeout(() => {
if (kbEl) void openKb(kbEl)
else if (webEl) openWeb(webEl)
}, kbEl ? 80 : 40)
}
const onMouseOut = (e: Event) => {
const rt = (e as MouseEvent).relatedTarget as HTMLElement | null
if (rt?.closest?.('.citation-kb, .citation-web, .embed-citation-float')) return
if (hoverTimer) {
window.clearTimeout(hoverTimer)
hoverTimer = null
}
scheduleClose()
}
const onClick = (e: Event) => {
const target = e.target as HTMLElement
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null
if (kbEl) {
e.preventDefault()
e.stopPropagation()
void openKb(kbEl)
return
}
const wikiEl = target.closest?.('.citation-wiki') as HTMLElement | null
if (wikiEl) {
e.preventDefault()
e.stopPropagation()
}
}
const bind = () => {
const root = rootRef.value
if (!root) return
root.addEventListener('mouseover', onMouseOver, true)
root.addEventListener('mouseout', onMouseOut, true)
root.addEventListener('click', onClick, true)
}
const unbind = () => {
const root = rootRef.value
if (!root) return
root.removeEventListener('mouseover', onMouseOver, true)
root.removeEventListener('mouseout', onMouseOut, true)
root.removeEventListener('click', onClick, true)
}
watch(rootRef, () => {
unbind()
bind()
}, { flush: 'post' })
onBeforeUnmount(() => {
unbind()
if (hoverTimer) window.clearTimeout(hoverTimer)
if (closeTimer) window.clearTimeout(closeTimer)
})
return { float, rebind: () => { unbind(); bind() } }
}