"use client"; import { useRouter } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { toast } from "sonner"; import { type PromptInputMessage } from "@/components/ai-elements/prompt-input"; import { getAPIClient } from "@/core/api"; import { usePromptPrefixSettings } from "@/core/system-settings/hooks"; import { useUserPreferencesQuery } from "@/core/user-preferences"; import { ArtifactTrigger, useArtifacts } from "@/components/workspace/artifacts"; import { ChatBox, useSpecificChatMode, useThreadChat, } from "@/components/workspace/chats"; import { ExportTrigger } from "@/components/workspace/export-trigger"; import { InputBox } from "@/components/workspace/input-box"; import { MessageList, MESSAGE_LIST_DEFAULT_PADDING_BOTTOM, MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM, } from "@/components/workspace/messages"; import { ThreadContext } from "@/components/workspace/messages/context"; import { ThreadTitle } from "@/components/workspace/thread-title"; import { TodoList } from "@/components/workspace/todo-list"; import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator"; import { Welcome } from "@/components/workspace/welcome"; import { useAgentSelector } from "@/core/agents"; import { useI18n } from "@/core/i18n/hooks"; import { useModels } from "@/core/models/hooks"; import { useNotification } from "@/core/notification/hooks"; import { getLastAgentId, saveLastAgentId, useThreadSettings, } from "@/core/settings"; import { useThreadStream } from "@/core/threads/hooks"; import { useRouteBase } from "@/core/route-base"; import { textOfMessage } from "@/core/threads/utils"; import { env } from "@/env"; import { cn } from "@/lib/utils"; export default function ChatPage() { const routeBase = useRouteBase(); const router = useRouter(); const { t } = useI18n(); const [showFollowups, setShowFollowups] = useState(false); const [hasStartedConversation, setHasStartedConversation] = useState(false); const { threadId, setThreadId, isNewThread, setIsNewThread, isMock } = useThreadChat(); const [settings, setSettings] = useThreadSettings(threadId); const [mounted, setMounted] = useState(false); const { tokenUsageEnabled } = useModels(); const { data: promptPrefixSettings } = usePromptPrefixSettings(); // Personal opt-out: when set, hide the admin prompt-prefix switch entirely and // never apply the prefix — the user uses only their own prompts. const { data: userPreferences, isLoading: preferencesLoading } = useUserPreferencesQuery(); const hideAdminPrompt = userPreferences?.hide_admin_prompt_prefix === true; const [promptPrefixOn, setPromptPrefixOn] = useState(false); const [selectedAgentId, setSelectedAgentId] = useState(null); const [agentHandoffPending, setAgentHandoffPending] = useState(false); const agentHandoffPendingRef = useRef(false); const { agents: selectorAgents, isLoading: selectorLoading } = useAgentSelector(); const { selectedArtifact } = useArtifacts(); useSpecificChatMode(); useEffect(() => { setMounted(true); }, []); useEffect(() => { if (isNewThread) { setHasStartedConversation(false); setPromptPrefixOn(false); // Pre-select the agent the user last started a conversation with so a // fresh chat defaults to it. Validated against the selector list below. setSelectedAgentId(getLastAgentId()); } }, [isNewThread, threadId]); // Drop a restored last-used agent that is no longer in the selector list // (deleted / unpublished / no longer curated), so we never hand off to a // dead agent. Wait for the list to load before deciding. useEffect(() => { if (selectorLoading || !selectedAgentId) return; if (!selectorAgents.some((a) => a.id === selectedAgentId)) { setSelectedAgentId(null); } }, [selectedAgentId, selectorAgents, selectorLoading]); const { showNotification } = useNotification(); const [thread, sendMessage, isUploading] = useThreadStream({ threadId: isNewThread ? undefined : threadId, context: settings.context, isMock, onStart: (createdThreadId) => { setThreadId(createdThreadId); setIsNewThread(false); // Keep the current component mounted while updating the hash route. history.replaceState( null, "", `${window.location.pathname}${window.location.search}#${routeBase}/chats/${createdThreadId}`, ); }, onFinish: (state) => { if (document.hidden || !document.hasFocus()) { let body = "Conversation finished"; const lastMessage = state.messages.at(-1); if (lastMessage) { const textContent = textOfMessage(lastMessage); if (textContent) { body = textContent.length > 200 ? textContent.substring(0, 200) + "..." : textContent; } } showNotification(state.title, { body }); } }, }); const writingArtifactPath = useMemo(() => { const isMarkdown = (path: string | null | undefined) => !!path && /\.(md|markdown)(?:$|[?#])/i.test(path); if (isMarkdown(selectedArtifact)) { return selectedArtifact ?? undefined; } return [...(thread.values.artifacts ?? [])] .reverse() .find((path) => isMarkdown(path)); }, [selectedArtifact, thread.values.artifacts]); const handleSubmit = useCallback( (message: PromptInputMessage) => { // If the user picked an agent before sending the opening turn, hand off // to AgentChatPage so the conversation runs against that agent. We stash // the pending text in sessionStorage because the next/navigation shim // doesn't carry router state across hash-route pushes. File attachments // are bound to the current thread upload directory and would not match // the new thread, so we skip the handoff when files are present and let // the message run on Lead Agent instead. if ( selectedAgentId && isNewThread && !hasStartedConversation && message.text && (!message.files || message.files.length === 0) ) { if (agentHandoffPendingRef.current) return; const text = message.text.trim(); agentHandoffPendingRef.current = true; setAgentHandoffPending(true); setHasStartedConversation(true); void (async () => { try { const created = await getAPIClient(isMock).threads.create({ metadata: { agent_id: selectedAgentId }, }); sessionStorage.setItem( "pendingAgentMessage", JSON.stringify({ agentId: selectedAgentId, threadId: created.thread_id, text, }), ); saveLastAgentId(selectedAgentId); router.push( `/page/workspace/agents/${selectedAgentId}/chats/${created.thread_id}`, ); } catch (err) { agentHandoffPendingRef.current = false; setAgentHandoffPending(false); setHasStartedConversation(false); toast.error( err instanceof Error ? err.message : "创建智能体对话失败", ); } })(); return; } // Only the opening turn of a brand-new thread may carry the prefix. const shouldApplyPrefix = isNewThread && !hasStartedConversation && promptPrefixOn && !preferencesLoading && !hideAdminPrompt && promptPrefixSettings?.enabled === true; setHasStartedConversation(true); window.dispatchEvent( new CustomEvent("workspace:sandbox-resume-autoscroll"), ); // The prefix is intentionally NOT concatenated into the message text: // doing so would make the user see it. We only flag the request via // context; the backend tags the message and PromptPrefixMiddleware // injects the prefix into the LLM request only. Writing mode adds the // active markdown artifact path so the agent keeps editing the canvas. const extraContext: Record = {}; if (shouldApplyPrefix) { extraContext.prompt_prefix_enabled = true; } if (settings.context.writing_mode && writingArtifactPath) { extraContext.writing_artifact_path = writingArtifactPath; } void sendMessage( threadId, message, Object.keys(extraContext).length > 0 ? extraContext : undefined, ); }, [ sendMessage, threadId, isNewThread, hasStartedConversation, promptPrefixOn, promptPrefixSettings, hideAdminPrompt, preferencesLoading, selectedAgentId, agentHandoffPending, isMock, router, settings.context.writing_mode, writingArtifactPath, ], ); const handleClarificationSubmit = useCallback( (answer: string) => { setHasStartedConversation(true); void sendMessage(threadId, { text: answer, files: [] }); }, [sendMessage, threadId], ); // Persist the picked agent the moment it changes so the next new chat // defaults to it — even if the user never sends a message this session. // Passing null (the ✕ clear) wipes the stored preference. const handleAgentChange = useCallback((agentId: string | null) => { setSelectedAgentId(agentId); saveLastAgentId(agentId); }, []); const handleStop = useCallback(async () => { await thread.stop(); }, [thread]); const promptPrefixProp = useMemo(() => { if (!promptPrefixSettings?.enabled) return undefined; if (preferencesLoading) return undefined; // Personal opt-out hides the admin prompt-prefix switch entirely. if (hideAdminPrompt) return undefined; // The prefix toggle is offered only on the opening turn of a new thread. if (!isNewThread || hasStartedConversation) return undefined; return { label: promptPrefixSettings.switch_label || "前缀", on: promptPrefixOn, onToggle: () => setPromptPrefixOn((v) => !v), }; }, [ promptPrefixSettings, hideAdminPrompt, preferencesLoading, isNewThread, hasStartedConversation, promptPrefixOn, ]); const messageListPaddingBottom = showFollowups ? MESSAGE_LIST_DEFAULT_PADDING_BOTTOM + MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM : undefined; const isLandingState = isNewThread && !hasStartedConversation; return (
{/* Landing state covers two cases: (a) a brand-new chat that hasn't sent anything yet, and (b) the user clicking 「新对话」 mid-stream. In (b) the underlying useStream's internal stream.values takes one or two effect ticks to clear, so rendering MessageList unconditionally would leak the previous conversation under the welcome card. Skip rendering during the landing state to guarantee a clean slate. */} {!isLandingState && ( handleSubmit({ text, files: [] }) } /> )}
{isLandingState && mounted && ( )} {mounted ? (
setSettings("context", context) } promptPrefix={promptPrefixProp} agentSelector={ isLandingState ? { selectedAgentId, onAgentChange: handleAgentChange, } : undefined } onFollowupsVisibilityChange={setShowFollowups} onSubmit={handleSubmit} onStop={handleStop} />
) : (
); }