π€― 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
β¨ feat(chat): auto-generate topic title for gateway & hetero via shared lifecycle (#16119)
Arvin Xu3464bba25ee5
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex b2e5c6ca598..5a05f75ac4f 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -40,6 +40,8 @@ import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGrimport { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';import { resolveHeteroResume } from '@/store/chat/slices/aiChat/actions/heteroResume';import { dispatchNonHeteroSubAgent } from '@/store/chat/slices/aiChat/actions/nonHeteroSubAgentDispatcher';+import { buildRunLifecycle } from '@/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle';+import type { RunScope } from '@/store/chat/slices/aiChat/actions/runLifecycle/types';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';import { type ChatStore } from '@/store/chat/store';@@ -465,6 +467,21 @@ export class ConversationLifecycleActionImpl {},});+ // Shared run lifecycle for the post-persist topic-title hook. Built once here+ // so all three runtime branches fire the SAME `afterUserMessagePersisted`+ // (LOBE-10379 "θ‘₯ι½ηΌΊε title" β gateway/hetero previously had no LLM title).+ // `parentMessage*` are unused by this hook.+ const sendRunScope: RunScope =+ operationContext.scope === 'sub_agent' ? 'sub_agent' : 'top_level';+ const sendRunLifecycle = buildRunLifecycle(this.#get, {+ context: operationContext,+ parentMessageId: parentId ?? tempId,+ parentMessageType: 'user',+ runId: operationId,+ runScope: sendRunScope,+ runtimeType,+ });+// Construct local media preview for server-mode temporary messages (S3 URL takes priority).// Use the captured `files` param (not the global file store) so the optimistic preview// also works on the queue-drain path, where chatUploadFileList has already been cleared.@@ -645,6 +662,22 @@ export class ConversationLifecycleActionImpl {// Complete sendMessage operation, start ACP execution as child operationthis.#get().completeOperation(operationId);+ // Topic title (LOBE-10379): hetero used to set only a sliced placeholder+ // title on new topics β upgrade it to the LLM summary via the shared hook+ // (reads the just-persisted conversation from the store). Fire-and-forget.+ void sendRunLifecycle+ .afterUserMessagePersisted({+ assistantMessageId: heteroData.assistantMessageId,+ context: heteroContext,+ isCreateNewTopic: heteroData.isCreateNewTopic,+ operationId,+ runId: operationId,+ runScope: sendRunScope,+ runtimeType,+ topicId: heteroData.topicId,+ })+ .catch(console.error);+// Clear editor temp state β the user's message is already persisted, so// a later Stop click must NOT restore it into the input (would feel like// the app re-sent the message). Client/Gateway paths clear this at@@ -733,6 +766,25 @@ export class ConversationLifecycleActionImpl {tempMessageIds: [tempAssistantId],});+ // Topic title (LOBE-10379): gateway-created topics had no LLM-summarized+ // title. executeGatewayAgent has already replaced messages + switched to+ // the new topic, so the shared hook reads the persisted conversation from+ // the store and titles it. Fire-and-forget.+ if (result.topicId) {+ void sendRunLifecycle+ .afterUserMessagePersisted({+ assistantMessageId: result.assistantMessageId,+ context: { ...operationContext, topicId: result.topicId },+ isCreateNewTopic: !operationContext.topicId,+ operationId,+ runId: operationId,+ runScope: sendRunScope,+ runtimeType,+ topicId: result.topicId,+ })+ .catch(console.error);+ }+return {assistantMessageId: result.assistantMessageId,userMessageId: result.userMessageId,@@ -976,46 +1028,23 @@ export class ConversationLifecycleActionImpl {if (data.topicId) this.#get().internal_updateTopicLoading(data.topicId, true);- // Dev-only fast path: fall back to slicing the first user message instead of calling- // the LLM. Keeps chat logs uncluttered while still giving the topic a usable title.- // Only honored in non-production builds so a misconfigured prod env can't disable it.- const shouldSliceTopicTitle = __DEV__ && process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC === '1';-- const applyTopicTitle = async (topicId: string, messages: UIChatMessage[]) => {- if (!shouldSliceTopicTitle) {- await this.#get().summaryTopicTitle(topicId, messages);- return;- }-- const firstUserText = messages.find((m) => m.role === 'user')?.content?.trim() ?? '';- const title = markdownToTxt(firstUserText).slice(0, 80) || 'New Topic';- await this.#get().internal_updateTopic(topicId, { title });- // summaryTopicTitle would normally clear loading via onLoadingChange; do it manually.- this.#get().internal_updateTopicLoading(topicId, false);- console.info('[dev] sliced topic title (NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC=1):', title);- };-- const summaryTitle = async () => {- // check activeTopic and then auto update topic title- if (data.isCreateNewTopic) {- await applyTopicTitle(data.topicId, data.messages);- return;- }-- if (!data.topicId) return;-- const topic = topicSelectors.getTopicById(data.topicId)(this.#get());-- if (topic && !topic.title) {- const chats = displayMessageSelectors- .getDisplayMessagesByKey(messageMapKey({ agentId, topicId: topic.id }))(this.#get())- .filter((item) => item.id !== data.assistantMessageId);-- await applyTopicTitle(topic.id, chats);- }- };-- summaryTitle().catch(console.error);+ // Topic title auto-generation, now via the shared `afterUserMessagePersisted`+ // hook (LOBE-10379). The client passes its freshly-created `data.messages`+ // (not yet in the store under the real topicId); gateway/hetero call the same+ // hook from their branches and let it read the persisted conversation.+ void sendRunLifecycle+ .afterUserMessagePersisted({+ assistantMessageId: data.assistantMessageId,+ context: operationContext,+ isCreateNewTopic: data.isCreateNewTopic,+ messages: data.messages,+ operationId,+ runId: operationId,+ runScope: sendRunScope,+ runtimeType,+ topicId: data.topicId,+ })+ .catch(console.error);// Complete sendMessage operation here - message creation is done// execAgentRuntime is a separate operation (child) that handles AI response generationdiff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.tsindex 647c9a9698e..ba4bbf2fd08 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.test.ts@@ -5,7 +5,7 @@ import type { ChatStore } from '@/store/chat/store';import type { AgentRuntimeType } from '../agentDispatcher';import { buildRunLifecycle } from './buildRunLifecycle';-import type { RunCompleteEvent, RunTerminalStatus } from './types';+import type { RunCompleteEvent, RunTerminalStatus, UserMessagePersistedEvent } from './types';const agentSignalBridgeMock = vi.hoisted(() => ({emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),@@ -20,10 +20,15 @@ const CONTEXT: ConversationContext = { agentId: 'a1', topicId: 't1' } as Conversconst makeStore = (afterCompletionCallbacks?: Array<() => void>) => {const store = {+ activeAgentId: 'a1',+ activeGroupId: undefined,+ activeTopicId: 't1',completeOperation: vi.fn(),dbMessagesMap: {},drainQueuedMessages: vi.fn(() => []),failOperation: vi.fn(),+ internal_updateTopic: vi.fn(),+ internal_updateTopicLoading: vi.fn(),markTopicUnread: vi.fn(),messagesMap: {},operations: {@@ -33,6 +38,10 @@ const makeStore = (afterCompletionCallbacks?: Array<() => void>) => {status: 'running',},},+ refreshTopic: vi.fn(async () => {}),+ summaryTopicTitle: vi.fn(),+ // topicDataMap / messagesMap reads default to empty (no topic, no messages).+ topicDataMap: {},};return { get: (() => store) as unknown as () => ChatStore, store };};@@ -174,3 +183,68 @@ describe('buildRunLifecycle β sub-agent runs skip top-level effects', () => {).resolves.toBeUndefined();});});++describe('buildRunLifecycle.afterUserMessagePersisted β topic title (all runtimes)', () => {+ const persistedEvent = (+ runtimeType: AgentRuntimeType,+ runScope: 'sub_agent' | 'top_level',+ fields: Partial<UserMessagePersistedEvent>,+ ): UserMessagePersistedEvent => ({+ context: CONTEXT,+ isCreateNewTopic: true,+ operationId: OP,+ runId: OP,+ runScope,+ runtimeType,+ topicId: 't1',+ ...fields,+ });++ it('new topic (top_level) summarizes the title with the caller-provided messages', async () => {+ const { get, store } = makeStore();+ const messages = [{ content: 'hello there', id: 'm1', role: 'user' } as any];++ await lifecycle('gateway', get, 'top_level').afterUserMessagePersisted(+ persistedEvent('gateway', 'top_level', { isCreateNewTopic: true, messages, topicId: 't1' }),+ );++ expect(store.summaryTopicTitle).toHaveBeenCalledWith('t1', messages);+ });++ 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 undefined+ const messages = [{ content: 'hi', id: 'm1', role: 'user' } as any];++ await lifecycle('gateway', get, 'top_level').afterUserMessagePersisted(+ persistedEvent('gateway', 'top_level', { isCreateNewTopic: true, messages, topicId: 't1' }),+ );++ // The new gateway topic isn't in the store yet β refreshTopic is awaited+ // before summarizing so summaryTopicTitle doesn't bail on a missing topic.+ expect(store.refreshTopic).toHaveBeenCalled();+ expect(store.summaryTopicTitle).toHaveBeenCalledWith('t1', messages);+ });++ it('does NOT title for a sub_agent run', async () => {+ const { get, store } = makeStore();++ await lifecycle('client', get, 'sub_agent').afterUserMessagePersisted(+ persistedEvent('client', 'sub_agent', {+ isCreateNewTopic: true,+ messages: [{ content: 'x', id: 'm1', role: 'user' } as any],+ }),+ );++ expect(store.summaryTopicTitle).not.toHaveBeenCalled();+ });++ it('does nothing when no topicId is resolved', async () => {+ const { get, store } = makeStore();++ await lifecycle('hetero', get, 'top_level').afterUserMessagePersisted(+ persistedEvent('hetero', 'top_level', { isCreateNewTopic: true, topicId: undefined }),+ );++ expect(store.summaryTopicTitle).not.toHaveBeenCalled();+ });+});diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.tsindex 3eb1be2af77..6bb4e8c184a 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts@@ -13,14 +13,17 @@ import { markdownToTxt } from '@/utils/markdownToTxt';import { messageMapKey } from '../../../../utils/messageMapKey';import { topicMapKey } from '../../../../utils/topicMapKey';+import { displayMessageSelectors } from '../../../message/selectors/displayMessage';import type { OperationStatus } from '../../../operation/types';import { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../../operation/types';+import { topicSelectors } from '../../../topic/selectors';import type {AgentRunLifecycle,RunCompleteEvent,RunCompleteResult,RunParkedEvent,RunScope,+ UserMessagePersistedEvent,} from './types';/**@@ -169,7 +172,62 @@ export const buildRunLifecycle = (};return {- afterUserMessagePersisted: NOOP,+ afterUserMessagePersisted: async (event: UserMessagePersistedEvent) => {+ // Topic title auto-generation. Single home for all three runtimes+ // (LOBE-10379 "θ‘₯ι½ηΌΊε title"): the client used to do this inline in+ // sendMessage and gateway/hetero had no LLM-summarized title at all.+ // Top-level only β a nested sub-agent / `/compact` run must not retitle the+ // user's topic. See RunScope.+ if (adapter.runScope !== 'top_level') return;+ const { isCreateNewTopic, topicId, assistantMessageId } = event;+ if (!topicId) return;++ // Dev-only fast path: slice the first user message instead of calling the+ // LLM. Only honored in non-production builds. Relocated verbatim.+ const shouldSliceTopicTitle =+ __DEV__ && process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC === '1';++ const applyTopicTitle = async (tid: string, messages: UIChatMessage[]) => {+ if (!shouldSliceTopicTitle) {+ await get().summaryTopicTitle(tid, messages);+ return;+ }+ const firstUserText = messages.find((m) => m.role === 'user')?.content?.trim() ?? '';+ const title = markdownToTxt(firstUserText).slice(0, 80) || 'New Topic';+ 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);+ };++ const readStoreChats = () =>+ displayMessageSelectors.getDisplayMessagesByKey(messageMapKey({ agentId, topicId }))(get());++ // New topic β always title. Use caller-provided messages when present+ // (client's freshly-created rows aren't in the store under topicId yet);+ // otherwise read the persisted conversation from the store (gateway/hetero).+ if (isCreateNewTopic) {+ // The gateway path adds the new topic via a FIRE-AND-FORGET refreshTopic+ // (gateway.ts), so it may not be in the store yet β and `summaryTopicTitle`+ // bails on a missing topic. Load it first when absent (client / hetero+ // already inserted it synchronously, so this is a no-op for them).+ if (!topicSelectors.getTopicById(topicId)(get())) {+ await get()+ .refreshTopic()+ .catch(() => {});+ }+ await applyTopicTitle(topicId, event.messages ?? readStoreChats());+ return;+ }++ // Existing topic β title only when it still has none. Read from the store,+ // excluding the just-created assistant placeholder.+ const topic = topicSelectors.getTopicById(topicId)(get());+ if (topic && !topic.title) {+ const chats = readStoreChats().filter((item) => item.id !== assistantMessageId);+ await applyTopicTitle(topicId, chats);+ }+ },afterRunComplete: async (event: RunCompleteEvent) => {// Desktop notification + dock badge. Single home for all three runtimes'// completion notification (LOBE-10379 "ιη₯ε»ιοΌη»δΈε° afterRunComplete").diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/types.tsindex 20872e83279..08705787a25 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/types.ts@@ -1,5 +1,5 @@import type { AgentState } from '@lobechat/agent-runtime';-import type { ConversationContext } from '@lobechat/types';+import type { ConversationContext, UIChatMessage } from '@lobechat/types';import type { AgentRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';import type { OperationStatus } from '@/store/chat/slices/operation/types';@@ -37,7 +37,15 @@ interface RunLifecycleEventBase extends RunLifecycleContext {}export interface UserMessagePersistedEvent extends RunLifecycleEventBase {+ /** The just-created assistant placeholder β excluded from the title context. */+ assistantMessageId?: string;isCreateNewTopic: boolean;+ /**+ * Title-context messages, supplied by the client path (`data.messages`) where+ * the new-topic rows aren't in the store under the real topicId yet. Gateway /+ * hetero omit it β the hook reads the persisted conversation from the store.+ */+ messages?: UIChatMessage[];topicId?: string;}