๐คฏ 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(topic): generate the auto title as JSON instead of a streamed completion (#18485)
Arvin Xued71b29b0d6a
diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.tsindex e8f92a37e4c..ee8ebe60188 100644--- a/src/store/chat/slices/thread/action.test.ts+++ b/src/store/chat/slices/thread/action.test.ts@@ -1,9 +1,11 @@+import { LOADING_FLAT } from '@lobechat/const';import { type UIChatMessage } from '@lobechat/types';import { act, renderHook, waitFor } from '@testing-library/react';import { type Mock } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mutate } from '@/libs/swr';+import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { threadService } from '@/services/thread';import { type ThreadItem } from '@/types/topic';@@ -45,6 +47,12 @@ vi.mock('@/services/chat', () => ({},}));+vi.mock('@/services/aiChat', () => ({+ aiChatService: {+ generateJSON: vi.fn(),+ },+}));+// Mock mutate from SWRvi.mock('swr', async () => {const actual = await vi.importActual('swr');@@ -597,14 +605,10 @@ describe('thread action', () => {},];- (chatService.fetchPresetTaskResult as Mock).mockImplementation(- async ({ onMessageHandle, onFinish }) => {- await onMessageHandle?.({ text: 'New', type: 'text' });- await onMessageHandle?.({ text: ' Generated', type: 'text' });- await onMessageHandle?.({ text: ' Title', type: 'text' });- await onFinish?.('New Generated Title');- },- );+ (aiChatService.generateJSON as Mock).mockResolvedValue({+ data: { title: 'New Generated Title' },+ tracingId: 'tracing-1',+ });const internalUpdateSpy = vi.spyOn(result.current, 'internal_updateThread')@@ -614,7 +618,13 @@ describe('thread action', () => {await result.current.summaryThreadTitle('thread-id', messages);});- expect(chatService.fetchPresetTaskResult).toHaveBeenCalled();+ // Structured generation, not a chat completion โ the raw text used to be+ // written straight to the title, which leaked `{"title":"..."}`.+ expect(chatService.fetchPresetTaskResult).not.toHaveBeenCalled();+ expect((aiChatService.generateJSON as Mock).mock.calls[0][0]).toMatchObject({+ schema: { name: 'topic_title' },+ tracing: { scenario: 'topic_title' },+ });expect(internalUpdateSpy).toHaveBeenCalledWith('thread-id', {title: 'New Generated Title',});@@ -645,13 +655,11 @@ describe('thread action', () => {});});- (chatService.fetchPresetTaskResult as Mock).mockImplementation(- async ({ onLoadingChange, onFinish }) => {- await onLoadingChange?.(true);- await onFinish?.('Title');- await onLoadingChange?.(false);- },- );+ const loadingSpy = vi.spyOn(result.current, 'internal_updateThreadLoading');+ (aiChatService.generateJSON as Mock).mockResolvedValue({+ data: { title: 'Title' },+ tracingId: 'tracing-1',+ });vi.spyOn(result.current, 'internal_updateThread').mockResolvedValue(undefined);@@ -659,7 +667,8 @@ describe('thread action', () => {await result.current.summaryThreadTitle('thread-id', []);});- expect(chatService.fetchPresetTaskResult).toHaveBeenCalled();+ expect(loadingSpy).toHaveBeenNthCalledWith(1, 'thread-id', true);+ expect(loadingSpy).toHaveBeenLastCalledWith('thread-id', false);});it('should revert title on error', async () => {@@ -687,9 +696,9 @@ describe('thread action', () => {});});- (chatService.fetchPresetTaskResult as Mock).mockImplementation(async ({ onError }) => {- await onError?.();- });+ const titleSpy = vi.spyOn(result.current, 'internal_updateThreadTitleInSummary');+ (aiChatService.generateJSON as Mock).mockRejectedValue(new Error('provider down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});vi.spyOn(result.current, 'internal_updateThread').mockResolvedValue(undefined);@@ -697,8 +706,9 @@ describe('thread action', () => {await result.current.summaryThreadTitle('thread-id', []);});- // Should have called with LOADING_FLAT first, then reverted to old title on error- expect(chatService.fetchPresetTaskResult).toHaveBeenCalled();+ // LOADING_FLAT first, then reverted to the old title on error+ expect(titleSpy).toHaveBeenNthCalledWith(1, 'thread-id', LOADING_FLAT);+ expect(titleSpy).toHaveBeenLastCalledWith('thread-id', 'Old Title');});it('should not run if no portal thread found', async () => {diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.tsindex 854149304f6..36bebb0655a 100644--- a/src/store/chat/slices/thread/action.ts+++ b/src/store/chat/slices/thread/action.ts@@ -1,6 +1,10 @@// Disable the auto sort key eslint rule to make the code more logic and readable-import { LOADING_FLAT } from '@lobechat/const';-import { chainSummaryTitle } from '@lobechat/prompts';+import { LOADING_FLAT, TRACING_SCENARIOS } from '@lobechat/const';+import {+ chainSummaryTitle,+ TOPIC_TITLE_JSON_SCHEMA,+ TOPIC_TITLE_PROMPT_VERSION,+} from '@lobechat/prompts';import {type CreateMessageParams,type IThreadType,@@ -12,7 +16,7 @@ import { type SWRResponse } from 'swr';import { mutate, useClientDataSWR } from '@/libs/swr';import { threadKeys } from '@/libs/swr/keys';-import { chatService } from '@/services/chat';+import { aiChatService } from '@/services/aiChat';import { threadService } from '@/services/thread';import { threadSelectors } from '@/store/chat/selectors';import { type ChatStore } from '@/store/chat/store';@@ -20,7 +24,6 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';-import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';import { PortalViewType } from '../portal/initialState';@@ -203,36 +206,43 @@ export class ChatThreadActionImpl {internal_updateThreadTitleInSummary(threadId, LOADING_FLAT);- let output = '';- const threadConfig = systemAgentSelectors.thread(useUserStore.getState());-- await chatService.fetchPresetTaskResult({- onError: () => {- internal_updateThreadTitleInSummary(threadId, portalThread.title);- },- onFinish: async (text) => {- await this.#get().internal_updateThread(threadId, { title: text });- },- onLoadingChange: (loading) => {- internal_updateThreadLoading(threadId, loading);- },- onMessageHandle: (chunk) => {- switch (chunk.type) {- case 'text': {- output += chunk.text;- }- }-- internal_updateThreadTitleInSummary(threadId, output);- },- params: merge(- threadConfig,- chainSummaryTitle(- messages,- userGeneralSettingsSelectors.currentResponseLanguage(useUserStore.getState()),- ),- ),- });+ const { model, provider } = systemAgentSelectors.thread(useUserStore.getState());++ const restorePreviousTitle = () => {+ internal_updateThreadTitleInSummary(threadId, portalThread.title);+ };++ // Structured generation, same as `summaryTopicTitle` โ see the note there.+ internal_updateThreadLoading(threadId, true);+ try {+ const { data } = await aiChatService.generateJSON(+ {+ ...chainSummaryTitle(+ messages,+ userGeneralSettingsSelectors.currentResponseLanguage(useUserStore.getState()),+ ),+ model,+ provider,+ schema: TOPIC_TITLE_JSON_SCHEMA,+ tracing: {+ promptVersion: TOPIC_TITLE_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TopicTitle,+ schemaName: TOPIC_TITLE_JSON_SCHEMA.name,+ },+ },+ new AbortController(),+ );++ const title = (data as { title?: string } | undefined)?.title?.trim();+ if (!title) return restorePreviousTitle();++ await this.#get().internal_updateThread(threadId, { title });+ } catch (error) {+ console.error('[summaryThreadTitle] failed to generate a title:', error);+ restorePreviousTitle();+ } finally {+ internal_updateThreadLoading(threadId, false);+ }};internal_updateThreadTitleInSummary = (id: string, title: string): void => {diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 5876aa77d2b..ab85b3cef69 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -1,4 +1,5 @@import { DEFAULT_MODEL, DEFAULT_PROVIDER } from '@lobechat/business-const';+import { TOPIC_TITLE_JSON_SCHEMA } from '@lobechat/prompts';import type { LobeUser, UIChatMessage } from '@lobechat/types';import { act, renderHook, waitFor } from '@testing-library/react';import { type Mock } from 'vitest';@@ -6,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LOADING_FLAT } from '@/const/message';import { mutate } from '@/libs/swr';+import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';@@ -2590,13 +2592,10 @@ describe('topic action', () => {);const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');- // Mock the `chatService.fetchPresetTaskResult` to simulate the AI response- vi.spyOn(chatService, 'fetchPresetTaskResult').mockImplementation((params) => {- if (params) {- params.onFinish?.('Summarized Title', { type: 'done' });- }- return Promise.resolve(undefined);- });+ vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({+ data: { title: 'Summarized Title' },+ tracingId: 'tracing-1',+ } as any);await act(async () => {await result.current.summaryTopicTitle(topicId, messages);@@ -2605,8 +2604,6 @@ describe('topic action', () => {// Verify that the title was updated and the topic was refreshedexpect(updateTopicTitleInSummarySpy).toHaveBeenCalledWith(topicId, LOADING_FLAT);expect(refreshTopicSpy).toHaveBeenCalled();-- // TODO: need to test with fetchPresetTaskResult});it('should keep an optimistic title visible until the summarized title is ready', async () => {@@ -2636,19 +2633,114 @@ describe('topic action', () => {);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' });- });+ vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({+ data: { title: 'Summarized Title' },+ tracingId: 'tracing-1',+ } as any);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('structured generation', () => {+ const topicId = 'topic-1';+ const messages = [{ id: 'message-1', content: 'Hello' }] as UIChatMessage[];++ const seedTopic = async (title: string) => {+ const topics = [{ id: topicId, title }] 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',+ });+ });++ return result;+ };++ it('generates against the topic-title schema instead of a chat completion', async () => {+ const result = await seedTopic('');+ const generateSpy = vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({+ data: { title: '็ฎๅ้ฎๅ' },+ tracingId: 'tracing-1',+ } as any);+ const completionSpy = vi.spyOn(chatService, 'fetchPresetTaskResult');++ await act(async () => {+ await result.current.summaryTopicTitle(topicId, messages);+ });++ expect(completionSpy).not.toHaveBeenCalled();+ expect(generateSpy.mock.calls[0][0]).toMatchObject({+ schema: TOPIC_TITLE_JSON_SCHEMA,+ tracing: { scenario: 'topic_title', topicId },+ });+ });++ it('reads the title off the parsed object', async () => {+ const result = await seedTopic('');+ const updateTopicSpy = vi.spyOn(result.current, 'internal_updateTopic');++ vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({+ data: { title: '็ฎๅ้ฎๅ' },+ tracingId: 'tracing-1',+ } as any);++ await act(async () => {+ await result.current.summaryTopicTitle(topicId, messages);+ });++ expect(updateTopicSpy).toHaveBeenCalledWith(topicId, { title: '็ฎๅ้ฎๅ' });+ });++ it('restores the previous title when generation returns nothing', async () => {+ const result = await seedTopic('');+ const updateTopicSpy = vi.spyOn(result.current, 'internal_updateTopic');+ const updateTitleSpy = vi.spyOn(result.current, 'internal_updateTopicTitleInSummary');++ vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({+ data: { title: ' ' },+ tracingId: 'tracing-1',+ } as any);++ await act(async () => {+ await result.current.summaryTopicTitle(topicId, messages);+ });++ expect(updateTopicSpy).not.toHaveBeenCalled();+ expect(updateTitleSpy).toHaveBeenLastCalledWith(topicId, '');+ });++ it('restores the previous title when generation throws', async () => {+ const result = await seedTopic('');+ const updateTopicSpy = vi.spyOn(result.current, 'internal_updateTopic');+ const updateTitleSpy = vi.spyOn(result.current, 'internal_updateTopicTitleInSummary');++ vi.spyOn(aiChatService, 'generateJSON').mockRejectedValue(new Error('provider down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await act(async () => {+ await result.current.summaryTopicTitle(topicId, messages);+ });++ expect(updateTopicSpy).not.toHaveBeenCalled();+ expect(updateTitleSpy).toHaveBeenLastCalledWith(topicId, '');+ });+ });});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 d31cc5ea431..d4e4958dba9 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -1,8 +1,12 @@// Note: To make the code more logic and readable, we just disable the auto sort key eslint rule// DON'T REMOVE THE FIRST LINE-import { chainSummaryTitle } from '@lobechat/prompts';+import { TRACING_SCENARIOS } from '@lobechat/const';+import {+ chainSummaryTitle,+ TOPIC_TITLE_JSON_SCHEMA,+ TOPIC_TITLE_PROMPT_VERSION,+} from '@lobechat/prompts';import { type ChatTopicMetadata, type MessageMapScope, type UIChatMessage } from '@lobechat/types';-import { TraceNameMap } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';import { t } from 'i18next';@@ -12,7 +16,7 @@ import useSWR from 'swr';import { LOADING_FLAT } from '@/const/message';import { mutate, useClientDataSWRWithSync } from '@/libs/swr';import { cronKeys, deviceKeys, topicKeys } from '@/libs/swr/keys';-import { chatService } from '@/services/chat';+import { aiChatService } from '@/services/aiChat';import { type GitLinkedPRSummary, gitService } from '@/services/git';import { messageService } from '@/services/message';import type { TopicBatchDeleteScope } from '@/services/topic';@@ -44,7 +48,6 @@ import {type CreateTopicParams,type TopicQuerySortBy,} from '@/types/topic';-import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';import { displayMessageSelectors } from '../message/selectors';@@ -289,44 +292,51 @@ export class ChatTopicActionImpl {// 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;+ const shouldShowPlaceholder = !topic.title || topic.title === LOADING_FLAT;- if (shouldStreamSummaryTitle) internal_updateTopicTitleInSummary(topicId, LOADING_FLAT);+ if (shouldShowPlaceholder) internal_updateTopicTitleInSummary(topicId, LOADING_FLAT);- let output = '';+ const restorePreviousTitle = () => {+ if (shouldShowPlaceholder) internal_updateTopicTitleInSummary(topicId, topic.title);+ };// Get current agent for topic- const topicConfig = systemAgentSelectors.topic(useUserStore.getState());+ const { model, provider } = systemAgentSelectors.topic(useUserStore.getState());- // Automatically summarize the topic title- await chatService.fetchPresetTaskResult({- onError: () => {- if (shouldStreamSummaryTitle) internal_updateTopicTitleInSummary(topicId, topic.title);- },- onFinish: async (text) => {- await this.#get().internal_updateTopic(topicId, { title: text });- },- onMessageHandle: (chunk) => {- switch (chunk.type) {- case 'text': {- output += chunk.text;- }- }+ // Structured generation, the same way `SystemAgentService.generateTopicTitle`+ // does it: the chain asks for `TOPIC_TITLE_JSON_SCHEMA`, so read the title+ // off the parsed object. Streaming a completion here used to write the raw+ // answer to `topic.title`, which named topics `{"title":"็ฎๅ้ฎๅ"}`.+ try {+ const { data } = await aiChatService.generateJSON(+ {+ ...chainSummaryTitle(+ messages,+ userGeneralSettingsSelectors.currentResponseLanguage(useUserStore.getState()),+ ),+ model,+ provider,+ schema: TOPIC_TITLE_JSON_SCHEMA,+ tracing: {+ promptVersion: TOPIC_TITLE_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TopicTitle,+ schemaName: TOPIC_TITLE_JSON_SCHEMA.name,+ topicId,+ },+ },+ new AbortController(),+ );- if (shouldStreamSummaryTitle) internal_updateTopicTitleInSummary(topicId, output);- },- params: merge(- topicConfig,- chainSummaryTitle(- messages,- userGeneralSettingsSelectors.currentResponseLanguage(useUserStore.getState()),- ),- ),- trace: this.#get().getCurrentTracePayload({- traceName: TraceNameMap.SummaryTopicTitle,- topicId,- }),- });+ const title = (data as { title?: string } | undefined)?.title?.trim();+ // An empty result must not blank the title โ the placeholder would+ // otherwise stay in the sidebar forever.+ if (!title) return restorePreviousTitle();++ await this.#get().internal_updateTopic(topicId, { title });+ } catch (error) {+ console.error('[summaryTopicTitle] failed to generate a title:', error);+ restorePreviousTitle();+ }};markTopicCompleted = async (id: string): Promise<void> => {