Skip to content

Commit 4917d17

Browse files
authored
💄 style: add notification for desktop (#8523)
* add notification for desktop * update i18n * fix tests
1 parent 5b53773 commit 4917d17

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+465
-17
lines changed
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
import {
2+
DesktopNotificationResult,
3+
ShowDesktopNotificationParams,
4+
} from '@lobechat/electron-client-ipc';
5+
import { Notification, app } from 'electron';
6+
import { macOS, windows } from 'electron-is';
7+
8+
import { createLogger } from '@/utils/logger';
9+
10+
import { ControllerModule, ipcClientEvent } from './index';
11+
12+
const logger = createLogger('controllers:NotificationCtr');
13+
14+
export default class NotificationCtr extends ControllerModule {
15+
/**
16+
* 在应用准备就绪后设置桌面通知
17+
*/
18+
afterAppReady() {
19+
this.setupNotifications();
20+
}
21+
22+
/**
23+
* 设置桌面通知权限和配置
24+
*/
25+
private setupNotifications() {
26+
logger.debug('Setting up desktop notifications');
27+
28+
try {
29+
// 检查通知支持
30+
if (!Notification.isSupported()) {
31+
logger.warn('Desktop notifications are not supported on this platform');
32+
return;
33+
}
34+
35+
// 在 macOS 上,我们可能需要显式请求通知权限
36+
if (macOS()) {
37+
logger.debug('macOS detected, notification permissions should be handled by system');
38+
}
39+
40+
// 在 Windows 上设置应用用户模型 ID
41+
if (windows()) {
42+
app.setAppUserModelId('com.lobehub.chat');
43+
logger.debug('Set Windows App User Model ID for notifications');
44+
}
45+
46+
logger.info('Desktop notifications setup completed');
47+
} catch (error) {
48+
logger.error('Failed to setup desktop notifications:', error);
49+
}
50+
}
51+
/**
52+
* 显示系统桌面通知(仅当窗口隐藏时)
53+
*/
54+
@ipcClientEvent('showDesktopNotification')
55+
async showDesktopNotification(
56+
params: ShowDesktopNotificationParams,
57+
): Promise<DesktopNotificationResult> {
58+
logger.debug('收到桌面通知请求:', params);
59+
60+
try {
61+
// 检查通知支持
62+
if (!Notification.isSupported()) {
63+
logger.warn('系统不支持桌面通知');
64+
return { error: 'Desktop notifications not supported', success: false };
65+
}
66+
67+
// 检查窗口是否隐藏
68+
const isWindowHidden = this.isMainWindowHidden();
69+
70+
if (!isWindowHidden) {
71+
logger.debug('主窗口可见,跳过桌面通知');
72+
return { reason: 'Window is visible', skipped: true, success: true };
73+
}
74+
75+
logger.info('窗口已隐藏,显示桌面通知:', params.title);
76+
77+
const notification = new Notification({
78+
body: params.body,
79+
// 添加更多配置以确保通知能正常显示
80+
hasReply: false,
81+
82+
silent: params.silent || false,
83+
84+
timeoutType: 'default',
85+
title: params.title,
86+
urgency: 'normal',
87+
});
88+
89+
// 添加更多事件监听来调试
90+
notification.on('show', () => {
91+
logger.info('通知已显示');
92+
});
93+
94+
notification.on('click', () => {
95+
logger.debug('用户点击通知,显示主窗口');
96+
const mainWindow = this.app.browserManager.getMainWindow();
97+
mainWindow.show();
98+
mainWindow.browserWindow.focus();
99+
});
100+
101+
notification.on('close', () => {
102+
logger.debug('通知已关闭');
103+
});
104+
105+
notification.on('failed', (error) => {
106+
logger.error('通知显示失败:', error);
107+
});
108+
109+
// 使用 Promise 来确保通知显示
110+
return new Promise((resolve) => {
111+
notification.show();
112+
113+
// 给通知一些时间来显示,然后检查结果
114+
setTimeout(() => {
115+
logger.info('通知显示调用完成');
116+
resolve({ success: true });
117+
}, 100);
118+
});
119+
} catch (error) {
120+
logger.error('显示桌面通知失败:', error);
121+
return {
122+
error: error instanceof Error ? error.message : 'Unknown error',
123+
success: false,
124+
};
125+
}
126+
}
127+
128+
/**
129+
* 检查主窗口是否隐藏
130+
*/
131+
@ipcClientEvent('isMainWindowHidden')
132+
isMainWindowHidden(): boolean {
133+
try {
134+
const mainWindow = this.app.browserManager.getMainWindow();
135+
const browserWindow = mainWindow.browserWindow;
136+
137+
// 如果窗口被销毁,认为是隐藏的
138+
if (browserWindow.isDestroyed()) {
139+
return true;
140+
}
141+
142+
// 检查窗口是否可见和聚焦
143+
const isVisible = browserWindow.isVisible();
144+
const isFocused = browserWindow.isFocused();
145+
const isMinimized = browserWindow.isMinimized();
146+
147+
logger.debug('窗口状态检查:', { isFocused, isMinimized, isVisible });
148+
149+
// 窗口隐藏的条件:不可见或最小化或失去焦点
150+
return !isVisible || isMinimized || !isFocused;
151+
} catch (error) {
152+
logger.error('检查窗口状态失败:', error);
153+
return true; // 发生错误时认为窗口隐藏,确保通知能显示
154+
}
155+
}
156+
}

locales/ar/electron.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
{
2+
"notification": {
3+
"finishChatGeneration": "تم إنشاء رسالة الذكاء الاصطناعي بنجاح"
4+
},
25
"proxy": {
36
"auth": "يتطلب المصادقة",
47
"authDesc": "إذا كان خادم الوكيل يتطلب اسم مستخدم وكلمة مرور",

locales/ar/models.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,6 +1499,12 @@
14991499
"hunyuan-vision": {
15001500
"description": "نموذج Hunyuan الأحدث متعدد الوسائط، يدعم إدخال الصور والنصوص لتوليد محتوى نصي."
15011501
},
1502+
"imagen-4.0-generate-preview-06-06": {
1503+
"description": "سلسلة نموذج Imagen للجيل الرابع لتحويل النص إلى صورة"
1504+
},
1505+
"imagen-4.0-ultra-generate-preview-06-06": {
1506+
"description": "نسخة ألترا من سلسلة نموذج Imagen للجيل الرابع لتحويل النص إلى صورة"
1507+
},
15021508
"imagen4/preview": {
15031509
"description": "نموذج توليد الصور الأعلى جودة من Google"
15041510
},
@@ -1919,6 +1925,9 @@
19191925
"moonshotai/Kimi-Dev-72B": {
19201926
"description": "Kimi-Dev-72B هو نموذج مفتوح المصدر للبرمجة، تم تحسينه عبر تعلم معزز واسع النطاق، قادر على إنتاج تصحيحات مستقرة وجاهزة للإنتاج مباشرة. حقق هذا النموذج نتيجة قياسية جديدة بنسبة 60.4% على SWE-bench Verified، محطماً الأرقام القياسية للنماذج المفتوحة المصدر في مهام هندسة البرمجيات الآلية مثل إصلاح العيوب ومراجعة الشيفرة."
19211927
},
1928+
"moonshotai/kimi-k2-instruct": {
1929+
"description": "kimi-k2 هو نموذج أساسي مبني على بنية MoE يتمتع بقدرات فائقة في البرمجة والوكيل، مع إجمالي 1 تريليون معلمة و32 مليار معلمة مفعلة. في اختبارات الأداء المعيارية في مجالات المعرفة العامة، البرمجة، الرياضيات، والوكيل، يتفوق نموذج K2 على النماذج المفتوحة المصدر الرئيسية الأخرى."
1930+
},
19221931
"nousresearch/hermes-2-pro-llama-3-8b": {
19231932
"description": "Hermes 2 Pro Llama 3 8B هو إصدار مطور من Nous Hermes 2، ويحتوي على أحدث مجموعات البيانات المطورة داخليًا."
19241933
},

locales/bg-BG/electron.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
{
2+
"notification": {
3+
"finishChatGeneration": "Съобщението от AI е генерирано успешно"
4+
},
25
"proxy": {
36
"auth": "Необходимо удостоверяване",
47
"authDesc": "Ако прокси сървърът изисква потребителско име и парола",

locales/bg-BG/models.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,6 +1499,12 @@
14991499
"hunyuan-vision": {
15001500
"description": "Най-новият мултимодален модел на HunYuan, поддържащ генериране на текстово съдържание от изображения и текстови входове."
15011501
},
1502+
"imagen-4.0-generate-preview-06-06": {
1503+
"description": "Imagen 4-то поколение текст-към-изображение модел серия"
1504+
},
1505+
"imagen-4.0-ultra-generate-preview-06-06": {
1506+
"description": "Imagen 4-то поколение текст-към-изображение модел серия Ултра версия"
1507+
},
15021508
"imagen4/preview": {
15031509
"description": "Най-висококачественият модел за генериране на изображения на Google."
15041510
},
@@ -1919,6 +1925,9 @@
19191925
"moonshotai/Kimi-Dev-72B": {
19201926
"description": "Kimi-Dev-72B е голям отворен модел за код, оптимизиран чрез мащабно подсилено обучение, способен да генерира стабилни и директно приложими пачове. Този модел постига нов рекорд от 60,4 % на SWE-bench Verified, подобрявайки резултатите на отворени модели в автоматизирани задачи за софтуерно инженерство като поправка на дефекти и преглед на код."
19211927
},
1928+
"moonshotai/kimi-k2-instruct": {
1929+
"description": "kimi-k2 е базов модел с MoE архитектура с изключителни способности за кодиране и агент, с общо 1 трилион параметри и 32 милиарда активни параметри. В бенчмаркови тестове за общи знания, програмиране, математика и агенти, моделът K2 превъзхожда други водещи отворени модели."
1930+
},
19221931
"nousresearch/hermes-2-pro-llama-3-8b": {
19231932
"description": "Hermes 2 Pro Llama 3 8B е обновена версия на Nous Hermes 2, включваща най-новите вътрешно разработени набори от данни."
19241933
},

locales/de-DE/electron.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
{
2+
"notification": {
3+
"finishChatGeneration": "KI-Nachricht wurde vollständig generiert"
4+
},
25
"proxy": {
36
"auth": "Authentifizierung erforderlich",
47
"authDesc": "Wenn der Proxy-Server Benutzername und Passwort benötigt",

locales/de-DE/models.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,6 +1499,12 @@
14991499
"hunyuan-vision": {
15001500
"description": "Das neueste multimodale Modell von Hunyuan unterstützt die Eingabe von Bildern und Text zur Generierung von Textinhalten."
15011501
},
1502+
"imagen-4.0-generate-preview-06-06": {
1503+
"description": "Imagen 4. Generation Text-zu-Bild Modellserie"
1504+
},
1505+
"imagen-4.0-ultra-generate-preview-06-06": {
1506+
"description": "Imagen 4. Generation Text-zu-Bild Modellserie Ultra-Version"
1507+
},
15021508
"imagen4/preview": {
15031509
"description": "Googles hochwertigstes Bildgenerierungsmodell"
15041510
},
@@ -1919,6 +1925,9 @@
19191925
"moonshotai/Kimi-Dev-72B": {
19201926
"description": "Kimi-Dev-72B ist ein Open-Source-Großmodell für Quellcode, das durch umfangreiche Verstärkungslernoptimierung robuste und direkt produktionsreife Patches erzeugen kann. Dieses Modell erreichte auf SWE-bench Verified eine neue Höchstpunktzahl von 60,4 % und stellte damit einen Rekord für Open-Source-Modelle bei automatisierten Software-Engineering-Aufgaben wie Fehlerbehebung und Code-Review auf."
19211927
},
1928+
"moonshotai/kimi-k2-instruct": {
1929+
"description": "kimi-k2 ist ein MoE-Architektur-Basismodell mit außergewöhnlichen Fähigkeiten in Code und Agenten, mit insgesamt 1 Billion Parametern und 32 Milliarden aktiven Parametern. In Benchmark-Tests zu allgemeinem Wissen, Programmierung, Mathematik und Agenten übertrifft das K2-Modell andere führende Open-Source-Modelle."
1930+
},
19221931
"nousresearch/hermes-2-pro-llama-3-8b": {
19231932
"description": "Hermes 2 Pro Llama 3 8B ist die aktualisierte Version von Nous Hermes 2 und enthält die neuesten intern entwickelten Datensätze."
19241933
},

locales/en-US/electron.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
{
2+
"notification": {
3+
"finishChatGeneration": "AI message generation completed"
4+
},
25
"proxy": {
36
"auth": "Authentication Required",
47
"authDesc": "If the proxy server requires a username and password",

locales/en-US/models.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,6 +1499,12 @@
14991499
"hunyuan-vision": {
15001500
"description": "The latest multimodal model from Hunyuan, supporting image + text input to generate textual content."
15011501
},
1502+
"imagen-4.0-generate-preview-06-06": {
1503+
"description": "Imagen 4th generation text-to-image model series"
1504+
},
1505+
"imagen-4.0-ultra-generate-preview-06-06": {
1506+
"description": "Imagen 4th generation text-to-image model series Ultra version"
1507+
},
15021508
"imagen4/preview": {
15031509
"description": "Google's highest quality image generation model."
15041510
},
@@ -1919,6 +1925,9 @@
19191925
"moonshotai/Kimi-Dev-72B": {
19201926
"description": "Kimi-Dev-72B is an open-source large code model optimized through extensive reinforcement learning, capable of producing robust, production-ready patches. This model achieved a new high score of 60.4% on SWE-bench Verified, setting a record for open-source models in automated software engineering tasks such as defect repair and code review."
19211927
},
1928+
"moonshotai/kimi-k2-instruct": {
1929+
"description": "kimi-k2 is a MoE architecture base model with powerful coding and Agent capabilities, featuring a total of 1 trillion parameters and 32 billion active parameters. In benchmark tests across key categories such as general knowledge reasoning, programming, mathematics, and Agent tasks, the K2 model outperforms other mainstream open-source models."
1930+
},
19221931
"nousresearch/hermes-2-pro-llama-3-8b": {
19231932
"description": "Hermes 2 Pro Llama 3 8B is an upgraded version of Nous Hermes 2, featuring the latest internally developed datasets."
19241933
},

locales/es-ES/electron.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
{
2+
"notification": {
3+
"finishChatGeneration": "El mensaje de IA se ha generado por completo"
4+
},
25
"proxy": {
36
"auth": "Se requiere autenticación",
47
"authDesc": "Si el servidor proxy requiere nombre de usuario y contraseña",

0 commit comments

Comments
 (0)