@mysterycode-liwen/dsh-mail 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1880 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@mysterycode-liwen/dsh-mail',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const { useState, useEffect, useRef, useLayoutEffect } = React;
7
+
8
+ const NS = 'dsh-mail';
9
+ const API = '/api/dsh-mail';
10
+
11
+ function escHtml(s) {
12
+ return String(s == null ? '' : s)
13
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
14
+ }
15
+
16
+ let t = (key) => key;
17
+
18
+ // Map a structured bridge error ({ code, error, stage }) to a short,
19
+ // human-readable message. The raw server text is kept as a second line so
20
+ // nothing diagnostic is lost, but it is no longer the whole message.
21
+ function friendlyError(data) {
22
+ const info = (data && typeof data === 'object') ? data : { error: String(data || '') };
23
+ const stage = info.stage
24
+ ? (info.stage === 'imap' ? t('imapHost') : t('smtpHost')) + ' · '
25
+ : '';
26
+ const map = {
27
+ auth_failed: t('errAuthFailed'),
28
+ rate_limited: t('errRateLimited'),
29
+ service_disabled: t('errServiceDisabled'),
30
+ timeout: t('errTimeout'),
31
+ tls: t('errTls'),
32
+ network: t('errNetwork'),
33
+ folder: t('errFolder'),
34
+ search: t('errSearch'),
35
+ not_found: t('errNotFound'),
36
+ generic: t('errGeneric'),
37
+ };
38
+ const known = Object.prototype.hasOwnProperty.call(map, info.code);
39
+ const head = known ? map[info.code] : t('errGeneric');
40
+ const raw = String(info.error || '').trim();
41
+ const detail = (!known && raw && raw !== head) ? '\n' + t('errDetail') + raw : '';
42
+ return stage + head + detail;
43
+ }
44
+
45
+ const zh = {
46
+ label: '邮件',
47
+ badgeTitle: '有新邮件',
48
+ accounts: '账号',
49
+ addAccount: '添加账号',
50
+ noAccounts: '还没有账号,添加一个即可开始收发邮件。',
51
+ name: '名称',
52
+ username: '邮箱地址',
53
+ authCode: '密码 / 授权码',
54
+ imapHost: 'IMAP 主机',
55
+ imapPort: 'IMAP 端口',
56
+ smtpHost: 'SMTP 主机',
57
+ smtpPort: 'SMTP 端口',
58
+ save: '保存',
59
+ cancel: '取消',
60
+ test: '测试连接',
61
+ delete: '删除',
62
+ refresh: '刷新',
63
+ refreshing: '刷新中…',
64
+ refreshed: '已刷新',
65
+ refreshFailed: '刷新失败',
66
+ inbox: '收件箱',
67
+ compose: '写邮件',
68
+ to: '收件人',
69
+ subject: '主题',
70
+ body: '正文',
71
+ send: '发送',
72
+ back: '返回',
73
+ from: '发件人',
74
+ date: '日期',
75
+ noMessages: '没有邮件。',
76
+ filterAll: '全部',
77
+ filterUnread: '未读',
78
+ filterRead: '已读',
79
+ noFiltered: '没有符合条件的邮件。',
80
+ loading: '加载中…',
81
+ selectAccount: '请选择一个账号。',
82
+ qq: 'QQ 邮箱',
83
+ netease: '网易 163',
84
+ gmail: 'Gmail',
85
+ custom: '自定义',
86
+ presets: '快速设置',
87
+ note: 'QQ / 163 需要邮箱授权码,而不是登录密码。授权码保存在凭据保险箱中。',
88
+ confirmDelete: '确定删除此账号吗?',
89
+ noSubject: '(无主题)',
90
+ ok: '成功',
91
+ failed: '失败',
92
+ errAuthFailed: '登录失败:邮箱账号或授权码不正确,也可能是 IMAP/SMTP 服务未开启、操作太频繁。QQ/163 请使用「授权码」而非登录密码,并确认已在邮箱设置中开启 IMAP/SMTP 服务。',
93
+ errRateLimited: '登录过于频繁,邮箱服务器暂时拒绝了请求。请稍等几分钟后再试。',
94
+ errServiceDisabled: '邮箱的 IMAP/SMTP 服务未开启。请登录邮箱网页版,在「设置 → 账户」中开启 POP3/IMAP/SMTP 服务后再试。',
95
+ errTimeout: '连接邮箱服务器超时,请检查网络后重试。',
96
+ errTls: '加密连接失败,请检查服务器地址和端口,确认已启用 TLS/SSL(993 / 465 端口)。',
97
+ errNetwork: '无法连接邮箱服务器,请检查网络、服务器地址和端口是否正确。',
98
+ errFolder: '读取邮件文件夹失败,请刷新后重试。',
99
+ errSearch: '搜索邮件失败,请稍后重试。',
100
+ errNotFound: '未找到这封邮件,它可能已被删除。',
101
+ errGeneric: '操作失败,请稍后重试。',
102
+ errDetail: '服务器返回:',
103
+ sent: '发件箱',
104
+ contacts: '联系人',
105
+ noSent: '还没有已发送的邮件。',
106
+ noContacts: '还没有联系人,请在下方手动添加。',
107
+ addContact: '添加联系人',
108
+ contactName: '姓名',
109
+ contactEmail: '邮箱地址',
110
+ saveContact: '保存联系人',
111
+ deleteContact: '删除',
112
+ contactsHint: '手动添加的联系人仅保存在本地,不会上传到邮箱服务器。',
113
+ emailRequired: '请填写有效的邮箱地址。',
114
+ saved: '已保存。',
115
+ selectContact: '用此地址写邮件',
116
+ attached: '附件',
117
+ settingsTitle: '邮件',
118
+ settingsDescription: '配置 AI 助手是否可以读取你的邮箱。',
119
+ agentMailAccessLabel: '允许 AI 助手查询邮箱',
120
+ agentMailAccessHint: '开启后,AI 助手可以列出账号、读取邮件列表与内容、查看发件箱;不会暴露密码或授权码,也不能发送或删除邮件。默认关闭。',
121
+ agentMailAccessOn: '已开启:AI 助手可以读取邮箱。',
122
+ agentMailAccessOff: '已关闭:AI 助手无法读取邮箱。',
123
+ settingsUnavailable: '本页没有可编辑的配置表单;请在 profile 配置中设置 agentMailAccess。',
124
+ settingsReadOnly: '本部署的设置为只读。',
125
+ settingsSave: '保存',
126
+ settingsSaving: '保存中…',
127
+ settingsSaveFailed: '设置保存失败,请重试。',
128
+ settingsSaveSuccess: '设置已保存。',
129
+ notifySectionTitle: '新邮件通知',
130
+ notifySectionHint: '后台定时检查邮箱,收到新邮件时让桌宠气泡播报;若浏览器已授权,也会同时弹出系统通知。',
131
+ notifySectionHintSystem: '后台定时检查邮箱,收到新邮件时弹出系统通知(需浏览器授权)。',
132
+ notifyEnabledLabel: '启用新邮件提醒(桌宠播报)',
133
+ notifyEnabledLabelSystem: '启用新邮件提醒(系统通知)',
134
+ notifyIntervalLabel: '检查间隔(秒)',
135
+ notifyPermission: '申请通知权限',
136
+ notifyPermissionGranted: '通知权限已开启',
137
+ notifyPermissionDenied: '通知权限被浏览器阻止,请在浏览器设置中允许本站通知',
138
+ notifyPermissionUnsupported: '当前环境不支持系统通知',
139
+ notifyPermissionAsking: '申请中…',
140
+ notifyTest: '发送测试通知',
141
+ notifyTestSent: '测试通知已发出(请到系统通知中心查看)',
142
+ notifyTestFailed: '测试通知发送失败',
143
+ notifyTitle: '新邮件',
144
+ notifyBody: '封未读新邮件',
145
+ notifyTestTitle: '邮件播报测试',
146
+ notifyTestBody: '如果你看到桌宠说话,说明新邮件播报已正常工作。',
147
+ notifyTestTitleSystem: '新邮件通知测试',
148
+ notifyTestBodySystem: '如果你在系统通知中心看到这条消息,说明新邮件通知已正常工作。',
149
+ notifyPetOk: '已让桌宠播报(请留意桌面桌宠)',
150
+ notifyPetNone: '未发现可用的桌宠,仅发送了系统通知',
151
+ notifyMode: '通知方式',
152
+ notifyModePet: '桌宠播报',
153
+ notifyModeSystem: '系统通知(需浏览器权限)',
154
+ notifyModeBoth: '桌宠播报 + 系统通知',
155
+ notifyCheckNow: '立即检查新邮件',
156
+ notifyChecking: '检查中…',
157
+ notifyCheckDone: '检查完成:发现 {n} 封新邮件',
158
+ notifyDiagTitle: '检测状态',
159
+ notifyDiagRunning: '轮询运行中',
160
+ notifyDiagStopped: '轮询未运行',
161
+ notifyDiagAccounts: '账号数',
162
+ notifyDiagChecks: '检查次数',
163
+ notifyDiagAlerts: '播报次数',
164
+ notifyDiagAlertsSystem: '通知次数',
165
+ notifyDiagLastCheck: '上次检查',
166
+ notifyDiagNever: '从未',
167
+ notifyDiagError: '最近错误',
168
+ notifyDiagOk: '正常',
169
+ };
170
+ const en = {
171
+ label: 'Mail',
172
+ badgeTitle: 'New mail',
173
+ accounts: 'Accounts',
174
+ addAccount: 'Add account',
175
+ noAccounts: 'No accounts yet. Add one to start sending and receiving mail.',
176
+ name: 'Name',
177
+ username: 'Email address',
178
+ authCode: 'Password / app code',
179
+ imapHost: 'IMAP host',
180
+ imapPort: 'IMAP port',
181
+ smtpHost: 'SMTP host',
182
+ smtpPort: 'SMTP port',
183
+ save: 'Save',
184
+ cancel: 'Cancel',
185
+ test: 'Test connection',
186
+ delete: 'Delete',
187
+ refresh: 'Refresh',
188
+ refreshing: 'Refreshing…',
189
+ refreshed: 'Refreshed',
190
+ refreshFailed: 'Refresh failed',
191
+ inbox: 'Inbox',
192
+ compose: 'Compose',
193
+ to: 'To',
194
+ subject: 'Subject',
195
+ body: 'Body',
196
+ send: 'Send',
197
+ back: 'Back',
198
+ from: 'From',
199
+ date: 'Date',
200
+ noMessages: 'No messages.',
201
+ filterAll: 'All',
202
+ filterUnread: 'Unread',
203
+ filterRead: 'Read',
204
+ noFiltered: 'No messages match this filter.',
205
+ loading: 'Loading…',
206
+ selectAccount: 'Select an account.',
207
+ qq: 'QQ Mail',
208
+ netease: 'NetEase 163',
209
+ gmail: 'Gmail',
210
+ custom: 'Custom',
211
+ presets: 'Presets',
212
+ note: 'QQ / 163 need an app password, not your login password. Stored in the credential vault.',
213
+ confirmDelete: 'Delete this account?',
214
+ noSubject: '(no subject)',
215
+ ok: 'OK',
216
+ failed: 'Failed',
217
+ errAuthFailed: 'Login failed: the email address or app password is wrong, or IMAP/SMTP is disabled / you tried too often. For QQ/163 use an app password (not your login password) and enable IMAP/SMTP in your mailbox settings.',
218
+ errRateLimited: 'Too many login attempts — the mail server temporarily refused the request. Please wait a few minutes and try again.',
219
+ errServiceDisabled: 'IMAP/SMTP is not enabled for this mailbox. Sign in to the webmail, enable POP3/IMAP/SMTP under settings, then retry.',
220
+ errTimeout: 'Connection to the mail server timed out. Check your network and try again.',
221
+ errTls: 'Encrypted connection failed. Check the server and port, and make sure TLS/SSL is enabled (port 993 / 465).',
222
+ errNetwork: 'Could not reach the mail server. Check your network and verify the server address and port.',
223
+ errFolder: 'Could not open the mail folder. Please refresh and try again.',
224
+ errSearch: 'Search failed. Please try again later.',
225
+ errNotFound: 'This message was not found — it may have been deleted.',
226
+ errGeneric: 'The operation failed. Please try again later.',
227
+ errDetail: 'Server said: ',
228
+ sent: 'Sent',
229
+ contacts: 'Contacts',
230
+ noSent: 'No sent messages yet.',
231
+ noContacts: 'No contacts yet. Add one with the form below.',
232
+ addContact: 'Add contact',
233
+ contactName: 'Name',
234
+ contactEmail: 'Email address',
235
+ saveContact: 'Save contact',
236
+ deleteContact: 'Delete',
237
+ contactsHint: 'Contacts you add are saved locally only and are not uploaded to the mail server.',
238
+ emailRequired: 'Please enter a valid email address.',
239
+ saved: 'Saved.',
240
+ selectContact: 'Compose to this address',
241
+ attached: 'Attachments',
242
+ settingsTitle: 'Mail',
243
+ settingsDescription: 'Control whether the AI assistant may read your mailbox.',
244
+ agentMailAccessLabel: 'Allow AI assistant to query mail',
245
+ agentMailAccessHint: 'When on, the AI assistant can list accounts, read message lists and bodies, and view sent mail. Passwords and app codes are never exposed, and it cannot send or delete mail. Off by default.',
246
+ agentMailAccessOn: 'On: the AI assistant can read your mailbox.',
247
+ agentMailAccessOff: 'Off: the AI assistant cannot read your mailbox.',
248
+ settingsUnavailable: 'This page has no editable configuration form; set `agentMailAccess` in the profile configuration instead.',
249
+ settingsReadOnly: 'This deployment stores settings read-only.',
250
+ settingsSave: 'Save',
251
+ settingsSaving: 'Saving…',
252
+ settingsSaveFailed: 'Failed to save settings. Please try again.',
253
+ settingsSaveSuccess: 'Settings saved.',
254
+ notifySectionTitle: 'New mail notifications',
255
+ notifySectionHint: 'Check your mailbox in the background and have your desktop pet announce new mail in a speech bubble; a system notification is also shown when browser permission is granted.',
256
+ notifySectionHintSystem: 'Check your mailbox in the background and show a system notification for new mail (needs browser permission).',
257
+ notifyEnabledLabel: 'Enable new mail alerts (pet announcement)',
258
+ notifyEnabledLabelSystem: 'Enable new mail alerts (system notification)',
259
+ notifyIntervalLabel: 'Check interval (seconds)',
260
+ notifyPermission: 'Grant notification permission',
261
+ notifyPermissionGranted: 'Notification permission is granted',
262
+ notifyPermissionDenied: 'Notifications are blocked by the browser; allow them for this site in browser settings',
263
+ notifyPermissionUnsupported: 'System notifications are not supported here',
264
+ notifyPermissionAsking: 'Requesting…',
265
+ notifyTest: 'Send a test notification',
266
+ notifyTestSent: 'Test notification sent (check your notification center)',
267
+ notifyTestFailed: 'Failed to send test notification',
268
+ notifyTitle: 'New mail',
269
+ notifyBody: 'new unread message(s)',
270
+ notifyTestTitle: 'Mail announcement test',
271
+ notifyTestBody: 'If your desktop pet speaks, new mail announcements are working.',
272
+ notifyTestTitleSystem: 'New mail notification test',
273
+ notifyTestBodySystem: 'If you see this message in your notification center, new mail notifications are working.',
274
+ notifyPetOk: 'Asked your desktop pet to announce it (watch the desktop)',
275
+ notifyPetNone: 'No desktop pet available; only a system notification was sent',
276
+ notifyMode: 'Notification mode',
277
+ notifyModePet: 'Pet announcement',
278
+ notifyModeSystem: 'System notification (needs browser permission)',
279
+ notifyModeBoth: 'Pet announcement + system notification',
280
+ notifyCheckNow: 'Check new mail now',
281
+ notifyChecking: 'Checking…',
282
+ notifyCheckDone: 'Check complete: {n} new message(s)',
283
+ notifyDiagTitle: 'Detection status',
284
+ notifyDiagRunning: 'Poller running',
285
+ notifyDiagStopped: 'Poller not running',
286
+ notifyDiagAccounts: 'Accounts',
287
+ notifyDiagChecks: 'Checks',
288
+ notifyDiagAlerts: 'Alerts',
289
+ notifyDiagAlertsSystem: 'Notifications',
290
+ notifyDiagLastCheck: 'Last check',
291
+ notifyDiagNever: 'Never',
292
+ notifyDiagError: 'Last error',
293
+ notifyDiagOk: 'OK',
294
+ };
295
+
296
+ // ---------------------------------------------------------------------
297
+ // Visual layer. Everything is class-based and scoped under .dsh-mail so
298
+ // it cannot leak into the host app. Colors come only from DSH theme
299
+ // tokens, so light/dark themes both look native. Interaction feedback
300
+ // uses transform/opacity/brightness (theme-independent) instead of the
301
+ // hardcoded gray buttons the previous version had.
302
+ // ---------------------------------------------------------------------
303
+ const CSS = [
304
+ '.dsh-mail { display:flex; flex-direction:column; height:100%; box-sizing:border-box; background:var(--dsw-alias-bg-base); color:var(--dsw-alias-label-primary); font-family:inherit; font-size:13px; line-height:1.5; }',
305
+ '.dsh-mail * { box-sizing:border-box; }',
306
+ '.dsh-mail button, .dsh-mail input, .dsh-mail textarea, .dsh-mail select { font-family:inherit; }',
307
+ '.dsh-mail-spacer { flex:1; min-width:0; }',
308
+
309
+ /* top bar */
310
+ '.dsh-mail-topbar { display:flex; align-items:center; gap:12px; padding:14px 18px 13px; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-1); }',
311
+ '.dsh-mail-brand { display:flex; align-items:center; gap:10px; font-size:16px; font-weight:650; letter-spacing:.2px; }',
312
+ '.dsh-mail-brandmark { width:32px; height:32px; border-radius:10px; display:grid; place-items:center; background:var(--dsw-alias-brand-primary); color:var(--dsw-alias-bg-base); box-shadow:0 2px 8px rgba(0,0,0,.14); }',
313
+ '.dsh-mail-brandsub { font-size:11px; color:var(--dsw-alias-label-secondary); font-weight:400; }',
314
+
315
+ /* buttons */
316
+ '.dsh-mail-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; padding:7px 12px; font-size:12px; font-weight:600; line-height:1.4; cursor:pointer; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); transition:filter .12s, transform .06s, box-shadow .12s; white-space:nowrap; }',
317
+ '.dsh-mail-btn:hover:not(:disabled) { filter:brightness(.94); }',
318
+ '.dsh-mail-btn:active:not(:disabled) { transform:translateY(1px); box-shadow:inset 0 2px 5px rgba(0,0,0,.12); }',
319
+ '.dsh-mail-btn:focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:2px; }',
320
+ '.dsh-mail-btn:disabled { opacity:.45; cursor:not-allowed; }',
321
+ '.dsh-mail-btn-primary { background:var(--dsw-alias-brand-primary); border-color:transparent; color:var(--dsw-alias-bg-base); box-shadow:0 2px 8px rgba(0,0,0,.16); }',
322
+ '.dsh-mail-btn-primary:hover:not(:disabled) { filter:brightness(1.08); }',
323
+ '.dsh-mail-btn-danger { color:var(--dsw-alias-state-error-primary); border-color:var(--dsw-alias-state-error-primary); background:transparent; }',
324
+ '.dsh-mail-btn-danger:hover:not(:disabled) { filter:none; background:var(--dsw-alias-state-error-primary); color:#fff; }',
325
+ '.dsh-mail-iconbtn { width:30px; height:30px; padding:0; border-radius:8px; }',
326
+ '.dsh-mail-iconbtn .dsh-mail-spinicon { animation:dsh-mail-spin .8s linear infinite; }',
327
+ '.dsh-mail-refresh-ok { color:var(--dsw-alias-state-success-primary); }',
328
+ '.dsh-mail-refresh-err { color:var(--dsw-alias-state-error-primary); }',
329
+
330
+ /* segmented navigation */
331
+ '.dsh-mail-tabs { display:flex; align-items:center; gap:2px; padding:0 12px; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-1); overflow-x:auto; }',
332
+ '.dsh-mail-tab { position:relative; display:inline-flex; align-items:center; gap:7px; padding:11px 13px 12px; border:0; background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; font-weight:600; cursor:pointer; white-space:nowrap; transition:color .12s; }',
333
+ '.dsh-mail-tab:hover { color:var(--dsw-alias-label-primary); }',
334
+ '.dsh-mail-tab.is-active { color:var(--dsw-alias-brand-primary); }',
335
+ '.dsh-mail-tab.is-active::after { content:""; position:absolute; left:10px; right:10px; bottom:0; height:2px; border-radius:2px 2px 0 0; background:var(--dsw-alias-brand-primary); }',
336
+ '.dsh-mail-badge { display:grid; place-items:center; min-width:17px; height:17px; padding:0 5px; border-radius:9px; background:var(--dsw-alias-brand-primary); color:var(--dsw-alias-bg-base); font-size:10px; font-weight:700; }',
337
+
338
+ /* account chip */
339
+ '.dsh-mail-accountbar { display:flex; align-items:center; gap:9px; padding:9px 16px; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-base); }',
340
+ '.dsh-mail-select { flex:1; min-width:0; max-width:320px; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; padding:6px 9px; background:var(--dsw-alias-bg-layer-1); color:var(--dsw-alias-label-primary); font-size:12px; cursor:pointer; }',
341
+
342
+ /* read/unread filter */
343
+ '.dsh-mail-filterbar { display:flex; align-items:center; gap:4px; padding:7px 12px; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-base); }',
344
+ '.dsh-mail-filter { display:inline-flex; align-items:center; gap:6px; padding:5px 11px; border:1px solid transparent; border-radius:8px; background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; font-weight:600; cursor:pointer; transition:background .12s,color .12s; }',
345
+ '.dsh-mail-filter:hover { background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); }',
346
+ '.dsh-mail-filter.is-active { background:color-mix(in srgb, var(--dsw-alias-brand-primary) 12%, transparent); color:var(--dsw-alias-brand-primary); }',
347
+ '.dsh-mail-filtercount { display:grid; place-items:center; min-width:17px; height:17px; padding:0 5px; border-radius:9px; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-secondary); font-size:10px; font-weight:700; }',
348
+ '.dsh-mail-filter.is-active .dsh-mail-filtercount { background:var(--dsw-alias-brand-primary); color:var(--dsw-alias-bg-base); }',
349
+
350
+ /* message list */
351
+ '.dsh-mail-list { flex:1; min-height:0; overflow:auto; padding:6px 8px 18px; }',
352
+ '.dsh-mail-row { display:flex; align-items:flex-start; gap:11px; padding:12px 11px; border-radius:11px; border:1px solid transparent; cursor:pointer; transition:background .12s, border-color .12s; }',
353
+ '.dsh-mail-row:hover { background:var(--dsw-alias-bg-layer-2); }',
354
+ '.dsh-mail-row:active { transform:scale(.995); }',
355
+ '.dsh-mail-avatar { width:36px; height:36px; flex:none; border-radius:50%; display:grid; place-items:center; color:#fff; font-size:14px; font-weight:700; box-shadow:inset 0 -6px 10px rgba(0,0,0,.10); }',
356
+ '.dsh-mail-rowmain { flex:1; min-width:0; }',
357
+ '.dsh-mail-rowtop { display:flex; align-items:baseline; gap:8px; }',
358
+ '.dsh-mail-from { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-weight:600; font-size:13px; }',
359
+ '.dsh-mail-time { flex:none; font-size:11px; color:var(--dsw-alias-label-secondary); }',
360
+ '.dsh-mail-subject { margin-top:2px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:12.5px; }',
361
+ '.dsh-mail-preview { margin-top:2px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11.5px; color:var(--dsw-alias-label-secondary); }',
362
+ '.dsh-mail-row.is-unread { background:color-mix(in srgb, var(--dsw-alias-brand-primary) 7%, transparent); border-left:3px solid var(--dsw-alias-brand-primary); padding-left:8px; }',
363
+ '.dsh-mail-row.is-unread .dsh-mail-from, .dsh-mail-row.is-unread .dsh-mail-subject { color:var(--dsw-alias-label-primary); font-weight:700; }',
364
+ '.dsh-mail-unread { width:9px; height:9px; margin-top:7px; flex:none; border-radius:50%; background:var(--dsw-alias-brand-primary); box-shadow:0 0 0 3px color-mix(in srgb, var(--dsw-alias-brand-primary) 18%, transparent); }',
365
+ '.dsh-mail-read .dsh-mail-from, .dsh-mail-read .dsh-mail-subject { color:var(--dsw-alias-label-secondary); font-weight:400; }',
366
+
367
+ /* cards / forms */
368
+ '.dsh-mail-card { border:1px solid var(--dsw-alias-border-l1); border-radius:12px; padding:16px; margin-bottom:12px; background:var(--dsw-alias-bg-layer-1); box-shadow:0 1px 3px rgba(0,0,0,.05); }',
369
+ '.dsh-mail-cardhead { display:flex; align-items:center; gap:8px; margin-bottom:14px; font-size:14px; font-weight:650; }',
370
+ '.dsh-mail-grid { display:flex; gap:12px; flex-wrap:wrap; }',
371
+ '.dsh-mail-field { display:flex; flex-direction:column; gap:5px; flex:1; min-width:160px; margin-bottom:11px; }',
372
+ '.dsh-mail-label { font-size:11px; font-weight:600; color:var(--dsw-alias-label-secondary); }',
373
+ '.dsh-mail-input, .dsh-mail-textarea, .dsh-mail-selectinput { width:100%; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; padding:8px 10px; background:var(--dsw-alias-bg-base); color:var(--dsw-alias-label-primary); font-size:13px; transition:border-color .12s, box-shadow .12s; }',
374
+ '.dsh-mail-input:focus, .dsh-mail-textarea:focus, .dsh-mail-selectinput:focus { outline:none; border-color:var(--dsw-alias-brand-primary); box-shadow:0 0 0 3px color-mix(in srgb, var(--dsw-alias-brand-primary) 18%, transparent); }',
375
+ '.dsh-mail-textarea { min-height:200px; resize:vertical; line-height:1.6; }',
376
+ '.dsh-mail-hint { font-size:11.5px; color:var(--dsw-alias-label-secondary); line-height:1.6; }',
377
+
378
+ /* presets */
379
+ '.dsh-mail-pill { display:inline-flex; align-items:center; gap:5px; border:1px solid var(--dsw-alias-border-l2); border-radius:999px; padding:5px 12px; font-size:11.5px; font-weight:600; cursor:pointer; background:var(--dsw-alias-bg-base); color:var(--dsw-alias-label-secondary); transition:all .12s; }',
380
+ '.dsh-mail-pill:hover { color:var(--dsw-alias-label-primary); border-color:var(--dsw-alias-brand-primary); }',
381
+ '.dsh-mail-pill:active { transform:translateY(1px); }',
382
+ '.dsh-mail-pill.is-active { background:var(--dsw-alias-brand-primary); border-color:transparent; color:var(--dsw-alias-bg-base); }',
383
+
384
+ /* flash */
385
+ '.dsh-mail-flash { display:flex; align-items:flex-start; gap:8px; margin:12px 16px 0; padding:10px 12px; border-radius:9px; font-size:12px; line-height:1.55; white-space:pre-wrap; }',
386
+ '.dsh-mail-flash-error { background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 14%, transparent); color:var(--dsw-alias-state-error-primary); border:1px solid color-mix(in srgb, var(--dsw-alias-state-error-primary) 30%, transparent); }',
387
+ '.dsh-mail-flash-success { background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 14%, transparent); color:var(--dsw-alias-state-success-primary); border:1px solid color-mix(in srgb, var(--dsw-alias-state-success-primary) 30%, transparent); }',
388
+
389
+ /* empty & loading */
390
+ '.dsh-mail-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; padding:64px 28px; text-align:center; }',
391
+ '.dsh-mail-emptyicon { width:56px; height:56px; border-radius:18px; display:grid; place-items:center; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-secondary); margin-bottom:4px; }',
392
+ '.dsh-mail-emptytitle { font-size:14px; font-weight:650; color:var(--dsw-alias-label-primary); }',
393
+ '.dsh-mail-emptysub { font-size:12px; color:var(--dsw-alias-label-secondary); max-width:320px; line-height:1.6; }',
394
+ '.dsh-mail-loading { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px; padding:56px 16px; color:var(--dsw-alias-label-secondary); animation:dsh-mail-fade .25s ease-out; }',
395
+ '.dsh-mail-spinner { display:inline-block; width:20px; height:20px; border:2px solid var(--dsw-alias-border-l2); border-top-color:var(--dsw-alias-brand-primary); border-radius:50%; animation:dsh-mail-spin .7s linear infinite; }',
396
+ '@keyframes dsh-mail-spin { to { transform:rotate(360deg); } }',
397
+ '@keyframes dsh-mail-fade { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }',
398
+ '.dsh-mail-progress { position:relative; height:3px; overflow:hidden; background:var(--dsw-alias-bg-layer-1); }',
399
+ '.dsh-mail-progress::after { content:""; position:absolute; top:0; bottom:0; left:0; width:40%; background:var(--dsw-alias-brand-primary); animation:dsh-mail-slide 1.1s ease-in-out infinite; }',
400
+ '@keyframes dsh-mail-slide { 0% { transform:translateX(-100%); } 100% { transform:translateX(350%); } }',
401
+ '.dsh-mail-view { flex:1; min-height:0; display:flex; flex-direction:column; animation:dsh-mail-fade .2s ease-out; }',
402
+ '.dsh-mail-scroll { flex:1; min-height:0; overflow:auto; padding:16px; }',
403
+ '@media (prefers-reduced-motion: reduce) { .dsh-mail-spinner, .dsh-mail-progress::after, .dsh-mail-loading, .dsh-mail-view { animation:none; } }',
404
+
405
+ /* detail */
406
+ '.dsh-mail-detailhead { padding:20px 4px 14px; border-bottom:1px solid var(--dsw-alias-border-l1); margin-bottom:16px; }',
407
+ '.dsh-mail-detailtitle { margin:0 0 12px; font-size:20px; font-weight:650; line-height:1.4; }',
408
+ '.dsh-mail-detailfrom { display:flex; align-items:center; gap:10px; }',
409
+ '.dsh-mail-detailmeta { font-size:11.5px; color:var(--dsw-alias-label-secondary); margin-top:2px; }',
410
+ '.dsh-mail-mailbody { width:100%; padding:18px; border:1px solid var(--dsw-alias-border-l1); border-radius:12px; background:var(--dsw-alias-bg-layer-1); color:var(--dsw-alias-label-primary); line-height:1.75; overflow-wrap:anywhere; word-break:break-word; }',
411
+
412
+ // Third-party HTML: force theme colors so hardcoded mail colors (usually
413
+ // white bg / dark text) never clash with the dark theme. Buttons and links
414
+ // keep their own styling so CTA buttons stay interactive.
415
+ '.dsh-mail-html { text-align:left; }',
416
+ '.dsh-mail-html.dsh-mail-html *:not(button, button *, a, a *, [role="button"], [role="button"] *) { max-width:100% !important; box-sizing:border-box !important; color:var(--dsw-alias-label-primary) !important; background-color:transparent !important; border-color:var(--dsw-alias-border-l2) !important; }',
417
+ '.dsh-mail-html.dsh-mail-html a, .dsh-mail-html.dsh-mail-html a * { color:var(--dsw-alias-brand-primary) !important; text-decoration:underline; cursor:pointer; }',
418
+ '.dsh-mail-html img { max-width:100%; height:auto; border-radius:6px; }',
419
+ '.dsh-mail-html p, .dsh-mail-html div { margin:0 0 8px; }',
420
+ '.dsh-mail-html table { max-width:100%; border-collapse:collapse; }',
421
+ '.dsh-mail-html blockquote { margin:8px 0; padding-left:12px; border-left:3px solid var(--dsw-alias-border-l2) !important; }',
422
+ ].join('\n');
423
+
424
+ const PRESETS = {
425
+ qq: { nameKey: 'qq', imapHost: 'imap.qq.com', imapPort: 993, smtpHost: 'smtp.qq.com', smtpPort: 465 },
426
+ netease: { nameKey: 'netease', imapHost: 'imap.163.com', imapPort: 993, smtpHost: 'smtp.163.com', smtpPort: 465 },
427
+ gmail: { nameKey: 'gmail', imapHost: 'imap.gmail.com', imapPort: 993, smtpHost: 'smtp.gmail.com', smtpPort: 465 },
428
+ custom: { nameKey: 'custom', imapHost: '', imapPort: 993, smtpHost: '', smtpPort: 465 },
429
+ };
430
+
431
+ // Module-level store survives MailPanel unmount/remount when the user
432
+ // switches sidebar panels, so coming back never refetches everything.
433
+ const PERSIST = {
434
+ accounts: null,
435
+ activeId: '',
436
+ view: 'inbox',
437
+ inboxFilter: 'all',
438
+ messages: [],
439
+ detail: null,
440
+ form: null,
441
+ compose: { to: '', subject: '', body: '' },
442
+ loadedId: '',
443
+ sent: [],
444
+ contacts: [],
445
+ contactForm: { name: '', email: '' },
446
+ loadedIds: { inbox: '', sent: '', contacts: '' },
447
+ };
448
+ function usePersistent(key, initial) {
449
+ // `!= null` treats both null and undefined as "not cached yet", so the
450
+ // default object is used for keys like `form` that start as null.
451
+ const [value, setValue] = useState(() => (PERSIST[key] != null ? PERSIST[key] : initial));
452
+ const update = (next) => {
453
+ const current = PERSIST[key] != null ? PERSIST[key] : value;
454
+ const resolved = typeof next === 'function' ? next(current) : next;
455
+ PERSIST[key] = resolved;
456
+ setValue(resolved);
457
+ };
458
+ return [value, update];
459
+ }
460
+
461
+ // ---------------------------------------------------------------------
462
+ // New-mail detection + system notification engine.
463
+ // DSH has no dedicated toast service: like DSH itself and the pet plugin,
464
+ // we use the browser Notification API. A single process-wide timer polls
465
+ // every configured account via the existing listMessages op and compares
466
+ // UID baselines; newly arrived messages raise a system notification. This
467
+ // lives at module scope so it keeps working even while the mail panel is
468
+ // closed, and is intentionally independent of MailPanel's React state.
469
+ // ---------------------------------------------------------------------
470
+ const NOTIFY = {
471
+ ctx: null,
472
+ disposeTimer: null,
473
+ settings: { notifyEnabled: true, notifyInterval: 60, notifyMode: 'pet' },
474
+ baselines: {}, // accountId -> array of last-seen uids
475
+ busy: false,
476
+ lastError: null, // last notification failure reason, surfaced in settings
477
+ petId: null, // cached desktop-pet instance id
478
+ // Live diagnostics. The detection chain runs in the background with no UI,
479
+ // so without this the user cannot tell a working poller from a dead one.
480
+ diag: {
481
+ running: false, // is a poll timer armed?
482
+ accounts: 0, // accounts seen on the last check
483
+ checks: 0, // successful poll ticks
484
+ alerts: 0, // new-mail alerts fired
485
+ lastCheck: 0, // epoch ms of last successful poll
486
+ lastAlert: 0, // epoch ms of last alert
487
+ error: null, // last detection/delivery failure reason
488
+ },
489
+ };
490
+
491
+ // Unread badge on the sidebar entry. Kept at module scope because the
492
+ // shell renders Icon inside its own button (not as part of MailPanel), so
493
+ // the badge must survive the panel being closed. The background poller
494
+ // increments it; Icon subscribes; opening the panel clears it.
495
+ const BADGE = {
496
+ count: 0,
497
+ listeners: new Set(),
498
+ get() { return this.count; },
499
+ subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); },
500
+ emit() { for (const fn of this.listeners) { try { fn(this.count); } catch { /* dead listener */ } } },
501
+ add(n) {
502
+ n = Math.max(0, Number(n) || 0);
503
+ if (!n) return;
504
+ this.count += n;
505
+ this.emit();
506
+ },
507
+ clear() {
508
+ if (!this.count) return;
509
+ this.count = 0;
510
+ this.emit();
511
+ },
512
+ };
513
+
514
+ // A mail that arrived while DSH was restarting must not be swallowed by
515
+ // baseline seeding. On first sight we still alert on unseen messages whose
516
+ // Date header is within this window.
517
+ const RECENT_MAIL_MS = 3 * 60 * 1000;
518
+
519
+ const PET_ROUTE = '/dsh-pet-7340';
520
+
521
+ // The desktop pet exposes a same-origin prefix route on the DSH web server.
522
+ // /state lists every pet instance under `pets`; pick the first one. Cached
523
+ // because it rarely changes, but refreshed on a miss so a late pet works.
524
+ async function resolvePetId() {
525
+ if (NOTIFY.petId) return NOTIFY.petId;
526
+ try {
527
+ const r = await fetch(PET_ROUTE + '/state', { cache: 'no-store' });
528
+ const data = await r.json();
529
+ const pets = data && data.pets && typeof data.pets === 'object' ? data.pets : null;
530
+ if (pets) {
531
+ const ids = Object.keys(pets);
532
+ if (ids.length > 0) { NOTIFY.petId = ids[0]; return NOTIFY.petId; }
533
+ }
534
+ } catch { /* pet not installed or route unavailable */ }
535
+ return null;
536
+ }
537
+
538
+ // Feed a speech bubble to the desktop pet. `speak:true` asks the pet to
539
+ // voice the line; surface=web works for the common web-displayed pet and
540
+ // we fall back to `any` (bubble only) if the surface gate rejects us.
541
+ async function announceViaPet(text) {
542
+ const petId = await resolvePetId();
543
+ if (!petId) return false;
544
+ const post = async (surface) => {
545
+ const body = { text, speak: true, anim: false, duration: 8000 };
546
+ const r = await fetch(PET_ROUTE + '/broadcast?pet=' + encodeURIComponent(petId) + '&surface=' + surface, {
547
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
548
+ });
549
+ let ok = false;
550
+ try { const d = await r.json(); ok = !!(d && d.ok); } catch { ok = r.ok; }
551
+ return ok;
552
+ };
553
+ try {
554
+ if (await post('web')) return true;
555
+ if (await post('any')) return true;
556
+ } catch { /* fall through */ }
557
+ NOTIFY.petId = null; // force re-resolve next time (pet may have changed)
558
+ return false;
559
+ }
560
+
561
+ function notifyPermission() {
562
+ return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission;
563
+ }
564
+
565
+ async function askNotifyPermission() {
566
+ if (typeof Notification === 'undefined') return 'unsupported';
567
+ if (Notification.permission === 'granted') return 'granted';
568
+ if (Notification.permission === 'denied') return 'denied';
569
+ try {
570
+ return await Notification.requestPermission();
571
+ } catch {
572
+ return 'error';
573
+ }
574
+ }
575
+
576
+ function showSystemToast(title, body, opts) {
577
+ const perm = notifyPermission();
578
+ if (perm !== 'granted') {
579
+ NOTIFY.lastError = perm === 'unsupported' ? 'unsupported' : 'permission:' + perm;
580
+ return null;
581
+ }
582
+ try {
583
+ // For real new-mail alerts a stable tag coalesces bursts. Test
584
+ // notifications pass a unique tag so a lingering toast never hides
585
+ // them (a stale tagged notification is a common "nothing happened"
586
+ // cause in Electron shells).
587
+ const options = { body };
588
+ const tag = opts && opts.tag;
589
+ if (tag) options.tag = tag;
590
+ const n = new Notification(title, options);
591
+ n.onclick = () => {
592
+ try { n.close(); } catch { /* already closed */ }
593
+ try { window.focus(); } catch { /* headless */ }
594
+ if (NOTIFY.ctx) {
595
+ try { NOTIFY.ctx.get('layout').selectPanel('dsh-mail'); } catch { /* panel service unavailable */ }
596
+ }
597
+ };
598
+ return n;
599
+ } catch (e) {
600
+ NOTIFY.lastError = 'construct: ' + (e && e.message ? e.message : String(e));
601
+ return null;
602
+ }
603
+ }
604
+
605
+ // Deliver a new-mail alert according to the configured mode.
606
+ // Returns a short status string used by the test button for inline feedback.
607
+ async function deliverAlert(title, body, opts) {
608
+ const mode = (opts && opts.mode) || NOTIFY.settings.notifyMode || 'pet';
609
+ let petOk = false;
610
+ let sysOk = false;
611
+ if (mode === 'pet' || mode === 'both') {
612
+ petOk = await announceViaPet(body);
613
+ }
614
+ if (mode === 'system' || mode === 'both' || (mode === 'pet' && !petOk)) {
615
+ // In pet mode, fall back to a system toast when the pet route is absent.
616
+ const n = showSystemToast(title, body, opts);
617
+ sysOk = !!n;
618
+ }
619
+ NOTIFY.lastError = (petOk || sysOk) ? null : 'no-channel';
620
+ return { petOk, sysOk };
621
+ }
622
+
623
+ // Prefer the Cordis timer service; fall back to the browser timer so the
624
+ // engine works in every client runtime variant.
625
+ function armPoller(callback, delayMs) {
626
+ const ctx = NOTIFY.ctx;
627
+ let timer = ctx && ctx.timer;
628
+ if ((!timer || typeof timer.interval !== 'function') && ctx && typeof ctx.get === 'function') {
629
+ try { timer = ctx.get('timer'); } catch { timer = null; }
630
+ }
631
+ if (timer && typeof timer.interval === 'function') return timer.interval(callback, delayMs);
632
+ // Last resort: plain browser timer (client halves expose setInterval).
633
+ const id = setInterval(callback, delayMs);
634
+ return () => clearInterval(id);
635
+ }
636
+
637
+ function stopPoller() {
638
+ if (NOTIFY.disposeTimer) {
639
+ try { NOTIFY.disposeTimer(); } catch { /* already disposed */ }
640
+ NOTIFY.disposeTimer = null;
641
+ }
642
+ NOTIFY.diag.running = false;
643
+ }
644
+
645
+ function startPoller() {
646
+ stopPoller();
647
+ if (!NOTIFY.ctx || !NOTIFY.settings.notifyEnabled) {
648
+ NOTIFY.diag.error = NOTIFY.ctx ? 'notifyEnabled=false' : 'no-ctx';
649
+ return;
650
+ }
651
+ // A desktop-pet announcement needs no browser permission. Only the
652
+ // pure "system notification" mode requires it; in that case start the
653
+ // poller once permission is granted via the settings button.
654
+ const mode = NOTIFY.settings.notifyMode || 'pet';
655
+ if (mode === 'system' && notifyPermission() !== 'granted') {
656
+ NOTIFY.diag.error = 'permission:' + notifyPermission();
657
+ return;
658
+ }
659
+ const delayMs = Math.max(15, NOTIFY.settings.notifyInterval || 60) * 1000;
660
+ // The Cordis timer service can throw on some runtime variants (wrong
661
+ // signature, disposed context). Fall back to a browser timer instead of
662
+ // letting the exception kill the whole poller — and, when called from
663
+ // settings save(), falsely report the save as failed.
664
+ try {
665
+ NOTIFY.disposeTimer = armPoller(() => { void pollNewMail(); }, delayMs);
666
+ } catch (e) {
667
+ NOTIFY.diag.error = 'timer: ' + (e && e.message ? e.message : String(e));
668
+ const id = setInterval(() => { void pollNewMail(); }, delayMs);
669
+ NOTIFY.disposeTimer = () => clearInterval(id);
670
+ }
671
+ NOTIFY.diag.running = true;
672
+ if (!NOTIFY.diag.error) NOTIFY.diag.error = null;
673
+ void pollNewMail(); // seed baselines on start without spamming old mail
674
+ }
675
+
676
+ // Detect new mail and alert. Returns a diag snapshot so the "check now"
677
+ // button can show what actually happened.
678
+ async function pollNewMail() {
679
+ if (NOTIFY.busy) return Object.assign({}, NOTIFY.diag);
680
+ NOTIFY.busy = true;
681
+ try {
682
+ const mode = NOTIFY.settings.notifyMode || 'pet';
683
+ if (mode === 'system' && notifyPermission() !== 'granted') {
684
+ NOTIFY.diag.error = 'permission:' + notifyPermission();
685
+ return Object.assign({}, NOTIFY.diag);
686
+ }
687
+ const ar = await fetch(API, {
688
+ method: 'POST', headers: { 'content-type': 'application/json' },
689
+ body: JSON.stringify({ op: 'listAccounts' }),
690
+ });
691
+ const ad = await ar.json();
692
+ if (!ad || ad.ok === false || !Array.isArray(ad.accounts)) {
693
+ NOTIFY.diag.error = 'listAccounts:' + (ad && ad.error ? ad.error : 'bad-response');
694
+ return Object.assign({}, NOTIFY.diag);
695
+ }
696
+ const accounts = ad.accounts;
697
+ NOTIFY.diag.accounts = accounts.length;
698
+ NOTIFY.diag.checks += 1;
699
+ NOTIFY.diag.lastCheck = Date.now();
700
+ NOTIFY.diag.error = null;
701
+ const now = Date.now();
702
+ for (const acc of accounts) {
703
+ try {
704
+ const mr = await fetch(API, {
705
+ method: 'POST', headers: { 'content-type': 'application/json' },
706
+ body: JSON.stringify({ op: 'listMessages', id: acc.id, limit: 20 }),
707
+ });
708
+ const md = await mr.json();
709
+ if (!md || md.ok === false || !Array.isArray(md.messages)) {
710
+ NOTIFY.diag.error = 'listMessages:' + (acc.name || acc.id) + ':' + (md && md.error ? md.error : 'bad-response');
711
+ continue;
712
+ }
713
+ const uids = md.messages.map(m => String(m.uid));
714
+ const prev = NOTIFY.baselines[acc.id];
715
+ NOTIFY.baselines[acc.id] = uids;
716
+ if (!prev) {
717
+ // First observation: normally seed only, but a mail that arrived
718
+ // during a restart (unread + recent Date header) must still alert.
719
+ const recent = md.messages.filter(m =>
720
+ m && m.seen === false && m.date &&
721
+ (now - Date.parse(m.date)) >= 0 &&
722
+ (now - Date.parse(m.date)) <= RECENT_MAIL_MS
723
+ );
724
+ if (recent.length === 0) continue;
725
+ const latest = recent[0] || {};
726
+ const who = acc.name ? acc.name + ':' : '';
727
+ const res = await deliverAlert(
728
+ t('notifyTitle'),
729
+ who + (latest.subject || t('noSubject')) + ' · ' + recent.length + ' ' + t('notifyBody'),
730
+ { tag: 'dsh-mail-new' }
731
+ );
732
+ NOTIFY.diag.alerts += 1;
733
+ NOTIFY.diag.lastAlert = Date.now();
734
+ BADGE.add(recent.length);
735
+ if (!res.petOk && !res.sysOk) NOTIFY.diag.error = 'deliver:' + (NOTIFY.lastError || 'no-channel');
736
+ continue;
737
+ }
738
+ const prevSet = new Set(prev);
739
+ const fresh = md.messages.filter(m => !prevSet.has(String(m.uid)));
740
+ if (fresh.length > 0) {
741
+ const latest = fresh[0] || {};
742
+ const who = acc.name ? acc.name + ':' : '';
743
+ const res = await deliverAlert(
744
+ t('notifyTitle'),
745
+ who + (latest.subject || t('noSubject')) + ' · ' + fresh.length + ' ' + t('notifyBody'),
746
+ { tag: 'dsh-mail-new' }
747
+ );
748
+ NOTIFY.diag.alerts += 1;
749
+ NOTIFY.diag.lastAlert = Date.now();
750
+ BADGE.add(fresh.length);
751
+ if (!res.petOk && !res.sysOk) NOTIFY.diag.error = 'deliver:' + (NOTIFY.lastError || 'no-channel');
752
+ }
753
+ } catch (e) {
754
+ NOTIFY.diag.error = 'account:' + (acc.name || acc.id) + ':' + (e && e.message ? e.message : String(e));
755
+ }
756
+ }
757
+ } catch (e) {
758
+ NOTIFY.diag.error = 'poll:' + (e && e.message ? e.message : String(e));
759
+ } finally {
760
+ NOTIFY.busy = false;
761
+ }
762
+ return Object.assign({}, NOTIFY.diag);
763
+ }
764
+
765
+ async function refreshNotifySettings() {
766
+ try {
767
+ const r = await fetch(API, {
768
+ method: 'POST', headers: { 'content-type': 'application/json' },
769
+ body: JSON.stringify({ op: 'getSettings' }),
770
+ });
771
+ const data = await r.json();
772
+ if (data && data.ok && data.settings) {
773
+ NOTIFY.settings = {
774
+ notifyEnabled: data.settings.notifyEnabled !== false,
775
+ notifyInterval: Number(data.settings.notifyInterval) || 60,
776
+ notifyMode: data.settings.notifyMode || 'pet',
777
+ };
778
+ }
779
+ } catch { /* keep current settings */ }
780
+ startPoller();
781
+ }
782
+
783
+ // Solid envelope for the sidebar panel icon. The sidebar owns the button
784
+ // ([panelGlyph(our icon)] [panelTitle(label text)]); the label is a plain
785
+ // string also used for aria-label, so we cannot inject a React node there.
786
+ // Instead we mount a small unread dot imperatively as the LAST child of the
787
+ // button, which renders it AFTER the label text in the expanded state (and
788
+ // beside the icon when the sidebar is collapsed and has no text). A quiet
789
+ // dot (no number) is the least intrusive unread cue and ages well.
790
+ const BADGE_STYLE = {
791
+ display: 'block', width: '7px', height: '7px', borderRadius: '50%',
792
+ background: 'var(--dsw-alias-state-error-primary)',
793
+ flex: 'none', alignSelf: 'center', marginLeft: '4px',
794
+ boxShadow: '0 0 0 2px var(--dsw-alias-bg-base)',
795
+ };
796
+ function Icon(props) {
797
+ const size = (props && props.size) || 20;
798
+ const active = !!(props && props.active);
799
+ const rootRef = useRef(null);
800
+ const badgeRef = useRef(null);
801
+ const [count, setCount] = useState(() => BADGE.get());
802
+ useEffect(() => BADGE.subscribe(setCount), []);
803
+ useEffect(() => () => {
804
+ if (badgeRef.current && badgeRef.current.parentNode) badgeRef.current.parentNode.removeChild(badgeRef.current);
805
+ badgeRef.current = null;
806
+ }, []);
807
+ useLayoutEffect(() => {
808
+ const root = rootRef.current;
809
+ // Find the owning sidebar button by structure, not by DSH's hashed
810
+ // CSS-module class names. closest('button') tolerates any wrapper
811
+ // elements that renderSlot/renderFactorySlot may insert.
812
+ const button = root && root.closest && root.closest('button');
813
+ if (!button) return;
814
+ if (!count) {
815
+ if (badgeRef.current && badgeRef.current.parentNode) badgeRef.current.parentNode.removeChild(badgeRef.current);
816
+ badgeRef.current = null;
817
+ return;
818
+ }
819
+ let badge = badgeRef.current;
820
+ if (!badge || badge.parentNode !== button) {
821
+ badge = document.createElement('span');
822
+ badge.className = 'dsh-mail-sidebadge';
823
+ badge.title = t('badgeTitle');
824
+ Object.assign(badge.style, BADGE_STYLE);
825
+ button.appendChild(badge);
826
+ badgeRef.current = badge;
827
+ }
828
+ // Keep the count as accessible metadata (tooltip) but render only a dot.
829
+ badge.title = t('badgeTitle') + ' (' + count + ')';
830
+ });
831
+ return h('span', { ref: rootRef, style: { display: 'inline-flex', alignItems: 'center', lineHeight: 0 } },
832
+ h('svg', { viewBox: '0 0 24 24', width: size, height: size, 'aria-hidden': true, style: { display: 'block' } },
833
+ h('path', { fill: active ? 'var(--dsw-alias-brand-primary)' : 'currentColor', d: 'M3 5h18a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1zm9 8.2L4.2 7h15.6L12 13.2zM4 8.3V17h16V8.3l-8 6.1-8-6.1z' })
834
+ )
835
+ );
836
+ }
837
+
838
+ // Stroke-style glyphs for in-panel navigation (unified icon language).
839
+ const ICONS = {
840
+ inbox: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1zm0 11v5h16v-5h-5a3 3 0 0 1-6 0H4z',
841
+ sent: 'M21 3L3 10.5l7 2.5 2.5 7L21 3zM10 13l4-4',
842
+ contacts: 'M16 20v-1.5a3.5 3.5 0 0 0-3.5-3.5h-5A3.5 3.5 0 0 0 4 18.5V20M11 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7zM20 20v-1.5a3.5 3.5 0 0 0-2.6-3.38M16 3.6a3.5 3.5 0 0 1 0 6.8',
843
+ accounts: 'M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7zM19.4 12c0-.4-.04-.8-.11-1.18l2.03-1.58-2-3.47-2.4.97a7 7 0 0 0-2.02-1.17L14.6 3h-4l-.3 2.57a7 7 0 0 0-2.03 1.17l-2.4-.97-2 3.47 2.03 1.58A8 8 0 0 0 6 12c0 .4.04.8.11 1.18l-2.03 1.58 2 3.47 2.4-.97c.62.51 1.3.9 2.02 1.17l.3 2.57h4l.31-2.57c.72-.27 1.4-.66 2.02-1.17l2.39.97 2-3.47-2.02-1.58c.07-.38.11-.78.11-1.18z',
844
+ compose: 'M4 20h4l10.6-10.6a2.1 2.1 0 0 0-3-3L5 17v3zM14.5 6.5l3 3',
845
+ refresh: 'M20 11a8 8 0 1 0-2.34 5.66M20 5v6h-6',
846
+ back: 'M15 18l-6-6 6-6',
847
+ trash: 'M4 7h16M9 7V4h6v3m3 0-1 13H7L6 7M10 11v6m4-6v6',
848
+ mail: 'M3 6h18a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zm9 7L3.5 7.5h17L12 13z',
849
+ user: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0',
850
+ users: 'M16 20v-1.5a3.5 3.5 0 0 0-3.5-3.5h-5A3.5 3.5 0 0 0 4 18.5V20M11 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z',
851
+ check: 'M4 12l5 5L20 6',
852
+ warning: 'M12 3L2 20h20L12 3zm0 6v5m0 3v.5',
853
+ plus: 'M12 5v14M5 12h14',
854
+ };
855
+ function Ico(props) {
856
+ // Rendered as a React component via h(Ico, { name, size }); the first
857
+ // argument is a props object, not a positional name string.
858
+ const name = (props && props.name) || 'mail';
859
+ const size = (props && props.size) || 18;
860
+ return h('svg', {
861
+ viewBox: '0 0 24 24', width: size, height: size, 'aria-hidden': true,
862
+ style: { display: 'block', flex: 'none', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' },
863
+ }, h('path', { d: ICONS[name] || ICONS.mail }));
864
+ }
865
+
866
+ const AVATAR_COLORS = ['#6366f1', '#0891b2', '#059669', '#d97706', '#dc2626', '#7c3aed', '#0d9488', '#e11d48'];
867
+ function avatarColor(seed) {
868
+ let hash = 0;
869
+ const s = String(seed || '');
870
+ for (let i = 0; i < s.length; i++) hash = (hash * 31 + s.charCodeAt(i)) >>> 0;
871
+ return AVATAR_COLORS[hash % AVATAR_COLORS.length];
872
+ }
873
+ function avatarLetter(s) {
874
+ const v = String(s || '').trim();
875
+ return v ? v.charAt(0).toUpperCase() : '?';
876
+ }
877
+ function fmtDate(iso) {
878
+ if (!iso) return '';
879
+ const d = new Date(iso);
880
+ if (isNaN(d.getTime())) return String(iso).slice(0, 16);
881
+ const now = new Date();
882
+ const hh = ('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2);
883
+ if (d.toDateString() === now.toDateString()) return hh;
884
+ if (d.getFullYear() === now.getFullYear()) return (d.getMonth() + 1) + '/' + d.getDate();
885
+ return d.getFullYear() + '.' + (d.getMonth() + 1) + '.' + d.getDate();
886
+ }
887
+
888
+ function Loading(props) {
889
+ // Rendered as a React component via h(Loading), so the first argument is
890
+ // a props object ({} when none is passed) — never treat it as a string.
891
+ const label = (props && typeof props.label === 'string' && props.label) || t('loading');
892
+ return h('div', { className: 'dsh-mail-loading' },
893
+ h('div', { className: 'dsh-mail-spinner' }),
894
+ h('span', null, label)
895
+ );
896
+ }
897
+
898
+ function Empty({ icon, title, sub }) {
899
+ return h('div', { className: 'dsh-mail-empty' },
900
+ h('div', { className: 'dsh-mail-emptyicon' }, h(Ico, { name: icon, size: 26 })),
901
+ h('div', { className: 'dsh-mail-emptytitle' }, title),
902
+ sub ? h('div', { className: 'dsh-mail-emptysub' }, sub) : null
903
+ );
904
+ }
905
+
906
+ function MailPanel() {
907
+ const [accounts, setAccounts] = usePersistent('accounts', null);
908
+ const [activeId, setActiveId] = usePersistent('activeId', '');
909
+ const [view, setView] = usePersistent('view', 'inbox');
910
+ const [inboxFilter, setInboxFilter] = usePersistent('inboxFilter', 'all');
911
+ const [messages, setMessages] = usePersistent('messages', []);
912
+ const [detail, setDetail] = usePersistent('detail', null);
913
+ const [busy, setBusy] = useState(false);
914
+ const [loadingMessages, setLoadingMessages] = useState(false);
915
+ const [loadingSent, setLoadingSent] = useState(false);
916
+ const [loadingContacts, setLoadingContacts] = useState(false);
917
+ const [refreshState, setRefreshState] = useState('idle'); // idle | loading | ok | error
918
+ const refreshTimerRef = useRef(null);
919
+ const [flash, setFlash] = useState(null);
920
+ const [form, setForm] = usePersistent('form', { preset: 'qq', name: '', username: '', authCode: '', imapHost: PRESETS.qq.imapHost, imapPort: 993, smtpHost: PRESETS.qq.smtpHost, smtpPort: 465 });
921
+ const [compose, setCompose] = usePersistent('compose', { to: '', subject: '', body: '' });
922
+ const [sent, setSent] = usePersistent('sent', []);
923
+ const [contacts, setContacts] = usePersistent('contacts', []);
924
+ const [contactForm, setContactForm] = usePersistent('contactForm', { name: '', email: '' });
925
+ const [sentDetail, setSentDetail] = useState(null);
926
+ // Per-account cache of fetched message lists. Survives account switching
927
+ // and remounts so we can show cached mail immediately while refreshing.
928
+ const [cache, setCache] = usePersistent('mailCache', {});
929
+
930
+ useEffect(() => {
931
+ if (!PERSIST.accounts) refreshAccounts();
932
+ return () => { if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current); };
933
+ }, []);
934
+
935
+ function notify(kind, text) {
936
+ setFlash({ kind, text });
937
+ }
938
+
939
+ function reportError(e) {
940
+ notify('error', e && e.info ? friendlyError(e.info) : (e && e.message ? e.message : t('errGeneric')));
941
+ }
942
+
943
+ async function rpc(op, extra) {
944
+ const res = await fetch(API, {
945
+ method: 'POST',
946
+ headers: { 'content-type': 'application/json' },
947
+ body: JSON.stringify(Object.assign({ op }, extra || {})),
948
+ });
949
+ const data = await res.json();
950
+ if (!res.ok || data.ok === false) {
951
+ const err = new Error(data.error || ('HTTP ' + res.status));
952
+ err.info = data;
953
+ throw err;
954
+ }
955
+ return data;
956
+ }
957
+
958
+ async function refreshAccounts() {
959
+ try {
960
+ const data = await rpc('listAccounts');
961
+ setAccounts(data.accounts || []);
962
+ if (!activeId && data.accounts && data.accounts.length) setActiveId(data.accounts[0].id);
963
+ } catch (e) {
964
+ reportError(e);
965
+ }
966
+ }
967
+
968
+ async function loadMessages(showProgress) {
969
+ if (!activeId) return false;
970
+ // Cache-first: if we already have this account's list, keep it visible
971
+ // while the fresh list loads in the background (no blank/Loading flash).
972
+ const cached = cache[activeId];
973
+ if (showProgress !== false) setLoadingMessages(!(cached && cached.length));
974
+ try {
975
+ const data = await rpc('listMessages', { id: activeId, limit: 25 });
976
+ const fresh = data.messages || [];
977
+ setMessages(fresh);
978
+ setCache(prev => Object.assign({}, prev, { [activeId]: fresh }));
979
+ return true;
980
+ } catch (e) {
981
+ reportError(e);
982
+ return false;
983
+ } finally {
984
+ setLoadingMessages(false);
985
+ }
986
+ }
987
+
988
+ async function loadSent() {
989
+ if (!activeId) return false;
990
+ setBusy(true);
991
+ setLoadingSent(true);
992
+ try {
993
+ const data = await rpc('sentMessages', { id: activeId });
994
+ setSent(data.sent || []);
995
+ return true;
996
+ } catch (e) {
997
+ reportError(e);
998
+ return false;
999
+ } finally {
1000
+ setLoadingSent(false);
1001
+ setBusy(false);
1002
+ }
1003
+ }
1004
+
1005
+ async function loadContacts() {
1006
+ if (!activeId) return false;
1007
+ setBusy(true);
1008
+ setLoadingContacts(true);
1009
+ try {
1010
+ const data = await rpc('listContacts', { id: activeId });
1011
+ setContacts(data.contacts || []);
1012
+ return true;
1013
+ } catch (e) {
1014
+ reportError(e);
1015
+ return false;
1016
+ } finally {
1017
+ setLoadingContacts(false);
1018
+ setBusy(false);
1019
+ }
1020
+ }
1021
+
1022
+ // Only (re)load the list when the ACCOUNT actually changes — never on
1023
+ // view changes (inbox→detail→inbox), so entering a mail no longer blanks
1024
+ // it and returning does not refetch. PERSIST.loadedIds guards remounts.
1025
+ useEffect(() => {
1026
+ if (!activeId) {
1027
+ setMessages([]);
1028
+ setSent([]);
1029
+ setContacts([]);
1030
+ setDetail(null);
1031
+ PERSIST.loadedIds = { inbox: '', sent: '', contacts: '' };
1032
+ return;
1033
+ }
1034
+ if (PERSIST.loadedIds.inbox !== activeId) {
1035
+ // Show this account's cached messages immediately, then refresh in
1036
+ // the background. Only clear when there is no cache for the account.
1037
+ const cached = cache[activeId];
1038
+ setMessages(cached || []);
1039
+ setSent([]);
1040
+ setContacts([]);
1041
+ setDetail(null);
1042
+ PERSIST.loadedIds = { inbox: activeId, sent: activeId, contacts: activeId };
1043
+ loadMessages();
1044
+ loadSent();
1045
+ loadContacts();
1046
+ }
1047
+ }, [activeId]);
1048
+
1049
+ function applyPreset(preset) {
1050
+ const p = PRESETS[preset] || PRESETS.custom;
1051
+ setForm(Object.assign({}, form, {
1052
+ preset,
1053
+ name: preset === 'custom' ? '' : t(p.nameKey),
1054
+ imapHost: p.imapHost,
1055
+ imapPort: p.imapPort,
1056
+ smtpHost: p.smtpHost,
1057
+ smtpPort: p.smtpPort,
1058
+ }));
1059
+ }
1060
+
1061
+ async function saveAccount() {
1062
+ setBusy(true);
1063
+ try {
1064
+ await rpc('saveAccount', {
1065
+ name: form.name || form.username,
1066
+ username: form.username,
1067
+ authCode: form.authCode,
1068
+ imapHost: form.imapHost,
1069
+ imapPort: Number(form.imapPort),
1070
+ smtpHost: form.smtpHost,
1071
+ smtpPort: Number(form.smtpPort),
1072
+ });
1073
+ notify('success', t('ok'));
1074
+ setForm(Object.assign({}, form, { authCode: '' }));
1075
+ await refreshAccounts();
1076
+ setView('inbox');
1077
+ } catch (e) {
1078
+ reportError(e);
1079
+ } finally {
1080
+ setBusy(false);
1081
+ }
1082
+ }
1083
+
1084
+ async function testAccount(id) {
1085
+ setBusy(true);
1086
+ try {
1087
+ const data = await rpc('testAccount', { id });
1088
+ notify(data.ok ? 'success' : 'error', data.ok ? t('ok') : friendlyError(data));
1089
+ } catch (e) {
1090
+ reportError(e);
1091
+ } finally {
1092
+ setBusy(false);
1093
+ }
1094
+ }
1095
+
1096
+ async function deleteAccount(id) {
1097
+ if (typeof window !== 'undefined' && window.confirm && !window.confirm(t('confirmDelete'))) return;
1098
+ setBusy(true);
1099
+ try {
1100
+ await rpc('deleteAccount', { id });
1101
+ if (activeId === id) setActiveId('');
1102
+ await refreshAccounts();
1103
+ } catch (e) {
1104
+ reportError(e);
1105
+ } finally {
1106
+ setBusy(false);
1107
+ }
1108
+ }
1109
+
1110
+ async function openMessage(msg) {
1111
+ const uid = typeof msg === 'object' ? msg.uid : msg;
1112
+ // Mark as read locally right away: update the visible list, the unread
1113
+ // badge, and the per-account cache so the change survives switching away.
1114
+ const markRead = (list) => (list || []).map(m => String(m.uid) === String(uid) ? Object.assign({}, m, { seen: true }) : m);
1115
+ setMessages(prev => markRead(prev));
1116
+ setCache(prev => Object.assign({}, prev, { [activeId]: markRead(prev[activeId]) }));
1117
+ BADGE.clear();
1118
+ setBusy(true);
1119
+ try {
1120
+ const data = await rpc('getMessage', { id: activeId, uid });
1121
+ const full = data.message || data;
1122
+ setDetail(Object.assign({}, full, { seen: true }));
1123
+ setView('detail');
1124
+ } catch (e) {
1125
+ reportError(e);
1126
+ } finally {
1127
+ setBusy(false);
1128
+ }
1129
+ }
1130
+
1131
+ async function sendMail() {
1132
+ setBusy(true);
1133
+ try {
1134
+ await rpc('sendMessage', { id: activeId, to: compose.to, subject: compose.subject, body: compose.body });
1135
+ notify('success', t('ok'));
1136
+ setCompose({ to: '', subject: '', body: '' });
1137
+ await loadSent();
1138
+ setView('sent');
1139
+ } catch (e) {
1140
+ reportError(e);
1141
+ } finally {
1142
+ setBusy(false);
1143
+ }
1144
+ }
1145
+
1146
+ async function saveContact() {
1147
+ const email = String(contactForm.email || '').trim();
1148
+ if (!email || !email.includes('@')) {
1149
+ notify('error', t('emailRequired'));
1150
+ return;
1151
+ }
1152
+ setBusy(true);
1153
+ try {
1154
+ const data = await rpc('saveContact', { id: activeId, email, name: contactForm.name });
1155
+ setContactForm({ name: '', email: '' });
1156
+ if (Array.isArray(data.contacts)) setContacts(data.contacts);
1157
+ notify('success', t('saved'));
1158
+ } catch (e) {
1159
+ reportError(e);
1160
+ } finally {
1161
+ setBusy(false);
1162
+ }
1163
+ }
1164
+
1165
+ async function deleteContact(email) {
1166
+ setBusy(true);
1167
+ const next = contacts.filter(c => String(c.email).toLowerCase() !== String(email).toLowerCase());
1168
+ setContacts(next);
1169
+ try {
1170
+ const data = await rpc('deleteContact', { id: activeId, email });
1171
+ if (Array.isArray(data.contacts)) setContacts(data.contacts);
1172
+ } catch (e) {
1173
+ reportError(e);
1174
+ } finally {
1175
+ setBusy(false);
1176
+ }
1177
+ }
1178
+
1179
+ async function refreshCurrent() {
1180
+ if (!activeId || refreshState === 'loading') return;
1181
+ setRefreshState('loading');
1182
+ // Clear any previous terminal state timer so a new click starts clean.
1183
+ if (refreshTimerRef.current) { clearTimeout(refreshTimerRef.current); refreshTimerRef.current = null; }
1184
+ let ok = false;
1185
+ try {
1186
+ if (view === 'sent') ok = await loadSent();
1187
+ else if (view === 'contacts') ok = await loadContacts();
1188
+ else ok = await loadMessages();
1189
+ } catch (e) {
1190
+ reportError(e);
1191
+ ok = false;
1192
+ }
1193
+ // Tie the spinner result to the actual outcome, then revert to idle.
1194
+ setRefreshState(ok ? 'ok' : 'error');
1195
+ refreshTimerRef.current = setTimeout(() => {
1196
+ setRefreshState('idle');
1197
+ refreshTimerRef.current = null;
1198
+ }, 1400);
1199
+ }
1200
+
1201
+ function composeTo(email) {
1202
+ setCompose(Object.assign({}, compose, { to: email }));
1203
+ setView('compose');
1204
+ }
1205
+
1206
+ const account = (accounts || []).find(a => a.id === activeId);
1207
+ const unread = (messages || []).filter(m => m && m.seen === false).length;
1208
+ const readCount = (messages || []).length - unread;
1209
+ const filters = [
1210
+ { key: 'all', label: t('filterAll'), count: (messages || []).length },
1211
+ { key: 'unread', label: t('filterUnread'), count: unread },
1212
+ { key: 'read', label: t('filterRead'), count: readCount },
1213
+ ];
1214
+ const filteredMessages = inboxFilter === 'unread'
1215
+ ? (messages || []).filter(m => m && m.seen === false)
1216
+ : inboxFilter === 'read'
1217
+ ? (messages || []).filter(m => m && m.seen !== false)
1218
+ : (messages || []);
1219
+ const tabs = [
1220
+ { key: 'inbox', icon: 'inbox', label: t('inbox'), badge: unread },
1221
+ { key: 'sent', icon: 'sent', label: t('sent') },
1222
+ { key: 'contacts', icon: 'users', label: t('contacts') },
1223
+ { key: 'accounts', icon: 'accounts', label: t('accounts') },
1224
+ ];
1225
+ const isList = view === 'inbox' || view === 'sent' || view === 'contacts' || view === 'accounts';
1226
+
1227
+ function navTo(key) {
1228
+ setSentDetail(null);
1229
+ setView(key);
1230
+ }
1231
+
1232
+ return h('div', { className: 'dsh-mail' },
1233
+ h('style', null, CSS),
1234
+ (loadingMessages || loadingSent || loadingContacts) && h('div', { className: 'dsh-mail-progress' }),
1235
+
1236
+ // Brand header + primary action
1237
+ h('div', { className: 'dsh-mail-topbar' },
1238
+ h('div', { className: 'dsh-mail-brand' },
1239
+ h('div', { className: 'dsh-mail-brandmark' }, h(Ico, { name: 'mail', size: 18 })),
1240
+ h('div', null, t('label'), h('div', { className: 'dsh-mail-brandsub' }, t('note').slice(0, 0) || 'IMAP / SMTP'))
1241
+ ),
1242
+ h('span', { className: 'dsh-mail-spacer' }),
1243
+ h('button', {
1244
+ className: 'dsh-mail-btn dsh-mail-btn-primary',
1245
+ onClick: () => navTo('compose'),
1246
+ disabled: !activeId || view === 'compose',
1247
+ }, h(Ico, { name: 'compose', size: 15 }), t('compose'))
1248
+ ),
1249
+
1250
+ // Segmented navigation
1251
+ h('div', { className: 'dsh-mail-tabs' },
1252
+ tabs.map(tab => h('button', {
1253
+ key: tab.key,
1254
+ className: 'dsh-mail-tab' + (view === tab.key ? ' is-active' : ''),
1255
+ onClick: () => navTo(tab.key),
1256
+ },
1257
+ h(Ico, { name: tab.icon, size: 16 }),
1258
+ h('span', null, tab.label),
1259
+ tab.badge > 0 ? h('span', { className: 'dsh-mail-badge' }, tab.badge) : null
1260
+ ))
1261
+ ),
1262
+
1263
+ flash && h('div', { className: 'dsh-mail-flash ' + (flash.kind === 'error' ? 'dsh-mail-flash-error' : 'dsh-mail-flash-success') },
1264
+ h(Ico, { name: flash.kind === 'error' ? 'warning' : 'check', size: 15 }),
1265
+ h('span', null, flash.text)
1266
+ ),
1267
+
1268
+ // Account switcher + contextual refresh, shown on data views
1269
+ isList && view !== 'accounts' && h('div', { className: 'dsh-mail-accountbar' },
1270
+ h(Ico, { name: 'user', size: 15 }),
1271
+ accounts && accounts.length > 0
1272
+ ? h('select', { className: 'dsh-mail-select', value: activeId, onChange: e => setActiveId(e.target.value) },
1273
+ accounts.map(a => h('option', { key: a.id, value: a.id }, a.name + ' · ' + a.username)))
1274
+ : h('span', { className: 'dsh-mail-hint' }, t('noAccounts')),
1275
+ h('span', { className: 'dsh-mail-spacer' }),
1276
+ h('button', {
1277
+ className: 'dsh-mail-btn dsh-mail-iconbtn' + (refreshState === 'ok' ? ' dsh-mail-refresh-ok' : refreshState === 'error' ? ' dsh-mail-refresh-err' : ''),
1278
+ onClick: refreshCurrent,
1279
+ disabled: !activeId || busy || refreshState === 'loading',
1280
+ title: refreshState === 'loading' ? t('refreshing') : refreshState === 'ok' ? t('refreshed') : refreshState === 'error' ? t('refreshFailed') : t('refresh'),
1281
+ 'aria-label': refreshState === 'loading' ? t('refreshing') : t('refresh'),
1282
+ }, h('span', { className: refreshState === 'loading' ? 'dsh-mail-spinicon' : '', style: { display: 'inline-flex' } },
1283
+ h(Ico, { name: refreshState === 'ok' ? 'check' : refreshState === 'error' ? 'warning' : 'refresh', size: 15 })))
1284
+ ),
1285
+
1286
+ /* ------------------------------- INBOX ------------------------------ */
1287
+ view === 'inbox' && h('div', { className: 'dsh-mail-view' },
1288
+ !activeId
1289
+ ? h(Empty, { icon: 'user', title: t('accounts'), sub: t('noAccounts') })
1290
+ : h('div', { className: 'dsh-mail-filterbar' }, filters.map(f =>
1291
+ h('button', {
1292
+ key: f.key,
1293
+ className: 'dsh-mail-filter' + (inboxFilter === f.key ? ' is-active' : ''),
1294
+ onClick: () => setInboxFilter(f.key),
1295
+ },
1296
+ f.label,
1297
+ h('span', { className: 'dsh-mail-filtercount' }, f.count)
1298
+ )
1299
+ )),
1300
+ !activeId
1301
+ ? null
1302
+ : (loadingMessages && messages.length === 0)
1303
+ ? h(Loading)
1304
+ : (filteredMessages.length === 0)
1305
+ ? h(Empty, { icon: 'inbox', title: t('inbox'), sub: inboxFilter === 'all' ? t('noMessages') : t('noFiltered') })
1306
+ : h('div', { className: 'dsh-mail-list' }, filteredMessages.map(m =>
1307
+ h('div', {
1308
+ key: m.uid,
1309
+ className: 'dsh-mail-row' + (m.seen === false ? ' is-unread' : ' dsh-mail-read'),
1310
+ onClick: () => openMessage(m),
1311
+ },
1312
+ h('div', { className: 'dsh-mail-avatar', style: { background: avatarColor(m.from || m.subject) } }, avatarLetter(m.from || m.subject)),
1313
+ h('div', { className: 'dsh-mail-rowmain' },
1314
+ h('div', { className: 'dsh-mail-rowtop' },
1315
+ h('span', { className: 'dsh-mail-from' }, String(m.from || '').replace(/<.*>/, '').trim() || m.from || ''),
1316
+ h('span', { className: 'dsh-mail-time' }, fmtDate(m.date))
1317
+ ),
1318
+ h('div', { className: 'dsh-mail-subject' }, m.subject || t('noSubject')),
1319
+ h('div', { className: 'dsh-mail-preview' }, m.snippet || '')
1320
+ ),
1321
+ m.seen === false ? h('span', { className: 'dsh-mail-unread', title: t('inbox') }) : null
1322
+ )
1323
+ ))
1324
+ ),
1325
+
1326
+ /* -------------------------------- SENT ------------------------------ */
1327
+ view === 'sent' && h('div', { className: 'dsh-mail-view' },
1328
+ sentDetail
1329
+ ? h('div', { className: 'dsh-mail-scroll' },
1330
+ h('button', { className: 'dsh-mail-btn', onClick: () => setSentDetail(null) }, h(Ico, { name: 'back', size: 15 }), t('back')),
1331
+ h('div', { className: 'dsh-mail-detailhead' },
1332
+ h('h2', { className: 'dsh-mail-detailtitle' }, sentDetail.subject || t('noSubject')),
1333
+ h('div', { className: 'dsh-mail-detailmeta' }, t('to') + ': ' + (sentDetail.to || '') + ' · ' + fmtDate(sentDetail.date))
1334
+ ),
1335
+ h('div', { className: 'dsh-mail-mailbody', style: { whiteSpace: 'pre-wrap' } }, String(sentDetail.body || ''))
1336
+ )
1337
+ : h('div', { className: 'dsh-mail-view' },
1338
+ loadingSent && sent.length === 0
1339
+ ? h(Loading)
1340
+ : (sent.length === 0)
1341
+ ? h(Empty, { icon: 'sent', title: t('sent'), sub: t('noSent') })
1342
+ : h('div', { className: 'dsh-mail-list' }, sent.map(m =>
1343
+ h('div', { key: m.id, className: 'dsh-mail-row dsh-mail-read', onClick: () => setSentDetail(m) },
1344
+ h('div', { className: 'dsh-mail-avatar', style: { background: avatarColor(m.to || m.subject) } }, avatarLetter(m.to || m.subject)),
1345
+ h('div', { className: 'dsh-mail-rowmain' },
1346
+ h('div', { className: 'dsh-mail-rowtop' },
1347
+ h('span', { className: 'dsh-mail-from' }, t('to') + ': ' + (m.to || '')),
1348
+ h('span', { className: 'dsh-mail-time' }, fmtDate(m.date))
1349
+ ),
1350
+ h('div', { className: 'dsh-mail-subject' }, m.subject || t('noSubject')),
1351
+ h('div', { className: 'dsh-mail-preview' }, m.body || '')
1352
+ )
1353
+ )
1354
+ ))
1355
+ )
1356
+ ),
1357
+
1358
+ /* ------------------------------ CONTACTS ---------------------------- */
1359
+ view === 'contacts' && h('div', { className: 'dsh-mail-view' },
1360
+ h('div', { className: 'dsh-mail-scroll' },
1361
+ h('div', { className: 'dsh-mail-card' },
1362
+ h('div', { className: 'dsh-mail-cardhead' }, h(Ico, { name: 'user', size: 16 }), t('addContact')),
1363
+ h('div', { className: 'dsh-mail-hint', style: { marginBottom: 12 } }, t('contactsHint')),
1364
+ h('div', { className: 'dsh-mail-grid' },
1365
+ h('div', { className: 'dsh-mail-field' },
1366
+ h('span', { className: 'dsh-mail-label' }, t('contactName')),
1367
+ h('input', { className: 'dsh-mail-input', value: contactForm.name, placeholder: t('contactName'), onChange: e => setContactForm(Object.assign({}, contactForm, { name: e.target.value })) })
1368
+ ),
1369
+ h('div', { className: 'dsh-mail-field' },
1370
+ h('span', { className: 'dsh-mail-label' }, t('contactEmail')),
1371
+ h('input', { className: 'dsh-mail-input', value: contactForm.email, placeholder: 'friend@example.com', onChange: e => setContactForm(Object.assign({}, contactForm, { email: e.target.value })) })
1372
+ )
1373
+ ),
1374
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-primary', onClick: saveContact, disabled: busy || !contactForm.email }, h(Ico, { name: 'check', size: 15 }), t('saveContact'))
1375
+ ),
1376
+ loadingContacts && contacts.length === 0
1377
+ ? h(Loading)
1378
+ : (contacts.length === 0)
1379
+ ? h(Empty, { icon: 'users', title: t('contacts'), sub: t('noContacts') })
1380
+ : h('div', null, contacts.map(c =>
1381
+ h('div', { key: c.email, className: 'dsh-mail-card', style: { padding: '12px 14px' } },
1382
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
1383
+ h('div', { className: 'dsh-mail-avatar', style: { width: 32, height: 32, fontSize: 13, background: avatarColor(c.email) } }, avatarLetter(c.name || c.email)),
1384
+ h('div', { style: { flex: 1, minWidth: 0 } },
1385
+ h('div', { style: { fontWeight: 600 } }, c.name || c.email),
1386
+ c.name ? h('div', { className: 'dsh-mail-hint' }, c.email) : null
1387
+ ),
1388
+ h('button', { className: 'dsh-mail-btn', onClick: () => composeTo(c.email) }, h(Ico, { name: 'compose', size: 14 }), t('selectContact')),
1389
+ h('button', { className: 'dsh-mail-btn dsh-mail-iconbtn dsh-mail-btn-danger', onClick: () => deleteContact(c.email), disabled: busy, title: t('deleteContact') }, h(Ico, { name: 'trash', size: 14 }))
1390
+ )
1391
+ )
1392
+ ))
1393
+ )
1394
+ ),
1395
+
1396
+ /* ------------------------------- ACCOUNTS --------------------------- */
1397
+ view === 'accounts' && h('div', { className: 'dsh-mail-view' },
1398
+ h('div', { className: 'dsh-mail-scroll' },
1399
+ (accounts || []).map(a => h('div', { key: a.id, className: 'dsh-mail-card' },
1400
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 } },
1401
+ h('div', { className: 'dsh-mail-avatar', style: { background: avatarColor(a.username) } }, avatarLetter(a.name || a.username)),
1402
+ h('div', { style: { flex: 1, minWidth: 0 } },
1403
+ h('div', { style: { fontWeight: 650 } }, a.name),
1404
+ h('div', { className: 'dsh-mail-hint' }, a.username)
1405
+ )
1406
+ ),
1407
+ h('div', { className: 'dsh-mail-hint', style: { marginBottom: 12 } }, (a.imapHost || '') + ':' + a.imapPort + ' · ' + (a.smtpHost || '') + ':' + a.smtpPort),
1408
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
1409
+ h('button', { className: 'dsh-mail-btn', onClick: () => testAccount(a.id), disabled: busy }, h(Ico, { name: 'check', size: 14 }), t('test')),
1410
+ h('button', { className: 'dsh-mail-btn', onClick: () => { setActiveId(a.id); navTo('inbox'); } }, h(Ico, { name: 'inbox', size: 14 }), t('inbox')),
1411
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-danger', onClick: () => deleteAccount(a.id), disabled: busy }, h(Ico, { name: 'trash', size: 14 }), t('delete'))
1412
+ )
1413
+ )),
1414
+ h('div', { className: 'dsh-mail-card' },
1415
+ h('div', { className: 'dsh-mail-cardhead' }, h(Ico, { name: 'plus', size: 16 }), t('addAccount')),
1416
+ h('div', { className: 'dsh-mail-hint', style: { marginBottom: 12 } }, t('note')),
1417
+ h('div', { style: { display: 'flex', gap: 7, flexWrap: 'wrap', marginBottom: 14 } },
1418
+ Object.keys(PRESETS).map(k => h('button', {
1419
+ key: k, type: 'button', 'aria-pressed': form.preset === k,
1420
+ className: 'dsh-mail-pill' + (form.preset === k ? ' is-active' : ''),
1421
+ onClick: () => applyPreset(k),
1422
+ }, t(k)))
1423
+ ),
1424
+ h('div', { className: 'dsh-mail-grid' },
1425
+ h('div', { className: 'dsh-mail-field' },
1426
+ h('span', { className: 'dsh-mail-label' }, t('name')),
1427
+ h('input', { className: 'dsh-mail-input', value: form.name, onChange: e => setForm(Object.assign({}, form, { name: e.target.value })) })
1428
+ ),
1429
+ h('div', { className: 'dsh-mail-field' },
1430
+ h('span', { className: 'dsh-mail-label' }, t('username')),
1431
+ h('input', { className: 'dsh-mail-input', value: form.username, placeholder: 'me@qq.com', onChange: e => setForm(Object.assign({}, form, { username: e.target.value })) })
1432
+ )
1433
+ ),
1434
+ h('div', { className: 'dsh-mail-field' },
1435
+ h('span', { className: 'dsh-mail-label' }, t('authCode')),
1436
+ h('input', { className: 'dsh-mail-input', type: 'password', value: form.authCode, onChange: e => setForm(Object.assign({}, form, { authCode: e.target.value })) })
1437
+ ),
1438
+ h('div', { className: 'dsh-mail-grid' },
1439
+ h('div', { className: 'dsh-mail-field' },
1440
+ h('span', { className: 'dsh-mail-label' }, t('imapHost')),
1441
+ h('input', { className: 'dsh-mail-input', value: form.imapHost, onChange: e => setForm(Object.assign({}, form, { imapHost: e.target.value })) })
1442
+ ),
1443
+ h('div', { className: 'dsh-mail-field', style: { flex: '0 0 96px', minWidth: 96 } },
1444
+ h('span', { className: 'dsh-mail-label' }, t('imapPort')),
1445
+ h('input', { className: 'dsh-mail-input', value: form.imapPort, onChange: e => setForm(Object.assign({}, form, { imapPort: e.target.value })) })
1446
+ )
1447
+ ),
1448
+ h('div', { className: 'dsh-mail-grid' },
1449
+ h('div', { className: 'dsh-mail-field' },
1450
+ h('span', { className: 'dsh-mail-label' }, t('smtpHost')),
1451
+ h('input', { className: 'dsh-mail-input', value: form.smtpHost, onChange: e => setForm(Object.assign({}, form, { smtpHost: e.target.value })) })
1452
+ ),
1453
+ h('div', { className: 'dsh-mail-field', style: { flex: '0 0 96px', minWidth: 96 } },
1454
+ h('span', { className: 'dsh-mail-label' }, t('smtpPort')),
1455
+ h('input', { className: 'dsh-mail-input', value: form.smtpPort, onChange: e => setForm(Object.assign({}, form, { smtpPort: e.target.value })) })
1456
+ )
1457
+ ),
1458
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-primary', onClick: saveAccount, disabled: busy || !form.username || !form.authCode }, h(Ico, { name: 'check', size: 15 }), t('save'))
1459
+ )
1460
+ )
1461
+ ),
1462
+
1463
+ /* ------------------------------- DETAIL ----------------------------- */
1464
+ view === 'detail' && h('div', { className: 'dsh-mail-view' },
1465
+ h('div', { className: 'dsh-mail-scroll' },
1466
+ h('button', { className: 'dsh-mail-btn', onClick: () => { BADGE.clear(); setView('inbox'); } }, h(Ico, { name: 'back', size: 15 }), t('back')),
1467
+ detail && h('div', null,
1468
+ h('div', { className: 'dsh-mail-detailhead' },
1469
+ h('h2', { className: 'dsh-mail-detailtitle' }, detail.subject || t('noSubject')),
1470
+ h('div', { className: 'dsh-mail-detailfrom' },
1471
+ h('div', { className: 'dsh-mail-avatar', style: { background: avatarColor(detail.from || detail.subject) } }, avatarLetter(detail.from || detail.subject)),
1472
+ h('div', { style: { minWidth: 0 } },
1473
+ h('div', { style: { fontWeight: 600 } }, String(detail.from || '').replace(/<.*>/, '').trim() || detail.from || ''),
1474
+ h('div', { className: 'dsh-mail-detailmeta' }, t('to') + ': ' + (detail.to || '') + ' · ' + fmtDate(detail.date))
1475
+ )
1476
+ )
1477
+ ),
1478
+ h('div', {
1479
+ className: 'dsh-mail-mailbody',
1480
+ onClick: (e) => {
1481
+ const a = e.target && e.target.closest && e.target.closest('a[href]');
1482
+ if (!a) return;
1483
+ const href = a.getAttribute('href');
1484
+ if (!href) return;
1485
+ e.preventDefault();
1486
+ if (window.open) window.open(href, '_blank', 'noopener,noreferrer');
1487
+ },
1488
+ dangerouslySetInnerHTML: { __html: detail.html || ('<div style="white-space:pre-wrap">' + escHtml(detail.body || '') + '</div>') },
1489
+ })
1490
+ )
1491
+ )
1492
+ ),
1493
+
1494
+ /* ------------------------------- COMPOSE ---------------------------- */
1495
+ view === 'compose' && h('div', { className: 'dsh-mail-view' },
1496
+ h('div', { className: 'dsh-mail-scroll' },
1497
+ h('div', { className: 'dsh-mail-card' },
1498
+ h('div', { className: 'dsh-mail-cardhead' },
1499
+ h(Ico, { name: 'compose', size: 16 }), t('compose'),
1500
+ h('span', { className: 'dsh-mail-spacer' }),
1501
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-primary', onClick: sendMail, disabled: busy || !compose.to }, h(Ico, { name: 'sent', size: 15 }), t('send'))
1502
+ ),
1503
+ h('div', { className: 'dsh-mail-hint', style: { marginBottom: 12 } }, account ? account.username : ''),
1504
+ h('div', { className: 'dsh-mail-field' },
1505
+ h('span', { className: 'dsh-mail-label' }, t('to')),
1506
+ h('input', { className: 'dsh-mail-input', value: compose.to, placeholder: 'friend@example.com', onChange: e => setCompose(Object.assign({}, compose, { to: e.target.value })) })
1507
+ ),
1508
+ h('div', { className: 'dsh-mail-field' },
1509
+ h('span', { className: 'dsh-mail-label' }, t('subject')),
1510
+ h('input', { className: 'dsh-mail-input', value: compose.subject, onChange: e => setCompose(Object.assign({}, compose, { subject: e.target.value })) })
1511
+ ),
1512
+ h('div', { className: 'dsh-mail-field' },
1513
+ h('span', { className: 'dsh-mail-label' }, t('body')),
1514
+ h('textarea', { className: 'dsh-mail-textarea', value: compose.body, onChange: e => setCompose(Object.assign({}, compose, { body: e.target.value })) })
1515
+ )
1516
+ )
1517
+ )
1518
+ )
1519
+ );
1520
+ }
1521
+
1522
+ // Dedicated "邮件" section in the main Settings panel. Reads/writes the
1523
+ // agentMailAccess switch through the plugin's own fetch route (the Host
1524
+ // half stores it in the credential store), so this toggle and the AI tool
1525
+ // share one host-owned value without depending on configForms, which is not
1526
+ // available on this DSH build.
1527
+ function MailSettingsSection(props) {
1528
+ const tr = props && props.t ? props.t : t;
1529
+ const [draft, setDraft] = useState({ agentMailAccess: false, notifyEnabled: true, notifyInterval: 60, notifyMode: 'pet' });
1530
+ const [stored, setStored] = useState({ agentMailAccess: false, notifyEnabled: true, notifyInterval: 60, notifyMode: 'pet' });
1531
+ const [saving, setSaving] = useState(false);
1532
+ const [loaded, setLoaded] = useState(false);
1533
+ const [failed, setFailed] = useState(false);
1534
+ const [saveError, setSaveError] = useState('');
1535
+ const [saved, setSaved] = useState(false);
1536
+ const [perm, setPerm] = useState(() => notifyPermission());
1537
+ const [asking, setAsking] = useState(false);
1538
+ const [tested, setTested] = useState(false);
1539
+ const [testMsg, setTestMsg] = useState('');
1540
+ const [checking, setChecking] = useState(false);
1541
+ const [checkMsg, setCheckMsg] = useState('');
1542
+ const [diag, setDiag] = useState(() => Object.assign({}, NOTIFY.diag));
1543
+
1544
+ useEffect(() => {
1545
+ let alive = true;
1546
+ fetch(API, {
1547
+ method: 'POST',
1548
+ headers: { 'content-type': 'application/json' },
1549
+ body: JSON.stringify({ op: 'getSettings' }),
1550
+ })
1551
+ .then(r => r.json())
1552
+ .then(data => {
1553
+ if (!alive) return;
1554
+ const s = data && data.ok && data.settings ? data.settings : {};
1555
+ const next = {
1556
+ agentMailAccess: s.agentMailAccess === true,
1557
+ notifyEnabled: s.notifyEnabled !== false,
1558
+ notifyInterval: Number(s.notifyInterval) || 60,
1559
+ notifyMode: s.notifyMode || 'pet',
1560
+ };
1561
+ setStored(next);
1562
+ setDraft(next);
1563
+ setLoaded(true);
1564
+ })
1565
+ .catch(() => { if (alive) setLoaded(true); });
1566
+ return () => { alive = false; };
1567
+ }, []);
1568
+
1569
+ // Clear stale save hints as soon as the user edits away from the
1570
+ // last saved state. Avoids a lingering "已保存" after a new change.
1571
+ useEffect(() => {
1572
+ if (JSON.stringify(draft) !== JSON.stringify(stored) && (saved || failed)) {
1573
+ setSaved(false);
1574
+ setFailed(false);
1575
+ setSaveError('');
1576
+ }
1577
+ }, [draft, stored]);
1578
+
1579
+ // Mirror the background engine's diagnostics into this panel while it is
1580
+ // open, so checks/alerts/errors update live without a manual refresh.
1581
+ useEffect(() => {
1582
+ const sync = () => setDiag(Object.assign({}, NOTIFY.diag));
1583
+ sync();
1584
+ const id = setInterval(sync, 3000);
1585
+ return () => clearInterval(id);
1586
+ }, []);
1587
+
1588
+ const save = async () => {
1589
+ if (saving) return;
1590
+ setSaving(true);
1591
+ setFailed(false);
1592
+ setSaveError('');
1593
+ setSaved(false);
1594
+ try {
1595
+ const r = await fetch(API, {
1596
+ method: 'POST',
1597
+ headers: { 'content-type': 'application/json' },
1598
+ body: JSON.stringify({ op: 'setSettings', value: draft }),
1599
+ });
1600
+ const data = await r.json();
1601
+ // Only the HTTP result decides success. Side effects below (mirroring
1602
+ // state, restarting the poller) must never turn a persisted save into
1603
+ // a "failed" message — that is exactly the "saved but says failed" bug.
1604
+ if (!r.ok || !data || data.ok === false) {
1605
+ setFailed(true);
1606
+ setSaveError('http:' + (r.status || '?'));
1607
+ setSaving(false);
1608
+ return;
1609
+ }
1610
+ const applied = data.settings || draft;
1611
+ setStored(applied);
1612
+ setDraft(applied);
1613
+ NOTIFY.settings = {
1614
+ notifyEnabled: applied.notifyEnabled !== false,
1615
+ notifyInterval: Number(applied.notifyInterval) || 60,
1616
+ notifyMode: applied.notifyMode || 'pet',
1617
+ };
1618
+ setSaved(true);
1619
+ // Poller restart is best-effort: wrap it so an error here cannot
1620
+ // retroactively fail the already-persisted save.
1621
+ try { startPoller(); } catch (e) {
1622
+ if (NOTIFY.diag) NOTIFY.diag.error = 'poller: ' + (e && e.message ? e.message : String(e));
1623
+ }
1624
+ } catch (e) {
1625
+ setFailed(true);
1626
+ setSaveError(e && e.message ? e.message : String(e));
1627
+ }
1628
+ setSaving(false);
1629
+ };
1630
+
1631
+ const requestPerm = async () => {
1632
+ if (asking) return;
1633
+ setAsking(true);
1634
+ const result = await askNotifyPermission();
1635
+ setPerm(result);
1636
+ setAsking(false);
1637
+ if (result === 'granted') startPoller();
1638
+ return result;
1639
+ };
1640
+
1641
+ // Fired from a user gesture. Pet announcements need no browser
1642
+ // permission; system-notification mode asks for it in-gesture first.
1643
+ const sendTest = async () => {
1644
+ if (asking) return;
1645
+ const mode = draft.notifyMode || NOTIFY.settings.notifyMode || 'pet';
1646
+ if ((mode === 'system' || mode === 'both') && notifyPermission() !== 'granted') {
1647
+ const p = await requestPerm();
1648
+ if (p !== 'granted' && mode === 'system') {
1649
+ setTested(false);
1650
+ setTestMsg(p === 'denied' ? tr('notifyPermissionDenied') : (tr('notifyTestFailed') + ' (' + p + ')'));
1651
+ return;
1652
+ }
1653
+ }
1654
+ const systemOnly = mode === 'system';
1655
+ const result = await deliverAlert(
1656
+ tr(systemOnly ? 'notifyTestTitleSystem' : 'notifyTestTitle'),
1657
+ tr(systemOnly ? 'notifyTestBodySystem' : 'notifyTestBody'),
1658
+ { mode } // 用当前选择的方式,而不是已保存的设置
1659
+ );
1660
+ if (result.petOk && !systemOnly) {
1661
+ setTested(true);
1662
+ setTestMsg(tr('notifyPetOk'));
1663
+ } else if (result.sysOk) {
1664
+ setTested(true);
1665
+ setTestMsg(tr('notifyTestSent'));
1666
+ } else {
1667
+ setTested(false);
1668
+ setTestMsg(tr('notifyTestFailed') + (NOTIFY.lastError ? ' (' + NOTIFY.lastError + ')' : ''));
1669
+ }
1670
+ };
1671
+
1672
+ // Run the real detection chain on demand and refresh the diagnostics.
1673
+ // This is the only way to tell a live poller from a dead one without
1674
+ // waiting for an actual mail to arrive.
1675
+ const checkNow = async () => {
1676
+ if (checking) return;
1677
+ setChecking(true);
1678
+ const before = NOTIFY.diag.alerts;
1679
+ try {
1680
+ const snap = await pollNewMail();
1681
+ setDiag(Object.assign({}, snap));
1682
+ const found = Math.max(0, (snap && snap.alerts ? snap.alerts : 0) - before);
1683
+ setCheckMsg(tr('notifyCheckDone').replace('{n}', String(found)));
1684
+ } catch (e) {
1685
+ setDiag(Object.assign({}, NOTIFY.diag));
1686
+ setCheckMsg(tr('notifyTestFailed') + (e && e.message ? ' (' + e.message + ')' : ''));
1687
+ }
1688
+ setChecking(false);
1689
+ };
1690
+
1691
+ const field = {
1692
+ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
1693
+ fontSize: 14, lineHeight: 1.5, color: 'var(--dsw-alias-label-primary)',
1694
+ };
1695
+ const hint = { margin: '6px 0 0', fontSize: 12, lineHeight: 1.6, color: 'var(--dsw-alias-label-secondary)' };
1696
+ const numInput = {
1697
+ width: 84, padding: '4px 8px', borderRadius: 6, fontSize: 13,
1698
+ border: '1px solid var(--dsw-alias-border-l2)',
1699
+ background: 'var(--dsw-alias-bg-layer-1)', color: 'var(--dsw-alias-label-primary)',
1700
+ };
1701
+ const dirty = JSON.stringify(draft) !== JSON.stringify(stored);
1702
+ // In pure system-notification mode, hide all pet-related copy.
1703
+ const isSystemOnly = (draft.notifyMode || 'pet') === 'system';
1704
+ return h('div', { style: { padding: 4, maxWidth: 560 } },
1705
+ h('h2', { style: { margin: '0 0 8px', fontSize: 18, lineHeight: 1.4 } }, tr('settingsTitle')),
1706
+
1707
+ // AI assistant access toggle (unchanged behaviour).
1708
+ h('p', { style: { margin: '0 0 12px', fontSize: 13, lineHeight: 1.7, color: 'var(--dsw-alias-label-secondary)' } }, tr('settingsDescription')),
1709
+ h('label', { htmlFor: 'settings-dsh-mail-agent-access', style: field },
1710
+ h('input', {
1711
+ id: 'settings-dsh-mail-agent-access', type: 'checkbox',
1712
+ checked: draft.agentMailAccess, disabled: saving || !loaded,
1713
+ onChange: (e) => setDraft({ ...draft, agentMailAccess: !!(e && e.target && e.target.checked) }),
1714
+ style: { width: 16, height: 16, accentColor: 'var(--dsw-alias-brand-primary)', cursor: 'pointer' },
1715
+ }),
1716
+ tr('agentMailAccessLabel')
1717
+ ),
1718
+ h('p', { style: hint }, tr('agentMailAccessHint')),
1719
+
1720
+ // New-mail notification section.
1721
+ h('h3', { style: { margin: '24px 0 8px', fontSize: 15, lineHeight: 1.4 } }, tr('notifySectionTitle')),
1722
+ h('p', { style: { margin: '0 0 12px', fontSize: 13, lineHeight: 1.7, color: 'var(--dsw-alias-label-secondary)' } }, tr(isSystemOnly ? 'notifySectionHintSystem' : 'notifySectionHint')),
1723
+ h('label', { htmlFor: 'settings-dsh-mail-notify', style: field },
1724
+ h('input', {
1725
+ id: 'settings-dsh-mail-notify', type: 'checkbox',
1726
+ checked: draft.notifyEnabled, disabled: saving || !loaded,
1727
+ onChange: (e) => setDraft({ ...draft, notifyEnabled: !!(e && e.target && e.target.checked) }),
1728
+ style: { width: 16, height: 16, accentColor: 'var(--dsw-alias-brand-primary)', cursor: 'pointer' },
1729
+ }),
1730
+ tr(isSystemOnly ? 'notifyEnabledLabelSystem' : 'notifyEnabledLabel')
1731
+ ),
1732
+ h('label', { htmlFor: 'settings-dsh-mail-interval', style: { ...field, marginTop: 10 } },
1733
+ h('span', null, tr('notifyIntervalLabel')),
1734
+ h('input', {
1735
+ id: 'settings-dsh-mail-interval', type: 'number', min: 15, max: 3600,
1736
+ value: draft.notifyInterval, disabled: saving || !loaded,
1737
+ onChange: (e) => setDraft({ ...draft, notifyInterval: Number(e && e.target && e.target.value) || 60 }),
1738
+ style: numInput,
1739
+ })
1740
+ ),
1741
+ h('label', { htmlFor: 'settings-dsh-mail-mode', style: { ...field, marginTop: 10 } },
1742
+ h('span', null, tr('notifyMode')),
1743
+ h('select', {
1744
+ id: 'settings-dsh-mail-mode',
1745
+ value: draft.notifyMode || 'pet',
1746
+ disabled: saving || !loaded,
1747
+ onChange: (e) => setDraft({ ...draft, notifyMode: (e && e.target && e.target.value) || 'pet' }),
1748
+ style: numInput,
1749
+ },
1750
+ h('option', { value: 'pet' }, tr('notifyModePet')),
1751
+ h('option', { value: 'system' }, tr('notifyModeSystem')),
1752
+ h('option', { value: 'both' }, tr('notifyModeBoth'))
1753
+ )
1754
+ ),
1755
+
1756
+ // Permission row.
1757
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: 14 } },
1758
+ h('button', {
1759
+ type: 'button', disabled: asking || perm === 'granted' || perm === 'unsupported',
1760
+ onClick: () => { void requestPerm(); },
1761
+ style: {
1762
+ padding: '6px 16px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)',
1763
+ background: 'var(--dsw-alias-bg-layer-1)', color: 'var(--dsw-alias-label-primary)',
1764
+ fontSize: 13, cursor: asking || perm === 'granted' ? 'default' : 'pointer',
1765
+ opacity: asking || perm === 'granted' ? 0.6 : 1,
1766
+ },
1767
+ }, asking ? tr('notifyPermissionAsking') : tr('notifyPermission')),
1768
+ h('span', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
1769
+ perm === 'granted' ? tr('notifyPermissionGranted')
1770
+ : perm === 'denied' ? tr('notifyPermissionDenied')
1771
+ : perm === 'unsupported' ? tr('notifyPermissionUnsupported') : ''
1772
+ ),
1773
+ h('button', {
1774
+ type: 'button', disabled: asking,
1775
+ onClick: () => { void sendTest(); },
1776
+ style: {
1777
+ padding: '6px 16px', borderRadius: 6, border: 'none',
1778
+ background: 'var(--dsw-alias-brand-primary)', color: 'var(--dsw-alias-bg-base)',
1779
+ fontSize: 13, cursor: asking ? 'default' : 'pointer',
1780
+ opacity: asking ? 0.5 : 1,
1781
+ },
1782
+ }, tr('notifyTest'))
1783
+ ),
1784
+ testMsg ? h('p', {
1785
+ style: { ...hint, color: tested ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-error-primary)' },
1786
+ }, testMsg) : null,
1787
+
1788
+ // Live detection diagnostics + manual check. These make the otherwise
1789
+ // invisible background chain observable to the user and to us.
1790
+ h('div', { style: { marginTop: 14, padding: 10, borderRadius: 6, background: 'var(--dsw-alias-bg-layer-1)', border: '1px solid var(--dsw-alias-border-l2)' } },
1791
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
1792
+ h('strong', { style: { fontSize: 13, color: 'var(--dsw-alias-label-primary)' } }, tr('notifyDiagTitle')),
1793
+ h('span', { style: { fontSize: 12, color: diag.running ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-error-primary)' } },
1794
+ diag.running ? tr('notifyDiagRunning') : tr('notifyDiagStopped')),
1795
+ h('span', { className: 'dsh-mail-spacer' }),
1796
+ h('button', {
1797
+ type: 'button', disabled: checking || !loaded,
1798
+ onClick: () => { void checkNow(); },
1799
+ style: {
1800
+ padding: '5px 12px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)',
1801
+ background: 'var(--dsw-alias-bg-base)', color: 'var(--dsw-alias-label-primary)',
1802
+ fontSize: 12, cursor: checking || !loaded ? 'default' : 'pointer',
1803
+ opacity: checking || !loaded ? 0.6 : 1,
1804
+ },
1805
+ }, checking ? tr('notifyChecking') : tr('notifyCheckNow'))
1806
+ ),
1807
+ h('div', { style: { marginTop: 6, fontSize: 12, lineHeight: 1.7, color: 'var(--dsw-alias-label-secondary)' } },
1808
+ tr('notifyDiagAccounts') + ': ' + (diag.accounts || 0) + ' · ' +
1809
+ tr('notifyDiagChecks') + ': ' + (diag.checks || 0) + ' · ' +
1810
+ tr(isSystemOnly ? 'notifyDiagAlertsSystem' : 'notifyDiagAlerts') + ': ' + (diag.alerts || 0) + ' · ' +
1811
+ tr('notifyDiagLastCheck') + ': ' + (diag.lastCheck ? new Date(diag.lastCheck).toLocaleString() : tr('notifyDiagNever'))
1812
+ ),
1813
+ h('div', { style: { marginTop: 2, fontSize: 12, lineHeight: 1.7, color: diag.error ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-state-success-primary)' } },
1814
+ tr('notifyDiagError') + ': ' + (diag.error || tr('notifyDiagOk'))
1815
+ ),
1816
+ checkMsg ? h('p', { style: { margin: '6px 0 0', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, checkMsg) : null
1817
+ ),
1818
+
1819
+ failed
1820
+ ? h('p', { style: { margin: '8px 0 0', fontSize: 12, color: 'var(--dsw-alias-state-error-primary)' } }, tr('settingsSaveFailed') + (saveError ? ' (' + saveError + ')' : ''))
1821
+ : saved
1822
+ ? h('p', { style: { margin: '8px 0 0', fontSize: 12, color: 'var(--dsw-alias-state-success-primary)' } }, tr('settingsSaveSuccess'))
1823
+ : null,
1824
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
1825
+ h('button', {
1826
+ type: 'button',
1827
+ disabled: !dirty || saving,
1828
+ onClick: () => { void save(); },
1829
+ style: {
1830
+ padding: '6px 16px', borderRadius: 6, border: 'none', cursor: dirty && !saving ? 'pointer' : 'default',
1831
+ background: 'var(--dsw-alias-brand-primary)', color: 'var(--dsw-alias-bg-base)', fontSize: 13,
1832
+ opacity: dirty && !saving ? 1 : 0.5,
1833
+ },
1834
+ }, saving ? tr('settingsSaving') : tr('settingsSave')),
1835
+ dirty ? h('button', {
1836
+ type: 'button',
1837
+ disabled: saving,
1838
+ onClick: () => setDraft(stored),
1839
+ style: {
1840
+ padding: '6px 16px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)',
1841
+ background: 'transparent', color: 'var(--dsw-alias-label-primary)', fontSize: 13, cursor: 'pointer',
1842
+ },
1843
+ }, tr('cancel')) : null
1844
+ )
1845
+ );
1846
+ }
1847
+
1848
+ return {
1849
+ inject: ['slots', 'locale'],
1850
+ apply(ctx) {
1851
+ t = ctx.locale.bind(NS);
1852
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-mail: dictionaries');
1853
+ // Start the always-on new-mail poller once the client context is live;
1854
+ // dispose it if this plugin half is torn down.
1855
+ ctx.effect(() => {
1856
+ NOTIFY.ctx = ctx;
1857
+ void refreshNotifySettings();
1858
+ return () => {
1859
+ stopPoller();
1860
+ NOTIFY.ctx = null;
1861
+ };
1862
+ }, 'dsh-mail: new-mail notifications');
1863
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
1864
+ name: 'settings.section',
1865
+ id: NS,
1866
+ order: 25,
1867
+ label: () => t('settingsTitle'),
1868
+ locale: NS,
1869
+ }, MailSettingsSection));
1870
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1871
+ name: 'sidebar.panellist', id: 'dsh-mail', order: 80,
1872
+ label: () => t('label'),
1873
+ }, Icon));
1874
+ ctx.slots.inject('main', () => ctx.slots.register({
1875
+ name: 'main', key: 'dsh-mail',
1876
+ }, MailPanel));
1877
+ },
1878
+ };
1879
+ },
1880
+ });