🤯 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(group): stop first-message flicker on new-topic creation (#16259)
Arvin Xu26db93ff9871
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 9defac845d3..a51c8c34e97 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -125,7 +125,11 @@ type ResponseCreateParamsWithPromptCacheKey = (| OpenAI.Responses.ResponseCreateParams) &OpenAIExtraParams;-export type CreateImageOptions = Omit<ClientOptions, 'apiKey'> &+// Exclude openai's own `provider` (added in openai SDK 6.45.0 as `provider?: Provider`+// for its third-party-provider feature) — otherwise intersecting it with our+// `provider: string` collapses to `Provider & string`, breaking every call site+// that passes a plain provider id string.+export type CreateImageOptions = Omit<ClientOptions, 'apiKey' | 'provider'> &ModelIdMappingOptions & {apiKey: string;provider: string;@@ -159,7 +163,8 @@ const getGenerateObjectResponsesReasoningParams = ({: {};};-export type CreateVideoOptions = Omit<ClientOptions, 'apiKey'> &+// See CreateImageOptions above: drop openai's `provider` so ours stays `string`.+export type CreateVideoOptions = Omit<ClientOptions, 'apiKey' | 'provider'> &ModelIdMappingOptions & {apiKey: string;provider: string;diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 1d075fa159e..8ad2dd5c31f 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -106,7 +106,10 @@ export const ConversationProvider = memo<ConversationProviderProps>();return (- <Provider createStore={() => createStore({ context, hooks, skipFetch })} key={contextKey}>+ <Provider+ createStore={() => createStore({ context, hooks, initialMessages: messages, skipFetch })}+ key={contextKey}+ ><StoreUpdateractionsBar={actionsBar}context={context}diff --git a/src/features/Conversation/store/action.ts b/src/features/Conversation/store/action.tsindex c845305ae2b..b23ab648a38 100644--- a/src/features/Conversation/store/action.ts+++ b/src/features/Conversation/store/action.ts@@ -1,3 +1,5 @@+import { parse } from '@lobechat/conversation-flow';+import { type UIChatMessage } from '@lobechat/types';import { type StateCreator } from 'zustand/vanilla';import { type ConversationContext, type ConversationHooks } from '../types';@@ -37,6 +39,20 @@ export type ConversationStore = Store;export interface CreateStoreParams {context: ConversationContext;hooks?: ConversationHooks;+ /**+ * Messages to seed the freshly-created store with, already known by the parent+ * (ConversationArea reads them from ChatStore's `dbMessagesMap`). Seeding at+ * creation — rather than waiting for StoreUpdater's post-mount effect — is what+ * keeps a store *remount* from painting an empty/skeleton frame first.+ *+ * Why this matters: ConversationProvider keys `<Provider>` by `contextKey`, so a+ * topic switch (e.g. group's first message creates a new topic) recreates the+ * store from scratch. Without a seed the new store starts `messagesInit: false`+ * with no messages and only gets populated by a post-paint effect — one blank+ * frame, i.e. the "message disappears then reappears" flicker. `undefined` means+ * "not fetched yet" (stay uninitialized); `[]` means "loaded, empty".+ */+ initialMessages?: UIChatMessage[];skipFetch?: boolean;}@@ -45,12 +61,22 @@ type CreateStore = () => StateCreator<Store, [['zustand/devtools', never]]>;export const createStoreAction: CreateStore =- ({ context, hooks = {}, skipFetch }) =>+ ({ context, hooks = {}, initialMessages, skipFetch }) =>(...params) => ({...initialState,context,hooks,skipFetch,+ // Seed known messages so a remount renders content on its first paint instead+ // of a blank/skeleton frame. `initialMessages` truthy ([] included) mirrors+ // StoreUpdater's `hasInitMessages = !!messages` → messagesInit semantics.+ ...(initialMessages+ ? {+ dbMessages: initialMessages,+ displayMessages: parse(initialMessages).flatList,+ messagesInit: true,+ }+ : {}),// ===== Slices =====...dataSlice(...params),...generationSlice(...params),diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.tsindex b44d88daff0..8fce165dc4b 100644--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts@@ -560,6 +560,34 @@ describe('agentGroup actions', () => {});});+ it('should populate the new topic bucket BEFORE switching into it (no blank flicker)', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse({+ isCreateNewTopic: true,+ topics: { items: [], total: 1 },+ }),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // The flicker bug: switchTopic both clears the optimistic (topicId: null)+ // bucket and points the view at the new, still-empty topic bucket. If it runs+ // before replaceMessages, the view lands on an empty key for a frame and the+ // just-sent message visibly disappears then reappears. Guard the ordering:+ // replaceMessages (populate new bucket) must precede switchTopic.+ const replaceOrder = vi.mocked(result.current.replaceMessages).mock.invocationCallOrder[0];+ const switchOrder = vi.mocked(result.current.switchTopic).mock.invocationCallOrder[0];+ expect(replaceOrder).toBeLessThan(switchOrder);+ });+it('should not switch topic when using existing topic', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsxnew file mode 100644index 00000000000..baef625b2c0--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx@@ -0,0 +1,217 @@+import { act, render } from '@testing-library/react';+import { useEffect } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ createStore,+ dataSelectors,+ Provider,+ useConversationStore,+} from '@/features/Conversation/store';+import StoreUpdater from '@/features/Conversation/StoreUpdater';+import { lambdaClient } from '@/libs/trpc/client';+import { agentRuntimeClient } from '@/services/agentRuntime';+import { useChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++// Keep zustand mock as it's needed globally for store reset between tests+vi.mock('zustand/traditional');++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ aiAgent: { execGroupAgent: { mutate: vi.fn() } },+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },+ },+}));++vi.mock('@/services/agentRuntime', () => ({+ agentRuntimeClient: { createStreamConnection: vi.fn() },+ StreamEvent: {},+}));++const IDS = {+ AGENT_ID: 'agt_flicker',+ GROUP_ID: 'grp_flicker',+ NEW_TOPIC_ID: 'tpc_new_from_server',+ OPERATION_ID: 'op_stream',+ ASSISTANT_MESSAGE_ID: 'msg_assistant',+ USER_MESSAGE_ID: 'msg_user',+} as const;++/**+ * One committed render frame of the conversation surface, recorded at paint+ * granularity (React useEffect = post-commit). `count` is how many messages the+ * UI would show; `showSkeleton` mirrors ChatList's blank gate exactly.+ */+interface Frame {+ count: number;+ messagesInit: boolean;+ showSkeleton: boolean;+ topicId: string | null | undefined;+}++let frames: Frame[] = [];++/**+ * Probe replicates ChatList's blank-decision (src/features/Conversation/ChatList/index.tsx):+ * const isNewConversation = !context.topicId;+ * if (!messagesInit && !isNewConversation) return <SkeletonList />; // blank+ * It records every committed frame so the test can assert the just-sent message+ * never disappears (count drops to 0, or a skeleton replaces it) mid-flow.+ */+const Probe = () => {+ const messagesInit = useConversationStore(dataSelectors.messagesInit);+ const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);+ const topicId = useConversationStore((s) => s.context.topicId);++ const isNewConversation = !topicId;+ const showSkeleton = !messagesInit && !isNewConversation;++ useEffect(() => {+ frames.push({+ count: displayMessageIds.length,+ messagesInit,+ showSkeleton,+ topicId,+ });+ });++ return null;+};++/**+ * Mirrors ConversationArea: derives the group context from the live ChatStore+ * (topicId follows activeTopicId, exactly like useGroupContext), reads the raw+ * bucket from dbMessagesMap, and feeds an isolated ConversationStore — keyed by+ * contextKey so a topic switch remounts the store, just like ConversationProvider.+ */+const GroupAreaHarness = () => {+ const activeAgentId = useChatStore((s) => s.activeAgentId);+ const activeGroupId = useChatStore((s) => s.activeGroupId);+ const activeTopicId = useChatStore((s) => s.activeTopicId ?? null);+ const replaceMessages = useChatStore((s) => s.replaceMessages);++ const context = {+ agentId: activeAgentId!,+ groupId: activeGroupId!,+ isSupervisor: true,+ scope: 'group' as const,+ threadId: null,+ topicId: activeTopicId,+ };+ const chatKey = messageMapKey(context);+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);++ return (+ <Provider+ key={chatKey}+ createStore={() =>+ createStore({ context, hooks: {}, initialMessages: messages, skipFetch: false })+ }+ >+ <StoreUpdater+ context={context}+ hasInitMessages={!!messages}+ messages={messages}+ onMessagesChange={(m, ctx) => replaceMessages(m, { context: ctx })}+ />+ <Probe />+ </Provider>+ );+};++const sendContext = () => ({+ agentId: IDS.AGENT_ID,+ groupId: IDS.GROUP_ID,+ threadId: null as string | null,+ topicId: null as string | null,+});++const mockNewTopicResponse = () => ({+ assistantMessageId: IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ {+ content: 'Hello group!',+ createdAt: Date.now(),+ id: IDS.USER_MESSAGE_ID,+ role: 'user' as const,+ updatedAt: Date.now(),+ },+ {+ content: '',+ createdAt: Date.now(),+ id: IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant' as const,+ updatedAt: Date.now(),+ },+ ],+ operationId: IDS.OPERATION_ID,+ topicId: IDS.NEW_TOPIC_ID,+ topics: { items: [{ id: IDS.NEW_TOPIC_ID }], total: 1 },+ userMessageId: IDS.USER_MESSAGE_ID,+});++describe('group chat — initial message flicker', () => {+ beforeEach(() => {+ frames = [];+ vi.clearAllMocks();+ // Real store actions (NOT mocked) — drive the genuine optimistic→switch→replace flow.+ useChatStore.setState(+ {+ activeAgentId: IDS.AGENT_ID,+ activeGroupId: IDS.GROUP_ID,+ activeTopicId: undefined,+ dbMessagesMap: {},+ isCreatingMessage: false,+ messageOperationMap: {},+ messagesMap: {},+ operations: {},+ },+ false,+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({ abort: vi.fn() } as any);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('sending the first message must never blank out across new-topic creation', async () => {+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ mockNewTopicResponse() as any,+ );++ render(<GroupAreaHarness />);++ await act(async () => {+ await useChatStore.getState().sendGroupMessage({+ context: sendContext(),+ message: 'Hello group!',+ });+ });++ // Sanity: messages did show up at some point.+ const firstVisibleIdx = frames.findIndex((f) => f.count >= 1);+ expect(firstVisibleIdx).toBeGreaterThanOrEqual(0);++ // The flicker invariant: once the just-sent message is visible, no later+ // committed frame may drop it (count → 0) or replace it with a skeleton,+ // until the flow settles. A regression (switchTopic before replaceMessages)+ // produces exactly such a frame: the remounted store lands on the empty+ // new-topic bucket → showSkeleton true / count 0.+ const framesAfterVisible = frames.slice(firstVisibleIdx);+ const blankFrame = framesAfterVisible.find((f) => f.count === 0 || f.showSkeleton);++ expect(+ blankFrame,+ `Message disappeared mid-flow. Frame timeline: ${JSON.stringify(frames, null, 2)}`,+ ).toBeUndefined();++ // Final state: the two server messages live under the new topic.+ const lastFrame = frames.at(-1)!;+ expect(lastFrame.topicId).toBe(IDS.NEW_TOPIC_ID);+ expect(lastFrame.count).toBe(2);+ expect(lastFrame.showSkeleton).toBe(false);+ });+});diff --git a/src/store/chat/slices/aiAgent/actions/agentGroup.ts b/src/store/chat/slices/aiAgent/actions/agentGroup.tsindex ae6ace49a17..ce4e9579f1f 100644--- a/src/store/chat/slices/aiAgent/actions/agentGroup.ts+++ b/src/store/chat/slices/aiAgent/actions/agentGroup.ts@@ -115,7 +115,28 @@ export class ChatGroupChatActionImpl {});}- // 4. Switch to new topic if created+ // 4. Create execContext with updated topicId from server response+ const execContext = { ...context, topicId: result.topicId || topicId };++ // 5. Populate the new topic's message bucket BEFORE switching into it.+ //+ // Temp messages live under the original (topicId: null) bucket. switchTopic+ // both clears that bucket (clearNewKey) AND points the active view at the new+ // topicId. If we switched first, the view would land on the still-empty new+ // bucket for a frame — StoreUpdater resets displayMessages/messagesInit and+ // ChatList renders <SkeletonList/>, so the just-sent message visibly+ // disappears and then reappears once replaceMessages runs. Writing the new+ // bucket first means the view always finds messages already present on switch.+ //+ // Messages include assistant message with error if operation failed to start.+ if (result.messages) {+ this.#get().replaceMessages(result.messages, {+ action: n('sendGroupMessage/syncMessages'),+ context: execContext,+ });+ }++ // 6. Switch to new topic if created (its bucket is already populated above)if (result.isCreateNewTopic && result.topicId) {await this.#get().switchTopic(result.topicId, {clearNewKey: true,@@ -123,24 +144,18 @@ export class ChatGroupChatActionImpl {});}- // 5. Create execContext with updated topicId from server response- const execContext = { ...context, topicId: result.topicId || topicId };-- // 6. Replace temp messages with server messages- // Messages include assistant message with error if operation failed to start+ // 7. Clean up temp messages from the original bucket.+ // For the new-topic path switchTopic's clearNewKey already wiped them; for the+ // same-topic path replaceMessages above overwrote the bucket. This dispatch is+ // a defensive no-op in both cases, kept to guard partial-result edge cases.if (result.messages) {- this.#get().replaceMessages(result.messages, {- action: n('sendGroupMessage/syncMessages'),- context: execContext,- });- // Delete temp messages - use execOperationId for correct contextthis.#get().internal_dispatchMessage({ ids: [tempUserId, tempAssistantId], type: 'deleteMessages' },{ operationId: execOperationId },);}- // 7. Check if operation failed to start (e.g., QStash unavailable)+ // 8. Check if operation failed to start (e.g., QStash unavailable)// In this case, messages are synced but we skip SSE connectionif (result.success === false) {log('Agent operation failed to start: %s', result.error);@@ -152,7 +167,7 @@ export class ChatGroupChatActionImpl {return;}- // 8. Create streaming context - use assistantMessageId from backend response+ // 9. Create streaming context - use assistantMessageId from backend responseconst streamContext = {assistantId: result.assistantMessageId,content: '',@@ -160,7 +175,7 @@ export class ChatGroupChatActionImpl {tmpAssistantId: tempAssistantId, // Used for cleanup if needed};- // 9. Start child operation for SSE stream using backend operationId+ // 10. Start child operation for SSE stream using backend operationIdthis.#get().startOperation({context: { ...execContext, messageId: result.assistantMessageId },label: 'Group Agent Stream',@@ -175,7 +190,7 @@ export class ChatGroupChatActionImpl {this.#get().associateMessageWithOperation(result.assistantMessageId, execOperationId);this.#get().associateMessageWithOperation(result.assistantMessageId, result.operationId);- // 10. Connect to SSE stream+ // 11. Connect to SSE stream// Server will automatically close the connection after sending agent_runtime_end eventconst eventSource = agentRuntimeClient.createStreamConnection(result.operationId, {includeHistory: false,@@ -204,7 +219,7 @@ export class ChatGroupChatActionImpl {},});- // 11. Register cancel handler for aborting SSE stream+ // 12. Register cancel handler for aborting SSE streamthis.#get().onOperationCancel(result.operationId, () => {log('Cancelling SSE stream for operation %s', result.operationId);eventSource.abort();