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): pin client completion notification to the current run's reply (#16661)

Arvin Xu1e7e2d2b9a5a
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index f2949e14246..c467a2f0132 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -2654,7 +2654,12 @@ describe('StreamingExecutor actions', () => {
...state.messagesMap,
[messageMapKey({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID })]: [
{
+ // The completion notification now anchors its body to THIS run's
+ // assistant (findCompletionAssistantMessageId walks parentMessageId),
+ // not a positional findLast β€” so the seeded assistant must descend
+ // from the run's parentMessageId (TEST_IDS.USER_MESSAGE_ID) to be found.
...createMockMessage({ id: 'assistant-notif', role: 'assistant' }),
+ parentId: TEST_IDS.USER_MESSAGE_ID,
...overrides,
},
],
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
index 4b36f1428ff..e9eae0c5461 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '../../../../utils/messageMapKey';
import type { AgentRuntimeType } from '../dispatch/agentDispatcher';
import { buildRunLifecycle } from './buildRunLifecycle';
import type { RunCompleteEvent, RunTerminalStatus, UserMessagePersistedEvent } from './types';
@@ -15,6 +16,22 @@ vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () =
emitClientAgentSignalSourceEvent: agentSignalBridgeMock.emitClientAgentSignalSourceEvent,
}));
+const desktopNotificationMock = vi.hoisted(() => ({
+ notifyDesktopAgentCompleted: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@/store/chat/utils/desktopNotification', () => ({
+ notifyDesktopAgentCompleted: desktopNotificationMock.notifyDesktopAgentCompleted,
+}));
+
+// Force the desktop branch of afterRunComplete on (isDesktop is false in the
+// test env). Only afterRunComplete reads isDesktop, and it early-returns for
+// sub_agent runs before the check, so this is inert for every other test.
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, isDesktop: true };
+});
+
const OP = 'op1';
const CONTEXT: ConversationContext = { agentId: 'a1', topicId: 't1' } as ConversationContext;
@@ -74,6 +91,7 @@ const completeEvent = (
beforeEach(() => {
agentSignalBridgeMock.emitClientAgentSignalSourceEvent.mockClear();
+ desktopNotificationMock.notifyDesktopAgentCompleted.mockClear();
});
describe('buildRunLifecycle.completeRun β€” transport-driven disposition', () => {
@@ -181,6 +199,70 @@ describe('buildRunLifecycle β€” sub-agent runs skip top-level effects', () => {
completeEvent('gateway', { runScope: 'sub_agent', status: 'completed' }),
),
).resolves.toBeUndefined();
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).not.toHaveBeenCalled();
+ });
+});
+
+describe('buildRunLifecycle.afterRunComplete β€” client desktop notification body', () => {
+ const KEY = messageMapKey(CONTEXT);
+ // parentMessageId for the run under test is 'u1' (see `lifecycle` helper), so
+ // the assistant this run produced is the child of 'u1'.
+ const thisTurnAssistant = {
+ content: 'second turn reply',
+ id: 'a-this',
+ parentId: 'u1',
+ role: 'assistant',
+ } as any;
+ const prevTurnAssistant = {
+ content: 'first turn reply',
+ id: 'a-prev',
+ parentId: 'u-prev',
+ role: 'assistant',
+ } as any;
+
+ it('anchors the body to THIS run reply even when messagesMap still ends on the previous turn', async () => {
+ const { get, store } = makeStore();
+ // messagesMap lags: its last assistant is the PREVIOUS turn. The current
+ // run's assistant has only settled into dbMessagesMap so far.
+ store.messagesMap = { [KEY]: [prevTurnAssistant] } as any;
+ store.dbMessagesMap = { [KEY]: [prevTurnAssistant, thisTurnAssistant] } as any;
+
+ await lifecycle('client', get).afterRunComplete(
+ completeEvent('client', { runtimeStatus: 'done' }),
+ );
+
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).toHaveBeenCalledTimes(1);
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).toHaveBeenCalledWith(
+ get,
+ expect.objectContaining({ content: 'second turn reply' }),
+ );
+ });
+
+ it('uses this run reply when it is present in messagesMap (linear happy path)', async () => {
+ const { get, store } = makeStore();
+ store.messagesMap = { [KEY]: [prevTurnAssistant, thisTurnAssistant] } as any;
+
+ await lifecycle('client', get).afterRunComplete(
+ completeEvent('client', { runtimeStatus: 'done' }),
+ );
+
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).toHaveBeenCalledWith(
+ get,
+ expect.objectContaining({ content: 'second turn reply' }),
+ );
+ });
+
+ it('suppresses the notification while this run assistant is still tool-calling', async () => {
+ const { get, store } = makeStore();
+ store.messagesMap = {
+ [KEY]: [{ ...thisTurnAssistant, content: 'partial', tools: [{ id: 'tool-1' }] }],
+ } as any;
+
+ await lifecycle('client', get).afterRunComplete(
+ completeEvent('client', { runtimeStatus: 'done' }),
+ );
+
+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).not.toHaveBeenCalled();
});
});
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index 0760ed41519..60e56d8e3d9 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
@@ -246,8 +246,23 @@ export const buildRunLifecycle = (
if (adapter.runtimeType === 'client') {
// CLIENT: notify only OUTSIDE tool-calling mode; content comes from the
// in-memory store. No badge (preserves the prior client behavior).
+ //
+ // Anchor to the assistant message THIS run produced (walk from
+ // parentMessageId), NOT a positional findLast on the topic. On a later
+ // turn the fresh assistant can still be settling into messagesMap while
+ // the previous turn's assistant is the last populated one β€” a naive
+ // findLast then surfaces the PRIOR turn's reply as the notification body.
+ // Mirror emitComplete's dual-map (messagesMap β†’ dbMessagesMap) lookup so
+ // the body is pinned to this run's freshest persisted content.
const finalMessages = get().messagesMap[messageKey] || [];
- const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');
+ const dbMessages = get().dbMessagesMap[messageKey] || [];
+ const assistantId =
+ findCompletionAssistantMessageId(finalMessages, parentMessageId, parentMessageType) ??
+ findCompletionAssistantMessageId(dbMessages, parentMessageId, parentMessageType);
+ const lastAssistant = assistantId
+ ? (finalMessages.find((m) => m.id === assistantId) ??
+ dbMessages.find((m) => m.id === assistantId))
+ : undefined;
if (!lastAssistant?.content || lastAssistant?.tools) return;
await notifyDesktopAgentCompleted(get, {