Skip to content

🤯 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.

🐛 fix(chat): keep optimistic topics in project group (#16571)

YuTengjing49ab8eafd100
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 4a764d56a1a..16f281ed9b4 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -8,6 +8,7 @@ import { aiChatService } from '@/services/aiChat';
import { chatService } from '@/services/chat';
import { messageService } from '@/services/message';
import * as agentGroupStore from '@/store/agentGroup';
+import { setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { getSessionStoreState } from '@/store/session';
@@ -78,6 +79,7 @@ beforeEach(() => {
afterEach(() => {
executeHeterogeneousAgentMock.mockReset();
mockConstEnv.isDesktop = false;
+ setPendingTopicRepos(TEST_IDS.SESSION_ID, []);
vi.restoreAllMocks();
});
@@ -565,6 +567,82 @@ describe('ConversationLifecycle actions', () => {
expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);
});
+ it('should keep a gateway optimistic topic in its pending repo project group', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const agentId = TEST_IDS.SESSION_ID;
+ const topicKey = topicMapKey({ agentId });
+ const selectedRepo = 'https://github.com/lobehub/lobehub';
+ let resolveGateway!: () => void;
+ const gatewayPromise = new Promise<any>((resolve) => {
+ resolveGateway = () =>
+ resolve({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'gateway-op-1',
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+ });
+ const executeGatewayAgentSpy = vi.fn().mockReturnValue(gatewayPromise);
+
+ setPendingTopicRepos(agentId, [selectedRepo]);
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ topicDataMap: {
+ [topicKey]: {
+ currentPage: 0,
+ hasMore: false,
+ isExpandingPageSize: false,
+ isLoadingMore: false,
+ items: [],
+ pageSize: 20,
+ total: 0,
+ },
+ },
+ });
+ });
+
+ let sendPromise!: ReturnType<typeof result.current.sendMessage>;
+ act(() => {
+ sendPromise = result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Create a project topic',
+ });
+ });
+
+ await waitFor(() => expect(executeGatewayAgentSpy).toHaveBeenCalled());
+
+ // A pending repo selected before the first send used to be missing from
+ // the tmp topic, so By Project grouped it under "No directory" until
+ // the server topic replaced it.
+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]).toEqual(
+ expect.objectContaining({
+ metadata: {
+ repos: [selectedRepo],
+ workingDirectory: selectedRepo,
+ },
+ }),
+ );
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ optimisticTopic: expect.objectContaining({
+ metadata: {
+ repos: [selectedRepo],
+ workingDirectory: selectedRepo,
+ },
+ }),
+ }),
+ );
+
+ await act(async () => {
+ resolveGateway();
+ await sendPromise;
+ });
+ });
+
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;
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 3bb3a1af451..9c8ab490c27 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -714,6 +714,48 @@ describe('GatewayActionImpl', () => {
});
});
+ it('should keep optimistic topic metadata when replacing the placeholder topic id', async () => {
+ const { action, internalReplaceTopicId } = createExecuteTestAction();
+ const selectedRepo = 'https://github.com/lobehub/lobehub';
+
+ 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: 'Create a project topic',
+ optimisticTopic: {
+ id: 'tmp-topic',
+ metadata: { repos: [selectedRepo], workingDirectory: selectedRepo },
+ title: 'Create a project topic',
+ },
+ });
+
+ expect(internalReplaceTopicId).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: undefined,
+ nextId: 'topic-1',
+ previousId: 'tmp-topic',
+ value: {
+ metadata: { repos: [selectedRepo], workingDirectory: selectedRepo },
+ sessionId: 'agent-1',
+ title: 'Create a project topic',
+ },
+ });
+ });
+
it('should forward metadata trigger to execAgentTask', async () => {
const { action } = createExecuteTestAction();
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 84bae9839a6..ef4e9894be7 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -12,6 +12,7 @@ import type {
ChatImageItem,
ChatThreadType,
ChatToolPayload,
+ ChatTopicMetadata,
ChatVideoItem,
ConversationContext,
MessageMetadata,
@@ -37,6 +38,7 @@ import {
chatConfigByIdSelectors,
} from '@/store/agent/selectors';
import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';
+import { getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import {
dbMessageSelectors,
displayMessageSelectors,
@@ -124,6 +126,7 @@ type SendMessageServerResponseMeta = SendMessageServerResponse & {
interface OptimisticTopicPlaceholder {
id: string;
+ metadata?: ChatTopicMetadata;
title: string;
}
@@ -558,9 +561,38 @@ export class ConversationLifecycleActionImpl {
this.#get().associateMessageWithOperation(tempId, operationId);
this.#get().associateMessageWithOperation(tempAssistantId, operationId);
+ const existingTopic = operationContext.topicId
+ ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
+ : undefined;
+ const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const agentWorkingDirectory =
+ runtimeType === 'hetero' && heterogeneousProvider
+ ? agentByIdSelectors.getAgentWorkingDirectoryById(
+ agentId,
+ currentDeviceId,
+ )(getAgentStoreState())
+ : undefined;
+ const workingDirectory = existingTopic?.metadata?.workingDirectory || agentWorkingDirectory;
+ const pendingTopicRepos =
+ runtimeType === 'gateway' && !operationContext.topicId && operationContext.agentId
+ ? getPendingTopicRepos(operationContext.agentId)
+ : [];
+ // Example: a pending repo topic without this metadata renders under "No directory"
+ // until the server topic replaces `tmp_topic_*`.
+ const optimisticTopicMetadata: ChatTopicMetadata | undefined =
+ pendingTopicRepos.length > 0
+ ? { repos: pendingTopicRepos, workingDirectory: pendingTopicRepos[0] }
+ : workingDirectory
+ ? { workingDirectory }
+ : undefined;
+
const optimisticTopic: OptimisticTopicPlaceholder | undefined =
!operationContext.topicId && !context.isolatedTopic
- ? { id: `tmp_topic_${nanoid()}`, title: newTopicTitle }
+ ? {
+ id: `tmp_topic_${nanoid()}`,
+ ...(optimisticTopicMetadata ? { metadata: optimisticTopicMetadata } : {}),
+ title: newTopicTitle,
+ }
: undefined;
let optimisticTopicActive = false;
let optimisticTopicResolved = false;
@@ -577,13 +609,19 @@ export class ConversationLifecycleActionImpl {
groupId: operationContext.groupId ?? undefined,
};
- const addResolvedTopicPlaceholder = (topicId: string, title: string, action: string) => {
+ const addResolvedTopicPlaceholder = (
+ topicId: string,
+ title: string,
+ action: string,
+ metadata?: ChatTopicMetadata,
+ ) => {
this.#get().internal_dispatchTopic(
{
...optimisticTopicScope,
type: 'addTopic',
value: {
id: topicId,
+ ...(metadata ? { metadata } : {}),
...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
title,
},
@@ -598,6 +636,7 @@ export class ConversationLifecycleActionImpl {
topicId,
title || t('defaultTitle', { ns: 'topic' }),
'sendMessage/reconcileOptimisticTopic/add',
+ optimisticTopic?.metadata,
);
return;
}
@@ -607,6 +646,7 @@ export class ConversationLifecycleActionImpl {
nextId: topicId,
previousId: optimisticTopic.id,
value: {
+ ...(optimisticTopic.metadata ? { metadata: optimisticTopic.metadata } : {}),
...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
title: title || t('defaultTitle', { ns: 'topic' }),
},
@@ -636,6 +676,7 @@ export class ConversationLifecycleActionImpl {
optimisticTopic.id,
optimisticTopic.title,
'sendMessage/optimisticCreateTopic',
+ optimisticTopic.metadata,
);
this.#get().internal_updateTopicLoading(optimisticTopic.id, true);
optimisticTopicActive = true;
@@ -660,16 +701,6 @@ export class ConversationLifecycleActionImpl {
// over the agent-level default. Without this, a topic pinned to dir A
// would silently execute under the agent's current default dir B and
// lose resume.
- const existingTopic = operationContext.topicId
- ? topicSelectors.getTopicById(operationContext.topicId)(this.#get())
- : undefined;
- const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
- const agentWorkingDirectory = agentByIdSelectors.getAgentWorkingDirectoryById(
- agentId,
- currentDeviceId,
- )(getAgentStoreState());
- const workingDirectory = existingTopic?.metadata?.workingDirectory || agentWorkingDirectory;
-
// Persist messages to DB first (same as client mode)
let heteroData: SendMessageServerResponse | undefined;
try {
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 89b97a418db..76ffcce8ffc 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -4,7 +4,12 @@ import {
type AgentStreamEvent,
type ConnectionStatus,
} from '@lobechat/agent-gateway-client';
-import type { ConversationContext, ExecAgentResult, MessageMetadata } from '@lobechat/types';
+import type {
+ ChatTopicMetadata,
+ ConversationContext,
+ ExecAgentResult,
+ MessageMetadata,
+} from '@lobechat/types';
import { isDesktop } from '@/const/version';
import { aiAgentService, type ResumeApprovalParam } from '@/services/aiAgent';
@@ -367,7 +372,7 @@ export class GatewayActionImpl {
/** 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 };
+ optimisticTopic?: { id: string; metadata?: ChatTopicMetadata; title: string };
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId?: string;
/**
@@ -492,12 +497,14 @@ export class GatewayActionImpl {
// Topic created successfully — now safe to clear the pending repo selection.
if (context.agentId) consumePendingTopicRepos(context.agentId);
if (optimisticTopic) {
+ const topicMetadata = optimisticTopic.metadata ?? initialTopicMetadata;
this.#get().internal_replaceTopicId({
agentId: context.agentId,
groupId: context.groupId,
nextId: result.topicId,
previousId: optimisticTopic.id,
value: {
+ ...(topicMetadata ? { metadata: topicMetadata } : {}),
...(context.groupId ? {} : { sessionId: context.agentId }),
title: optimisticTopic.title,
},