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.

✨ feat(desktop): unify agent-completion notification with click-to-deep-link (#16309)

Arvin Xu562fecc7e85c
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
index 64ff60623b7..d8dbbee6f8b 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts
@@ -2,18 +2,14 @@ import type { AgentState } from '@lobechat/agent-runtime';
import { isDesktop } from '@lobechat/const';
import type { ConversationContext, UIChatMessage } from '@lobechat/types';
import debug from 'debug';
-import { t } from 'i18next';
-import { getAgentStoreState } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
import type { AgentRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';
import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge';
import type { ChatStore } from '@/store/chat/store';
-import { resolveNotificationNavigatePath } from '@/store/chat/utils/desktopNotification';
+import { notifyDesktopAgentCompleted } from '@/store/chat/utils/desktopNotification';
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';
@@ -234,76 +230,47 @@ export const buildRunLifecycle = (
}
},
afterRunComplete: async (event: RunCompleteEvent) => {
- // Desktop notification + dock badge. Single home for all three runtimes'
- // completion notification β€” unified in afterRunComplete so every transport
- // fires the same notification/badge logic exactly once.
+ // Desktop notification + dock badge. Single home for all runtimes'
+ // completion notification β€” every transport funnels through the shared
+ // `notifyDesktopAgentCompleted` helper, so title (topic/agent name), body
+ // (the actual reply) and click-to-deep-link stay identical across them.
// Top-level-only: a nested sub-agent finishing is not a user-facing run
// completion β€” the parent run is still going, so it must not fire a
// "generation finished" notification / badge. See RunScope.
if (adapter.runScope === 'sub_agent') return;
if (!isDesktop) return;
- try {
- const { desktopNotificationService } =
- await import('@/services/electron/desktopNotification');
- const navigatePath = resolveNotificationNavigatePath({ agentId, groupId, topicId });
- const navigate = navigatePath ? { path: navigatePath } : undefined;
-
- if (adapter.runtimeType === 'client') {
- // CLIENT: notify only OUTSIDE tool-calling mode; title + body derived
- // from the in-memory store. Relocated verbatim β€” no badge (preserves
- // the prior client behavior).
- const finalMessages = get().messagesMap[messageKey] || [];
- const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');
- if (!lastAssistant?.content || lastAssistant?.tools) return;
-
- let notificationTitle = t('notification.finishChatGeneration', { ns: 'electron' });
- if (topicId) {
- const key = topicMapKey({ agentId, groupId });
- const topicData = get().topicDataMap[key];
- const topic = topicData?.items?.find((item) => item.id === topicId);
- if (topic?.title) notificationTitle = topic.title;
- } else {
- const agentMeta = agentSelectors.getAgentMetaById(agentId)(getAgentStoreState());
- if (agentMeta?.title) notificationTitle = agentMeta.title;
- }
- await desktopNotificationService.showNotification({
- body: markdownToTxt(lastAssistant.content),
- navigate,
- title: notificationTitle,
- });
- return;
- }
+ const notificationContext = { agentId, groupId, topicId };
- // GATEWAY / HETERO: the run-complete title is the generic completion
- // string; the body is executor-resolved (hetero's `accContent`) when
- // supplied, else derived from the store's final assistant content
- // (gateway, after its terminal DB reconciliation). Dock badge is set so a
- // backgrounded app still signals completion. Mirrors the prior
- // `notifyCompletion` fan-out.
- const fallbackContent = (
- get().messagesMap?.[messageKey] ||
- get().dbMessagesMap?.[messageKey] ||
- []
- ).findLast((m) => m.role === 'assistant')?.content;
- const body =
- event.notification?.body ??
- (fallbackContent
- ? markdownToTxt(fallbackContent)
- : t('notification.finishChatGeneration', { ns: 'electron' }));
- await Promise.allSettled([
- desktopNotificationService.showNotification({
- body,
- navigate,
- title:
- event.notification?.title ??
- t('notification.finishChatGeneration', { ns: 'electron' }),
- }),
- desktopNotificationService.setBadgeCount?.(1),
- ]);
- } catch (error) {
- console.error('Desktop notification error:', error);
+ 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).
+ const finalMessages = get().messagesMap[messageKey] || [];
+ const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');
+ if (!lastAssistant?.content || lastAssistant?.tools) return;
+
+ await notifyDesktopAgentCompleted(get, {
+ content: lastAssistant.content,
+ context: notificationContext,
+ });
+ return;
}
+
+ // GATEWAY / HETERO: the body content is executor-resolved (hetero's
+ // in-memory `accContent`) when supplied, else derived from the store's
+ // final assistant content (gateway, after its terminal DB reconciliation).
+ // Dock badge is set so a backgrounded app still signals completion.
+ const fallbackContent = (
+ get().messagesMap?.[messageKey] ||
+ get().dbMessagesMap?.[messageKey] ||
+ []
+ ).findLast((m) => m.role === 'assistant')?.content;
+
+ await notifyDesktopAgentCompleted(get, {
+ badge: true,
+ content: event.notification?.content ?? fallbackContent,
+ context: notificationContext,
+ });
},
beforeRunComplete: NOOP,
completeRun: async (event: RunCompleteEvent): Promise<RunCompleteResult> => {
diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/types.ts b/src/store/chat/slices/agentRun/actions/lifecycle/types.ts
index d39e250bfab..2d2927eeb7a 100644
--- a/src/store/chat/slices/agentRun/actions/lifecycle/types.ts
+++ b/src/store/chat/slices/agentRun/actions/lifecycle/types.ts
@@ -67,13 +67,13 @@ export interface TerminalPersistedEvent extends RunLifecycleEventBase {
export interface RunCompleteEvent extends RunLifecycleEventBase {
assistantMessageId?: string;
/**
- * Pre-resolved desktop-notification payload for transports whose final content
- * lives in executor memory rather than the store (hetero's `accContent`). When
- * present, {@link AgentRunLifecycle.afterRunComplete} shows it verbatim instead
- * of deriving the body from `messagesMap`. The client adapter omits it (it reads
- * the store); gateway/hetero supply it.
+ * Final assistant content (raw markdown) for transports whose reply lives in
+ * executor memory rather than the store (hetero's `accContent`). When present,
+ * {@link AgentRunLifecycle.afterRunComplete} feeds it to the notification body
+ * instead of deriving from `messagesMap`. The client adapter omits it (it reads
+ * the store); hetero supplies it.
*/
- notification?: { body: string; title?: string };
+ notification?: { content?: string };
operationStatus?: OperationStatus;
/**
* Raw runtime terminal/parked status (client `AgentState['status']`), used to
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 5a5840fb380..1e6265e8b1f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -45,7 +45,6 @@ import {
} from '@/store/chat/slices/operation/types';
import { type ChatStore, useChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { markdownToTxt } from '@/utils/markdownToTxt';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunScope } from '../../lifecycle/types';
@@ -1366,17 +1365,14 @@ export const executeHeterogeneousAgent = async (
// Signal completion to the user β€” dock badge + (window-hidden) notification,
// delegated to the shared `afterRunComplete` hook. It does the same
- // showNotification + setBadgeCount fan-out for non-client runtimes.
- // The body is resolved here from the
- // in-memory accumulated content (the store snapshot isn't durable yet).
+ // showNotification + setBadgeCount fan-out for non-client runtimes. We pass
+ // the in-memory accumulated content (the store snapshot isn't durable yet);
+ // the shared helper strips markdown + caps length + resolves the title.
// Skip for aborted runs and for error terminations.
if (!isAborted() && !isErrorTerminal) {
- const body = finalContent
- ? markdownToTxt(finalContent)
- : t('notification.finishChatGeneration', { ns: 'electron' });
await runLifecycle.afterRunComplete({
context,
- notification: { body },
+ notification: { content: finalContent },
operationId,
runId: operationId,
runScope,
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
index 019fe8ea5c7..3d25259a464 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
@@ -8,6 +8,7 @@ import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNo
// Keep zustand mock as it's needed globally
vi.mock('zustand/traditional');
vi.mock('@/store/chat/utils/desktopNotification', () => ({
+ notifyDesktopAgentCompleted: vi.fn().mockResolvedValue(undefined),
notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),
}));
diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.ts
index 19ce2e939cf..e188a66b9e5 100644
--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts
+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts
@@ -1,15 +1,13 @@
-import { isDesktop } from '@lobechat/const';
import { type ChatToolPayload } from '@lobechat/types';
import debug from 'debug';
-import i18n from 'i18next';
import { type StreamEvent } from '@/services/agentRuntime';
import { agentRuntimeService } from '@/services/agentRuntime';
-import { getAgentStoreState } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
import { type ChatStore } from '@/store/chat/store';
-import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
-import { topicMapKey } from '@/store/chat/utils/topicMapKey';
+import {
+ notifyDesktopAgentCompleted,
+ notifyDesktopHumanApprovalRequired,
+} from '@/store/chat/utils/desktopNotification';
import { type StoreSetter } from '@/store/types';
const log = debug('store:chat:ai-agent:runAgent');
@@ -245,37 +243,14 @@ export class AgentActionImpl {
// Stop loading state
log(`Stopping loading for ${assistantId}`);
- // Show desktop notification
- if (isDesktop) {
- try {
- const { desktopNotificationService } =
- await import('@/services/electron/desktopNotification');
-
- // Use topic title or agent title as notification title
- let notificationTitle = i18n.t('desktopNotification.aiReplyCompleted.title', {
- ns: 'chat',
- });
- const opCtx = operation.context;
- if (opCtx.topicId && opCtx.agentId) {
- const key = topicMapKey({ agentId: opCtx.agentId, groupId: opCtx.groupId });
- const topicData = this.#get().topicDataMap[key];
- const topic = topicData?.items?.find((item) => item.id === opCtx.topicId);
- if (topic?.title) notificationTitle = topic.title;
- } else if (opCtx.agentId) {
- const agentMeta = agentSelectors.getAgentMetaById(opCtx.agentId)(
- getAgentStoreState(),
- );
- if (agentMeta?.title) notificationTitle = agentMeta.title;
- }
-
- await desktopNotificationService.showNotification({
- body: i18n.t('desktopNotification.aiReplyCompleted.body', { ns: 'chat' }),
- title: notificationTitle,
- });
- } catch (error) {
- console.error('Desktop notification error:', error);
- }
- }
+ // Show desktop notification β€” unified completion notification: title =
+ // topic/agent name, body = the actual reply, click deep-links to the
+ // conversation. The helper no-ops off-desktop and resolves title/body
+ // from the operation context + final content.
+ await notifyDesktopAgentCompleted(this.#get, {
+ content: finalContent,
+ context: operation.context,
+ });
// Mark unread completion for background agents
const op = this.#get().operations[operationId];
diff --git a/src/store/chat/utils/desktopNotification.test.ts b/src/store/chat/utils/desktopNotification.test.ts
new file mode 100644
index 00000000000..59b427ee5c0
--- /dev/null
+++ b/src/store/chat/utils/desktopNotification.test.ts
@@ -0,0 +1,95 @@
+import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL, GROUP_CHAT_URL } from '@lobechat/const';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ChatStore } from '@/store/chat/store';
+
+import {
+ buildNotificationBody,
+ resolveNotificationNavigatePath,
+ resolveNotificationTitle,
+} from './desktopNotification';
+import { topicMapKey } from './topicMapKey';
+
+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ getAgentMetaById: (agentId: string) => () =>
+ agentId === 'agent-named' ? { title: 'My Agent' } : undefined,
+ },
+}));
+
+const FALLBACK = 'fallback';
+
+describe('resolveNotificationNavigatePath', () => {
+ it('deep-links a 1:1 agent + topic to the specific topic', () => {
+ expect(resolveNotificationNavigatePath({ agentId: 'a1', topicId: 't1' })).toBe(
+ AGENT_CHAT_TOPIC_URL('a1', 't1'),
+ );
+ });
+
+ it('falls back to the agent root when there is no topic', () => {
+ expect(resolveNotificationNavigatePath({ agentId: 'a1' })).toBe(AGENT_CHAT_URL('a1'));
+ });
+
+ it('lands a group chat on the group root, taking precedence over agent/topic', () => {
+ expect(
+ resolveNotificationNavigatePath({ agentId: 'a1', groupId: 'g1', topicId: 't1' }),
+ ).toBe(GROUP_CHAT_URL('g1'));
+ });
+
+ it('returns undefined when there is no routable context', () => {
+ expect(resolveNotificationNavigatePath({})).toBeUndefined();
+ });
+});
+
+describe('resolveNotificationTitle', () => {
+ const makeGet = (topicDataMap: unknown): (() => ChatStore) =>
+ (() => ({ topicDataMap }) as unknown as ChatStore);
+
+ it('prefers the topic title', () => {
+ const key = topicMapKey({ agentId: 'agent-named' });
+ const get = makeGet({ [key]: { items: [{ id: 't1', title: 'My Topic' }] } });
+ expect(resolveNotificationTitle(get, { agentId: 'agent-named', topicId: 't1' }, FALLBACK)).toBe(
+ 'My Topic',
+ );
+ });
+
+ it('falls back to the agent name when the topic has no title', () => {
+ const get = makeGet({});
+ expect(resolveNotificationTitle(get, { agentId: 'agent-named', topicId: 't1' }, FALLBACK)).toBe(
+ 'My Agent',
+ );
+ });
+
+ it('does not crash when the topic store slice is missing', () => {
+ const get = makeGet(undefined);
+ expect(resolveNotificationTitle(get, { agentId: 'agent-named', topicId: 't1' }, FALLBACK)).toBe(
+ 'My Agent',
+ );
+ });
+
+ it('uses the caller fallback when neither topic nor agent name resolves', () => {
+ const get = makeGet({});
+ expect(resolveNotificationTitle(get, { agentId: 'unknown-agent' }, FALLBACK)).toBe(FALLBACK);
+ });
+});
+
+describe('buildNotificationBody', () => {
+ it('strips markdown to plain text', () => {
+ const body = buildNotificationBody('**Done** with the `task`', FALLBACK);
+ expect(body).toContain('Done');
+ expect(body).not.toContain('**');
+ expect(body).not.toContain('`');
+ });
+
+ it('caps an overlong reply and appends an ellipsis', () => {
+ const body = buildNotificationBody('a'.repeat(500), FALLBACK);
+ expect(body).toHaveLength(257);
+ expect(body.endsWith('…')).toBe(true);
+ });
+
+ it('returns the fallback for empty / undefined content', () => {
+ expect(buildNotificationBody(undefined, FALLBACK)).toBe(FALLBACK);
+ expect(buildNotificationBody(' ', FALLBACK)).toBe(FALLBACK);
+ });
+});
diff --git a/src/store/chat/utils/desktopNotification.ts b/src/store/chat/utils/desktopNotification.ts
index 8ccda5b9b66..db7fbca56d5 100644
--- a/src/store/chat/utils/desktopNotification.ts
+++ b/src/store/chat/utils/desktopNotification.ts
@@ -5,6 +5,7 @@ import { t } from 'i18next';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import type { ChatStore } from '@/store/chat/store';
+import { markdownToTxt } from '@/utils/markdownToTxt';
import { topicMapKey } from './topicMapKey';
@@ -14,6 +15,9 @@ export interface DesktopNotificationContext {
topicId?: ConversationContext['topicId'];
}
+/** Cap the notification body so a long reply doesn't overflow the OS banner. */
+const NOTIFICATION_BODY_MAX_LENGTH = 256;
+
/**
* Resolve the SPA path that should be opened when the user clicks a desktop
* notification, based on the conversation context. Group chats land on the
@@ -31,15 +35,18 @@ export const resolveNotificationNavigatePath = (
return undefined;
};
-const resolveNotificationTitle = (
+/**
+ * Resolve the notification title from the conversation context. Prefers the
+ * topic title, then the agent name, and finally the caller-provided fallback.
+ */
+export const resolveNotificationTitle = (
get: () => ChatStore,
context: DesktopNotificationContext,
+ fallbackTitle: string,
): string => {
- const title = t('desktopNotification.humanApprovalRequired.title', { ns: 'chat' });
-
if (context.topicId && context.agentId) {
const key = topicMapKey({ agentId: context.agentId, groupId: context.groupId });
- const topicData = get().topicDataMap[key];
+ const topicData = get().topicDataMap?.[key];
const topic = topicData?.items?.find((item) => item.id === context.topicId);
if (topic?.title) return topic.title;
@@ -51,7 +58,19 @@ const resolveNotificationTitle = (
if (agentMeta?.title) return agentMeta.title;
}
- return title;
+ return fallbackTitle;
+};
+
+/** Convert the assistant's markdown reply to a length-capped plain-text body. */
+export const buildNotificationBody = (
+ content: string | undefined,
+ fallbackBody: string,
+): string => {
+ const text = content ? markdownToTxt(content).trim() : '';
+ if (!text) return fallbackBody;
+ return text.length > NOTIFICATION_BODY_MAX_LENGTH
+ ? `${text.slice(0, NOTIFICATION_BODY_MAX_LENGTH)}…`
+ : text;
};
export const notifyDesktopHumanApprovalRequired = async (
@@ -62,7 +81,11 @@ export const notifyDesktopHumanApprovalRequired = async (
try {
const { desktopNotificationService } = await import('@/services/electron/desktopNotification');
- const title = resolveNotificationTitle(get, context);
+ const title = resolveNotificationTitle(
+ get,
+ context,
+ t('desktopNotification.humanApprovalRequired.title', { ns: 'chat' }),
+ );
const navigatePath = resolveNotificationNavigatePath(context);
@@ -80,3 +103,49 @@ export const notifyDesktopHumanApprovalRequired = async (
console.error('Human approval desktop notification failed:', error);
}
};
+
+export interface AgentCompletedNotificationOptions {
+ /** Whether to also bump the dock/taskbar badge to 1 (background runs). */
+ badge?: boolean;
+ /** The assistant's final reply (markdown); rendered as the notification body. */
+ content?: string;
+ context: DesktopNotificationContext;
+}
+
+/**
+ * Unified "agent run finished" desktop notification β€” the single injection point
+ * every run path (client / gateway / hetero / group orchestration) calls so each
+ * completion notification stays consistent:
+ *
+ * - **title** = topic title β†’ agent name β†’ generic fallback,
+ * - **body** = the actual reply (markdown stripped + length-capped),
+ * - **click** = deep-links to the agent/topic (or group) conversation.
+ *
+ * Callers pass only their conversation context + the assistant reply; they never
+ * assemble the title / body / navigate themselves.
+ */
+export const notifyDesktopAgentCompleted = async (
+ get: () => ChatStore,
+ { context, content, badge }: AgentCompletedNotificationOptions,
+): Promise<void> => {
+ if (!isDesktop) return;
+
+ try {
+ const { desktopNotificationService } = await import('@/services/electron/desktopNotification');
+ const fallback = t('notification.finishChatGeneration', { ns: 'electron' });
+ const navigatePath = resolveNotificationNavigatePath(context);
+
+ const tasks: Promise<unknown>[] = [
+ desktopNotificationService.showNotification({
+ body: buildNotificationBody(content, fallback),
+ navigate: navigatePath ? { path: navigatePath } : undefined,
+ title: resolveNotificationTitle(get, context, fallback),
+ }),
+ ];
+ if (badge) tasks.push(desktopNotificationService.setBadgeCount(1));
+
+ await Promise.allSettled(tasks);
+ } catch (error) {
+ console.error('Agent completion desktop notification failed:', error);
+ }
+};