@mysterycode-liwen/dsh-mail 1.0.1 → 1.3.0

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 CHANGED
@@ -7,12 +7,195 @@ window.__ModuleLoader__.load({
7
7
 
8
8
  const NS = 'dsh-mail';
9
9
  const API = '/api/dsh-mail';
10
+ // ---- Credential-vault bridge client (self-contained, zero deps) ----
11
+ // Enables "fill from vault" only when the credential-vault plugin is installed.
12
+ // Uninstalled -> isAvailable() false -> the feature silently hides.
13
+ /*
14
+ * vault-bridge-client.js — reusable client module for the DSH credential vault bridge
15
+ * ------------------------------------------------------------------------------
16
+ * Copy this whole file's contents into your plugin's client.js (inside
17
+ * factory(require)), or load it through your plugin's build step. ZERO deps:
18
+ * it only uses window.crypto.subtle, btoa/atob and TextEncoder/TextDecoder.
19
+ *
20
+ * WHY THIS EXISTS
21
+ * The vault keeps real secrets in its own browser localStorage. The Harness
22
+ * Host process only ever sees metadata (secrets are masked), so a plugin that
23
+ * needs a real value (e.g. a mail app password) must talk to the vault's
24
+ * browser-side bridge. This module does that.
25
+ *
26
+ * All payloads are encrypted with an ECDH (P-256) + AES-GCM session:
27
+ * 1. client.query(...) -> bridge.hello() = vault ephemeral public key + id
28
+ * 2. client generates its own ephemeral key pair, derives the shared AES key
29
+ * 3. client seals the query, vault decrypts / reads secrets / seals result
30
+ * 4. client opens the result with the same derived key.
31
+ * No plaintext and no long-lived key ever crosses the bridge. If the vault is
32
+ * not installed, isAvailable() is false and query() rejects NOT_INSTALLED —
33
+ * gate your UI on isAvailable() so the feature silently disappears.
34
+ *
35
+ * SECURITY NOTE
36
+ * The bridge is a same-document JS object. ECDH stops passive observers and
37
+ * other plugins from reading the payload, but a hostile script in the same
38
+ * document could still call the bridge as if it were your plugin. The vault
39
+ * never auto-authorises: each session is one-time use and expires in 60s.
40
+ *
41
+ * USAGE
42
+ * const vault = createVaultV1Client();
43
+ * if (vault.isAvailable()) {
44
+ * const entries = await vault.query({ category: 'account', title: 'qq' });
45
+ * const secret = vault.secretOf(entries[0]); // real password / key value
46
+ * }
47
+ *
48
+ * Node (tests): also exported via module.exports when available.
49
+ */
50
+
51
+ function createVaultV1Client(options) {
52
+ options = options || {};
53
+ var win = options.window || (typeof window !== 'undefined' ? window : null);
54
+ var BRIDGE_KEY = '@mysterycode-liwen/dsh-credential-vault/bridge/v1';
55
+
56
+ function cryptoObj() {
57
+ return (win && win.crypto) || (typeof globalThis !== 'undefined' && globalThis.crypto) || null;
58
+ }
59
+ function subtle() {
60
+ var c = cryptoObj();
61
+ return c && c.subtle ? c.subtle : null;
62
+ }
63
+ function randomFill(bytes) {
64
+ var c = cryptoObj();
65
+ if (!c || !c.getRandomValues) throw new Error('NO_CRYPTO');
66
+ c.getRandomValues(bytes);
67
+ return bytes;
68
+ }
69
+ function toB64u(bytes) {
70
+ var s = '';
71
+ for (var i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
72
+ var btoaFn = options.btoa || (typeof btoa === 'function' ? btoa : (win && win.btoa));
73
+ return btoaFn(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
74
+ }
75
+ function fromB64u(str) {
76
+ var s = String(str).replace(/-/g, '+').replace(/_/g, '/');
77
+ while (s.length % 4) s += '=';
78
+ var atobFn = options.atob || (typeof atob === 'function' ? atob : (win && win.atob));
79
+ var bin = atobFn(s), out = new Uint8Array(bin.length);
80
+ for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
81
+ return out;
82
+ }
83
+ function enc(str) { return new TextEncoder().encode(str); }
84
+ function dec(bytes) { return new TextDecoder().decode(bytes); }
85
+
86
+ function bridge() {
87
+ if (!win || !win[BRIDGE_KEY]) return null;
88
+ var b = win[BRIDGE_KEY];
89
+ return b && b.version === 1 && typeof b.hello === 'function' && typeof b.query === 'function' ? b : null;
90
+ }
91
+
92
+ function generatePair(s) {
93
+ return s.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']);
94
+ }
95
+ function deriveKey(s, priv, peerJwk) {
96
+ return s.importKey('jwk', peerJwk, { name: 'ECDH', namedCurve: 'P-256' }, false, [])
97
+ .then(function (pub) { return s.deriveBits({ name: 'ECDH', public: pub }, priv, 256); })
98
+ .then(function (bits) { return s.importKey('raw', bits, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); });
99
+ }
100
+ function seal(s, key, obj) {
101
+ var iv = randomFill(new Uint8Array(12));
102
+ return s.encrypt({ name: 'AES-GCM', iv: iv }, key, enc(JSON.stringify(obj)))
103
+ .then(function (ct) { return { iv: toB64u(iv), ciphertext: toB64u(new Uint8Array(ct)) }; });
104
+ }
105
+ function open(s, key, payload) {
106
+ if (!payload || typeof payload.iv !== 'string' || typeof payload.ciphertext !== 'string') {
107
+ return Promise.reject(new Error('BAD_CIPHERTEXT'));
108
+ }
109
+ return s.decrypt({ name: 'AES-GCM', iv: fromB64u(payload.iv) }, key, fromB64u(payload.ciphertext))
110
+ .then(function (plain) { return JSON.parse(dec(new Uint8Array(plain))); });
111
+ }
112
+
113
+ function isAvailable() { return !!bridge(); }
114
+
115
+ function query(criteria) {
116
+ criteria = criteria || {};
117
+ var b = bridge();
118
+ if (!b) return Promise.reject(new Error('NOT_INSTALLED'));
119
+ var s = subtle();
120
+ if (!s) return Promise.reject(new Error('NO_CRYPTO'));
121
+ var vaultPub, sessionId, priv, aes;
122
+ return Promise.resolve(b.hello())
123
+ .then(function (hello) {
124
+ if (!hello || !hello.sessionId || !hello.publicKeyJwk) throw new Error('BAD_HELLO');
125
+ sessionId = hello.sessionId;
126
+ vaultPub = hello.publicKeyJwk;
127
+ return generatePair(s);
128
+ })
129
+ .then(function (kp) {
130
+ priv = kp.privateKey;
131
+ return s.exportKey('jwk', kp.publicKey);
132
+ })
133
+ .then(function (pubJwk) {
134
+ return deriveKey(s, priv, vaultPub).then(function (key) {
135
+ aes = key;
136
+ return seal(s, aes, {
137
+ category: criteria.category || 'all',
138
+ title: criteria.title || '',
139
+ limit: criteria.limit || 100
140
+ }).then(function (sealed) {
141
+ return b.query({
142
+ sessionId: sessionId,
143
+ publicKeyJwk: pubJwk,
144
+ iv: sealed.iv,
145
+ ciphertext: sealed.ciphertext
146
+ });
147
+ });
148
+ });
149
+ })
150
+ .then(function (result) {
151
+ if (!result) throw new Error('NO_RESPONSE');
152
+ if (result.error) throw new Error(result.error);
153
+ return open(s, aes, result);
154
+ })
155
+ .then(function (plain) { return plain && Array.isArray(plain.entries) ? plain.entries : []; });
156
+ }
157
+
158
+ function secretOf(entry) {
159
+ if (!entry) return '';
160
+ var keys = ['password', 'keyValue', 'apiKey', 'content', 'appSecret', 'token', 'encodingAesKey', 'uploadKey'];
161
+ for (var i = 0; i < keys.length; i++) {
162
+ if (typeof entry[keys[i]] === 'string' && entry[keys[i]]) return entry[keys[i]];
163
+ }
164
+ return '';
165
+ }
166
+
167
+ return {
168
+ version: 1,
169
+ isAvailable: isAvailable,
170
+ query: query,
171
+ secretOf: secretOf,
172
+ _debug: { toB64u: toB64u, fromB64u: fromB64u, deriveKey: deriveKey, seal: seal, open: open }
173
+ };
174
+ }
175
+
10
176
 
11
177
  function escHtml(s) {
12
178
  return String(s == null ? '' : s)
13
179
  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
14
180
  }
15
181
 
182
+ // Best-effort plain-text extraction from a sanitized mail body, used as the
183
+ // translation source when the bridge did not supply a plain-text part.
184
+ function htmlToText(html) {
185
+ return String(html == null ? '' : html)
186
+ .replace(/<br\s*\/?>/gi, '\n')
187
+ .replace(/<\/(p|div|li|tr|h[1-6]|blockquote)>/gi, '\n')
188
+ .replace(/<[^>]*>/g, '')
189
+ .replace(/&nbsp;/gi, ' ')
190
+ .replace(/&amp;/gi, '&')
191
+ .replace(/&lt;/gi, '<')
192
+ .replace(/&gt;/gi, '>')
193
+ .replace(/&quot;/gi, '"')
194
+ .replace(/&#39;/g, "'")
195
+ .replace(/\n{3,}/g, '\n\n')
196
+ .trim();
197
+ }
198
+
16
199
  let t = (key) => key;
17
200
 
18
201
  // Map a structured bridge error ({ code, error, stage }) to a short,
@@ -38,6 +221,10 @@ window.__ModuleLoader__.load({
38
221
  const known = Object.prototype.hasOwnProperty.call(map, info.code);
39
222
  const head = known ? map[info.code] : t('errGeneric');
40
223
  const raw = String(info.error || '').trim();
224
+ // "unknown op" means the Host half predates this Client half: the plugin
225
+ // was updated on disk but DeepSeek Harness was never restarted, so the
226
+ // running Host has no case for the op the UI just sent.
227
+ if (/unknown op/i.test(raw)) return t('errOutdatedHost');
41
228
  const detail = (!known && raw && raw !== head) ? '\n' + t('errDetail') + raw : '';
42
229
  return stage + head + detail;
43
230
  }
@@ -85,7 +272,16 @@ window.__ModuleLoader__.load({
85
272
  custom: '自定义',
86
273
  presets: '快速设置',
87
274
  note: 'QQ / 163 需要邮箱授权码,而不是登录密码。授权码保存在凭据保险箱中。',
275
+ fillFromVault: '从保险箱选择',
276
+ vaultUnavailable: '未安装凭据保险箱插件,或保险箱中没有账号类凭据。',
277
+ vaultPickTitle: '从凭据保险箱选择授权码',
278
+ vaultPickHint: '以下是保险箱中的账号凭据,选择一个用其密码/授权码填入。',
279
+ vaultPickEmpty: '保险箱中没有可用的账号凭据。',
280
+ vaultPickError: '读取保险箱失败,请确认保险箱插件已启用。',
281
+ vaultPickLoading: '正在读取…',
88
282
  confirmDelete: '确定删除此账号吗?',
283
+ rename: '重命名',
284
+ renameHint: '名称只在本机显示,默认用邮箱前缀。',
89
285
  noSubject: '(无主题)',
90
286
  ok: '成功',
91
287
  failed: '失败',
@@ -100,6 +296,7 @@ window.__ModuleLoader__.load({
100
296
  errNotFound: '未找到这封邮件,它可能已被删除。',
101
297
  errGeneric: '操作失败,请稍后重试。',
102
298
  errDetail: '服务器返回:',
299
+ errOutdatedHost: '插件已更新,但 DeepSeek Harness 仍在运行旧版本。请完全退出并重新启动 DeepSeek Harness(仅刷新页面不够)。',
103
300
  sent: '发件箱',
104
301
  contacts: '联系人',
105
302
  noSent: '还没有已发送的邮件。',
@@ -110,10 +307,24 @@ window.__ModuleLoader__.load({
110
307
  saveContact: '保存联系人',
111
308
  deleteContact: '删除',
112
309
  contactsHint: '手动添加的联系人仅保存在本地,不会上传到邮箱服务器。',
310
+ addSender: '加为联系人',
311
+ addRecipient: '加收件人',
312
+ contactAdded: '已加为联系人。',
313
+ contactExists: '已在联系人中。',
113
314
  emailRequired: '请填写有效的邮箱地址。',
114
315
  saved: '已保存。',
115
316
  selectContact: '用此地址写邮件',
116
317
  attached: '附件',
318
+ attachments: '附件',
319
+ attachmentsHint: '拖拽文件到此处,或点击「添加附件」',
320
+ addAttachment: '添加附件',
321
+ removeAttachment: '移除',
322
+ downloadAttachment: '下载',
323
+ noAttachments: '没有附件',
324
+ attachmentTooLarge: '附件总大小超过 25 MB,请分开发送。',
325
+ attachmentFailed: '附件操作失败:',
326
+ attachmentSaved: '已保存到下载目录:',
327
+ sending: '发送中…',
117
328
  settingsTitle: '邮件',
118
329
  settingsDescription: '配置 AI 助手是否可以读取你的邮箱。',
119
330
  agentMailAccessLabel: '允许 AI 助手查询邮箱',
@@ -166,6 +377,15 @@ window.__ModuleLoader__.load({
166
377
  notifyDiagNever: '从未',
167
378
  notifyDiagError: '最近错误',
168
379
  notifyDiagOk: '正常',
380
+ // 邮件翻译
381
+ translate: '翻译',
382
+ translating: '翻译中…',
383
+ translated: '译文',
384
+ translateShowOriginal: '查看原文',
385
+ translatedNotice: '由 DSH 翻译(机器翻译,仅供参考)',
386
+ translateFailed: '翻译失败:',
387
+ translateUnavailable: '当前环境未启用翻译服务。请在「设置 → 插件」中启用实验性翻译扩展后重试。',
388
+ translateTextLimit: '邮件内容过长,翻译失败。',
169
389
  };
170
390
  const en = {
171
391
  label: 'Mail',
@@ -210,7 +430,16 @@ window.__ModuleLoader__.load({
210
430
  custom: 'Custom',
211
431
  presets: 'Presets',
212
432
  note: 'QQ / 163 need an app password, not your login password. Stored in the credential vault.',
433
+ fillFromVault: 'Fill from vault',
434
+ vaultUnavailable: 'Credential vault plugin not installed, or no account credentials in it.',
435
+ vaultPickTitle: 'Choose app password from vault',
436
+ vaultPickHint: 'These are the account credentials in your vault. Pick one to fill its password / app code.',
437
+ vaultPickEmpty: 'No account credentials found in the vault.',
438
+ vaultPickError: 'Failed to read the vault. Make sure the vault plugin is enabled.',
439
+ vaultPickLoading: 'Reading…',
213
440
  confirmDelete: 'Delete this account?',
441
+ rename: 'Rename',
442
+ renameHint: 'The name is local to this machine; it defaults to the mailbox prefix.',
214
443
  noSubject: '(no subject)',
215
444
  ok: 'OK',
216
445
  failed: 'Failed',
@@ -225,6 +454,7 @@ window.__ModuleLoader__.load({
225
454
  errNotFound: 'This message was not found — it may have been deleted.',
226
455
  errGeneric: 'The operation failed. Please try again later.',
227
456
  errDetail: 'Server said: ',
457
+ errOutdatedHost: 'The plugin was updated but DeepSeek Harness is still running the old version. Fully quit and restart DeepSeek Harness (refreshing the page is not enough).',
228
458
  sent: 'Sent',
229
459
  contacts: 'Contacts',
230
460
  noSent: 'No sent messages yet.',
@@ -235,10 +465,24 @@ window.__ModuleLoader__.load({
235
465
  saveContact: 'Save contact',
236
466
  deleteContact: 'Delete',
237
467
  contactsHint: 'Contacts you add are saved locally only and are not uploaded to the mail server.',
468
+ addSender: 'Add sender',
469
+ addRecipient: 'Add recipient',
470
+ contactAdded: 'Added to contacts.',
471
+ contactExists: 'Already in contacts.',
238
472
  emailRequired: 'Please enter a valid email address.',
239
473
  saved: 'Saved.',
240
474
  selectContact: 'Compose to this address',
241
475
  attached: 'Attachments',
476
+ attachments: 'Attachments',
477
+ attachmentsHint: 'Drop files here, or click "Add attachment"',
478
+ addAttachment: 'Add attachment',
479
+ removeAttachment: 'Remove',
480
+ downloadAttachment: 'Download',
481
+ noAttachments: 'No attachments',
482
+ attachmentTooLarge: 'Attachments exceed 25 MB in total; please send them separately.',
483
+ attachmentFailed: 'Attachment failed: ',
484
+ attachmentSaved: 'Saved to your downloads folder: ',
485
+ sending: 'Sending…',
242
486
  settingsTitle: 'Mail',
243
487
  settingsDescription: 'Control whether the AI assistant may read your mailbox.',
244
488
  agentMailAccessLabel: 'Allow AI assistant to query mail',
@@ -291,6 +535,15 @@ window.__ModuleLoader__.load({
291
535
  notifyDiagNever: 'Never',
292
536
  notifyDiagError: 'Last error',
293
537
  notifyDiagOk: 'OK',
538
+ // Mail translation
539
+ translate: 'Translate',
540
+ translating: 'Translating…',
541
+ translated: 'Translation',
542
+ translateShowOriginal: 'Show original',
543
+ translatedNotice: 'Translated by DSH (machine translation, for reference only)',
544
+ translateFailed: 'Translation failed: ',
545
+ translateUnavailable: 'Translation is not enabled in this environment. Enable the experimental translation extension under Settings → Plugins and retry.',
546
+ translateTextLimit: 'This message is too long to translate.',
294
547
  };
295
548
 
296
549
  // ---------------------------------------------------------------------
@@ -301,25 +554,25 @@ window.__ModuleLoader__.load({
301
554
  // hardcoded gray buttons the previous version had.
302
555
  // ---------------------------------------------------------------------
303
556
  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; }',
557
+ '.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.55; -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility; }',
305
558
  '.dsh-mail * { box-sizing:border-box; }',
306
559
  '.dsh-mail button, .dsh-mail input, .dsh-mail textarea, .dsh-mail select { font-family:inherit; }',
307
560
  '.dsh-mail-spacer { flex:1; min-width:0; }',
308
561
 
309
562
  /* 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; }',
563
+ '.dsh-mail-topbar { display:flex; align-items:center; gap:12px; padding:15px 20px 14px; border-bottom:1px solid var(--dsw-alias-border-l1); background:linear-gradient(180deg, color-mix(in srgb, var(--dsw-alias-brand-primary) 6%, var(--dsw-alias-bg-layer-1)), var(--dsw-alias-bg-layer-1)); }',
564
+ '.dsh-mail-brand { display:flex; align-items:center; gap:11px; font-size:16px; font-weight:700; letter-spacing:.3px; }',
565
+ '.dsh-mail-brandmark { width:34px; height:34px; border-radius:11px; display:grid; place-items:center; background:linear-gradient(135deg, color-mix(in srgb, var(--dsw-alias-brand-primary) 78%, white), var(--dsw-alias-brand-primary)); color:var(--dsw-alias-bg-base); box-shadow:0 4px 12px color-mix(in srgb, var(--dsw-alias-brand-primary) 28%, transparent), inset 0 1px 0 rgba(255,255,255,.22); }',
566
+ '.dsh-mail-brandsub { font-size:10.5px; color:var(--dsw-alias-label-secondary); font-weight:500; letter-spacing:.6px; text-transform:uppercase; }',
314
567
 
315
568
  /* 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); }',
569
+ '.dsh-mail-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; border:1px solid var(--dsw-alias-border-l2); border-radius:9px; padding:7px 13px; 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 .15s, transform .08s, box-shadow .15s, border-color .15s, background .15s; white-space:nowrap; }',
570
+ '.dsh-mail-btn:hover:not(:disabled) { filter:brightness(.97); border-color:var(--dsw-alias-brand-primary); box-shadow:0 2px 8px rgba(0,0,0,.08); }',
318
571
  '.dsh-mail-btn:active:not(:disabled) { transform:translateY(1px); box-shadow:inset 0 2px 5px rgba(0,0,0,.12); }',
319
572
  '.dsh-mail-btn:focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:2px; }',
320
573
  '.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); }',
574
+ '.dsh-mail-btn-primary { background:linear-gradient(135deg, color-mix(in srgb, var(--dsw-alias-brand-primary) 82%, white), var(--dsw-alias-brand-primary)); border-color:transparent; color:var(--dsw-alias-bg-base); box-shadow:0 3px 10px color-mix(in srgb, var(--dsw-alias-brand-primary) 32%, transparent), inset 0 1px 0 rgba(255,255,255,.2); }',
575
+ '.dsh-mail-btn-primary:hover:not(:disabled) { filter:brightness(1.06); box-shadow:0 5px 14px color-mix(in srgb, var(--dsw-alias-brand-primary) 40%, transparent); }',
323
576
  '.dsh-mail-btn-danger { color:var(--dsw-alias-state-error-primary); border-color:var(--dsw-alias-state-error-primary); background:transparent; }',
324
577
  '.dsh-mail-btn-danger:hover:not(:disabled) { filter:none; background:var(--dsw-alias-state-error-primary); color:#fff; }',
325
578
  '.dsh-mail-iconbtn { width:30px; height:30px; padding:0; border-radius:8px; }',
@@ -328,12 +581,13 @@ window.__ModuleLoader__.load({
328
581
  '.dsh-mail-refresh-err { color:var(--dsw-alias-state-error-primary); }',
329
582
 
330
583
  /* 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; }',
584
+ '.dsh-mail-tabs { display:flex; align-items:center; gap:4px; padding:0 14px; border-bottom:1px solid var(--dsw-alias-border-l1); background:var(--dsw-alias-bg-layer-1); overflow-x:auto; }',
585
+ '.dsh-mail-tab { position:relative; display:inline-flex; align-items:center; gap:7px; padding:12px 14px 13px; border:0; background:transparent; color:var(--dsw-alias-label-secondary); font-size:12px; font-weight:600; cursor:pointer; white-space:nowrap; transition:color .15s, transform .08s; }',
333
586
  '.dsh-mail-tab:hover { color:var(--dsw-alias-label-primary); }',
587
+ '.dsh-mail-tab:active { transform:scale(.96); }',
334
588
  '.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; }',
589
+ '.dsh-mail-tab.is-active::after { content:""; position:absolute; left:12px; right:12px; bottom:0; height:3px; border-radius:3px 3px 0 0; background:linear-gradient(90deg, color-mix(in srgb, var(--dsw-alias-brand-primary) 60%, white), var(--dsw-alias-brand-primary)); box-shadow:0 -1px 6px color-mix(in srgb, var(--dsw-alias-brand-primary) 40%, transparent); }',
590
+ '.dsh-mail-badge { display:grid; place-items:center; min-width:18px; height:18px; padding:0 5px; border-radius:9px; background:linear-gradient(135deg, color-mix(in srgb, var(--dsw-alias-brand-primary) 80%, white), var(--dsw-alias-brand-primary)); color:var(--dsw-alias-bg-base); font-size:10px; font-weight:700; box-shadow:0 2px 6px color-mix(in srgb, var(--dsw-alias-brand-primary) 30%, transparent); }',
337
591
 
338
592
  /* account chip */
339
593
  '.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); }',
@@ -343,38 +597,52 @@ window.__ModuleLoader__.load({
343
597
  '.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
598
  '.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
599
  '.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); }',
600
+ '.dsh-mail-filter.is-active { background:color-mix(in srgb, var(--dsw-alias-brand-primary) 13%, transparent); color:var(--dsw-alias-brand-primary); box-shadow:inset 0 0 0 1px color-mix(in srgb, var(--dsw-alias-brand-primary) 22%, transparent); }',
347
601
  '.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
602
  '.dsh-mail-filter.is-active .dsh-mail-filtercount { background:var(--dsw-alias-brand-primary); color:var(--dsw-alias-bg-base); }',
349
603
 
350
604
  /* 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); }',
605
+ '.dsh-mail-list { flex:1; min-height:0; overflow:auto; padding:8px 10px 20px; }',
606
+ '.dsh-mail-list::-webkit-scrollbar, .dsh-mail-scroll::-webkit-scrollbar { width:8px; height:8px; }',
607
+ '.dsh-mail-list::-webkit-scrollbar-thumb, .dsh-mail-scroll::-webkit-scrollbar-thumb { background:color-mix(in srgb, var(--dsw-alias-label-secondary) 22%, transparent); border-radius:8px; border:2px solid transparent; background-clip:padding-box; }',
608
+ '.dsh-mail-list::-webkit-scrollbar-thumb:hover, .dsh-mail-scroll::-webkit-scrollbar-thumb:hover { background:color-mix(in srgb, var(--dsw-alias-label-secondary) 38%, transparent); background-clip:padding-box; }',
609
+ '.dsh-mail-row { display:flex; align-items:flex-start; gap:12px; padding:13px 12px; margin-bottom:3px; border-radius:12px; border:1px solid transparent; cursor:pointer; transition:background .15s, border-color .15s, transform .1s, box-shadow .15s; }',
610
+ '.dsh-mail-row:hover { background:var(--dsw-alias-bg-layer-2); border-color:var(--dsw-alias-border-l1); box-shadow:0 2px 8px rgba(0,0,0,.05); }',
611
+ '.dsh-mail-row:active { transform:scale(.992); }',
612
+ '.dsh-mail-avatar { width:38px; height:38px; flex:none; border-radius:12px; display:grid; place-items:center; color:#fff; font-size:14px; font-weight:700; box-shadow:inset 0 -6px 10px rgba(0,0,0,.10), 0 2px 6px rgba(0,0,0,.1); }',
356
613
  '.dsh-mail-rowmain { flex:1; min-width:0; }',
357
614
  '.dsh-mail-rowtop { display:flex; align-items:baseline; gap:8px; }',
358
615
  '.dsh-mail-from { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-weight:600; font-size:13px; }',
359
616
  '.dsh-mail-time { flex:none; font-size:11px; color:var(--dsw-alias-label-secondary); }',
360
617
  '.dsh-mail-subject { margin-top:2px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:12.5px; }',
361
618
  '.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); }',
619
+ '.dsh-mail-row.is-unread { background:color-mix(in srgb, var(--dsw-alias-brand-primary) 5%, transparent); }',
620
+ '.dsh-mail-row.is-unread:hover { background:color-mix(in srgb, var(--dsw-alias-brand-primary) 9%, var(--dsw-alias-bg-layer-2)); }',
621
+ '.dsh-mail-row.is-unread .dsh-mail-from, .dsh-mail-row.is-unread .dsh-mail-subject { color:var(--dsw-alias-label-primary); font-weight:650; }',
622
+ '.dsh-mail-unread { width:7px; height:7px; margin-top:8px; flex:none; border-radius:50%; background:var(--dsw-alias-brand-primary); box-shadow:0 0 0 2px var(--dsw-alias-bg-base); }',
365
623
  '.dsh-mail-read .dsh-mail-from, .dsh-mail-read .dsh-mail-subject { color:var(--dsw-alias-label-secondary); font-weight:400; }',
366
624
 
367
625
  /* 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; }',
626
+ '.dsh-mail-card { border:1px solid var(--dsw-alias-border-l1); border-radius:14px; padding:18px; margin-bottom:14px; background:linear-gradient(180deg, var(--dsw-alias-bg-layer-1), var(--dsw-alias-bg-base)); box-shadow:0 2px 10px rgba(0,0,0,.05), inset 0 1px 0 rgba(255,255,255,.04); }',
627
+ '.dsh-mail-cardhead { display:flex; align-items:center; gap:9px; margin-bottom:16px; font-size:14px; font-weight:700; }',
370
628
  '.dsh-mail-grid { display:flex; gap:12px; flex-wrap:wrap; }',
371
629
  '.dsh-mail-field { display:flex; flex-direction:column; gap:5px; flex:1; min-width:160px; margin-bottom:11px; }',
372
630
  '.dsh-mail-label { font-size:11px; font-weight:600; color:var(--dsw-alias-label-secondary); }',
373
631
  '.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); }',
632
+ '.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) 16%, transparent); background:var(--dsw-alias-bg-layer-1); }',
375
633
  '.dsh-mail-textarea { min-height:200px; resize:vertical; line-height:1.6; }',
376
634
  '.dsh-mail-hint { font-size:11.5px; color:var(--dsw-alias-label-secondary); line-height:1.6; }',
377
635
 
636
+ /* attachments */
637
+ '.dsh-mail-attachbar { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:10px; }',
638
+ '.dsh-mail-attachlist { display:flex; flex-direction:column; gap:6px; margin-bottom:12px; }',
639
+ '.dsh-mail-attach { display:flex; align-items:center; gap:8px; border:1px solid var(--dsw-alias-border-l1); border-radius:8px; padding:7px 10px; background:var(--dsw-alias-bg-base); font-size:12px; }',
640
+ '.dsh-mail-attach-name { font-weight:600; color:var(--dsw-alias-label-primary); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; }',
641
+ '.dsh-mail-attach-size { flex:none; font-size:11px; color:var(--dsw-alias-label-secondary); }',
642
+ '.dsh-mail-attach .dsh-mail-iconbtn { width:26px; height:26px; flex:none; }',
643
+ '.dsh-mail-drop { border:1px dashed var(--dsw-alias-border-l2); border-radius:8px; padding:12px; text-align:center; font-size:11.5px; color:var(--dsw-alias-label-secondary); margin-bottom:12px; }',
644
+ '.dsh-mail-drop.is-over { border-color:var(--dsw-alias-brand-primary); color:var(--dsw-alias-brand-primary); background:color-mix(in srgb, var(--dsw-alias-brand-primary) 8%, transparent); }',
645
+
378
646
  /* presets */
379
647
  '.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
648
  '.dsh-mail-pill:hover { color:var(--dsw-alias-label-primary); border-color:var(--dsw-alias-brand-primary); }',
@@ -385,10 +653,11 @@ window.__ModuleLoader__.load({
385
653
  '.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
654
  '.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
655
  '.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); }',
656
+ '.dsh-mail-flash-info { background:color-mix(in srgb, var(--dsw-alias-label-secondary) 12%, transparent); color:var(--dsw-alias-label-secondary); border:1px solid color-mix(in srgb, var(--dsw-alias-label-secondary) 28%, transparent); }',
388
657
 
389
658
  /* empty & loading */
390
659
  '.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; }',
660
+ '.dsh-mail-emptyicon { width:60px; height:60px; border-radius:20px; display:grid; place-items:center; background:color-mix(in srgb, var(--dsw-alias-brand-primary) 10%, var(--dsw-alias-bg-layer-2)); color:var(--dsw-alias-brand-primary); margin-bottom:4px; box-shadow:inset 0 1px 0 rgba(255,255,255,.06), 0 4px 14px rgba(0,0,0,.06); }',
392
661
  '.dsh-mail-emptytitle { font-size:14px; font-weight:650; color:var(--dsw-alias-label-primary); }',
393
662
  '.dsh-mail-emptysub { font-size:12px; color:var(--dsw-alias-label-secondary); max-width:320px; line-height:1.6; }',
394
663
  '.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; }',
@@ -403,11 +672,18 @@ window.__ModuleLoader__.load({
403
672
  '@media (prefers-reduced-motion: reduce) { .dsh-mail-spinner, .dsh-mail-progress::after, .dsh-mail-loading, .dsh-mail-view { animation:none; } }',
404
673
 
405
674
  /* 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; }',
675
+ '.dsh-mail-detailhead { padding:22px 4px 16px; border-bottom:1px solid var(--dsw-alias-border-l1); margin-bottom:18px; }',
676
+ '.dsh-mail-detailtitle { margin:0 0 12px; font-size:21px; font-weight:700; line-height:1.4; letter-spacing:.2px; }',
408
677
  '.dsh-mail-detailfrom { display:flex; align-items:center; gap:10px; }',
678
+ '.dsh-mail-detailfrom > div:nth-child(2) { flex:1; min-width:0; }',
679
+ // A sender already in the address book keeps the button as a quiet state
680
+ // marker instead of an action that would overwrite the saved name.
681
+ '.dsh-mail-btn.is-done { color:var(--dsw-alias-state-success-primary); border-color:var(--dsw-alias-state-success-primary); }',
409
682
  '.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; }',
683
+ '.dsh-mail-detailtoolbar { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-top:12px; }',
684
+ '.dsh-mail-mailbody { width:100%; padding:20px; border:1px solid var(--dsw-alias-border-l1); border-radius:14px; background:linear-gradient(180deg, var(--dsw-alias-bg-layer-1), var(--dsw-alias-bg-base)); color:var(--dsw-alias-label-primary); line-height:1.8; overflow-wrap:anywhere; word-break:break-word; box-shadow:inset 0 1px 0 rgba(255,255,255,.04), 0 2px 8px rgba(0,0,0,.04); }',
685
+ '.dsh-mail-translated { border-color:var(--dsw-alias-brand-primary); background:color-mix(in srgb, var(--dsw-alias-brand-primary) 7%, var(--dsw-alias-bg-layer-1)); }',
686
+ '.dsh-mail-translatednotice { display:flex; align-items:center; gap:6px; margin-bottom:10px; padding-bottom:10px; border-bottom:1px dashed var(--dsw-alias-border-l2); font-size:11px; color:var(--dsw-alias-label-secondary); }',
411
687
 
412
688
  // Third-party HTML: force theme colors so hardcoded mail colors (usually
413
689
  // white bg / dark text) never clash with the dark theme. Buttons and links
@@ -419,6 +695,13 @@ window.__ModuleLoader__.load({
419
695
  '.dsh-mail-html p, .dsh-mail-html div { margin:0 0 8px; }',
420
696
  '.dsh-mail-html table { max-width:100%; border-collapse:collapse; }',
421
697
  '.dsh-mail-html blockquote { margin:8px 0; padding-left:12px; border-left:3px solid var(--dsw-alias-border-l2) !important; }',
698
+ '.dsh-mail-modal-backdrop { position:fixed; inset:0; z-index:60; background:rgba(0,0,0,.5); display:flex; align-items:center; justify-content:center; padding:20px; }',
699
+ '.dsh-mail-modal { width:100%; max-width:480px; max-height:80vh; overflow:auto; background:var(--dsw-alias-bg-layer-1); border:1px solid var(--dsw-alias-border-l2); border-radius:14px; box-shadow:0 16px 48px rgba(0,0,0,.35); }',
700
+ '.dsh-mail-modal-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:16px 18px; border-bottom:1px solid var(--dsw-alias-border-l1); font-weight:700; color:var(--dsw-alias-label-primary); }',
701
+ '.dsh-mail-modal-body { padding:14px 18px 18px; }',
702
+ '.dsh-mail-hint { color:var(--dsw-alias-label-secondary); font-size:12px; line-height:1.6; margin-bottom:10px; }',
703
+ '.dsh-mail-vault-opt { display:flex; flex-direction:column; align-items:flex-start; gap:2px; width:100%; text-align:left; padding:10px 12px; border:1px solid var(--dsw-alias-border-l2); border-radius:9px; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); cursor:pointer; margin-top:8px; }',
704
+ '.dsh-mail-vault-opt:hover { border-color:var(--dsw-alias-brand-primary); filter:brightness(.98); }',
422
705
  ].join('\n');
423
706
 
424
707
  const PRESETS = {
@@ -511,6 +794,20 @@ window.__ModuleLoader__.load({
511
794
  },
512
795
  };
513
796
 
797
+ // When the background poller detects new mail it publishes the affected
798
+ // account ids plus the freshly seen messages, so an open MailPanel can
799
+ // merge them into its list without re-running the same IMAP query.
800
+ // Module scope because detection happens outside React, in the poller.
801
+ const MAIL_EVENTS = {
802
+ listeners: new Set(),
803
+ subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); },
804
+ emit(accountIds, freshByAccount) {
805
+ for (const fn of this.listeners) {
806
+ try { fn(accountIds, freshByAccount); } catch { /* dead listener */ }
807
+ }
808
+ },
809
+ };
810
+
514
811
  // A mail that arrived while DSH was restarting must not be swallowed by
515
812
  // baseline seeding. On first sight we still alert on unseen messages whose
516
813
  // Date header is within this window.
@@ -678,6 +975,8 @@ window.__ModuleLoader__.load({
678
975
  async function pollNewMail() {
679
976
  if (NOTIFY.busy) return Object.assign({}, NOTIFY.diag);
680
977
  NOTIFY.busy = true;
978
+ const changedAccounts = [];
979
+ const freshByAccount = Object.create(null);
681
980
  try {
682
981
  const mode = NOTIFY.settings.notifyMode || 'pet';
683
982
  if (mode === 'system' && notifyPermission() !== 'granted') {
@@ -699,7 +998,9 @@ window.__ModuleLoader__.load({
699
998
  NOTIFY.diag.lastCheck = Date.now();
700
999
  NOTIFY.diag.error = null;
701
1000
  const now = Date.now();
702
- for (const acc of accounts) {
1001
+ // Check every account concurrently; previously a slow IMAP session on
1002
+ // one account delayed every other account's check behind it.
1003
+ await Promise.all(accounts.map(async acc => {
703
1004
  try {
704
1005
  const mr = await fetch(API, {
705
1006
  method: 'POST', headers: { 'content-type': 'application/json' },
@@ -708,35 +1009,24 @@ window.__ModuleLoader__.load({
708
1009
  const md = await mr.json();
709
1010
  if (!md || md.ok === false || !Array.isArray(md.messages)) {
710
1011
  NOTIFY.diag.error = 'listMessages:' + (acc.name || acc.id) + ':' + (md && md.error ? md.error : 'bad-response');
711
- continue;
1012
+ return;
712
1013
  }
713
1014
  const uids = md.messages.map(m => String(m.uid));
714
1015
  const prev = NOTIFY.baselines[acc.id];
715
1016
  NOTIFY.baselines[acc.id] = uids;
1017
+ let fresh = [];
716
1018
  if (!prev) {
717
1019
  // First observation: normally seed only, but a mail that arrived
718
1020
  // during a restart (unread + recent Date header) must still alert.
719
- const recent = md.messages.filter(m =>
1021
+ fresh = md.messages.filter(m =>
720
1022
  m && m.seen === false && m.date &&
721
1023
  (now - Date.parse(m.date)) >= 0 &&
722
1024
  (now - Date.parse(m.date)) <= RECENT_MAIL_MS
723
1025
  );
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;
1026
+ } else {
1027
+ const prevSet = new Set(prev);
1028
+ fresh = md.messages.filter(m => !prevSet.has(String(m.uid)));
737
1029
  }
738
- const prevSet = new Set(prev);
739
- const fresh = md.messages.filter(m => !prevSet.has(String(m.uid)));
740
1030
  if (fresh.length > 0) {
741
1031
  const latest = fresh[0] || {};
742
1032
  const who = acc.name ? acc.name + ':' : '';
@@ -748,17 +1038,22 @@ window.__ModuleLoader__.load({
748
1038
  NOTIFY.diag.alerts += 1;
749
1039
  NOTIFY.diag.lastAlert = Date.now();
750
1040
  BADGE.add(fresh.length);
1041
+ changedAccounts.push(acc.id);
1042
+ // Hand the list we already fetched to the open panel so it can
1043
+ // update in place instead of issuing a second listMessages.
1044
+ freshByAccount[acc.id] = md.messages;
751
1045
  if (!res.petOk && !res.sysOk) NOTIFY.diag.error = 'deliver:' + (NOTIFY.lastError || 'no-channel');
752
1046
  }
753
1047
  } catch (e) {
754
1048
  NOTIFY.diag.error = 'account:' + (acc.name || acc.id) + ':' + (e && e.message ? e.message : String(e));
755
1049
  }
756
- }
1050
+ }));
757
1051
  } catch (e) {
758
1052
  NOTIFY.diag.error = 'poll:' + (e && e.message ? e.message : String(e));
759
1053
  } finally {
760
1054
  NOTIFY.busy = false;
761
1055
  }
1056
+ if (changedAccounts.length) MAIL_EVENTS.emit(changedAccounts, freshByAccount);
762
1057
  return Object.assign({}, NOTIFY.diag);
763
1058
  }
764
1059
 
@@ -851,6 +1146,9 @@ window.__ModuleLoader__.load({
851
1146
  check: 'M4 12l5 5L20 6',
852
1147
  warning: 'M12 3L2 20h20L12 3zm0 6v5m0 3v.5',
853
1148
  plus: 'M12 5v14M5 12h14',
1149
+ attach: 'M20 11.5l-8.2 8.2a4.5 4.5 0 0 1-6.4-6.4l8.5-8.5a3 3 0 0 1 4.3 4.3l-8.5 8.5a1.5 1.5 0 0 1-2.2-2.2l7.8-7.8',
1150
+ download: 'M12 4v11m0 0l-4-4m4 4l4-4M4 19h16',
1151
+ translate: 'M12.9 15L8 20l-4-5h3.1a7 7 0 0 0 1.4-4H4v-2h5.1A11 11 0 0 0 11 3h2c-.6 1.7-1.5 3.2-2.7 4.5A9 9 0 0 1 17 11h2.9l-4.3 4.3m-2-2.3c-.6-2.2-2-4-3.9-5.3A9 9 0 0 1 18 9',
854
1152
  };
855
1153
  function Ico(props) {
856
1154
  // Rendered as a React component via h(Ico, { name, size }); the first
@@ -874,6 +1172,27 @@ window.__ModuleLoader__.load({
874
1172
  const v = String(s || '').trim();
875
1173
  return v ? v.charAt(0).toUpperCase() : '?';
876
1174
  }
1175
+ // The local label shown for an account defaults to the part before "@", so
1176
+ // a fresh mailbox reads as "1101522940" instead of a generic "QQ邮箱" or a
1177
+ // guessed display name the user never chose.
1178
+ function defaultAccountName(username) {
1179
+ const v = String(username || '').trim();
1180
+ if (!v) return '';
1181
+ const at = v.indexOf('@');
1182
+ return at > 0 ? v.slice(0, at) : v;
1183
+ }
1184
+ // Split a raw address header ("李文" <li@x.com>, "b@y.com") into the parts a
1185
+ // contact needs. Accepts the first address only, which is what a sender or a
1186
+ // single recipient field carries in practice.
1187
+ function parseAddress(raw) {
1188
+ const s = String(raw || '').trim();
1189
+ if (!s) return null;
1190
+ const angled = s.match(/^(.*?)<([^<>]+)>/);
1191
+ const name = angled ? String(angled[1] || '').trim().replace(/^["']|["']$/g, '').trim() : '';
1192
+ const email = String(angled ? angled[2] : s).trim().replace(/^["']|["']$/g, '');
1193
+ if (!email || email.indexOf('@') < 1) return null;
1194
+ return { name, email: email.toLowerCase() };
1195
+ }
877
1196
  function fmtDate(iso) {
878
1197
  if (!iso) return '';
879
1198
  const d = new Date(iso);
@@ -885,6 +1204,47 @@ window.__ModuleLoader__.load({
885
1204
  return d.getFullYear() + '.' + (d.getMonth() + 1) + '.' + d.getDate();
886
1205
  }
887
1206
 
1207
+ function fmtSize(bytes) {
1208
+ const n = Number(bytes) || 0;
1209
+ if (n < 1024) return n + ' B';
1210
+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
1211
+ return (n / (1024 * 1024)).toFixed(1) + ' MB';
1212
+ }
1213
+
1214
+ // The Host half buffers the whole bridge reply, so keep one attachment under
1215
+ // this cap; the send path enforces a 25 MB total for the same reason.
1216
+ const MAX_ATTACH_BYTES = 25 * 1024 * 1024;
1217
+
1218
+ function readFileAsBase64(file) {
1219
+ return new Promise((resolve, reject) => {
1220
+ const reader = new FileReader();
1221
+ reader.onload = () => {
1222
+ const result = String(reader.result || '');
1223
+ const comma = result.indexOf(',');
1224
+ resolve(comma === -1 ? result : result.slice(comma + 1));
1225
+ };
1226
+ reader.onerror = () => reject(reader.error || new Error('read failed'));
1227
+ reader.readAsDataURL(file);
1228
+ });
1229
+ }
1230
+
1231
+ function saveAttachmentBytes(name, mime, base64) {
1232
+ // Decode base64 to bytes, then hand the browser a Blob download. This keeps
1233
+ // the file binary-exact and never goes through the network again.
1234
+ const bin = atob(base64 || '');
1235
+ const bytes = new Uint8Array(bin.length);
1236
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
1237
+ const blob = new Blob([bytes], { type: mime || 'application/octet-stream' });
1238
+ const url = URL.createObjectURL(blob);
1239
+ const a = document.createElement('a');
1240
+ a.href = url;
1241
+ a.download = name || 'attachment';
1242
+ document.body.appendChild(a);
1243
+ a.click();
1244
+ document.body.removeChild(a);
1245
+ setTimeout(() => URL.revokeObjectURL(url), 10000);
1246
+ }
1247
+
888
1248
  function Loading(props) {
889
1249
  // Rendered as a React component via h(Loading), so the first argument is
890
1250
  // a props object ({} when none is passed) — never treat it as a string.
@@ -910,15 +1270,54 @@ window.__ModuleLoader__.load({
910
1270
  const [inboxFilter, setInboxFilter] = usePersistent('inboxFilter', 'all');
911
1271
  const [messages, setMessages] = usePersistent('messages', []);
912
1272
  const [detail, setDetail] = usePersistent('detail', null);
1273
+ // Translated body for the currently open message. Kept out of PERSIST:
1274
+ // translations are disposable and never written to profile storage.
1275
+ const [translatedText, setTranslatedText] = useState(null);
1276
+ const [translating, setTranslating] = useState(false);
913
1277
  const [busy, setBusy] = useState(false);
914
1278
  const [loadingMessages, setLoadingMessages] = useState(false);
915
1279
  const [loadingSent, setLoadingSent] = useState(false);
916
1280
  const [loadingContacts, setLoadingContacts] = useState(false);
917
1281
  const [refreshState, setRefreshState] = useState('idle'); // idle | loading | ok | error
918
1282
  const refreshTimerRef = useRef(null);
1283
+ // In-flight dedupe must survive re-renders; a plain let would reset every
1284
+ // time React re-rendered the panel and allow duplicate IMAP sessions.
1285
+ const inflightRef = useRef({ messages: null, sent: null, contacts: null });
919
1286
  const [flash, setFlash] = useState(null);
920
1287
  const [form, setForm] = usePersistent('form', { preset: 'qq', name: '', username: '', authCode: '', imapHost: PRESETS.qq.imapHost, imapPort: 993, smtpHost: PRESETS.qq.smtpHost, smtpPort: 465 });
1288
+ // Credential-vault bridge (no-op if the vault plugin is not installed).
1289
+ const vaultClientRef = useRef(null);
1290
+ if (!vaultClientRef.current) vaultClientRef.current = createVaultV1Client();
1291
+ const [vaultOpen, setVaultOpen] = useState(false);
1292
+ const [vaultEntries, setVaultEntries] = useState(null);
1293
+ const [vaultBusy, setVaultBusy] = useState(false);
1294
+ async function openVaultPicker() {
1295
+ setVaultOpen(true);
1296
+ setVaultEntries(null);
1297
+ setVaultBusy(true);
1298
+ try {
1299
+ const list = await vaultClientRef.current.query({ category: 'account', limit: 100 });
1300
+ setVaultEntries(list);
1301
+ } catch (e) {
1302
+ setVaultEntries([]);
1303
+ } finally {
1304
+ setVaultBusy(false);
1305
+ }
1306
+ }
1307
+ function pickVaultSecret(entry) {
1308
+ const value = vaultClientRef.current.secretOf(entry);
1309
+ setForm(function (f) { return Object.assign({}, f, { authCode: value }); });
1310
+ setVaultOpen(false);
1311
+ notify('success', t('saved'));
1312
+ }
921
1313
  const [compose, setCompose] = usePersistent('compose', { to: '', subject: '', body: '' });
1314
+ // Outgoing attachments live in React state (not PERSIST): they hold base64
1315
+ // file bytes, which must not be written to profile storage.
1316
+ const [composeAtts, setComposeAtts] = useState([]);
1317
+ const [attachBusy, setAttachBusy] = useState(false);
1318
+ // Received attachments are fetched on demand from the mail server.
1319
+ const [attachState, setAttachState] = useState({});
1320
+ const [dropOver, setDropOver] = useState(false);
922
1321
  const [sent, setSent] = usePersistent('sent', []);
923
1322
  const [contacts, setContacts] = usePersistent('contacts', []);
924
1323
  const [contactForm, setContactForm] = usePersistent('contactForm', { name: '', email: '' });
@@ -926,10 +1325,42 @@ window.__ModuleLoader__.load({
926
1325
  // Per-account cache of fetched message lists. Survives account switching
927
1326
  // and remounts so we can show cached mail immediately while refreshing.
928
1327
  const [cache, setCache] = usePersistent('mailCache', {});
1328
+ // Inline rename: the account id being edited plus the draft label.
1329
+ const [renameId, setRenameId] = useState('');
1330
+ const [renameDraft, setRenameDraft] = useState('');
1331
+
1332
+ // Keep a fresh handler so the mail-event subscription never sees stale
1333
+ // activeId/view. New mail on the currently open account refreshes the
1334
+ // inbox list in place (silent, no spinner/flash).
1335
+ const onMailRef = useRef(() => {});
1336
+ onMailRef.current = (accountIds, freshByAccount) => {
1337
+ if (!activeId || view !== 'inbox') return;
1338
+ if (Array.isArray(accountIds) && accountIds.length && accountIds.indexOf(activeId) === -1) return;
1339
+ // The poller already fetched this account's list to detect the new
1340
+ // mail. Merge any new UIDs straight into state/cache instead of
1341
+ // opening a second IMAP session for the same data.
1342
+ const polled = freshByAccount && freshByAccount[activeId];
1343
+ const current = cache[activeId] || messages || [];
1344
+ if (Array.isArray(polled) && current.length) {
1345
+ const seen = new Set(current.map(m => String(m.uid)));
1346
+ const added = polled.filter(m => !seen.has(String(m.uid)));
1347
+ if (added.length) {
1348
+ const merged = added.concat(current);
1349
+ setMessages(merged);
1350
+ setCache(prev => Object.assign({}, prev, { [activeId]: merged }));
1351
+ }
1352
+ return;
1353
+ }
1354
+ void loadMessages(false);
1355
+ };
929
1356
 
930
1357
  useEffect(() => {
931
1358
  if (!PERSIST.accounts) refreshAccounts();
932
- return () => { if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current); };
1359
+ const off = MAIL_EVENTS.subscribe((ids, freshByAccount) => onMailRef.current(ids, freshByAccount));
1360
+ return () => {
1361
+ off();
1362
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
1363
+ };
933
1364
  }, []);
934
1365
 
935
1366
  function notify(kind, text) {
@@ -955,6 +1386,47 @@ window.__ModuleLoader__.load({
955
1386
  return data;
956
1387
  }
957
1388
 
1389
+ // Account labels are set by the user, not guessed from mail headers: a
1390
+ // mailbox's own display name is only visible after signing in to the
1391
+ // provider, so any guess is unreliable. The default label is the mailbox
1392
+ // prefix and this just persists whatever the user prefers.
1393
+ async function renameAccount(id, name) {
1394
+ const next = String(name == null ? '' : name).trim();
1395
+ if (!next) return false;
1396
+ try {
1397
+ const data = await rpc('renameAccount', { id, name: next });
1398
+ if (data && data.account) {
1399
+ setAccounts(prev => (prev || []).map(a => a.id === data.account.id ? Object.assign({}, a, { name: data.account.name }) : a));
1400
+ }
1401
+ return true;
1402
+ } catch (e) {
1403
+ reportError(e);
1404
+ return false;
1405
+ }
1406
+ }
1407
+
1408
+ function startRename(account) {
1409
+ setRenameId(account.id);
1410
+ setRenameDraft(account.name || defaultAccountName(account.username));
1411
+ }
1412
+
1413
+ function cancelRename() {
1414
+ setRenameId('');
1415
+ setRenameDraft('');
1416
+ }
1417
+
1418
+ async function commitRename(id) {
1419
+ const name = String(renameDraft || '').trim();
1420
+ if (!name) { cancelRename(); return; }
1421
+ setBusy(true);
1422
+ try {
1423
+ const ok = await renameAccount(id, name);
1424
+ if (ok) { notify('success', t('saved')); cancelRename(); }
1425
+ } finally {
1426
+ setBusy(false);
1427
+ }
1428
+ }
1429
+
958
1430
  async function refreshAccounts() {
959
1431
  try {
960
1432
  const data = await rpc('listAccounts');
@@ -967,55 +1439,90 @@ window.__ModuleLoader__.load({
967
1439
 
968
1440
  async function loadMessages(showProgress) {
969
1441
  if (!activeId) return false;
1442
+ // Collapse overlapping refreshes (account switch vs. new-mail event)
1443
+ // into one request per account instead of opening duplicate sessions.
1444
+ const inflight = inflightRef.current;
1445
+ if (inflight.messages && inflight.messages.id === activeId) return inflight.messages.promise;
970
1446
  // Cache-first: if we already have this account's list, keep it visible
971
1447
  // while the fresh list loads in the background (no blank/Loading flash).
972
1448
  const cached = cache[activeId];
973
1449
  if (showProgress !== false) setLoadingMessages(!(cached && cached.length));
1450
+ const id = activeId;
1451
+ const promise = (async () => {
1452
+ try {
1453
+ const data = await rpc('listMessages', { id, limit: 25 });
1454
+ const fresh = data.messages || [];
1455
+ setMessages(fresh);
1456
+ setCache(prev => Object.assign({}, prev, { [id]: fresh }));
1457
+ return true;
1458
+ } catch (e) {
1459
+ reportError(e);
1460
+ return false;
1461
+ } finally {
1462
+ setLoadingMessages(false);
1463
+ }
1464
+ })();
1465
+ inflight.messages = { id, promise };
974
1466
  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;
1467
+ return await promise;
983
1468
  } finally {
984
- setLoadingMessages(false);
1469
+ if (inflight.messages && inflight.messages.id === id) inflight.messages = null;
985
1470
  }
986
1471
  }
987
1472
 
988
1473
  async function loadSent() {
989
1474
  if (!activeId) return false;
1475
+ const inflight = inflightRef.current;
1476
+ if (inflight.sent && inflight.sent.id === activeId) return inflight.sent.promise;
990
1477
  setBusy(true);
991
1478
  setLoadingSent(true);
1479
+ const id = activeId;
1480
+ const promise = (async () => {
1481
+ try {
1482
+ const data = await rpc('sentMessages', { id });
1483
+ setSent(data.sent || []);
1484
+ return true;
1485
+ } catch (e) {
1486
+ reportError(e);
1487
+ return false;
1488
+ } finally {
1489
+ setLoadingSent(false);
1490
+ setBusy(false);
1491
+ }
1492
+ })();
1493
+ inflight.sent = { id, promise };
992
1494
  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;
1495
+ return await promise;
999
1496
  } finally {
1000
- setLoadingSent(false);
1001
- setBusy(false);
1497
+ if (inflight.sent && inflight.sent.id === id) inflight.sent = null;
1002
1498
  }
1003
1499
  }
1004
1500
 
1005
1501
  async function loadContacts() {
1006
1502
  if (!activeId) return false;
1503
+ const inflight = inflightRef.current;
1504
+ if (inflight.contacts && inflight.contacts.id === activeId) return inflight.contacts.promise;
1007
1505
  setBusy(true);
1008
1506
  setLoadingContacts(true);
1507
+ const id = activeId;
1508
+ const promise = (async () => {
1509
+ try {
1510
+ const data = await rpc('listContacts', { id });
1511
+ setContacts(data.contacts || []);
1512
+ return true;
1513
+ } catch (e) {
1514
+ reportError(e);
1515
+ return false;
1516
+ } finally {
1517
+ setLoadingContacts(false);
1518
+ setBusy(false);
1519
+ }
1520
+ })();
1521
+ inflight.contacts = { id, promise };
1009
1522
  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;
1523
+ return await promise;
1016
1524
  } finally {
1017
- setLoadingContacts(false);
1018
- setBusy(false);
1525
+ if (inflight.contacts && inflight.contacts.id === id) inflight.contacts = null;
1019
1526
  }
1020
1527
  }
1021
1528
 
@@ -1039,10 +1546,8 @@ window.__ModuleLoader__.load({
1039
1546
  setSent([]);
1040
1547
  setContacts([]);
1041
1548
  setDetail(null);
1042
- PERSIST.loadedIds = { inbox: activeId, sent: activeId, contacts: activeId };
1549
+ PERSIST.loadedIds = { inbox: activeId, sent: '', contacts: '' };
1043
1550
  loadMessages();
1044
- loadSent();
1045
- loadContacts();
1046
1551
  }
1047
1552
  }, [activeId]);
1048
1553
 
@@ -1050,7 +1555,6 @@ window.__ModuleLoader__.load({
1050
1555
  const p = PRESETS[preset] || PRESETS.custom;
1051
1556
  setForm(Object.assign({}, form, {
1052
1557
  preset,
1053
- name: preset === 'custom' ? '' : t(p.nameKey),
1054
1558
  imapHost: p.imapHost,
1055
1559
  imapPort: p.imapPort,
1056
1560
  smtpHost: p.smtpHost,
@@ -1062,7 +1566,7 @@ window.__ModuleLoader__.load({
1062
1566
  setBusy(true);
1063
1567
  try {
1064
1568
  await rpc('saveAccount', {
1065
- name: form.name || form.username,
1569
+ name: String(form.name || '').trim() || defaultAccountName(form.username),
1066
1570
  username: form.username,
1067
1571
  authCode: form.authCode,
1068
1572
  imapHost: form.imapHost,
@@ -1120,6 +1624,7 @@ window.__ModuleLoader__.load({
1120
1624
  const data = await rpc('getMessage', { id: activeId, uid });
1121
1625
  const full = data.message || data;
1122
1626
  setDetail(Object.assign({}, full, { seen: true }));
1627
+ setTranslatedText(null);
1123
1628
  setView('detail');
1124
1629
  } catch (e) {
1125
1630
  reportError(e);
@@ -1128,12 +1633,49 @@ window.__ModuleLoader__.load({
1128
1633
  }
1129
1634
  }
1130
1635
 
1636
+ // Translate the currently open message through the Host's `translate`
1637
+ // op. Prefer the plain-text part; fall back to stripping tags from the
1638
+ // sanitized HTML when the mail is HTML-only.
1639
+ async function translateMessage() {
1640
+ if (!detail || translating) return;
1641
+ const source = typeof detail.body === 'string' && detail.body.trim()
1642
+ ? detail.body
1643
+ : htmlToText(detail.html);
1644
+ if (!source.trim()) {
1645
+ notify('error', t('translateFailed') + t('errGeneric'));
1646
+ return;
1647
+ }
1648
+ setTranslating(true);
1649
+ try {
1650
+ const data = await rpc('translate', { text: source, targetLanguage: 'zh-CN' });
1651
+ setTranslatedText(String(data.text || ''));
1652
+ } catch (e) {
1653
+ const code = e && e.info && e.info.code;
1654
+ if (code === 'TRANSLATION_UNAVAILABLE') {
1655
+ notify('error', t('translateUnavailable'));
1656
+ } else if (code === 'TRANSLATION_TEXT_LIMIT') {
1657
+ notify('error', t('translateTextLimit'));
1658
+ } else {
1659
+ notify('error', t('translateFailed') + (e && e.message ? e.message : t('errGeneric')));
1660
+ }
1661
+ } finally {
1662
+ setTranslating(false);
1663
+ }
1664
+ }
1665
+
1131
1666
  async function sendMail() {
1132
1667
  setBusy(true);
1133
1668
  try {
1134
- await rpc('sendMessage', { id: activeId, to: compose.to, subject: compose.subject, body: compose.body });
1669
+ await rpc('sendMessage', {
1670
+ id: activeId,
1671
+ to: compose.to,
1672
+ subject: compose.subject,
1673
+ body: compose.body,
1674
+ attachments: composeAtts.map(a => ({ name: a.name, mime: a.mime, content: a.content })),
1675
+ });
1135
1676
  notify('success', t('ok'));
1136
1677
  setCompose({ to: '', subject: '', body: '' });
1678
+ setComposeAtts([]);
1137
1679
  await loadSent();
1138
1680
  setView('sent');
1139
1681
  } catch (e) {
@@ -1143,6 +1685,87 @@ window.__ModuleLoader__.load({
1143
1685
  }
1144
1686
  }
1145
1687
 
1688
+ async function addAttachments(fileList) {
1689
+ const files = Array.from(fileList || []);
1690
+ if (!files.length) return;
1691
+ setAttachBusy(true);
1692
+ try {
1693
+ const next = composeAtts.slice();
1694
+ for (const file of files) {
1695
+ if (next.some(a => a.name === file.name && a.size === file.size)) continue; // 去重同一个文件
1696
+ if (file.size > MAX_ATTACH_BYTES) {
1697
+ notify('error', t('attachmentTooLarge'));
1698
+ continue;
1699
+ }
1700
+ const content = await readFileAsBase64(file);
1701
+ next.push({ name: file.name, size: file.size, mime: file.type || '', content });
1702
+ }
1703
+ const total = next.reduce((sum, a) => sum + (Number(a.size) || 0), 0);
1704
+ if (total > MAX_ATTACH_BYTES) {
1705
+ // 超限时整体拒绝,避免用户以为附件已带上却发送失败。
1706
+ notify('error', t('attachmentTooLarge'));
1707
+ } else {
1708
+ setComposeAtts(next);
1709
+ }
1710
+ } catch (e) {
1711
+ notify('error', t('attachmentFailed') + (e && e.message ? e.message : ''));
1712
+ } finally {
1713
+ setAttachBusy(false);
1714
+ }
1715
+ }
1716
+
1717
+ function removeAttachment(index) {
1718
+ setComposeAtts(prev => prev.filter((_, i) => i !== index));
1719
+ }
1720
+
1721
+ async function downloadAttachment(att) {
1722
+ if (!detail || !activeId) return;
1723
+ const key = String(att.index);
1724
+ setAttachState(prev => Object.assign({}, prev, { [key]: 'loading' }));
1725
+ try {
1726
+ const data = await rpc('getAttachment', { id: activeId, uid: detail.uid, index: att.index });
1727
+ saveAttachmentBytes(data.name || att.name, data.mime || att.mime, data.content);
1728
+ setAttachState(prev => Object.assign({}, prev, { [key]: 'ok' }));
1729
+ } catch (e) {
1730
+ setAttachState(prev => Object.assign({}, prev, { [key]: 'error' }));
1731
+ reportError(e);
1732
+ }
1733
+ }
1734
+
1735
+ // Turn a raw address header ("李文" <li@x.com>) into a contact without
1736
+ // leaving the mail. An entry that already exists is reported instead of
1737
+ // being duplicated, since saveContact would otherwise just overwrite it.
1738
+ function contactKnown(email) {
1739
+ const key = String(email || '').toLowerCase();
1740
+ if (!key) return false;
1741
+ return (contacts || []).some(c => String(c.email || '').toLowerCase() === key);
1742
+ }
1743
+
1744
+ async function addAsContact(raw) {
1745
+ const parsed = parseAddress(raw);
1746
+ if (!parsed) {
1747
+ notify('error', t('emailRequired'));
1748
+ return false;
1749
+ }
1750
+ if (!activeId) return false;
1751
+ if (contactKnown(parsed.email)) {
1752
+ notify('info', t('contactExists'));
1753
+ return false;
1754
+ }
1755
+ setBusy(true);
1756
+ try {
1757
+ const data = await rpc('saveContact', { id: activeId, email: parsed.email, name: parsed.name });
1758
+ if (Array.isArray(data.contacts)) setContacts(data.contacts);
1759
+ notify('success', t('contactAdded'));
1760
+ return true;
1761
+ } catch (e) {
1762
+ reportError(e);
1763
+ return false;
1764
+ } finally {
1765
+ setBusy(false);
1766
+ }
1767
+ }
1768
+
1146
1769
  async function saveContact() {
1147
1770
  const email = String(contactForm.email || '').trim();
1148
1771
  if (!email || !email.includes('@')) {
@@ -1227,6 +1850,17 @@ window.__ModuleLoader__.load({
1227
1850
  function navTo(key) {
1228
1851
  setSentDetail(null);
1229
1852
  setView(key);
1853
+ // Sent/contacts are loaded on demand (first visit after an account
1854
+ // switch), so opening the mail panel no longer waits on three IMAP
1855
+ // sessions at once. Guard with PERSIST.loadedIds to avoid refetching
1856
+ // on every tab click or remount.
1857
+ if (key === 'sent' && activeId && PERSIST.loadedIds.sent !== activeId) {
1858
+ PERSIST.loadedIds.sent = activeId;
1859
+ loadSent();
1860
+ } else if (key === 'contacts' && activeId && PERSIST.loadedIds.contacts !== activeId) {
1861
+ PERSIST.loadedIds.contacts = activeId;
1862
+ loadContacts();
1863
+ }
1230
1864
  }
1231
1865
 
1232
1866
  return h('div', { className: 'dsh-mail' },
@@ -1260,8 +1894,8 @@ window.__ModuleLoader__.load({
1260
1894
  ))
1261
1895
  ),
1262
1896
 
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 }),
1897
+ flash && h('div', { className: 'dsh-mail-flash ' + (flash.kind === 'error' ? 'dsh-mail-flash-error' : (flash.kind === 'info' ? 'dsh-mail-flash-info' : 'dsh-mail-flash-success')) },
1898
+ h(Ico, { name: flash.kind === 'error' ? 'warning' : (flash.kind === 'info' ? 'inbox' : 'check'), size: 15 }),
1265
1899
  h('span', null, flash.text)
1266
1900
  ),
1267
1901
 
@@ -1329,10 +1963,35 @@ window.__ModuleLoader__.load({
1329
1963
  ? h('div', { className: 'dsh-mail-scroll' },
1330
1964
  h('button', { className: 'dsh-mail-btn', onClick: () => setSentDetail(null) }, h(Ico, { name: 'back', size: 15 }), t('back')),
1331
1965
  h('div', { className: 'dsh-mail-detailhead' },
1332
- h('h2', { className: 'dsh-mail-detailtitle' }, sentDetail.subject || t('noSubject')),
1966
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
1967
+ h('h2', { className: 'dsh-mail-detailtitle' }, sentDetail.subject || t('noSubject')),
1968
+ parseAddress(sentDetail.to)
1969
+ ? h('button', {
1970
+ className: 'dsh-mail-btn' + (contactKnown(parseAddress(sentDetail.to).email) ? ' is-done' : ''),
1971
+ 'data-testid': 'add-recipient',
1972
+ onClick: () => addAsContact(sentDetail.to),
1973
+ disabled: busy,
1974
+ title: t('addRecipient'),
1975
+ }, h(Ico, { name: contactKnown(parseAddress(sentDetail.to).email) ? 'check' : 'plus', size: 14 }), t('addRecipient'))
1976
+ : null
1977
+ ),
1333
1978
  h('div', { className: 'dsh-mail-detailmeta' }, t('to') + ': ' + (sentDetail.to || '') + ' · ' + fmtDate(sentDetail.date))
1334
1979
  ),
1335
- h('div', { className: 'dsh-mail-mailbody', style: { whiteSpace: 'pre-wrap' } }, String(sentDetail.body || ''))
1980
+ h('div', { className: 'dsh-mail-mailbody', style: { whiteSpace: 'pre-wrap' } }, String(sentDetail.body || '')),
1981
+ // Sent mail keeps attachment metadata only (names/sizes), which is
1982
+ // enough to confirm what went out with the message.
1983
+ Array.isArray(sentDetail.attachments) && sentDetail.attachments.length > 0
1984
+ ? h('div', { className: 'dsh-mail-field', style: { marginTop: 14 } },
1985
+ h('span', { className: 'dsh-mail-label' }, t('attachments') + ' (' + sentDetail.attachments.length + ')'),
1986
+ h('div', { className: 'dsh-mail-attachlist' }, sentDetail.attachments.map((att, i) =>
1987
+ h('div', { key: String(att.name) + i, className: 'dsh-mail-attach' },
1988
+ h(Ico, { name: 'attach', size: 14 }),
1989
+ h('span', { className: 'dsh-mail-attach-name', title: att.name }, att.name),
1990
+ att.size ? h('span', { className: 'dsh-mail-attach-size' }, fmtSize(att.size)) : null
1991
+ )
1992
+ ))
1993
+ )
1994
+ : null
1336
1995
  )
1337
1996
  : h('div', { className: 'dsh-mail-view' },
1338
1997
  loadingSent && sent.length === 0
@@ -1400,16 +2059,35 @@ window.__ModuleLoader__.load({
1400
2059
  h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 } },
1401
2060
  h('div', { className: 'dsh-mail-avatar', style: { background: avatarColor(a.username) } }, avatarLetter(a.name || a.username)),
1402
2061
  h('div', { style: { flex: 1, minWidth: 0 } },
1403
- h('div', { style: { fontWeight: 650 } }, a.name),
2062
+ renameId === a.id
2063
+ ? h('input', {
2064
+ className: 'dsh-mail-input',
2065
+ 'data-testid': 'rename-input',
2066
+ value: renameDraft,
2067
+ autoFocus: true,
2068
+ placeholder: defaultAccountName(a.username),
2069
+ onChange: e => setRenameDraft(e.target.value),
2070
+ onKeyDown: e => { if (e.key === 'Enter') commitRename(a.id); if (e.key === 'Escape') cancelRename(); },
2071
+ })
2072
+ : h('div', { style: { fontWeight: 650 } }, a.name || a.username),
1404
2073
  h('div', { className: 'dsh-mail-hint' }, a.username)
1405
2074
  )
1406
2075
  ),
1407
2076
  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
- )
2077
+ renameId === a.id
2078
+ ? h('div', null,
2079
+ h('div', { className: 'dsh-mail-hint', style: { marginBottom: 8 } }, t('renameHint')),
2080
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
2081
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-primary', onClick: () => commitRename(a.id), disabled: busy }, h(Ico, { name: 'check', size: 14 }), t('save')),
2082
+ h('button', { className: 'dsh-mail-btn', onClick: cancelRename, disabled: busy }, t('cancel'))
2083
+ )
2084
+ )
2085
+ : h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
2086
+ h('button', { className: 'dsh-mail-btn', onClick: () => testAccount(a.id), disabled: busy }, h(Ico, { name: 'check', size: 14 }), t('test')),
2087
+ h('button', { className: 'dsh-mail-btn', onClick: () => startRename(a), disabled: busy }, h(Ico, { name: 'compose', size: 14 }), t('rename')),
2088
+ h('button', { className: 'dsh-mail-btn', onClick: () => { setActiveId(a.id); navTo('inbox'); } }, h(Ico, { name: 'inbox', size: 14 }), t('inbox')),
2089
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-danger', onClick: () => deleteAccount(a.id), disabled: busy }, h(Ico, { name: 'trash', size: 14 }), t('delete'))
2090
+ )
1413
2091
  )),
1414
2092
  h('div', { className: 'dsh-mail-card' },
1415
2093
  h('div', { className: 'dsh-mail-cardhead' }, h(Ico, { name: 'plus', size: 16 }), t('addAccount')),
@@ -1424,7 +2102,7 @@ window.__ModuleLoader__.load({
1424
2102
  h('div', { className: 'dsh-mail-grid' },
1425
2103
  h('div', { className: 'dsh-mail-field' },
1426
2104
  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 })) })
2105
+ h('input', { className: 'dsh-mail-input', value: form.name, placeholder: defaultAccountName(form.username) || 'me', onChange: e => setForm(Object.assign({}, form, { name: e.target.value })) })
1428
2106
  ),
1429
2107
  h('div', { className: 'dsh-mail-field' },
1430
2108
  h('span', { className: 'dsh-mail-label' }, t('username')),
@@ -1433,7 +2111,10 @@ window.__ModuleLoader__.load({
1433
2111
  ),
1434
2112
  h('div', { className: 'dsh-mail-field' },
1435
2113
  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 })) })
2114
+ h('input', { className: 'dsh-mail-input', type: 'password', value: form.authCode, onChange: e => setForm(Object.assign({}, form, { authCode: e.target.value })) }),
2115
+ vaultClientRef.current.isAvailable()
2116
+ ? h('button', { className: 'dsh-mail-btn', type: 'button', style: { marginTop: 8 }, onClick: openVaultPicker }, h(Ico, { name: 'accounts', size: 15 }), t('fillFromVault'))
2117
+ : null
1437
2118
  ),
1438
2119
  h('div', { className: 'dsh-mail-grid' },
1439
2120
  h('div', { className: 'dsh-mail-field' },
@@ -1460,6 +2141,30 @@ window.__ModuleLoader__.load({
1460
2141
  )
1461
2142
  ),
1462
2143
 
2144
+ /* --------------------------- VAULT PICKER ---------------------------- */
2145
+ vaultOpen && h('div', { className: 'dsh-mail-modal-backdrop', onClick: () => setVaultOpen(false) },
2146
+ h('div', { className: 'dsh-mail-modal', onClick: e => e.stopPropagation() },
2147
+ h('div', { className: 'dsh-mail-modal-head' },
2148
+ h('span', null, t('vaultPickTitle')),
2149
+ h('button', { className: 'dsh-mail-btn', onClick: () => setVaultOpen(false) }, t('cancel'))
2150
+ ),
2151
+ h('div', { className: 'dsh-mail-modal-body' },
2152
+ h('div', { className: 'dsh-mail-hint' }, t('vaultPickHint')),
2153
+ vaultBusy ? h('div', { className: 'dsh-mail-hint' }, t('vaultPickLoading'))
2154
+ : (vaultEntries && vaultEntries.length === 0) ? h('div', { className: 'dsh-mail-hint' }, t('vaultPickEmpty'))
2155
+ : (vaultEntries || []).map(entry =>
2156
+ h('button', {
2157
+ key: entry.id, type: 'button', className: 'dsh-mail-vault-opt',
2158
+ onClick: () => pickVaultSecret(entry)
2159
+ },
2160
+ h('span', { style: { fontWeight: 650 } }, entry.title || '(untitled)'),
2161
+ h('span', { className: 'dsh-mail-hint' }, entry.username || entry.provider || '')
2162
+ )
2163
+ )
2164
+ )
2165
+ )
2166
+ ),
2167
+
1463
2168
  /* ------------------------------- DETAIL ----------------------------- */
1464
2169
  view === 'detail' && h('div', { className: 'dsh-mail-view' },
1465
2170
  h('div', { className: 'dsh-mail-scroll' },
@@ -1472,21 +2177,91 @@ window.__ModuleLoader__.load({
1472
2177
  h('div', { style: { minWidth: 0 } },
1473
2178
  h('div', { style: { fontWeight: 600 } }, String(detail.from || '').replace(/<.*>/, '').trim() || detail.from || ''),
1474
2179
  h('div', { className: 'dsh-mail-detailmeta' }, t('to') + ': ' + (detail.to || '') + ' · ' + fmtDate(detail.date))
1475
- )
2180
+ ),
2181
+ parseAddress(detail.from)
2182
+ ? h('button', {
2183
+ className: 'dsh-mail-btn' + (contactKnown(parseAddress(detail.from).email) ? ' is-done' : ''),
2184
+ 'data-testid': 'add-sender',
2185
+ onClick: () => addAsContact(detail.from),
2186
+ disabled: busy,
2187
+ title: t('addSender'),
2188
+ }, h(Ico, { name: contactKnown(parseAddress(detail.from).email) ? 'check' : 'plus', size: 14 }), t('addSender'))
2189
+ : null
1476
2190
  )
1477
2191
  ),
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');
2192
+ h('div', { className: 'dsh-mail-detailtoolbar' },
2193
+ h('button', {
2194
+ className: 'dsh-mail-btn',
2195
+ type: 'button',
2196
+ 'data-testid': 'translate-mail',
2197
+ onClick: () => void translateMessage(),
2198
+ disabled: translating || busy,
2199
+ title: t('translate'),
1487
2200
  },
1488
- dangerouslySetInnerHTML: { __html: detail.html || ('<div style="white-space:pre-wrap">' + escHtml(detail.body || '') + '</div>') },
1489
- })
2201
+ h(Ico, { name: 'translate', size: 14 }),
2202
+ translating ? t('translating') : t('translate')
2203
+ ),
2204
+ translatedText !== null
2205
+ ? h('button', {
2206
+ className: 'dsh-mail-btn',
2207
+ type: 'button',
2208
+ onClick: () => setTranslatedText(null),
2209
+ title: t('translateShowOriginal'),
2210
+ }, h(Ico, { name: 'back', size: 14 }), t('translateShowOriginal'))
2211
+ : null
2212
+ ),
2213
+ translatedText !== null
2214
+ ? h('div', null,
2215
+ h('div', {
2216
+ className: 'dsh-mail-mailbody dsh-mail-translated',
2217
+ onClick: (e) => {
2218
+ const a = e.target && e.target.closest && e.target.closest('a[href]');
2219
+ if (!a) return;
2220
+ const href = a.getAttribute('href');
2221
+ if (!href) return;
2222
+ e.preventDefault();
2223
+ if (window.open) window.open(href, '_blank', 'noopener,noreferrer');
2224
+ },
2225
+ },
2226
+ h('div', { className: 'dsh-mail-translatednotice' }, h(Ico, { name: 'translate', size: 13 }), t('translatedNotice')),
2227
+ h('div', { style: { whiteSpace: 'pre-wrap' } }, translatedText || t('noMessages'))
2228
+ ),
2229
+ h('div', { style: { height: 14 } })
2230
+ )
2231
+ : h('div', {
2232
+ className: 'dsh-mail-mailbody',
2233
+ onClick: (e) => {
2234
+ const a = e.target && e.target.closest && e.target.closest('a[href]');
2235
+ if (!a) return;
2236
+ const href = a.getAttribute('href');
2237
+ if (!href) return;
2238
+ e.preventDefault();
2239
+ if (window.open) window.open(href, '_blank', 'noopener,noreferrer');
2240
+ },
2241
+ dangerouslySetInnerHTML: { __html: detail.html || ('<div style="white-space:pre-wrap">' + escHtml(detail.body || '') + '</div>') },
2242
+ }),
2243
+ // Attachments are fetched on demand so opening a mail stays fast.
2244
+ Array.isArray(detail.attachments) && detail.attachments.length > 0
2245
+ ? h('div', { className: 'dsh-mail-field', style: { marginTop: 14 } },
2246
+ h('span', { className: 'dsh-mail-label' }, t('attachments') + ' (' + detail.attachments.length + ')'),
2247
+ h('div', { className: 'dsh-mail-attachlist' }, detail.attachments.map(att =>
2248
+ h('div', { key: String(att.index), className: 'dsh-mail-attach' },
2249
+ h(Ico, { name: 'attach', size: 14 }),
2250
+ h('span', { className: 'dsh-mail-attach-name', title: att.name }, att.name),
2251
+ h('span', { className: 'dsh-mail-attach-size' }, fmtSize(att.size)),
2252
+ h('button', {
2253
+ className: 'dsh-mail-btn' + (attachState[String(att.index)] === 'ok' ? ' dsh-mail-refresh-ok' : attachState[String(att.index)] === 'error' ? ' dsh-mail-refresh-err' : ''),
2254
+ type: 'button',
2255
+ disabled: attachState[String(att.index)] === 'loading',
2256
+ onClick: () => downloadAttachment(att),
2257
+ title: t('downloadAttachment'),
2258
+ },
2259
+ h(Ico, { name: attachState[String(att.index)] === 'ok' ? 'check' : attachState[String(att.index)] === 'error' ? 'warning' : 'download', size: 14 }),
2260
+ t('downloadAttachment'))
2261
+ )
2262
+ ))
2263
+ )
2264
+ : null
1490
2265
  )
1491
2266
  )
1492
2267
  ),
@@ -1498,7 +2273,7 @@ window.__ModuleLoader__.load({
1498
2273
  h('div', { className: 'dsh-mail-cardhead' },
1499
2274
  h(Ico, { name: 'compose', size: 16 }), t('compose'),
1500
2275
  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'))
2276
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-primary', onClick: sendMail, disabled: busy || attachBusy || !compose.to }, h(Ico, { name: 'sent', size: 15 }), t('send'))
1502
2277
  ),
1503
2278
  h('div', { className: 'dsh-mail-hint', style: { marginBottom: 12 } }, account ? account.username : ''),
1504
2279
  h('div', { className: 'dsh-mail-field' },
@@ -1512,6 +2287,49 @@ window.__ModuleLoader__.load({
1512
2287
  h('div', { className: 'dsh-mail-field' },
1513
2288
  h('span', { className: 'dsh-mail-label' }, t('body')),
1514
2289
  h('textarea', { className: 'dsh-mail-textarea', value: compose.body, onChange: e => setCompose(Object.assign({}, compose, { body: e.target.value })) })
2290
+ ),
2291
+ h('div', { className: 'dsh-mail-field' },
2292
+ h('span', { className: 'dsh-mail-label' }, t('attachments')),
2293
+ h('div', { className: 'dsh-mail-attachbar' },
2294
+ h('label', { className: 'dsh-mail-btn', style: { cursor: 'pointer' } },
2295
+ h(Ico, { name: 'attach', size: 15 }),
2296
+ t('addAttachment'),
2297
+ h('input', {
2298
+ type: 'file', multiple: true,
2299
+ 'data-testid': 'attachment-input',
2300
+ style: { display: 'none' },
2301
+ onChange: e => { void addAttachments(e.target.files); e.target.value = ''; },
2302
+ })
2303
+ ),
2304
+ attachBusy ? h('span', { className: 'dsh-mail-hint' }, t('loading')) : null
2305
+ ),
2306
+ // Dropping files anywhere on this card also adds them.
2307
+ h('div', {
2308
+ className: 'dsh-mail-drop' + (dropOver ? ' is-over' : ''),
2309
+ onDragOver: e => { e.preventDefault(); if (!dropOver) setDropOver(true); },
2310
+ onDragLeave: () => setDropOver(false),
2311
+ onDrop: e => {
2312
+ e.preventDefault();
2313
+ setDropOver(false);
2314
+ if (e.dataTransfer && e.dataTransfer.files) void addAttachments(e.dataTransfer.files);
2315
+ },
2316
+ }, dropOver ? t('addAttachment') : t('attachmentsHint')),
2317
+ composeAtts.length > 0
2318
+ ? h('div', { className: 'dsh-mail-attachlist' }, composeAtts.map((a, i) =>
2319
+ h('div', { key: a.name + '-' + i, className: 'dsh-mail-attach' },
2320
+ h(Ico, { name: 'attach', size: 14 }),
2321
+ h('span', { className: 'dsh-mail-attach-name', title: a.name }, a.name),
2322
+ h('span', { className: 'dsh-mail-attach-size' }, fmtSize(a.size)),
2323
+ h('button', {
2324
+ className: 'dsh-mail-btn dsh-mail-iconbtn',
2325
+ type: 'button',
2326
+ onClick: () => removeAttachment(i),
2327
+ title: t('removeAttachment'),
2328
+ 'aria-label': t('removeAttachment'),
2329
+ }, h(Ico, { name: 'trash', size: 14 }))
2330
+ )
2331
+ ))
2332
+ : null
1515
2333
  )
1516
2334
  )
1517
2335
  )
@@ -1524,6 +2342,42 @@ window.__ModuleLoader__.load({
1524
2342
  // half stores it in the credential store), so this toggle and the AI tool
1525
2343
  // share one host-owned value without depending on configForms, which is not
1526
2344
  // available on this DSH build.
2345
+ // Scoped stylesheet for the Settings-panel section. The mail panel's CSS
2346
+ // lives under .dsh-mail; the settings shell renders outside that tree, so
2347
+ // this section carries its own prefixed stylesheet (same design language:
2348
+ // soft gradients, 9/14px radii, hover/active/focus states, theme tokens).
2349
+ const SETTINGS_CSS = [
2350
+ '.dsh-mail-set { padding:4px; max-width:560px; color:var(--dsw-alias-label-primary); font-size:13px; line-height:1.55; -webkit-font-smoothing:antialiased; }',
2351
+ '.dsh-mail-set * { box-sizing:border-box; }',
2352
+ '.dsh-mail-set h2 { margin:0 0 8px; font-size:18px; font-weight:700; line-height:1.4; letter-spacing:.2px; }',
2353
+ '.dsh-mail-set h3 { margin:24px 0 8px; padding-top:18px; border-top:1px solid var(--dsw-alias-border-l1); font-size:15px; font-weight:650; line-height:1.4; }',
2354
+ '.dsh-mail-set p { margin:0 0 12px; font-size:13px; line-height:1.7; color:var(--dsw-alias-label-secondary); }',
2355
+ '.dsh-mail-set label { display:flex; align-items:center; gap:10px; cursor:pointer; font-size:14px; line-height:1.5; color:var(--dsw-alias-label-primary); }',
2356
+ '.dsh-mail-set label.dsh-mail-set-gap { margin-top:10px; }',
2357
+ '.dsh-mail-set input[type="checkbox"] { width:16px; height:16px; flex:none; accent-color:var(--dsw-alias-brand-primary); cursor:pointer; }',
2358
+ '.dsh-mail-set input[type="number"], .dsh-mail-set select { width:84px; padding:5px 8px; border:1px solid var(--dsw-alias-border-l2); border-radius:8px; background:var(--dsw-alias-bg-layer-1); color:var(--dsw-alias-label-primary); font-size:13px; font-family:inherit; transition:border-color .12s, box-shadow .12s; }',
2359
+ '.dsh-mail-set input[type="number"]:focus, .dsh-mail-set select: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) 16%, transparent); }',
2360
+ '.dsh-mail-set input:disabled, .dsh-mail-set select:disabled { opacity:.6; cursor:not-allowed; }',
2361
+ '.dsh-mail-set .dsh-mail-set-btn { display:inline-flex; align-items:center; justify-content:center; gap:6px; padding:6px 16px; border:1px solid var(--dsw-alias-border-l2); border-radius:9px; background:var(--dsw-alias-bg-layer-2); color:var(--dsw-alias-label-primary); font-size:13px; font-weight:600; font-family:inherit; cursor:pointer; transition:filter .15s, transform .08s, box-shadow .15s, border-color .15s; }',
2362
+ '.dsh-mail-set .dsh-mail-set-btn:hover:not(:disabled) { filter:brightness(.97); border-color:var(--dsw-alias-brand-primary); box-shadow:0 2px 8px rgba(0,0,0,.08); }',
2363
+ '.dsh-mail-set .dsh-mail-set-btn:active:not(:disabled) { transform:translateY(1px); box-shadow:inset 0 2px 5px rgba(0,0,0,.12); }',
2364
+ '.dsh-mail-set .dsh-mail-set-btn:focus-visible { outline:2px solid var(--dsw-alias-brand-primary); outline-offset:2px; }',
2365
+ '.dsh-mail-set .dsh-mail-set-btn:disabled { opacity:.5; cursor:not-allowed; }',
2366
+ '.dsh-mail-set .dsh-mail-set-btn-primary { background:linear-gradient(135deg, color-mix(in srgb, var(--dsw-alias-brand-primary) 82%, white), var(--dsw-alias-brand-primary)); border-color:transparent; color:var(--dsw-alias-bg-base); box-shadow:0 3px 10px color-mix(in srgb, var(--dsw-alias-brand-primary) 32%, transparent); }',
2367
+ '.dsh-mail-set .dsh-mail-set-btn-primary:hover:not(:disabled) { filter:brightness(1.06); box-shadow:0 5px 14px color-mix(in srgb, var(--dsw-alias-brand-primary) 40%, transparent); }',
2368
+ '.dsh-mail-set .dsh-mail-set-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin-top:14px; }',
2369
+ '.dsh-mail-set .dsh-mail-set-card { margin-top:14px; padding:12px; border:1px solid var(--dsw-alias-border-l1); border-radius:14px; background:linear-gradient(180deg, var(--dsw-alias-bg-layer-1), var(--dsw-alias-bg-base)); box-shadow:0 2px 10px rgba(0,0,0,.05), inset 0 1px 0 rgba(255,255,255,.04); }',
2370
+ '.dsh-mail-set .dsh-mail-set-cardhead { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }',
2371
+ '.dsh-mail-set .dsh-mail-spacer { flex:1; min-width:0; }',
2372
+ '.dsh-mail-set .dsh-mail-set-meta { margin-top:6px; font-size:12px; line-height:1.7; color:var(--dsw-alias-label-secondary); }',
2373
+ '.dsh-mail-set .dsh-mail-set-meta.is-ok { color:var(--dsw-alias-state-success-primary); }',
2374
+ '.dsh-mail-set .dsh-mail-set-meta.is-error { color:var(--dsw-alias-state-error-primary); }',
2375
+ '.dsh-mail-set p.dsh-mail-set-note { margin:8px 0 0; font-size:12px; line-height:1.6; }',
2376
+ '.dsh-mail-set p.dsh-mail-set-note.is-ok { color:var(--dsw-alias-state-success-primary); }',
2377
+ '.dsh-mail-set p.dsh-mail-set-note.is-error { color:var(--dsw-alias-state-error-primary); }',
2378
+ '@media (prefers-reduced-motion: reduce) { .dsh-mail-set .dsh-mail-set-btn { transition:none; } }',
2379
+ ].join('\n');
2380
+
1527
2381
  function MailSettingsSection(props) {
1528
2382
  const tr = props && props.t ? props.t : t;
1529
2383
  const [draft, setDraft] = useState({ agentMailAccess: false, notifyEnabled: true, notifyInterval: 60, notifyMode: 'pet' });
@@ -1688,64 +2542,51 @@ window.__ModuleLoader__.load({
1688
2542
  setChecking(false);
1689
2543
  };
1690
2544
 
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
2545
  const dirty = JSON.stringify(draft) !== JSON.stringify(stored);
1702
2546
  // In pure system-notification mode, hide all pet-related copy.
1703
2547
  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')),
2548
+ return h('div', { className: 'dsh-mail-set' },
2549
+ h('style', null, SETTINGS_CSS),
2550
+ h('h2', null, tr('settingsTitle')),
1706
2551
 
1707
2552
  // 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 },
2553
+ h('p', null, tr('settingsDescription')),
2554
+ h('label', { htmlFor: 'settings-dsh-mail-agent-access' },
1710
2555
  h('input', {
1711
2556
  id: 'settings-dsh-mail-agent-access', type: 'checkbox',
1712
2557
  checked: draft.agentMailAccess, disabled: saving || !loaded,
1713
2558
  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
2559
  }),
1716
2560
  tr('agentMailAccessLabel')
1717
2561
  ),
1718
- h('p', { style: hint }, tr('agentMailAccessHint')),
2562
+ h('p', null, tr('agentMailAccessHint')),
1719
2563
 
1720
2564
  // 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 },
2565
+ h('h3', null, tr('notifySectionTitle')),
2566
+ h('p', null, tr(isSystemOnly ? 'notifySectionHintSystem' : 'notifySectionHint')),
2567
+ h('label', { htmlFor: 'settings-dsh-mail-notify' },
1724
2568
  h('input', {
1725
2569
  id: 'settings-dsh-mail-notify', type: 'checkbox',
1726
2570
  checked: draft.notifyEnabled, disabled: saving || !loaded,
1727
2571
  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
2572
  }),
1730
2573
  tr(isSystemOnly ? 'notifyEnabledLabelSystem' : 'notifyEnabledLabel')
1731
2574
  ),
1732
- h('label', { htmlFor: 'settings-dsh-mail-interval', style: { ...field, marginTop: 10 } },
2575
+ h('label', { htmlFor: 'settings-dsh-mail-interval', className: 'dsh-mail-set-gap' },
1733
2576
  h('span', null, tr('notifyIntervalLabel')),
1734
2577
  h('input', {
1735
2578
  id: 'settings-dsh-mail-interval', type: 'number', min: 15, max: 3600,
1736
2579
  value: draft.notifyInterval, disabled: saving || !loaded,
1737
2580
  onChange: (e) => setDraft({ ...draft, notifyInterval: Number(e && e.target && e.target.value) || 60 }),
1738
- style: numInput,
1739
2581
  })
1740
2582
  ),
1741
- h('label', { htmlFor: 'settings-dsh-mail-mode', style: { ...field, marginTop: 10 } },
2583
+ h('label', { htmlFor: 'settings-dsh-mail-mode', className: 'dsh-mail-set-gap' },
1742
2584
  h('span', null, tr('notifyMode')),
1743
2585
  h('select', {
1744
2586
  id: 'settings-dsh-mail-mode',
1745
2587
  value: draft.notifyMode || 'pet',
1746
2588
  disabled: saving || !loaded,
1747
2589
  onChange: (e) => setDraft({ ...draft, notifyMode: (e && e.target && e.target.value) || 'pet' }),
1748
- style: numInput,
1749
2590
  },
1750
2591
  h('option', { value: 'pet' }, tr('notifyModePet')),
1751
2592
  h('option', { value: 'system' }, tr('notifyModeSystem')),
@@ -1754,92 +2595,68 @@ window.__ModuleLoader__.load({
1754
2595
  ),
1755
2596
 
1756
2597
  // Permission row.
1757
- h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: 14 } },
2598
+ h('div', { className: 'dsh-mail-set-row' },
1758
2599
  h('button', {
1759
- type: 'button', disabled: asking || perm === 'granted' || perm === 'unsupported',
2600
+ type: 'button', className: 'dsh-mail-set-btn',
2601
+ disabled: asking || perm === 'granted' || perm === 'unsupported',
1760
2602
  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
2603
  }, asking ? tr('notifyPermissionAsking') : tr('notifyPermission')),
1768
- h('span', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
2604
+ h('span', null,
1769
2605
  perm === 'granted' ? tr('notifyPermissionGranted')
1770
2606
  : perm === 'denied' ? tr('notifyPermissionDenied')
1771
2607
  : perm === 'unsupported' ? tr('notifyPermissionUnsupported') : ''
1772
2608
  ),
1773
2609
  h('button', {
1774
- type: 'button', disabled: asking,
2610
+ type: 'button', className: 'dsh-mail-set-btn dsh-mail-set-btn-primary',
2611
+ disabled: asking,
1775
2612
  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
2613
  }, tr('notifyTest'))
1783
2614
  ),
1784
2615
  testMsg ? h('p', {
1785
- style: { ...hint, color: tested ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-error-primary)' },
2616
+ className: 'dsh-mail-set-note ' + (tested ? 'is-ok' : 'is-error'),
1786
2617
  }, testMsg) : null,
1787
2618
 
1788
2619
  // Live detection diagnostics + manual check. These make the otherwise
1789
2620
  // 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)' } },
2621
+ h('div', { className: 'dsh-mail-set-card' },
2622
+ h('div', { className: 'dsh-mail-set-cardhead' },
2623
+ h('strong', null, tr('notifyDiagTitle')),
2624
+ h('span', { className: diag.running ? 'dsh-mail-set-meta is-ok' : 'dsh-mail-set-meta is-error' },
1794
2625
  diag.running ? tr('notifyDiagRunning') : tr('notifyDiagStopped')),
1795
2626
  h('span', { className: 'dsh-mail-spacer' }),
1796
2627
  h('button', {
1797
- type: 'button', disabled: checking || !loaded,
2628
+ type: 'button', className: 'dsh-mail-set-btn',
2629
+ disabled: checking || !loaded,
1798
2630
  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
2631
  }, checking ? tr('notifyChecking') : tr('notifyCheckNow'))
1806
2632
  ),
1807
- h('div', { style: { marginTop: 6, fontSize: 12, lineHeight: 1.7, color: 'var(--dsw-alias-label-secondary)' } },
2633
+ h('div', { className: 'dsh-mail-set-meta' },
1808
2634
  tr('notifyDiagAccounts') + ': ' + (diag.accounts || 0) + ' · ' +
1809
2635
  tr('notifyDiagChecks') + ': ' + (diag.checks || 0) + ' · ' +
1810
2636
  tr(isSystemOnly ? 'notifyDiagAlertsSystem' : 'notifyDiagAlerts') + ': ' + (diag.alerts || 0) + ' · ' +
1811
2637
  tr('notifyDiagLastCheck') + ': ' + (diag.lastCheck ? new Date(diag.lastCheck).toLocaleString() : tr('notifyDiagNever'))
1812
2638
  ),
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)' } },
2639
+ h('div', { className: 'dsh-mail-set-meta ' + (diag.error ? 'is-error' : 'is-ok') },
1814
2640
  tr('notifyDiagError') + ': ' + (diag.error || tr('notifyDiagOk'))
1815
2641
  ),
1816
- checkMsg ? h('p', { style: { margin: '6px 0 0', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, checkMsg) : null
2642
+ checkMsg ? h('p', { className: 'dsh-mail-set-note' }, checkMsg) : null
1817
2643
  ),
1818
2644
 
1819
2645
  failed
1820
- ? h('p', { style: { margin: '8px 0 0', fontSize: 12, color: 'var(--dsw-alias-state-error-primary)' } }, tr('settingsSaveFailed') + (saveError ? ' (' + saveError + ')' : ''))
2646
+ ? h('p', { className: 'dsh-mail-set-note is-error' }, tr('settingsSaveFailed') + (saveError ? ' (' + saveError + ')' : ''))
1821
2647
  : saved
1822
- ? h('p', { style: { margin: '8px 0 0', fontSize: 12, color: 'var(--dsw-alias-state-success-primary)' } }, tr('settingsSaveSuccess'))
2648
+ ? h('p', { className: 'dsh-mail-set-note is-ok' }, tr('settingsSaveSuccess'))
1823
2649
  : null,
1824
- h('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
2650
+ h('div', { className: 'dsh-mail-set-row' },
1825
2651
  h('button', {
1826
- type: 'button',
2652
+ type: 'button', className: 'dsh-mail-set-btn dsh-mail-set-btn-primary',
1827
2653
  disabled: !dirty || saving,
1828
2654
  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
2655
  }, saving ? tr('settingsSaving') : tr('settingsSave')),
1835
2656
  dirty ? h('button', {
1836
- type: 'button',
2657
+ type: 'button', className: 'dsh-mail-set-btn',
1837
2658
  disabled: saving,
1838
2659
  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
2660
  }, tr('cancel')) : null
1844
2661
  )
1845
2662
  );