🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(chat): preserve topics across cold route sends (#14284)
Innei3b1eef72d868
diff --git a/e2e/src/features/home/chat-input.feature b/e2e/src/features/home/chat-input.featurenew file mode 100644index 00000000000..f52681f10ea--- /dev/null+++ b/e2e/src/features/home/chat-input.feature@@ -0,0 +1,14 @@+@journey @home @chat-input+Feature: Home 页面默认 Chat Input 发送链路+ 作为用户,我希望首次从 Home 页面发送默认消息时,可以稳定进入新建 Topic 对话页面++ Background:+ Given 用户已登录系统++ @HOME-CHAT-COLD-001 @P0+ Scenario: 首次打开 Agent 路由且无缓存时,Home 默认输入发送后应跳转到新建 Topic+ Given 用户在冷启动 Home 页面并延迟 Agent 路由加载+ When 用户在输入框中输入 "cold route home message"+ And 用户按 Enter 从 Home 默认输入发送+ Then 页面应该跳转到新建 Topic 对话页面+ And 用户消息 "cold route home message" 应该保留在对话中diff --git a/e2e/src/steps/home/chat-input.steps.ts b/e2e/src/steps/home/chat-input.steps.tsnew file mode 100644index 00000000000..4092dd52917--- /dev/null+++ b/e2e/src/steps/home/chat-input.steps.ts@@ -0,0 +1,99 @@+import { After, Given, Then, When } from '@cucumber/cucumber';+import { expect } from '@playwright/test';++import { llmMockManager } from '../../mocks/llm';+import { type CustomWorld, WAIT_TIMEOUT } from '../../support/world';++const COLD_ROUTE_SCRIPT_DELAY = 2500;++const delay = (ms: number) =>+ new Promise((resolve) => {+ setTimeout(resolve, ms);+ });++Given(+ '用户在冷启动 Home 页面并延迟 Agent 路由加载',+ { timeout: 45_000 },+ async function (this: CustomWorld) {+ console.log(' 📍 Step: 设置快速 LLM mock...');+ llmMockManager.clearResponses();+ llmMockManager.setConfig({+ responseDelay: 0,+ streamChunkSize: 1024,+ streamDelay: 0,+ });+ llmMockManager.setResponse('cold route home message', 'cold route response');+ await llmMockManager.setup(this.page);++ console.log(' 📍 Step: 注册冷路由脚本延迟...');+ this.testContext.delayColdAgentScripts = false;++ await this.page.route('**/*', async (route) => {+ const request = route.request();+ const url = request.url();+ const shouldDelay =+ this.testContext.delayColdAgentScripts === true &&+ request.resourceType() === 'script' &&+ (url.includes('/_next/static/') ||+ url.includes('/src/routes/(main)/agent') ||+ url.includes('/src/routes/%28main%29/agent'));++ if (shouldDelay) {+ console.log(` ⏳ Delaying cold agent script: ${url}`);+ await delay(COLD_ROUTE_SCRIPT_DELAY);+ }++ await route.continue();+ });++ console.log(' 📍 Step: 导航到 Home 页面...');+ await this.page.goto('/');++ const chatInputContainer = this.page.locator('[data-testid="chat-input"]').first();+ await expect(chatInputContainer).toBeVisible({ timeout: WAIT_TIMEOUT });++ console.log(' ✅ 已进入冷启动 Home 页面');+ },+);++When('用户按 Enter 从 Home 默认输入发送', { timeout: 45_000 }, async function (this: CustomWorld) {+ console.log(' 📍 Step: 启用冷路由延迟并发送默认 Home 消息...');++ await this.page.waitForTimeout(200);+ this.testContext.delayColdAgentScripts = true;++ await this.page.keyboard.press('Enter');++ await this.page.waitForURL(/\/agent\/[^/?#]+/, { timeout: WAIT_TIMEOUT });++ console.log(' ✅ 已触发 Home 默认发送');+});++Then('页面应该跳转到新建 Topic 对话页面', { timeout: 45_000 }, async function (this: CustomWorld) {+ console.log(' 📍 Step: 验证 URL 进入新建 Topic...');++ await this.page.waitForURL(/\/agent\/[^/?#]+\/[^/?#]+/, { timeout: 30_000 });++ const currentUrl = this.page.url();+ expect(currentUrl).toMatch(/\/agent\/[^/?#]+\/[^/?#]+/);++ console.log(` ✅ 已跳转到 Topic 页面: ${currentUrl}`);+});++Then(+ '用户消息 {string} 应该保留在对话中',+ { timeout: 45_000 },+ async function (this: CustomWorld, message: string) {+ console.log(` 📍 Step: 验证用户消息仍在对话中: ${message}`);++ await expect(this.page.getByText(message).first()).toBeVisible({ timeout: WAIT_TIMEOUT });++ console.log(' ✅ 用户消息已保留在对话中');+ },+);++After({ tags: '@chat-input' }, async function (this: CustomWorld) {+ llmMockManager.resetConfig();+ llmMockManager.clearResponses();+ this.testContext.delayColdAgentScripts = false;+});diff --git a/e2e/src/support/seedTestUser.ts b/e2e/src/support/seedTestUser.tsindex 7f87306ca82..bf973f3dc33 100644--- a/e2e/src/support/seedTestUser.ts+++ b/e2e/src/support/seedTestUser.ts@@ -1,3 +1,5 @@+import { randomBytes } from 'node:crypto';+import bcrypt from 'bcryptjs';// Test user credentials - these are used for e2e testing only@@ -92,6 +94,39 @@ export async function seedTestUser(): Promise<void> {}}+export async function createTestSession(): Promise<string | null> {+ const databaseUrl = process.env.DATABASE_URL;++ if (!databaseUrl) {+ console.log('⚠️ DATABASE_URL not set, cannot create test session');+ return null;+ }++ await seedTestUser();++ const { default: pg } = await import('pg');+ const client = new pg.Client({ connectionString: databaseUrl });++ try {+ await client.connect();++ const now = new Date();+ const expiresAt = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);+ const sessionId = randomBytes(9).toString('base64url');+ const sessionToken = randomBytes(24).toString('base64url');++ await client.query(+ `INSERT INTO auth_sessions (id, token, user_id, expires_at, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $5)`,+ [sessionId, sessionToken, TEST_USER.id, expiresAt.toISOString(), now.toISOString()],+ );++ return sessionToken;+ } finally {+ await client.end();+ }+}+/*** Clean up test user data after tests*/diff --git a/src/features/PageEditor/Copilot/Conversation.tsx b/src/features/PageEditor/Copilot/Conversation.tsxindex 1f1396ec662..2757de11327 100644--- a/src/features/PageEditor/Copilot/Conversation.tsx+++ b/src/features/PageEditor/Copilot/Conversation.tsx@@ -1,6 +1,6 @@import { isChatGroupSessionId } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';-import { memo, useCallback, useEffect, useMemo } from 'react';+import { memo, useCallback, useMemo } from 'react';import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';import { actionMap } from '@/features/ChatInput/ActionBar/config';@@ -18,7 +18,6 @@ import {} from '@/features/Conversation';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';import AgentSelectorAction from './AgentSelector/AgentSelectorAction';import CopilotModelSelect from './CopilotModelSelect';@@ -36,25 +35,6 @@ const Conversation = memo(() => {]);const currentAgentId = useConversationStore(conversationSelectors.agentId);- useEffect(() => {- if (!currentAgentId) return;-- if (useAgentStore.getState().activeAgentId !== currentAgentId) {- setActiveAgentId(currentAgentId);- }-- const { activeAgentId, activeTopicId, switchTopic } = useChatStore.getState();-- if (activeAgentId !== currentAgentId) {- useChatStore.setState({ activeAgentId: currentAgentId });- }-- // Reset topic on agent/context switch to avoid reusing old topic scope.- if (activeAgentId !== currentAgentId || !!activeTopicId) {- void switchTopic(null, { scope: 'page', skipRefreshMessage: true });- }- }, [currentAgentId, setActiveAgentId]);-useFetchAgentConfig(true, currentAgentId);const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(currentAgentId)(s));diff --git a/src/features/PageEditor/PageAgentProvider.test.tsx b/src/features/PageEditor/PageAgentProvider.test.tsxnew file mode 100644index 00000000000..294fa579bfc--- /dev/null+++ b/src/features/PageEditor/PageAgentProvider.test.tsx@@ -0,0 +1,160 @@+/**+ * @vitest-environment happy-dom+ */+import { render, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { PageAgentProvider } from './PageAgentProvider';++interface AgentState {+ activeAgentId?: string;+ pageAgentId: string;+ setActiveAgentId: (agentId: string) => void;+ useInitBuiltinAgent: (slug: string) => void;+}++interface ChatState {+ activeAgentId?: string;+ activeTopicId?: string | null;+ dbMessagesMap: Record<string, unknown[]>;+ replaceMessages: (messages: unknown[], options: unknown) => void;+ switchTopic: (topicId: string | null, options: unknown) => Promise<void>;+}++const conversationProviderSpy = vi.fn();+const operationState = { isInputLoading: false };++let agentState: AgentState;+let chatState: ChatState;++vi.mock('@/components/Loading/BrandTextLoading', () => ({+ default: () => <div data-testid="loading" />,+}));++vi.mock('@/features/Conversation', () => ({+ ConversationProvider: (props: { children: ReactNode }) => {+ conversationProviderSpy(props);+ return <div data-testid="conversation-provider">{props.children}</div>;+ },+}));++vi.mock('@/hooks/useOperationState', () => ({+ useOperationState: () => operationState,+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: Object.assign((selector: (state: AgentState) => unknown) => selector(agentState), {+ getState: () => agentState,+ }),+}));++vi.mock('@/store/agent/selectors', () => ({+ builtinAgentSelectors: {+ pageAgentId: (state: AgentState) => state.pageAgentId,+ },+}));++vi.mock('@/store/chat', () => ({+ useChatStore: Object.assign((selector: (state: ChatState) => unknown) => selector(chatState), {+ getState: () => chatState,+ setState: (partial: Partial<ChatState>) => {+ chatState = { ...chatState, ...partial };+ },+ }),+}));++vi.mock('@/store/chat/utils/messageMapKey', () => ({+ messageMapKey: (context: { agentId?: string; scope?: string; topicId?: string | null }) =>+ `${context.scope}_${context.agentId}_${context.topicId ?? 'new'}`,+}));++beforeEach(() => {+ conversationProviderSpy.mockClear();++ agentState = {+ activeAgentId: 'page-agent',+ pageAgentId: 'page-agent',+ setActiveAgentId: vi.fn((agentId: string) => {+ agentState.activeAgentId = agentId;+ }),+ useInitBuiltinAgent: vi.fn(),+ };++ chatState = {+ activeAgentId: 'previous-agent',+ activeTopicId: 'stale-topic',+ dbMessagesMap: {},+ replaceMessages: vi.fn(),+ switchTopic: vi.fn(async () => {}),+ };+});++describe('PageAgentProvider', () => {+ it('resets a stale page topic on initial scoped agent sync only', async () => {+ const { rerender } = render(+ <PageAgentProvider>+ <div>child</div>+ </PageAgentProvider>,+ );++ await waitFor(() => {+ expect(chatState.switchTopic).toHaveBeenCalledWith(null, {+ scope: 'page',+ skipRefreshMessage: true,+ });+ });++ chatState.activeTopicId = 'created-topic';++ rerender(+ <PageAgentProvider>+ <div>child</div>+ </PageAgentProvider>,+ );++ expect(chatState.switchTopic).toHaveBeenCalledTimes(1);+ });++ it('resets transient state on scoped agent sync even without an active topic', async () => {+ chatState.activeTopicId = null;++ render(+ <PageAgentProvider>+ <div>child</div>+ </PageAgentProvider>,+ );++ await waitFor(() => {+ expect(chatState.switchTopic).toHaveBeenCalledWith(null, {+ scope: 'page',+ skipRefreshMessage: true,+ });+ });+ });++ it('resets the page topic when the scoped agent changes', async () => {+ const { rerender } = render(+ <PageAgentProvider>+ <div>child</div>+ </PageAgentProvider>,+ );++ await waitFor(() => {+ expect(chatState.switchTopic).toHaveBeenCalledTimes(1);+ });++ agentState.activeAgentId = 'next-agent';+ chatState.activeTopicId = 'other-topic';++ rerender(+ <PageAgentProvider>+ <div>child</div>+ </PageAgentProvider>,+ );++ await waitFor(() => {+ expect(chatState.switchTopic).toHaveBeenCalledTimes(2);+ });+ });+});diff --git a/src/features/PageEditor/PageAgentProvider.tsx b/src/features/PageEditor/PageAgentProvider.tsxindex 5ca8d6c40b7..db5b2c19304 100644--- a/src/features/PageEditor/PageAgentProvider.tsx+++ b/src/features/PageEditor/PageAgentProvider.tsx@@ -1,7 +1,7 @@import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';import { isChatGroupSessionId } from '@lobechat/types';-import { type ReactNode } from 'react';-import { memo, useMemo } from 'react';+import type { ReactNode } from 'react';+import { memo, useEffect, useMemo, useRef } from 'react';import Loading from '@/components/Loading/BrandTextLoading';import { ConversationProvider } from '@/features/Conversation';@@ -9,7 +9,7 @@ import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';+import type { MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface PageAgentProviderProps {@@ -21,6 +21,8 @@ export const PageAgentProvider = memo<PageAgentProviderProps>(({ children }) =>const pageAgentId = useAgentStore(builtinAgentSelectors.pageAgentId);const activeTopicId = useChatStore((s) => s.activeTopicId);const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);+ const syncedAgentIdRef = useRef<string | undefined>(undefined);useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.pageAgent);@@ -29,6 +31,33 @@ export const PageAgentProvider = memo<PageAgentProviderProps>(({ children }) =>const selectedAgentId =!activeAgentId || isChatGroupSessionId(activeAgentId) ? pageAgentId : activeAgentId;+ useEffect(() => {+ if (!selectedAgentId) return;++ if (useAgentStore.getState().activeAgentId !== selectedAgentId) {+ setActiveAgentId(selectedAgentId);+ }++ const chatState = useChatStore.getState();+ const shouldResetTopic =+ chatState.activeAgentId !== selectedAgentId || !!chatState.activeTopicId;++ if (chatState.activeAgentId !== selectedAgentId) {+ useChatStore.setState(+ { activeAgentId: selectedAgentId },+ false,+ 'PageEditor/PageAgentProvider/syncActiveAgentId',+ );+ }++ if (syncedAgentIdRef.current === selectedAgentId) return;+ syncedAgentIdRef.current = selectedAgentId;++ if (shouldResetTopic) {+ void chatState.switchTopic(null, { scope: 'page', skipRefreshMessage: true });+ }+ }, [selectedAgentId, setActiveAgentId]);+const context = useMemo<MessageMapKeyInput>(() => ({agentId: selectedAgentId,diff --git a/src/features/ResourceManager/components/Editor/FileCopilot.tsx b/src/features/ResourceManager/components/Editor/FileCopilot.tsxindex 539f26a301e..9c134949145 100644--- a/src/features/ResourceManager/components/Editor/FileCopilot.tsx+++ b/src/features/ResourceManager/components/Editor/FileCopilot.tsx@@ -1,7 +1,7 @@'use client';import { Flexbox } from '@lobehub/ui';-import { memo, useEffect } from 'react';+import { memo } from 'react';import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';import { type ActionKeys } from '@/features/ChatInput';@@ -14,7 +14,6 @@ import {import RightPanel from '@/features/RightPanel';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';const actions: ActionKeys[] = ['model', 'search'];@@ -22,34 +21,9 @@ const actions: ActionKeys[] = ['model', 'search'];* Help analyze and work with files*/const FileCopilot = memo(() => {- const [setActiveAgentId, useFetchAgentConfig] = useAgentStore((s) => [- s.setActiveAgentId,- s.useFetchAgentConfig,- ]);+ const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);const currentAgentId = useConversationStore(conversationSelectors.agentId);- useEffect(() => {- if (!currentAgentId) return;-- if (useAgentStore.getState().activeAgentId !== currentAgentId) {- setActiveAgentId(currentAgentId);- }-- const { activeAgentId, activeTopicId, switchTopic } = useChatStore.getState();-- if (activeAgentId !== currentAgentId) {- useChatStore.setState(- { activeAgentId: currentAgentId },- false,- 'ResourceManager/FileCopilot/syncActiveAgentId',- );- }-- if (activeAgentId !== currentAgentId || !!activeTopicId) {- void switchTopic(null, { scope: 'page', skipRefreshMessage: true });- }- }, [currentAgentId, setActiveAgentId]);-// Fetch agent config when activeAgentId changes to ensure it's loaded in the storeuseFetchAgentConfig(true, currentAgentId);diff --git a/src/routes/(main)/home/features/InputArea/useSend.test.ts b/src/routes/(main)/home/features/InputArea/useSend.test.tsnew file mode 100644index 00000000000..a84b99acf4c--- /dev/null+++ b/src/routes/(main)/home/features/InputArea/useSend.test.ts@@ -0,0 +1,131 @@+/**+ * @vitest-environment happy-dom+ */+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';++import { useSend } from './useSend';++const routerMock = vi.hoisted(() => ({+ push: vi.fn(),+ replace: vi.fn(),+}));++const sendMessageMock = vi.hoisted(() => vi.fn());+const clearContentMock = vi.hoisted(() => vi.fn());+const clearChatUploadFileListMock = vi.hoisted(() => vi.fn());+const clearChatContextSelectionsMock = vi.hoisted(() => vi.fn());++const chatState = vi.hoisted(() => ({+ inputMessage: 'hello',+ mainInputEditor: {+ clearContent: clearContentMock,+ getJSONState: vi.fn(() => ({ type: 'doc' })),+ },+ sendMessage: sendMessageMock,+}));++const fileState = vi.hoisted(() => ({+ chatContextSelections: [],+ chatUploadFileList: [],+ clearChatContextSelections: clearChatContextSelectionsMock,+ clearChatUploadFileList: clearChatUploadFileListMock,+}));++const homeState = vi.hoisted(() => ({+ homeInputLoading: false,+ inputActiveMode: null,+ sendAsAgent: vi.fn(),+ sendAsGroup: vi.fn(),+ sendAsResearch: vi.fn(),+ sendAsWrite: vi.fn(),+}));++const agentState = vi.hoisted(() => ({+ inboxAgentId: 'agt_inbox',+}));++vi.mock('@/hooks/useQueryRoute', () => ({+ useQueryRoute: () => routerMock,+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: typeof agentState) => unknown) => selector(agentState),+}));++vi.mock('@/store/agent/selectors', () => ({+ builtinAgentSelectors: {+ inboxAgentId: (state: typeof agentState) => state.inboxAgentId,+ },+}));++vi.mock('@/store/chat', () => {+ const useChatStore = (selector: (state: typeof chatState) => unknown) => selector(chatState);+ useChatStore.getState = () => chatState;++ return { useChatStore };+});++vi.mock('@/store/file', () => {+ const useFileStore = (selector: (state: typeof fileState) => unknown) => selector(fileState);+ useFileStore.getState = () => fileState;++ return {+ fileChatSelectors: {+ chatContextSelections: (state: typeof fileState) => state.chatContextSelections,+ chatUploadFileList: (state: typeof fileState) => state.chatUploadFileList,+ },+ useFileStore,+ };+});++vi.mock('@/store/home', () => {+ const useHomeStore = (selector: (state: typeof homeState) => unknown) => selector(homeState);+ useHomeStore.getState = () => homeState;++ return { useHomeStore };+});++describe('Home InputArea useSend', () => {+ beforeEach(() => {+ routerMock.push.mockReset();+ routerMock.replace.mockReset();+ sendMessageMock.mockReset();+ clearContentMock.mockReset();+ clearChatUploadFileListMock.mockReset();+ clearChatContextSelectionsMock.mockReset();+ });++ it('routes cold homepage sends to the created topic instead of relying on ChatHydration timing', async () => {+ const { result } = renderHook(() => useSend());+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => undefined,+ getMarkdownContent: () => 'hello',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(sendMessageMock).toHaveBeenCalledWith(+ expect.objectContaining({+ context: { agentId: 'agt_inbox', isolatedTopic: true },+ message: 'hello',+ onTopicCreated: expect.any(Function),+ }),+ );+ expect(routerMock.push).toHaveBeenCalledWith('/agent/agt_inbox');++ const sentPayload = sendMessageMock.mock.calls[0][0];++ await act(async () => {+ await sentPayload.onTopicCreated('tpc_created');+ });++ expect(routerMock.replace).toHaveBeenCalledWith('/agent/agt_inbox/tpc_created');+ });+});diff --git a/src/routes/(main)/home/features/InputArea/useSend.ts b/src/routes/(main)/home/features/InputArea/useSend.tsindex d0a706784f8..c7e500f1791 100644--- a/src/routes/(main)/home/features/InputArea/useSend.ts+++ b/src/routes/(main)/home/features/InputArea/useSend.ts@@ -1,4 +1,4 @@-import { SESSION_CHAT_URL } from '@lobechat/const';+import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@lobechat/const';import { useCallback } from 'react';import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';@@ -85,11 +85,14 @@ export const useSend = () => {await ensureAgentConfigLoaded(activeAgentId);sendMessage({- context: { agentId: activeAgentId },+ context: { agentId: activeAgentId, isolatedTopic: true },contexts: contextList,editorData,files: fileList,message: inputMessage,+ onTopicCreated: (topicId) => {+ router.replace(SESSION_CHAT_TOPIC_URL(activeAgentId, topicId, false));+ },});router.push(SESSION_CHAT_URL(activeAgentId, false));