🤯 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(desktop): surface human approval notifications (#14092)
Arvin Xu3b94f86303ee
diff --git a/apps/desktop/src/main/controllers/NotificationCtr.ts b/apps/desktop/src/main/controllers/NotificationCtr.tsindex b0362cd0685..ed69c24116b 100644--- a/apps/desktop/src/main/controllers/NotificationCtr.ts+++ b/apps/desktop/src/main/controllers/NotificationCtr.ts@@ -99,7 +99,9 @@ export default class NotificationCtr extends ControllerModule {}}/**- * Show system desktop notification (only when window is hidden)+ * Show system desktop notification.+ * By default notifications only appear when the main window is hidden or unfocused.+ * High-priority callers can pass `force` to surface a banner even while focused.*/@IpcMethod()async showDesktopNotification(@@ -117,12 +119,16 @@ export default class NotificationCtr extends ControllerModule {// Check if window is hiddenconst isWindowHidden = this.isMainWindowHidden();- if (!isWindowHidden) {+ if (!params.force && !isWindowHidden) {logger.debug('Main window is visible, skipping desktop notification');return { reason: 'Window is visible', skipped: true, success: true };}- logger.info('Window is hidden, showing desktop notification:', params.title);+ if (params.requestAttention && isWindowHidden) {+ this.requestUserAttention();+ }++ logger.info('Showing desktop notification:', params.title);const notification = new Notification({body: params.body,@@ -178,6 +184,23 @@ export default class NotificationCtr extends ControllerModule {}}+ private requestUserAttention(): void {+ try {+ const mainWindow = this.app.browserManager.getMainWindow().browserWindow;++ if (mainWindow.isDestroyed()) return;++ if (electronIs.macOS()) {+ app.dock?.bounce?.('informational');+ return;+ }++ mainWindow.flashFrame(true);+ } catch (error) {+ logger.error('Failed to request user attention:', error);+ }+ }+/*** Set the app-level badge count (dock red dot on macOS, Unity counter on Linux,* overlay icon on Windows). Pass 0 to clear.diff --git a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.tsindex 83ce25039b4..76398d868ae 100644--- a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts@@ -34,6 +34,9 @@ vi.mock('electron', () => {},Notification: MockNotification,app: {+ dock: {+ bounce: vi.fn(),+ },setAppUserModelId: vi.fn(),},};@@ -48,6 +51,7 @@ vi.mock('electron-is', () => ({// Mock browserManagerconst mockBrowserWindow = {+ flashFrame: vi.fn(),focus: vi.fn(),isDestroyed: vi.fn(() => false),isFocused: vi.fn(() => true),@@ -181,6 +185,24 @@ describe('NotificationCtr', () => {expect(result).toEqual({ success: true });});+ it('should show notification when force is true even if window is visible and focused', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(false);++ const promise = controller.showDesktopNotification({+ ...params,+ force: true,+ });+ vi.advanceTimersByTime(100);+ const result = await promise;++ expect(Notification).toHaveBeenCalled();+ expect(result).toEqual({ success: true });+ });+it('should use low urgency on Linux to prevent GNOME Shell freeze', async () => {const { linux } = await import('electron-is');const { Notification } = await import('electron');@@ -252,6 +274,40 @@ describe('NotificationCtr', () => {);});+ it('should request window attention when requested and window is hidden', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);++ const promise = controller.showDesktopNotification({+ ...params,+ requestAttention: true,+ });+ vi.advanceTimersByTime(100);+ await promise;++ expect(mockBrowserWindow.flashFrame).toHaveBeenCalledWith(true);+ });++ it('should bounce dock on macOS when attention is requested', async () => {+ const { app, Notification } = await import('electron');+ const { macOS } = await import('electron-is');+ vi.mocked(macOS).mockReturnValue(true);+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(false);++ const promise = controller.showDesktopNotification({+ ...params,+ requestAttention: true,+ });+ vi.advanceTimersByTime(100);+ await promise;++ expect(app.dock.bounce).toHaveBeenCalledWith('informational');++ vi.mocked(macOS).mockReturnValue(false);+ });+it('should register click handler to show main window', async () => {const { Notification } = await import('electron');vi.mocked(Notification.isSupported).mockReturnValue(true);diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 77c8a3ef254..407b7d38899 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -105,6 +105,8 @@"defaultSession": "Default Agent","desktopNotification.aiReplyCompleted.body": "Agent reply is ready","desktopNotification.aiReplyCompleted.title": "Reply completed",+ "desktopNotification.humanApprovalRequired.body": "An Agent needs your approval to continue",+ "desktopNotification.humanApprovalRequired.title": "Approval required","dm.placeholder": "Your private messages with {{agentTitle}} will appear here.","dm.tooltip": "Send a private message","dm.visibleTo": "Visible to {{target}} only",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 571c774917e..56a91d39a2e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -105,6 +105,8 @@"defaultSession": "自定义助理","desktopNotification.aiReplyCompleted.body": "AI 回复生成完成","desktopNotification.aiReplyCompleted.title": "AI 回复完成",+ "desktopNotification.humanApprovalRequired.body": "Agent 需要你的批准后才能继续",+ "desktopNotification.humanApprovalRequired.title": "需要你的批准","dm.placeholder": "你与 {{agentTitle}} 的私信会显示在这里。","dm.tooltip": "发送私信","dm.visibleTo": "仅 {{target}} 可见",diff --git a/packages/electron-client-ipc/src/types/notification.ts b/packages/electron-client-ipc/src/types/notification.tsindex 08a6cf61bbb..26e94cde88e 100644--- a/packages/electron-client-ipc/src/types/notification.ts+++ b/packages/electron-client-ipc/src/types/notification.ts@@ -1,5 +1,7 @@export interface ShowDesktopNotificationParams {body: string;+ force?: boolean;+ requestAttention?: boolean;silent?: boolean;title: string;}diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex bd29154e7e2..41bb1fb8575 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -68,6 +68,8 @@ export default {'defaultSession': 'Default Agent','desktopNotification.aiReplyCompleted.body': 'Agent reply is ready','desktopNotification.aiReplyCompleted.title': 'Reply completed',+ 'desktopNotification.humanApprovalRequired.body': 'An Agent needs your approval to continue',+ 'desktopNotification.humanApprovalRequired.title': 'Approval required','dm.placeholder': 'Your private messages with {{agentTitle}} will appear here.','dm.tooltip': 'Send a private message','dm.visibleTo': 'Visible to {{target}} only',diff --git a/src/services/electron/desktopNotification.ts b/src/services/electron/desktopNotification.tsindex 7b438cca3f0..6bfd707b076 100644--- a/src/services/electron/desktopNotification.ts+++ b/src/services/electron/desktopNotification.ts@@ -10,7 +10,9 @@ import { ensureElectronIpc } from '@/utils/electron/ipc';*/export class DesktopNotificationService {/**- * Show desktop notification (only when window is hidden)+ * Show a desktop notification.+ * By default notifications only appear when the main window is hidden or unfocused.+ * Callers can override this with `force` for high-priority reminders.* @param params Notification parameters* @returns Notification result*/diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.tsindex f52b8c2baf0..083a65981f6 100644--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts@@ -3,9 +3,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { type StreamEvent } from '@/services/agentRuntime';import { useChatStore } from '@/store/chat/store';+import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');+vi.mock('@/store/chat/utils/desktopNotification', () => ({+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),+}));// Test Constantsconst TEST_IDS = {@@ -314,5 +318,66 @@ describe('runAgent actions', () => {expect(result.current.internal_dispatchMessage).not.toHaveBeenCalled();});});++ describe('step_start event', () => {+ it('should notify desktop when human approval is required', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ operations: {+ [TEST_IDS.OPERATION_ID]: {+ abortController: new AbortController(),+ context: { agentId: 'agent-1', groupId: 'group-1', topicId: 'topic-1' },+ id: TEST_IDS.OPERATION_ID,+ metadata: {+ lastEventId: '0',+ startTime: Date.now(),+ stepCount: 0,+ },+ status: 'running',+ type: 'groupAgentGenerate',+ },+ },+ });+ });++ const context = createStreamingContext({+ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ });++ const event: StreamEvent = {+ type: 'step_start',+ timestamp: Date.now(),+ operationId: TEST_IDS.OPERATION_ID,+ data: {+ pendingToolsCalling: [{ id: 'tool-1' }],+ phase: 'human_approval',+ requiresApproval: true,+ },+ };++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ expect(result.current.updateOperationMetadata).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID, {+ needsHumanInput: true,+ pendingApproval: [{ id: 'tool-1' }],+ });+ expect(notifyDesktopHumanApprovalRequired).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({+ agentId: 'agent-1',+ groupId: 'group-1',+ topicId: 'topic-1',+ }),+ );+ });+ });});});diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.tsindex 0ea263d3e1a..7f012b2668e 100644--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts@@ -8,6 +8,7 @@ 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 { type StoreSetter } from '@/store/types';@@ -285,6 +286,8 @@ export class AgentActionImpl {pendingApproval: pendingToolsCalling,});+ await notifyDesktopHumanApprovalRequired(this.#get, operation.context);+// Stop loading state, waiting for human interventionlog(`Stopping loading for human approval: ${assistantId}`);} else if (phase === 'tool_execution' && toolCall) {diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex ef443271a36..30eb230b42d 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -2,6 +2,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { beforeEach, describe, expect, it, vi } from 'vitest';import { messageService } from '@/services/message';+import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';import { createGatewayEventHandler } from '../gatewayEventHandler';@@ -11,6 +12,9 @@ vi.mock('@/services/message', () => ({updateMessageError: vi.fn().mockResolvedValue({ success: true }),},}));+vi.mock('@/store/chat/utils/desktopNotification', () => ({+ notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),+}));// ─── Test Helpers ───@@ -211,6 +215,29 @@ describe('createGatewayEventHandler', () => {});});+ describe('step_start', () => {+ it('should notify desktop when human approval is required', () => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(+ makeEvent('step_start', {+ pendingToolsCalling: [{ id: 'tool-1' }],+ phase: 'human_approval',+ requiresApproval: true,+ }),+ );++ expect(notifyDesktopHumanApprovalRequired).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({+ agentId: 'agent-1',+ topicId: 'topic-1',+ }),+ );+ });+ });+describe('tool_execute', () => {const toolExecuteData = {apiName: 'readFile',diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex 2c14ecbbd40..5c3c5b22130 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -10,6 +10,7 @@ import { AgentRuntimeErrorType } from '@lobechat/types';import { messageService } from '@/services/message';import type { ChatStore } from '@/store/chat/store';+import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';/*** Fetch messages from DB and replace them in the chat store's dbMessagesMap.@@ -197,6 +198,20 @@ export const createGatewayEventHandler = (break;}+ case 'step_start': {+ const data = event.data as {+ pendingToolsCalling?: unknown[];+ phase?: string;+ requiresApproval?: boolean;+ };++ if (data?.phase === 'human_approval' && data.requiresApproval && data.pendingToolsCalling) {+ void notifyDesktopHumanApprovalRequired(get, context);+ }++ break;+ }+case 'tool_execute': {// Fire-and-forget: the client-side tool may take a long time, and we// must keep processing other events (stream_chunk, tool_end, etc.) ondiff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 7acf053f71c..e7825ac8f1c 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -29,6 +29,7 @@ import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';import { type ChatStore, useChatStore } from '@/store/chat/store';+import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';import { getTaskStoreState } from '@/store/task';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { type StoreSetter } from '@/store/types';@@ -637,6 +638,15 @@ export class StreamingExecutorActionImpl {break;}+ case 'human_approve_required': {+ await notifyDesktopHumanApprovalRequired(this.#get, {+ agentId,+ groupId,+ topicId,+ });+ break;+ }+case 'error': {log('[internal_execAgentRuntime] Received error event: %o', event.error);// Find the assistant message to update errordiff --git a/src/store/chat/utils/desktopNotification.ts b/src/store/chat/utils/desktopNotification.tsnew file mode 100644index 00000000000..ae003e157ed--- /dev/null+++ b/src/store/chat/utils/desktopNotification.ts@@ -0,0 +1,62 @@+import { isDesktop } from '@lobechat/const';+import type { ConversationContext } from '@lobechat/types';+import { t } from 'i18next';++import { getAgentStoreState } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import type { ChatStore } from '@/store/chat/store';++import { topicMapKey } from './topicMapKey';++interface DesktopNotificationContext {+ agentId?: ConversationContext['agentId'];+ groupId?: ConversationContext['groupId'];+ topicId?: ConversationContext['topicId'];+}++const resolveNotificationTitle = (+ get: () => ChatStore,+ context: DesktopNotificationContext,+): 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 topic = topicData?.items?.find((item) => item.id === context.topicId);++ if (topic?.title) return topic.title;+ }++ if (context.agentId) {+ const agentMeta = agentSelectors.getAgentMetaById(context.agentId)(getAgentStoreState());++ if (agentMeta?.title) return agentMeta.title;+ }++ return title;+};++export const notifyDesktopHumanApprovalRequired = async (+ get: () => ChatStore,+ context: DesktopNotificationContext,+): Promise<void> => {+ if (!isDesktop) return;++ try {+ const { desktopNotificationService } = await import('@/services/electron/desktopNotification');+ const title = resolveNotificationTitle(get, context);++ await Promise.allSettled([+ desktopNotificationService.setBadgeCount(1),+ desktopNotificationService.showNotification({+ body: t('desktopNotification.humanApprovalRequired.body', { ns: 'chat' }),+ force: true,+ requestAttention: true,+ title,+ }),+ ]);+ } catch (error) {+ console.error('Human approval desktop notification failed:', error);+ }+};