๐คฏ 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): stabilize topic creation lifecycle (#16467)
YuTengjing30da7020f307
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsxindex b21f754edde..d76ce3e5688 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsx@@ -17,28 +17,7 @@ const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {const handleSave = useCallback(async (newTitle: string) => {- try {- // Set loading state- useChatStore.setState(- {- topicLoadingIds: [...useChatStore.getState().topicLoadingIds, id],- },- false,- 'setTopicUpdating',- );- await updateTopicTitle(id, newTitle);- } finally {- // Clear loading state- useChatStore.setState(- {- topicLoadingIds: useChatStore- .getState()- .topicLoadingIds.filter((loadingId) => loadingId !== id),- },- false,- 'clearTopicUpdating',- );- }+ await updateTopicTitle(id, newTitle);},[id, updateTopicTitle],);diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsxindex 8ca2b992ef5..e119995e111 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/Editing.tsx@@ -20,28 +20,7 @@ const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {const handleUpdate = useCallback(async () => {if (newTitle && title !== newTitle) {- try {- // Set loading state- useChatStore.setState(- {- topicLoadingIds: [...useChatStore.getState().topicLoadingIds, id],- },- false,- 'setTopicUpdating',- );- await updateTopicTitle(id, newTitle);- } finally {- // Clear loading state- useChatStore.setState(- {- topicLoadingIds: useChatStore- .getState()- .topicLoadingIds.filter((loadingId) => loadingId !== id),- },- false,- 'clearTopicUpdating',- );- }+ await updateTopicTitle(id, newTitle);}toggleEditing(false);}, [newTitle, title, id, updateTopicTitle, toggleEditing]);diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 01e94700b5a..aae523d5dfb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -1,5 +1,5 @@import type * as LobechatConstModule from '@lobechat/const';-import { act, renderHook } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';import { TRPCClientError } from '@trpc/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -468,6 +468,317 @@ describe('ConversationLifecycle actions', () => {expect(result.current.executeClientAgent).toHaveBeenCalled();});+ it('should show an optimistic topic while the first message is still creating the server topic', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;+ let resolveServerSend!: (value: any) => void;+ const serverSendPromise = new Promise<any>((resolve) => {+ resolveServerSend = resolve;+ });+ let resolveExecute!: () => void;+ const executePromise = new Promise<void>((resolve) => {+ resolveExecute = resolve;+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeClientAgent: vi.fn().mockReturnValue(executePromise),+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ const sendMessageInServerSpy = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockReturnValue(serverSendPromise);++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: '**666**',+ });+ });++ await waitFor(() => expect(sendMessageInServerSpy).toHaveBeenCalled());++ const optimisticTopic = useChatStore.getState().topicDataMap[topicKey]?.items[0];+ expect(optimisticTopic).toEqual(+ expect.objectContaining({+ sessionId: agentId,+ title: '666',+ }),+ );+ expect(optimisticTopic?.id).toMatch(/^tmp_topic_/);+ expect(useChatStore.getState().topicLoadingIds).toContain(optimisticTopic!.id);++ await act(async () => {+ resolveServerSend({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: newTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ],+ topicId: newTopicId,+ topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ });++ await waitFor(() =>+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id).toBe(newTopicId),+ );+ const finalTopics = useChatStore.getState().topicDataMap[topicKey]?.items ?? [];+ expect(finalTopics).toEqual([expect.objectContaining({ id: newTopicId })]);+ expect(finalTopics.some((topic) => topic.id === optimisticTopic?.id)).toBe(false);+ expect(useChatStore.getState().topicLoadingIds).not.toContain(optimisticTopic!.id);+ expect(useChatStore.getState().topicLoadingIds).toContain(newTopicId);++ await act(async () => {+ resolveExecute();+ await sendPromise;+ });++ expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);+ });++ it('should rollback an optimistic topic if the create response resolves without a topic id', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeClientAgent: vi.fn().mockResolvedValue(undefined),+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ expect(useChatStore.getState().topicDataMap[topicKey]?.items ?? []).toEqual([]);+ expect(useChatStore.getState().topicLoadingIds).toEqual([]);+ expect(useChatStore.getState().topicLoadingIdCounts).toEqual({});+ });++ it('should show a group optimistic topic in the group topic bucket', async () => {+ const { result } = renderHook(() => useChatStore());+ const groupId = 'group-1';+ const supervisorAgentId = 'supervisor-agent';+ const groupKey = topicMapKey({ groupId });+ const groupAgentKey = topicMapKey({ agentId: supervisorAgentId, groupId });+ let resolveServerSend!: (value: any) => void;+ const serverSendPromise = new Promise<any>((resolve) => {+ resolveServerSend = resolve;+ });++ vi.spyOn(agentGroupStore, 'getChatGroupStoreState').mockReturnValue({+ groupMap: {+ [groupId]: {+ id: groupId,+ supervisorAgentId,+ },+ },+ } as any);++ act(() => {+ useChatStore.setState({+ activeAgentId: undefined,+ activeGroupId: groupId,+ activeTopicId: undefined,+ executeClientAgent: vi.fn().mockResolvedValue(undefined),+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [groupKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockReturnValue(serverSendPromise);++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: {+ agentId: supervisorAgentId,+ groupId,+ scope: 'group',+ threadId: null,+ topicId: null,+ },+ message: 'Group first message',+ });+ });++ await waitFor(() =>+ expect(useChatStore.getState().topicDataMap[groupKey]?.items[0]?.id).toMatch(+ /^tmp_topic_/,+ ),+ );++ const optimisticTopic = useChatStore.getState().topicDataMap[groupKey]?.items[0];+ expect(optimisticTopic).toEqual(+ expect.objectContaining({+ title: 'Group first message',+ }),+ );+ expect(useChatStore.getState().topicDataMap[groupAgentKey]?.items ?? []).toEqual([]);++ await act(async () => {+ resolveServerSend({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: TEST_IDS.NEW_TOPIC_ID,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: TEST_IDS.NEW_TOPIC_ID,+ }),+ ],+ topicId: TEST_IDS.NEW_TOPIC_ID,+ topics: { items: [{ id: TEST_IDS.NEW_TOPIC_ID, title: 'Group Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ await sendPromise;+ });++ expect(useChatStore.getState().topicDataMap[groupKey]?.items).toEqual([+ expect.objectContaining({ id: TEST_IDS.NEW_TOPIC_ID, title: 'Group Topic' }),+ ]);+ expect(useChatStore.getState().topicDataMap[groupAgentKey]?.items ?? []).toEqual([]);+ });++ it('should clear the active temp topic when rolling back an optimistic topic', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ let resolveServerSend!: (value: any) => void;+ const serverSendPromise = new Promise<any>((resolve) => {+ resolveServerSend = resolve;+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeClientAgent: vi.fn().mockResolvedValue(undefined),+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockReturnValue(serverSendPromise);++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ await waitFor(() =>+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id).toMatch(+ /^tmp_topic_/,+ ),+ );+ const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]!.items[0].id;++ act(() => {+ useChatStore.setState({ activeTopicId: optimisticTopicId });+ });++ await act(async () => {+ resolveServerSend({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ await sendPromise;+ });++ expect(useChatStore.getState().topicDataMap[topicKey]?.items ?? []).toEqual([]);+ expect(useChatStore.getState().activeTopicId).not.toBe(optimisticTopicId);+ });+it('should persist selected tool tags into user message content before runtime execution', async () => {const { result } = renderHook(() => useChatStore());@@ -1856,6 +2167,44 @@ describe('ConversationLifecycle actions', () => {);});+ it('CLIENT new-topic path: summaryTopicTitle still runs when the response omits isCreateNewTopic', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;++ const summaryTopicTitleSpy = vi.fn().mockResolvedValue(undefined);+ act(() => {+ useChatStore.setState({ summaryTopicTitle: summaryTopicTitleSpy });+ });++ const persistedMessages = [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', topicId: newTopicId }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ];++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: persistedMessages,+ topicId: newTopicId,+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ expect(summaryTopicTitleSpy).toHaveBeenCalledWith(newTopicId, expect.any(Array));+ });+it('CLIENT existing-topic with EMPTY title: summaryTopicTitle IS invoked', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 3fd4b8b52af..484c857dc5b 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -509,6 +509,17 @@ describe('GatewayActionImpl', () => {function createExecuteTestAction() {const mockClient = createMockClient();const state: Record<string, any> = { gatewayConnections: {}, topicDataMap: {} };+ const associateMessageWithOperation = vi.fn();+ const connectToGateway = vi.fn();+ const internalDispatchTopic = vi.fn();+ const internalReplaceTopicId = vi.fn();+ const internalUpdateTopicLoading = vi.fn();+ const onOperationCancel = vi.fn();+ const replaceMessages = vi.fn();+ const refreshTopic = vi.fn().mockResolvedValue(undefined);+ const startOperation = vi.fn(() => ({ operationId: 'gw-op-1' }));+ const switchTopic = vi.fn();+ const updateTopicStatus = vi.fn();const set = vi.fn((updater: any) => {if (typeof updater === 'function') {Object.assign(state, updater(state));@@ -519,14 +530,17 @@ describe('GatewayActionImpl', () => {const get = vi.fn(() => ({...state,- associateMessageWithOperation: vi.fn(),- connectToGateway: vi.fn(),- internal_dispatchTopic: vi.fn(),- internal_updateTopicLoading: vi.fn(),- onOperationCancel: vi.fn(),- replaceMessages: vi.fn(),- startOperation: vi.fn(() => ({ operationId: 'gw-op-1' })),- switchTopic: vi.fn(),+ associateMessageWithOperation,+ connectToGateway,+ internal_dispatchTopic: internalDispatchTopic,+ internal_replaceTopicId: internalReplaceTopicId,+ internal_updateTopicLoading: internalUpdateTopicLoading,+ onOperationCancel,+ replaceMessages,+ refreshTopic,+ startOperation,+ switchTopic,+ updateTopicStatus,})) as any;// Set up window.global_serverConfigStore@@ -541,7 +555,24 @@ describe('GatewayActionImpl', () => {const action = new GatewayActionImpl(set as any, get, undefined);action.createClient = vi.fn(() => mockClient);- return { action, get, mockClient, set, state };+ return {+ action,+ associateMessageWithOperation,+ connectToGateway,+ get,+ internalDispatchTopic,+ internalReplaceTopicId,+ internalUpdateTopicLoading,+ mockClient,+ onOperationCancel,+ replaceMessages,+ refreshTopic,+ set,+ startOperation,+ state,+ switchTopic,+ updateTopicStatus,+ };}afterEach(() => {@@ -613,6 +644,42 @@ describe('GatewayActionImpl', () => {);});+ it('should replace the optimistic topic placeholder with the server topic id', async () => {+ const { action, internalReplaceTopicId } = createExecuteTestAction();++ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'ast-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'test-token',+ topicId: 'topic-1',+ userMessageId: 'usr-1',+ });++ await action.executeGatewayAgent({+ context: { agentId: 'agent-1', topicId: null, threadId: null, scope: 'main' },+ message: '666',+ optimisticTopic: { id: 'tmp-topic', title: '666' },+ });++ expect(internalReplaceTopicId).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: undefined,+ nextId: 'topic-1',+ previousId: 'tmp-topic',+ value: {+ sessionId: 'agent-1',+ title: '666',+ },+ });+ });+it('should forward metadata trigger to execAgentTask', async () => {const { action } = createExecuteTestAction();diff --git a/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts b/src/store/chat/slices/agentRun/actions/__tests__/helpers.tsindex 58c5faacedd..f2e4d640799 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/helpers.ts@@ -114,6 +114,8 @@ export const resetTestEnvironment = () => {activeTopicId: TEST_IDS.TOPIC_ID,messagesMap: {},toolCallingStreamIds: {},+ topicLoadingIdCounts: {},+ topicLoadingIds: [],},false,);diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex fabb5251213..7a76cd893f5 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -121,6 +121,11 @@ type SendMessageServerResponseMeta = SendMessageServerResponse & {__isPartialMessages?: boolean;};+interface OptimisticTopicPlaceholder {+ id: string;+ title: string;+}+/*** Actions managing the complete lifecycle of conversations including sending,* regenerating, and resending messages@@ -392,6 +397,8 @@ export class ConversationLifecycleActionImpl {// if message is empty or no files, then stopif (!message && !hasFile) return;+ const newTopicTitle = markdownToTxt(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });+// โโโ Message Queue: enqueue if agent is currently running โโโ// Check if there's a running agent-runtime operation in the current context.// If so, enqueue the message instead of starting a new operation. Covers all@@ -546,6 +553,89 @@ export class ConversationLifecycleActionImpl {this.#get().associateMessageWithOperation(tempId, operationId);this.#get().associateMessageWithOperation(tempAssistantId, operationId);+ const optimisticTopic: OptimisticTopicPlaceholder | undefined =+ !operationContext.topicId && !context.isolatedTopic+ ? { id: `tmp_topic_${nanoid()}`, title: newTopicTitle }+ : undefined;+ let optimisticTopicActive = false;+ let optimisticTopicResolved = false;++ // Group main topic lists are keyed by `group_${groupId}`. Keeping the+ // supervisor agent id here would write "group first message" placeholders+ // into `group_agent_${groupId}_${agentId}`, invisible to the group sidebar.+ const topicListAgentId =+ operationContext.groupId && operationContext.scope === 'group'+ ? undefined+ : operationContext.agentId;+ const optimisticTopicScope = {+ agentId: topicListAgentId,+ groupId: operationContext.groupId ?? undefined,+ };++ const addResolvedTopicPlaceholder = (topicId: string, title: string, action: string) => {+ this.#get().internal_dispatchTopic(+ {+ ...optimisticTopicScope,+ type: 'addTopic',+ value: {+ id: topicId,+ ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),+ title,+ },+ },+ action,+ );+ };++ const resolveOptimisticTopic = (topicId: string, title = optimisticTopic?.title) => {+ if (!optimisticTopic || !optimisticTopicActive) {+ addResolvedTopicPlaceholder(+ topicId,+ title || t('defaultTitle', { ns: 'topic' }),+ 'sendMessage/reconcileOptimisticTopic/add',+ );+ return;+ }++ this.#get().internal_replaceTopicId({+ ...optimisticTopicScope,+ nextId: topicId,+ previousId: optimisticTopic.id,+ value: {+ ...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),+ title: title || t('defaultTitle', { ns: 'topic' }),+ },+ });+ optimisticTopicActive = false;+ optimisticTopicResolved = true;+ };++ const rollbackOptimisticTopic = (action: string) => {+ if (!optimisticTopic || !optimisticTopicActive) return;++ this.#get().internal_updateTopicLoading(optimisticTopic.id, false);+ if (this.#get().activeTopicId === optimisticTopic.id) {+ void this.#get().switchTopic(null, { skipRefreshMessage: true });+ }+ this.#get().internal_dispatchTopic(+ { ...optimisticTopicScope, type: 'deleteTopic', id: optimisticTopic.id },+ action,+ );+ optimisticTopicActive = false;+ };++ if (optimisticTopic) {+ // Input "666" used to leave the sidebar unchanged until the server returned+ // a topicId; insert a temporary topic so the new conversation is visible immediately.+ addResolvedTopicPlaceholder(+ optimisticTopic.id,+ optimisticTopic.title,+ 'sendMessage/optimisticCreateTopic',+ );+ this.#get().internal_updateTopicLoading(optimisticTopic.id, true);+ optimisticTopicActive = true;+ }+// Store editor state in operation metadata for cancel restorationconst jsonState = inputEditorData ?? mainInputEditor?.getJSONState();this.#get().updateOperationMetadata(operationId, {@@ -590,7 +680,7 @@ export class ConversationLifecycleActionImpl {newTopic: !operationContext.topicId? {metadata: workingDirectory ? { workingDirectory } : undefined,- title: markdownToTxt(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' }),+ title: newTopicTitle,topicMessageIds: messages.map((m) => m.id),}: undefined,@@ -604,7 +694,7 @@ export class ConversationLifecycleActionImpl {},threadId: operationContext.threadId ?? undefined,topicFilter: this.#getTopicFilter(- operationContext.agentId,+ topicListAgentId,operationContext.groupId ?? undefined,),topicPageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),@@ -618,10 +708,14 @@ export class ConversationLifecycleActionImpl {message: e instanceof Error ? e.message : 'Unknown error',type: 'HeterogeneousAgentError',});+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');return;}- if (!heteroData) return;+ if (!heteroData) {+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ return;+ }// Update context with server-created topicIdconst heteroContext = {@@ -647,13 +741,19 @@ export class ConversationLifecycleActionImpl {// Handle new topic creationif (heteroData.isCreateNewTopic && heteroData.topicId) {if (heteroData.topics) {+ if (optimisticTopic && optimisticTopicActive) {+ resolveOptimisticTopic(heteroData.topicId, newTopicTitle);+ }const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());- this.#get().internal_updateTopics(operationContext.agentId, {+ this.#get().internal_updateTopics(topicListAgentId, {groupId: operationContext.groupId,items: heteroData.topics.items,pageSize,total: heteroData.topics.total,});+ } else if (!context.isolatedTopic) {+ resolveOptimisticTopic(heteroData.topicId, newTopicTitle);+ void Promise.resolve(this.#get().refreshTopic()).catch(console.error);}await this.#get().switchTopic(heteroData.topicId, {clearNewKey: true,@@ -693,7 +793,9 @@ export class ConversationLifecycleActionImpl {// branch returns early (line 498) and never reaches that clear.this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });- if (heteroData.topicId) this.#get().internal_updateTopicLoading(heteroData.topicId, true);+ if (heteroData.topicId && !optimisticTopicResolved) {+ this.#get().internal_updateTopicLoading(heteroData.topicId, true);+ }// Start heterogeneous agent executionconst { operationId: heteroOpId } = this.#get().startOperation({@@ -769,6 +871,7 @@ export class ConversationLifecycleActionImpl {message,metadata: requestMetadata,parentOperationId: operationId,+ optimisticTopic,// Pass temp message IDs so the UI doesn't show a blank loading// state while waiting for the first step_start event to replace// messages with the server's real IDs.@@ -792,6 +895,8 @@ export class ConversationLifecycleActionImpl {topicId: result.topicId,}).catch(console.error);+ } else {+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');}return {@@ -803,19 +908,29 @@ export class ConversationLifecycleActionImpl {// the op to 'cancelled' and `executeGatewayAgent` cleaned up the// server task. Don't clobber that with 'failed'.const op = this.#get().operations[operationId];- if (op?.status === 'cancelled') return;+ if (op?.status === 'cancelled') {+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ return;+ }console.error('[Gateway] Failed to start server-side agent:', e);this.#get().failOperation(operationId, {message: e instanceof Error ? e.message : 'Unknown error',type: 'GatewayError',});+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');return;}}// โโ Client mode: send via server API then run agent locally โโlet data: SendMessageServerResponse | undefined;+ const isCreatedTopicResponse = (response?: SendMessageServerResponse) =>+ Boolean(+ response &&+ (response.isCreateNewTopic || (!operationContext.topicId && !!response.topicId)),+ );+try {const { model, provider } = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());@@ -846,8 +961,6 @@ export class ConversationLifecycleActionImpl {const toolContext = formatSelectedToolsContext(dedupedTools);const contextSuffix = [skillContext, toolContext].filter(Boolean).join('\n');const persistedContent = contextSuffix ? `${message}\n\n${contextSuffix}` : message;- const newTopicTitle = message.slice(0, 80) || t('defaultTitle', { ns: 'topic' });-data = await aiChatService.sendMessageInServer({newUserMessage: {@@ -862,7 +975,7 @@ export class ConversationLifecycleActionImpl {// if there is topicId, then add topicId to messagetopicId: topicId ?? undefined,topicFilter: this.#getTopicFilter(- operationContext.agentId,+ topicListAgentId,operationContext.groupId ?? undefined,),topicPageSize: systemStatusSelectors.topicPageSize(useGlobalStore.getState()),@@ -898,6 +1011,7 @@ export class ConversationLifecycleActionImpl {// Use created topicId/threadId if available, otherwise use original from contextlet finalTopicId = data.topicId ?? operationContext.topicId;const finalThreadId = data.createdThreadId ?? operationContext.threadId;+ const isCreateNewTopic = isCreatedTopicResponse(data);// refresh the total dataif (data?.topics) {@@ -908,8 +1022,11 @@ export class ConversationLifecycleActionImpl {// Otherwise the newly created isolated-trigger topic would flash in the// main sidebar until the next SWR revalidation filters it out.if (!context.isolatedTopic) {+ if (optimisticTopic && optimisticTopicActive && data.topicId) {+ resolveOptimisticTopic(data.topicId, newTopicTitle);+ }const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());- this.#get().internal_updateTopics(operationContext.agentId, {+ this.#get().internal_updateTopics(topicListAgentId, {groupId: operationContext.groupId,items: data.topics.items,pageSize,@@ -919,17 +1036,8 @@ export class ConversationLifecycleActionImpl {// Record the created topicId in metadata (not context)this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });}- } else if (data.isCreateNewTopic && data.topicId && !context.isolatedTopic) {- this.#get().internal_dispatchTopic(- {- type: 'addTopic',- value: {- id: data.topicId,- title: newTopicTitle,- },- },- 'sendMessage/createTopicPlaceholder',- );+ } else if (isCreateNewTopic && data.topicId && !context.isolatedTopic) {+ resolveOptimisticTopic(data.topicId, newTopicTitle);this.#get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });void Promise.resolve(this.#get().refreshTopic()).catch(console.error);} else if (operationContext.topicId) {@@ -986,7 +1094,7 @@ export class ConversationLifecycleActionImpl {action: 'sendMessage/serverResponse',});- if (data.isCreateNewTopic && data.topicId) {+ if (isCreateNewTopic && data.topicId) {if (context.isolatedTopic) {// Notify the isolated caller immediately so its UI re-subscribes to// the new topic key and picks up the streaming AI response.@@ -1001,6 +1109,7 @@ export class ConversationLifecycleActionImpl {}} catch (e) {console.error(e);+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');// Fail operation on errorthis.#get().failOperation(operationId, {type: e instanceof Error ? e.name : 'unknown_error',@@ -1022,7 +1131,7 @@ export class ConversationLifecycleActionImpl {}} finally {// A new topic was created, or the user cancelled the message (or it failed), so data is absent here- if (data?.isCreateNewTopic || !data) {+ if (isCreatedTopicResponse(data) || !data) {this.#get().internal_dispatchMessage({ type: 'deleteMessages', ids: [tempId, tempAssistantId] },{ operationId },@@ -1035,9 +1144,16 @@ export class ConversationLifecycleActionImpl {this.#get().updateOperationMetadata(operationId, { inputEditorTempState: null });}- if (!data) return;+ if (!data) {+ rollbackOptimisticTopic('sendMessage/rollbackOptimisticTopic');+ return;+ }++ rollbackOptimisticTopic('sendMessage/rollbackUnresolvedOptimisticTopic');- if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, true);+ if (data.topicId && !optimisticTopicResolved) {+ this.#get().internal_updateTopicLoading(data.topicId, true);+ }// Topic title auto-generation, now via the shared `afterUserMessagePersisted`// hook. The client passes its freshly-created `data.messages`@@ -1047,7 +1163,7 @@ export class ConversationLifecycleActionImpl {.afterUserMessagePersisted({assistantMessageId: data.assistantMessageId,context: operationContext,- isCreateNewTopic: data.isCreateNewTopic,+ isCreateNewTopic: isCreatedTopicResponse(data),messages: data.messages,operationId,runId: operationId,@@ -1179,7 +1295,9 @@ export class ConversationLifecycleActionImpl {} catch (e) {console.error(e);} finally {- if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, false);+ if (data.topicId) {+ this.#get().internal_updateTopicLoading(data.topicId, false);+ }}}@@ -1187,7 +1305,7 @@ export class ConversationLifecycleActionImpl {return {assistantMessageId: data.assistantMessageId,createdThreadId: data.createdThreadId,- createdTopicId: data.isCreateNewTopic ? data.topicId : undefined,+ createdTopicId: isCreatedTopicResponse(data) ? data.topicId : undefined,userMessageId: data.userMessageId,};};diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.tsindex 5cf662db026..4b36f1428ff 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts@@ -211,6 +211,38 @@ describe('buildRunLifecycle.afterUserMessagePersisted โ topic title (all runtiexpect(store.summaryTopicTitle).toHaveBeenCalledWith('t1', messages);});+ it('dev-slice title update does not clear the client runtime loading owner', async () => {+ const previous = process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC;+ process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC = '1';++ try {+ const { get, store } = makeStore();+ const messages = [+ { content: '้ ่ฏปไธ้ข็ๆๆ๏ผๆ นๆฎ่ฆๆฑๅไฝใ', id: 'm1', role: 'user' } as any,+ ];++ await lifecycle('client', get, 'top_level').afterUserMessagePersisted(+ persistedEvent('client', 'top_level', {+ isCreateNewTopic: true,+ messages,+ topicId: 't1',+ }),+ );++ expect(store.internal_updateTopic).toHaveBeenCalledWith('t1', {+ title: '้ ่ฏปไธ้ข็ๆๆ๏ผๆ นๆฎ่ฆๆฑๅไฝใ',+ });+ expect(store.internal_updateTopicLoading).not.toHaveBeenCalledWith('t1', false);+ expect(store.summaryTopicTitle).not.toHaveBeenCalled();+ } finally {+ if (previous === undefined) {+ delete process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC;+ } else {+ process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC = previous;+ }+ }+ });+it('loads the topic first when it is absent from the store (gateway fire-and-forget refreshTopic race)', async () => {const { get, store } = makeStore(); // topicMaps empty โ getTopicById returns undefinedconst messages = [{ content: 'hi', id: 'm1', role: 'user' } as any];diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex d8dbbee6f8b..5e7f0b0cb9a 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -195,9 +195,10 @@ export const buildRunLifecycle = (}const firstUserText = messages.find((m) => m.role === 'user')?.content?.trim() ?? '';const title = markdownToTxt(firstUserText).slice(0, 80) || 'New Topic';+ // `internal_updateTopic` already balances its own loading owner. For a+ // new client-runtime topic like "้ ่ฏปไธ้ข...", an extra `false` here would+ // consume the runtime's loading owner and hide the sidebar spinner early.await get().internal_updateTopic(tid, { title });- // summaryTopicTitle would normally clear loading via onLoadingChange; do it manually.- get().internal_updateTopicLoading(tid, false);console.info('[dev] sliced topic title (NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC=1):', title);};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex cbeb253e020..65cf8338355 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -365,6 +365,8 @@ export class GatewayActionImpl {metadata?: Pick<MessageMetadata, 'trigger'>;/** Called when the gateway session completes (agent finished running) */onComplete?: () => void;+ /** Temporary sidebar topic inserted by sendMessage before the server creates the real topic. */+ optimisticTopic?: { id: string; title: string };/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */parentMessageId?: string;/**@@ -397,6 +399,7 @@ export class GatewayActionImpl {message,metadata,onComplete,+ optimisticTopic,parentMessageId,parentOperationId,resumeApproval,@@ -487,6 +490,18 @@ export class GatewayActionImpl {if (isCreateNewTopic && result.topicId) {// Topic created successfully โ now safe to clear the pending repo selection.if (context.agentId) consumePendingTopicRepos(context.agentId);+ if (optimisticTopic) {+ this.#get().internal_replaceTopicId({+ agentId: context.agentId,+ groupId: context.groupId,+ nextId: result.topicId,+ previousId: optimisticTopic.id,+ value: {+ ...(context.groupId ? {} : { sessionId: context.agentId }),+ title: optimisticTopic.title,+ },+ });+ }try {const newContext = { ...context, topicId: result.topicId };const messages = await messageService.getMessages(newContext);@@ -520,7 +535,7 @@ export class GatewayActionImpl {const execContext = { ...context, topicId: result.topicId };if (result.topicId) {- this.#get().internal_updateTopicLoading(result.topicId, true);+ if (!optimisticTopic) this.#get().internal_updateTopicLoading(result.topicId, true);void this.#get().updateTopicStatus?.({agentId: context.agentId,groupId: context.groupId,diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 1b6b997eb02..c4b22a4324c 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -76,6 +76,7 @@ beforeEach(() => {activeTopicId: undefined,searchTopics: [],topicDataMap: {},+ topicLoadingIdCounts: {},topicLoadingIds: [],// ... initial state},@@ -177,6 +178,46 @@ describe('topic action', () => {);expect(topicId).toEqual('new-topic-id');});++ it('should release the fire-and-forget summary loading owner when title summary finishes', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [{ id: 'message1' }, { id: 'message2' }] as UIChatMessage[];+ let resolveSummary!: () => void;+ const summaryPromise = new Promise<void>((resolve) => {+ resolveSummary = resolve;+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: 'session-id',+ messagesMap: {+ [messageMapKey({ agentId: 'session-id' })]: messages,+ },+ topicLoadingIdCounts: {},+ topicLoadingIds: [],+ });+ });++ vi.spyOn(result.current, 'internal_createTopic').mockResolvedValue('new-topic-id');+ vi.spyOn(result.current, 'summaryTopicTitle').mockReturnValue(summaryPromise);++ await act(async () => {+ await result.current.saveToTopic();+ });++ expect(useChatStore.getState().topicLoadingIds).toEqual(['new-topic-id']);+ expect(useChatStore.getState().topicLoadingIdCounts).toEqual({ 'new-topic-id': 1 });++ await act(async () => {+ resolveSummary();+ await summaryPromise;+ });++ await waitFor(() => {+ expect(useChatStore.getState().topicLoadingIds).toEqual([]);+ expect(useChatStore.getState().topicLoadingIdCounts).toEqual({});+ });+ });});describe('refreshTopic', () => {beforeEach(() => {@@ -1279,6 +1320,52 @@ describe('topic action', () => {expect(switchTopicSpy).toHaveBeenCalled();});});+ describe('internal_updateTopic', () => {+ it('should release the loading owner when updating a topic fails', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'agent-1';+ const topicId = 'topic-1';+ const key = topicMapKey({ agentId });+ const topic: ChatTopic = {+ createdAt: Date.now(),+ favorite: false,+ id: topicId,+ sessionId: agentId,+ title: 'Topic',+ updatedAt: Date.now(),+ };++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ topicDataMap: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [topic],+ pageSize: 20,+ total: 1,+ },+ },+ topicLoadingIdCounts: {},+ topicLoadingIds: [],+ });+ });++ vi.spyOn(topicService, 'updateTopic').mockRejectedValue(new Error('rename failed'));++ await act(async () => {+ await expect(+ result.current.internal_updateTopic(topicId, { title: 'New' }),+ ).rejects.toThrow('rename failed');+ });++ expect(useChatStore.getState().topicLoadingIds).not.toContain(topicId);+ expect(useChatStore.getState().topicLoadingIdCounts[topicId]).toBeUndefined();+ });+ });describe('updateTopicLoading', () => {it('should call update topicLoadingId', async () => {const { result } = renderHook(() => useChatStore());@@ -1295,12 +1382,94 @@ describe('topic action', () => {expect(result.current.topicLoadingIds).toEqual(['loading-id']);});++ it('should keep a topic loading until all loading owners finish', () => {+ const { result } = renderHook(() => useChatStore());+ act(() => {+ useChatStore.setState({ topicLoadingIdCounts: {}, topicLoadingIds: [] });+ });++ act(() => {+ result.current.internal_updateTopicLoading('topic-1', true);+ result.current.internal_updateTopicLoading('topic-1', true);+ });++ expect(result.current.topicLoadingIds).toEqual(['topic-1']);+ expect(result.current.topicLoadingIdCounts).toEqual({ 'topic-1': 2 });++ act(() => {+ result.current.internal_updateTopicLoading('topic-1', false);+ });++ expect(result.current.topicLoadingIds).toEqual(['topic-1']);+ expect(result.current.topicLoadingIdCounts).toEqual({ 'topic-1': 1 });++ act(() => {+ result.current.internal_updateTopicLoading('topic-1', false);+ });++ expect(result.current.topicLoadingIds).toEqual([]);+ expect(result.current.topicLoadingIdCounts).toEqual({});+ });+ });+ describe('replaceTopicId', () => {+ it('should migrate a loading optimistic topic to the server topic id', () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'agent-1';+ const key = topicMapKey({ agentId });+ const optimisticTopic: ChatTopic = {+ createdAt: Date.now(),+ favorite: false,+ id: 'tmp_topic_1',+ sessionId: agentId,+ title: '666',+ updatedAt: Date.now(),+ };++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ topicDataMap: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [optimisticTopic],+ pageSize: 20,+ total: 1,+ },+ },+ topicLoadingIdCounts: { tmp_topic_1: 2 },+ topicLoadingIds: ['tmp_topic_1'],+ });+ });++ act(() => {+ result.current.internal_replaceTopicId({+ agentId,+ nextId: 'topic-1',+ previousId: 'tmp_topic_1',+ value: { sessionId: agentId },+ });+ });++ expect(result.current.topicDataMap[key].items).toEqual([+ expect.objectContaining({+ id: 'topic-1',+ sessionId: agentId,+ title: '666',+ }),+ ]);+ expect(result.current.topicLoadingIds).toEqual(['topic-1']);+ expect(result.current.topicLoadingIdCounts).toEqual({ 'topic-1': 2 });+ });});describe('summaryTopicTitle', () => {- it('should auto-summarize the topic title and update it', async () => {+ it('should show a loading placeholder when auto-summarizing a topic without a title', async () => {const topicId = 'topic-1';const messages = [{ id: 'message-1', content: 'Hello' }] as UIChatMessage[];- const topics = [{ id: 'topic-1', title: 'Test Topic' }] as ChatTopic[];+ const topics = [{ id: 'topic-1', title: '' }] as ChatTopic[];const { result } = renderHook(() => useChatStore());await act(async () => {useChatStore.setState({@@ -1342,6 +1511,47 @@ describe('topic action', () => {// TODO: need to test with fetchPresetTaskResult});++ it('should keep an optimistic title visible until the summarized title is ready', async () => {+ const topicId = 'topic-1';+ const messages = [{ id: 'message-1', content: 'Hello' }] as UIChatMessage[];+ const optimisticTitle = '้ ่ฏปไธ้ข็ๆๆ๏ผๆ นๆฎ่ฆๆฑๅไฝใ';+ const topics = [{ id: topicId, title: optimisticTitle }] as ChatTopic[];+ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ useChatStore.setState({+ topicDataMap: {+ [topicMapKey({ agentId: 'test' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: 'test',+ });+ });++ const updateTopicTitleInSummarySpy = vi.spyOn(+ result.current,+ 'internal_updateTopicTitleInSummary',+ );+ const updateTopicSpy = vi.spyOn(result.current, 'internal_updateTopic');++ vi.spyOn(chatService, 'fetchPresetTaskResult').mockImplementation(async (params) => {+ params?.onMessageHandle?.({ type: 'text', text: 'Partial Title' } as any);+ await params?.onFinish?.('Summarized Title', { type: 'done' });+ });++ await act(async () => {+ await result.current.summaryTopicTitle(topicId, messages);+ });++ expect(updateTopicTitleInSummarySpy).not.toHaveBeenCalledWith(topicId, LOADING_FLAT);+ expect(updateTopicTitleInSummarySpy).not.toHaveBeenCalledWith(topicId, 'Partial Title');+ expect(updateTopicSpy).toHaveBeenCalledWith(topicId, { title: 'Summarized Title' });+ });});describe('createTopic', () => {it('should create a new topic and update the store', async () => {diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex f42e9ae3c1f..65b0a054b91 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -138,8 +138,15 @@ export class ChatTopicActionImpl {this.#get().internal_updateTopicLoading(topicId, true);// 2. auto summary topic Title- // we don't need to wait for summary, just let it run async- summaryTopicTitle(topicId, messages);+ // We don't need to await the summary, but this owner keeps the new topic+ // spinning immediately until the fire-and-forget title summary settles.+ void summaryTopicTitle(topicId, messages)+ .catch((error) => {+ console.error('[saveToTopic] Failed to summarize topic title:', error);+ })+ .finally(() => {+ this.#get().internal_updateTopicLoading(topicId, false);+ });return topicId;};@@ -204,7 +211,11 @@ export class ChatTopicActionImpl {const topic = topicSelectors.getTopicById(topicId)(this.#get());if (!topic) return;- internal_updateTopicTitleInSummary(topicId, LOADING_FLAT);+ // Keep an optimistic title like "้ ่ฏปไธ้ข..." stable while AI rename runs;+ // otherwise the sidebar flickers `title -> ... -> final title`.+ const shouldStreamSummaryTitle = !topic.title || topic.title === LOADING_FLAT;++ if (shouldStreamSummaryTitle) internal_updateTopicTitleInSummary(topicId, LOADING_FLAT);let output = '';@@ -214,7 +225,7 @@ export class ChatTopicActionImpl {// Automatically summarize the topic titleawait chatService.fetchPresetTaskResult({onError: () => {- internal_updateTopicTitleInSummary(topicId, topic.title);+ if (shouldStreamSummaryTitle) internal_updateTopicTitleInSummary(topicId, topic.title);},onFinish: async (text) => {await this.#get().internal_updateTopic(topicId, { title: text });@@ -229,7 +240,7 @@ export class ChatTopicActionImpl {}}- internal_updateTopicTitleInSummary(topicId, output);+ if (shouldStreamSummaryTitle) internal_updateTopicTitleInSummary(topicId, output);},params: merge(topicConfig,@@ -969,22 +980,100 @@ export class ChatTopicActionImpl {internal_updateTopicLoading = (id: string, loading: boolean): void => {this.#set((state) => {- if (loading) return { topicLoadingIds: [...state.topicLoadingIds, id] };+ const currentCount =+ state.topicLoadingIdCounts[id] ?? (state.topicLoadingIds.includes(id) ? 1 : 0);+ const nextCounts = { ...state.topicLoadingIdCounts };++ if (loading) {+ nextCounts[id] = currentCount + 1;+ const nextIds = state.topicLoadingIds.includes(id)+ ? state.topicLoadingIds+ : [...state.topicLoadingIds, id];++ return {+ topicLoadingIdCounts: nextCounts,+ topicLoadingIds: nextIds,+ };+ }++ if (currentCount > 1) {+ nextCounts[id] = currentCount - 1;++ return { topicLoadingIdCounts: nextCounts, topicLoadingIds: state.topicLoadingIds };+ }++ delete nextCounts[id];+ const nextIds = state.topicLoadingIds.filter((i) => i !== id);- return { topicLoadingIds: state.topicLoadingIds.filter((i) => i !== id) };+ return {+ topicLoadingIdCounts: nextCounts,+ topicLoadingIds: nextIds,+ };},false,n('updateTopicLoading'),);};+ internal_replaceTopicId = (params: {+ agentId?: string;+ groupId?: string;+ nextId: string;+ previousId: string;+ value?: Partial<ChatTopic>;+ }): void => {+ const { agentId, groupId, nextId, previousId, value } = params;++ // The first-message optimistic topic starts as `tmp_topic_*`. Once the+ // server returns the real id, keep the same row alive so loading state and+ // title-summary updates continue targeting the visible topic.+ this.#get().internal_dispatchTopic(+ {+ agentId,+ groupId,+ id: previousId,+ nextId,+ type: 'replaceTopicId',+ value,+ },+ n('replaceTopicId'),+ );++ this.#set(+ (state) => {+ const previousCount = state.topicLoadingIdCounts[previousId] ?? 0;+ const nextCount = state.topicLoadingIdCounts[nextId] ?? 0;+ const topicLoadingIdCounts = { ...state.topicLoadingIdCounts };+ delete topicLoadingIdCounts[previousId];+ if (previousCount > 0 || nextCount > 0) {+ topicLoadingIdCounts[nextId] = previousCount + nextCount;+ }+ const topicLoadingIds = Array.from(+ new Set(state.topicLoadingIds.map((id) => (id === previousId ? nextId : id))),+ );++ return {+ activeTopicId: state.activeTopicId === previousId ? nextId : state.activeTopicId,+ topicLoadingIdCounts,+ topicLoadingIds,+ };+ },+ false,+ n('replaceTopicId/loading'),+ );+ };+internal_updateTopic = async (id: string, data: Partial<ChatTopic>): Promise<void> => {this.#get().internal_dispatchTopic({ type: 'updateTopic', id, value: data });this.#get().internal_updateTopicLoading(id, true);- await topicService.updateTopic(id, data);- await this.#get().refreshTopic();- this.#get().internal_updateTopicLoading(id, false);+ try {+ await topicService.updateTopic(id, data);+ await this.#get().refreshTopic();+ } finally {+ // Rename "Topic" -> "New" can fail after opening a loading owner; always release it.+ this.#get().internal_updateTopicLoading(id, false);+ }};internal_createTopic = async (params: CreateTopicParams): Promise<string> => {@@ -1081,7 +1170,7 @@ export class ChatTopicActionImpl {};internal_updateTopics = (- agentId: string,+ agentId: string | undefined,params: {append?: boolean;currentPage?: number;diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.tsindex 19519060123..d690a722da4 100644--- a/src/store/chat/slices/topic/initialState.ts+++ b/src/store/chat/slices/topic/initialState.ts@@ -51,6 +51,11 @@ export interface ChatTopicState {* Contains items, total count, pagination state, and loading states*/topicDataMap: Record<string, TopicData>;+ /**+ * Internal ref-count for topic loading owners. A topic can be loading because+ * the agent is running and because title-summary is streaming at the same time.+ */+ topicLoadingIdCounts: Record<string, number>;topicLoadingIds: string[];topicRenamingId?: string;topicSearchKeywords: string;@@ -64,6 +69,7 @@ export const initialTopicState: ChatTopicState = {isSearchingTopic: false,searchTopics: [],topicDataMap: {},+ topicLoadingIdCounts: {},topicLoadingIds: [],topicSearchKeywords: '',};diff --git a/src/store/chat/slices/topic/reducer.test.ts b/src/store/chat/slices/topic/reducer.test.tsindex 9ee52ec123c..962cb7d3c09 100644--- a/src/store/chat/slices/topic/reducer.test.ts+++ b/src/store/chat/slices/topic/reducer.test.ts@@ -72,6 +72,75 @@ describe('topicReducer', () => {});});+ describe('replaceTopicId', () => {+ it('should keep the optimistic topic row while replacing its id', () => {+ state.push(+ {+ createdAt: 1,+ id: 'tmp-topic',+ title: 'User input',+ updatedAt: 1,+ },+ {+ createdAt: 2,+ id: 'older-topic',+ title: 'Older',+ updatedAt: 2,+ },+ );++ const payload: ChatTopicDispatch = {+ id: 'tmp-topic',+ nextId: 'real-topic',+ type: 'replaceTopicId',+ value: { sessionId: 'agent-1' },+ };++ const newState = topicReducer(state, payload);++ expect(newState).toHaveLength(2);+ expect(newState[0]).toEqual(+ expect.objectContaining({+ id: 'real-topic',+ sessionId: 'agent-1',+ title: 'User input',+ }),+ );+ expect(newState[1].id).toBe('older-topic');+ });++ it('should merge and remove an existing real topic row', () => {+ state.push(+ {+ createdAt: 1,+ id: 'tmp-topic',+ title: 'User input',+ updatedAt: 1,+ },+ {+ createdAt: 2,+ id: 'real-topic',+ title: 'Server title',+ updatedAt: 2,+ },+ );++ const newState = topicReducer(state, {+ id: 'tmp-topic',+ nextId: 'real-topic',+ type: 'replaceTopicId',+ });++ expect(newState).toHaveLength(1);+ expect(newState[0]).toEqual(+ expect.objectContaining({+ id: 'real-topic',+ title: 'Server title',+ }),+ );+ });+ });+describe('deleteTopic', () => {it('should delete the specified ChatTopic object from state', () => {const topic: ChatTopic = {diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.tsindex 012ad952888..091dcb2fd2c 100644--- a/src/store/chat/slices/topic/reducer.ts+++ b/src/store/chat/slices/topic/reducer.ts@@ -31,7 +31,18 @@ type DeleteChatTopicAction = ChatTopicScope & {type: 'deleteTopic';};-export type ChatTopicDispatch = AddChatTopicAction | UpdateChatTopicAction | DeleteChatTopicAction;+type ReplaceChatTopicIdAction = ChatTopicScope & {+ id: string;+ nextId: string;+ type: 'replaceTopicId';+ value?: Partial<ChatTopic>;+};++export type ChatTopicDispatch =+ | AddChatTopicAction+ | UpdateChatTopicAction+ | DeleteChatTopicAction+ | ReplaceChatTopicIdAction;export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch): ChatTopic[] => {switch (payload.type) {@@ -70,6 +81,30 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch});}+ case 'replaceTopicId': {+ return produce(state, (draftState) => {+ const { value, id, nextId } = payload;+ const topicIndex = draftState.findIndex((topic) => topic.id === id);+ const existingNextIndex = draftState.findIndex((topic) => topic.id === nextId);++ if (topicIndex === -1) return;++ const currentTopic = draftState[topicIndex];+ const nextTopic = existingNextIndex === -1 ? undefined : draftState[existingNextIndex];+ draftState[topicIndex] = {+ ...currentTopic,+ ...nextTopic,+ ...value,+ id: nextId,+ updatedAt: Date.now(),+ };++ if (existingNextIndex !== -1 && existingNextIndex !== topicIndex) {+ draftState.splice(existingNextIndex, 1);+ }+ });+ }+case 'deleteTopic': {return produce(state, (draftState) => {const topicIndex = draftState.findIndex((topic) => topic.id === payload.id);