@mysterycode-liwen/dsh-mail 1.0.1 → 1.1.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/README.md CHANGED
@@ -14,6 +14,7 @@ A sidebar plugin for DeepSeek Harness that sends and receives mail from QQ / 163
14
14
  - [安装](#安装--install)
15
15
  - [快速上手](#快速上手--quick-start)
16
16
  - [功能](#功能--features)
17
+ - [新邮件通知](#新邮件通知--new-mail-alerts)
17
18
  - [AI 助手查询邮箱(需开启)](#ai-助手查询邮箱需开启--ai-assistant-mail-query)
18
19
  - [支持的邮箱与服务器](#支持的邮箱与服务器--server-presets)
19
20
  - [工作原理](#工作原理--how-it-works)
@@ -30,14 +31,18 @@ A sidebar plugin for DeepSeek Harness that sends and receives mail from QQ / 163
30
31
  dsh plugin --profile desktop add @mysterycode-liwen/dsh-mail
31
32
  ```
32
33
 
33
- 也可以在 DeepSeek Harness 的「设置 → 插件 → 插件市场」中搜索 `mail`(市场索引刷新后可见)。
34
-
35
- 从 GitHub 源码安装:
34
+ 从 GitHub 源码安装(跟踪 `main` 的最新改动):
36
35
 
37
36
  ```bash
38
37
  dsh plugin --profile desktop add github:mysterycode-liwen/dsh-email
39
38
  ```
40
39
 
40
+ 也可以在本仓库的插件索引中一键安装:在「设置 → 插件」中启用「自定义插件索引」,然后在「发现」标签添加索引源
41
+
42
+ ```
43
+ https://mysterycode-liwen.github.io/dsh-email/index.json
44
+ ```
45
+
41
46
  从本地目录安装(开发用):
42
47
 
43
48
  ```bash
@@ -53,18 +58,66 @@ dsh plugin --profile desktop add link:E:/DeepSeek/dsh-email
53
58
  1. 安装并重启 DSH → 左侧栏点「邮件」。
54
59
  2. 切到「账号」视图 → 点预设(QQ 邮箱 / 网易 163 / Gmail)自动填好服务器与端口,或手动填自定义服务器。
55
60
  3. 填邮箱地址、授权码,点「测试连接」验证 IMAP 登录 + SMTP 登录都通过,再点「保存」。
56
- 4. 回到「收件箱」,从下拉框选账号 → 点「刷新」拉取最近邮件。
57
- 5. 点列表中的邮件读正文(链接可点、图片可显示);点「写邮件」填写收件人 / 主题 / 正文发送。
61
+ 4. 回到「收件箱」,从顶部下拉框选账号 → 点「刷新」拉取最近邮件。
62
+ 5. 点列表中的邮件读正文(链接可点、图片可显示);点「写邮件」填写收件人 / 主题 / 正文发送或添加附件。
58
63
 
59
64
  ## 功能 / Features
60
65
 
66
+ **侧边栏面板**
67
+
61
68
  - 左侧栏「邮件」面板 + 主区域邮件视图,账号、邮件列表与正文在面板内缓存,切视图不会重新拉取。
69
+ - 有新邮件时侧边栏入口旁出现红色未读小圆点(鼠标悬停显示封数),点开邮件后清除。
70
+
71
+ **账号**
72
+
62
73
  - 多账号管理:添加 / 删除,快速设置预设,支持完全自定义的 IMAP/SMTP 主机、端口与 TLS 开关。
63
- - 收件箱:按 UID 拉取最近 N 封(默认 20,可调 1–100),显示主题 / 发件人 / 日期 / 摘要。
64
- - 读信:正文支持富文本——保留可点击链接与内嵌图片;HTML 经消毒(剥离脚本、样式、危险属性与 `javascript:` 链接),`cid:` 内嵌图片转成 `data:` URI 显示。
65
- - 写信:纯文本 / HTML 邮件正文通过 SMTP 发送(UTF-8)。
74
+ - 账号名称可随时在账号卡片上「重命名」;新账号默认用邮箱 `@` 前的部分作为名称。名称只在本机显示,不会写回邮箱服务器。
75
+
76
+ **收件**
77
+
78
+ - 收件箱:按 UID 拉取最近 N 封(默认 25,接口上限 100),显示主题 / 发件人 / 日期 / 摘要。
79
+ - 已读 / 未读筛选:收件箱顶部「全部 / 未读 / 已读」三个按钮带数量,选择后只显示对应邮件。
80
+ - 新邮件自动出现:后台检测到新邮件后,当前账号的列表会自动刷新,不用手动点刷新。
81
+ - 点「刷新」有加载动效:图标旋转 + 按钮禁用,完成后短暂显示对勾(成功)或感叹号(失败)再复位。
82
+
83
+ **读信**
84
+
85
+ - 正文支持富文本——保留可点击链接与内嵌图片;HTML 经消毒(剥离脚本、样式、危险属性与 `javascript:` 链接),`cid:` 内嵌图片转成 `data:` URI 显示。
86
+ - 附件:显示文件名 / 大小,点「下载」按需取回并保存到本地下载目录;单封邮件附件上限 25 MB。
87
+ - 一键把发件人加为联系人(已在联系人中的显示为已完成态,不会覆盖你改过的姓名)。
88
+
89
+ **写信**
90
+
91
+ - 收件人支持逗号分隔多个地址;正文 UTF-8 纯文本。
92
+ - 附件:点「添加附件」或直接把文件拖到投递区,可多选、可逐个移除;总大小超过 25 MB 会被拦下并提示分开发送。
93
+
94
+ **发件箱**
95
+
96
+ - 已发送读自服务器 Sent 文件夹(在别的设备上发的信也能看到),服务器不可达时回退到本地缓存。
97
+ - 发件详情可把收件人一键加为联系人;随信附件显示名称与大小。
98
+
99
+ **联系人**
100
+
101
+ - 本地地址簿:手动添加(姓名 + 邮箱)、删除、一键写信。
102
+ - 联系人只保存在本机,不上传到邮箱服务器。
103
+
104
+ **其他**
105
+
66
106
  - 连接测试:一键验证 IMAP 选定 INBOX + SMTP 登录。
67
107
  - 本地化:中文 / 英文界面,跟随 DSH 语言设置。
108
+ - 主题:全部样式使用 DSH `--dsw-alias-*` 变量,日间 / 夜间主题都能正常显示。
109
+
110
+ ## 新邮件通知 / New mail alerts
111
+
112
+ 设置页(「设置 → 插件 → 邮件」)里可配置后台检查:
113
+
114
+ - **通知方式**:桌宠播报 / 系统通知(需浏览器权限)/ 两者都要。
115
+ - **检查间隔**:15–3600 秒,默认 60 秒。
116
+ - **检测状态**:显示轮询是否运行、账号数、检查次数、告警次数、上次检查时间与最近错误,方便判断「为什么没提醒」。
117
+ - **立即检查新邮件**:立刻跑一次检测并报告发现几封。
118
+ - **发送测试通知**:验证所选通道是否真的能弹出来。
119
+
120
+ 桌宠播报不需要浏览器通知权限,走的是桌宠插件的同源广播接口(`/dsh-pet-7340/broadcast`),桌宠睡着时会被拒绝。系统通知需要浏览器授权,首次点按钮时申请。
68
121
 
69
122
  ## AI 助手查询邮箱(需开启)/ AI assistant mail query
70
123
 
@@ -91,7 +144,11 @@ The read-only `mail_query` tool lets the DSH AI assistant query mail (list accou
91
144
 
92
145
  - 账号与授权码存进 DSH 凭据保险箱(`ctx.credentials`),记录 key 形如 `mail/acct-xxxxxxxx`,只把脱敏后的账号元数据返回给 UI;
93
146
  - 每次操作启动一个 Python 子进程运行 `bridge.py`,通过环境变量 `MAIL_REQUEST` 传 JSON 请求、stdout 读 JSON 结果;
94
- - `bridge.py` 用标准库实现 `test` / `listMessages` / `getMessage` / `sendMessage` 四个操作;正文解码处理 charset 回退(UTF-8 / GB18030 / GBK / Big5 / Shift-JIS / EUC-KR)以消除中文乱码。
147
+ - `bridge.py` 用标准库实现 `test` / `listMessages` / `getMessage` / `getAttachment` / `sendMessage` / `listSent` 等操作;正文解码处理 charset 回退(UTF-8 / GB18030 / GBK / Big5 / Shift-JIS / EUC-KR)以消除中文乱码,附件按 RFC 2231 编码以保留中文文件名。
148
+
149
+ Host 端操作一览:`getSettings` / `setSettings` / `listAccounts` / `saveAccount` / `renameAccount` / `deleteAccount` / `testAccount` / `listMessages` / `getMessage` / `getAttachment` / `sendMessage` / `sentMessages` / `listContacts` / `saveContact` / `deleteContact`。
150
+
151
+ 联系人、发件箱缓存、设置都存在本机的 profile 存储里,不经过邮箱服务器(联系人不会同步到服务器通讯录)。
95
152
 
96
153
  所有邮件操作在同一台机器上完成;插件本身没有对外上传行为。
97
154
 
@@ -101,6 +158,7 @@ The read-only `mail_query` tool lets the DSH AI assistant query mail (list accou
101
158
  - 邮件正文的 HTML 经过白名单消毒:脚本、`<style>`、事件属性、`javascript:` 链接全部剥离,仅保留安全标签与属性;`data:` URL 仅允许 `data:image/`。
102
159
  - 子进程环境变量中会短暂包含授权码(进程生命周期内);该值不被记录到日志,也不回传浏览器。
103
160
  - 邮件正文中的远程图片 URL 由邮件发送方控制,阅读邮件时浏览器可能向其发起请求——这是所有邮件客户端的通用行为,请留意发件人是否可信。
161
+ - 附件由你主动点「下载」才会取回;发送时不经过任何中转服务器。
104
162
  - 本插件不加密本地缓存;请勿在公用电脑上使用。
105
163
 
106
164
  ## 常见问题 / FAQ
@@ -120,6 +178,15 @@ The read-only `mail_query` tool lets the DSH AI assistant query mail (list accou
120
178
  **授权码存在哪?会上传吗?**
121
179
  存在 DSH 凭据保险箱,仅本地;插件没有网络上传行为。你也可以在「凭据保险箱」侧栏面板中查看 / 删除这些记录(key 形如 `mail/acct-…`)。
122
180
 
181
+ **新邮件没有提醒?**
182
+ 先看设置页的「检测状态」:如果显示「轮询未运行」,检查开关是否打开;如果检查次数在涨但告警次数是 0,说明没检测到新邮件(可点「立即检查新邮件」验证)。用桌宠播报时,桌宠处于睡眠状态会被拒绝,叫醒它即可;用系统通知时,需要在浏览器里允许本页通知。
183
+
184
+ **改了插件代码但界面没反应,或报 `unknown op: xxx`?**
185
+ 插件分为 Host 与 Client 两半。Client 半在刷新页面时重新加载,Host 半只在 DSH 进程启动时加载一次。改了 Host 半(`index.js`、`bridge.py`)必须**完全退出** DeepSeek Harness 再启动——关掉窗口只是隐藏到托盘,请在托盘图标上右键退出,或用任务管理器结束所有 DeepSeek Harness 进程。
186
+
187
+ **附件发不出去 / 下载失败?**
188
+ 单封邮件附件总量上限 25 MB,超过请分开发送。下载失败请确认邮箱服务商允许 IMAP 取信(部分企业邮箱对附件大小有限制)。
189
+
123
190
  ## 从源码构建 / From source
124
191
 
125
192
  ```bash
@@ -131,6 +198,22 @@ dsh plugin --profile desktop add link:$(pwd)
131
198
 
132
199
  发布前 `prepublishOnly` 会自动跑 `npm run check`。
133
200
 
201
+ ## 更新日志 / Changelog
202
+
203
+ **1.1.0**
204
+
205
+ - 新增:附件收发(写信可添加 / 拖入附件,收信可下载附件,单封上限 25 MB,中文文件名正常)。
206
+ - 新增:新邮件被检测到后,当前账号的邮件列表自动刷新。
207
+ - 新增:侧边栏「邮件」入口的未读小红点,点开邮件后清除。
208
+ - 新增:账号重命名(取代此前从邮件头猜昵称的做法),新账号默认用邮箱前缀作为名称。
209
+ - 新增:在读信与发件详情中一键把发件人 / 收件人加为联系人。
210
+ - 改进:Host 半过期时提示「请完全退出并重启 DeepSeek Harness」,而不是抛出 `unknown op`。
211
+
212
+ **1.0.1**
213
+
214
+ - 新邮件通知(桌宠播报 / 系统通知 / 两者),带检测状态面板与「立即检查」「发送测试通知」。
215
+ - 收件箱已读 / 未读筛选,刷新按钮加载动效,设置保存提示修复。
216
+
134
217
  ## 许可 / License
135
218
 
136
219
  [MIT](LICENSE) © 李文 (mysterycode-liwen)
package/bridge.py CHANGED
@@ -11,7 +11,8 @@ Operations
11
11
  test verify IMAP + SMTP connectivity for an account
12
12
  listMessages list recent messages from a mailbox folder
13
13
  getMessage fetch one message's full body by UID
14
- sendMessage send a message over SMTP
14
+ getAttachment download one attachment of a message as base64
15
+ sendMessage send a message over SMTP (with attachments)
15
16
  listSent read the server's Sent folder (cross-device sync)
16
17
  getContacts read the synced contacts stored on the mail server
17
18
  setContacts write the synced contacts to the mail server
@@ -33,6 +34,7 @@ from email.header import decode_header, make_header
33
34
  from email.utils import parsedate_to_datetime, formatdate, getaddresses
34
35
  import uuid
35
36
  from email.mime.base import MIMEBase
37
+ from email.mime.multipart import MIMEMultipart
36
38
  from email import encoders
37
39
 
38
40
  # Local outbox records (mirrored to Sent so they appear in the IMAP Sent folder).
@@ -228,6 +230,45 @@ def _build_cid_map(msg):
228
230
  return cid_map
229
231
 
230
232
 
233
+ def attachments_of(msg):
234
+ """List downloadable attachments as metadata only (no payload).
235
+
236
+ Inline images referenced by Content-ID are part of the rendered body, not
237
+ attachments, so they are skipped unless the part also carries a filename.
238
+ ``index`` is the part's position in ``msg.walk()``; it is stable for the
239
+ same raw message, which lets a later call fetch exactly that part.
240
+ """
241
+ result = []
242
+ try:
243
+ for idx, part in enumerate(msg.walk()):
244
+ if part.is_multipart():
245
+ continue
246
+ disp = str(part.get("Content-Disposition") or "")
247
+ filename = part.get_filename()
248
+ if not filename and "attachment" not in disp.lower():
249
+ continue
250
+ if "inline" in disp.lower() and not filename:
251
+ continue
252
+ try:
253
+ filename = dec(filename)
254
+ except Exception:
255
+ filename = str(filename or "")
256
+ filename = filename or ("attachment-%d" % idx)
257
+ try:
258
+ size = len(part.get_payload(decode=True) or b"")
259
+ except Exception:
260
+ size = 0
261
+ result.append({
262
+ "index": idx,
263
+ "name": filename,
264
+ "size": size,
265
+ "mime": part.get_content_type(),
266
+ })
267
+ except Exception:
268
+ pass
269
+ return result
270
+
271
+
231
272
  def body_of(msg, want_html=False):
232
273
  """Extract body content from an email.message.Message.
233
274
 
@@ -574,6 +615,61 @@ def op_get_message(req):
574
615
  "date": date_iso,
575
616
  "body": body["text"],
576
617
  "html": body["html"],
618
+ "attachments": attachments_of(msg),
619
+ }
620
+ finally:
621
+ try:
622
+ client.close()
623
+ except Exception:
624
+ pass
625
+ try:
626
+ client.logout()
627
+ except Exception:
628
+ pass
629
+
630
+
631
+ def op_get_attachment(req):
632
+ """Return one attachment's bytes as base64, addressed by part index.
633
+
634
+ The index is the position in the message's part walk, as reported by
635
+ ``attachments_of`` when the message was read. Reading uses BODY.PEEK so
636
+ downloading an attachment never changes the read/unread flag.
637
+ """
638
+ acc = req["account"]
639
+ uid = str(req["uid"])
640
+ folder = req.get("folder") or "INBOX"
641
+ index = int(req.get("index") or 0)
642
+ try:
643
+ client = imap_connect(acc)
644
+ except Exception as exc:
645
+ return fail_result(exc)
646
+ try:
647
+ typ, data = client.select('"%s"' % folder.replace('"', ""), readonly=True)
648
+ if typ != "OK":
649
+ return {"ok": False, "error": "选择文件夹失败:%s" % imap_data_text(data), "code": "folder"}
650
+ typ, msg_data = client.uid("FETCH", uid, "(BODY.PEEK[])")
651
+ if typ != "OK" or not msg_data or msg_data[0] is None:
652
+ return {"ok": False, "error": "未找到这封邮件(可能已被删除)。", "code": "not_found"}
653
+ from email import message_from_bytes
654
+ msg = message_from_bytes(msg_data[0][1])
655
+ parts = list(msg.walk())
656
+ if index < 0 or index >= len(parts):
657
+ return {"ok": False, "error": "附件位置已失效,请重新打开邮件。", "code": "not_found"}
658
+ part = parts[index]
659
+ payload = part.get_payload(decode=True)
660
+ if payload is None:
661
+ return {"ok": False, "error": "这个附件没有可下载的内容。", "code": "generic"}
662
+ # Refuse absurdly large payloads: the JSON reply carries the bytes and
663
+ # the Host half buffers the whole bridge response in memory.
664
+ if len(payload) > 25 * 1024 * 1024:
665
+ return {"ok": False, "error": "附件超过 25 MB,暂不支持下载。", "code": "toolarge"}
666
+ filename = dec(part.get_filename()) or ("attachment-%d" % index)
667
+ return {
668
+ "ok": True,
669
+ "name": filename,
670
+ "mime": part.get_content_type(),
671
+ "size": len(payload),
672
+ "content": base64.b64encode(payload).decode("ascii"),
577
673
  }
578
674
  finally:
579
675
  try:
@@ -598,6 +694,48 @@ def _contact_entries(addr_header):
598
694
  return result
599
695
 
600
696
 
697
+ def _attachment_parts(attachments):
698
+ """Turn [{name, content(base64)}] into MIMEBase parts."""
699
+ import mimetypes
700
+ parts = []
701
+ for att in attachments or []:
702
+ fname = str(att.get("name") or "attachment")
703
+ try:
704
+ data = base64.b64decode(att.get("content") or "")
705
+ except Exception:
706
+ data = b""
707
+ mime = str(att.get("mime") or "").strip()
708
+ if "/" not in mime:
709
+ mime = mimetypes.guess_type(fname)[0] or "application/octet-stream"
710
+ maintype, subtype = mime.split("/", 1)
711
+ part = MIMEBase(maintype, subtype)
712
+ part.set_payload(data)
713
+ encoders.encode_base64(part)
714
+ safe = fname.replace("\r", "").replace("\n", "")
715
+ # RFC 2231 encoding keeps non-ASCII filenames intact for clients.
716
+ part.add_header("Content-Disposition", "attachment", filename=("utf-8", "", safe))
717
+ parts.append(part)
718
+ return parts
719
+
720
+
721
+ def build_message(acc, recipients, subject, body, attachments=None):
722
+ """Build the outgoing message, multipart only when attachments exist."""
723
+ attachments = attachments or []
724
+ if attachments:
725
+ msg = MIMEMultipart("mixed")
726
+ msg.attach(MIMEText(body or "", "plain", "utf-8"))
727
+ for part in _attachment_parts(attachments):
728
+ msg.attach(part)
729
+ else:
730
+ msg = MIMEText(body or "", "plain", "utf-8")
731
+ msg["From"] = acc["username"]
732
+ msg["To"] = ", ".join(recipients)
733
+ msg["Subject"] = subject or ""
734
+ msg["Date"] = formatdate(localtime=True)
735
+ msg["Message-ID"] = "<%s@%s>" % (uuid.uuid4().hex, acc["username"].split("@")[-1] or "local")
736
+ return msg
737
+
738
+
601
739
  def _append_to_sent(acc, recipients, subject, body, attachments=None):
602
740
  """Mirror a successfully sent message into the IMAP Sent folder.
603
741
 
@@ -605,30 +743,7 @@ def _append_to_sent(acc, recipients, subject, body, attachments=None):
605
743
  """
606
744
  client = None
607
745
  try:
608
- attachments = attachments or []
609
- if attachments:
610
- from email.mime.multipart import MIMEMultipart
611
- msg = MIMEMultipart("mixed")
612
- msg.attach(MIMEText(body or "", "plain", "utf-8"))
613
- for att in attachments:
614
- fname = str(att.get("name") or "attachment")
615
- try:
616
- data = base64.b64decode(att.get("content") or "")
617
- except Exception:
618
- data = b""
619
- part = MIMEBase("application", "octet-stream")
620
- part.set_payload(data)
621
- encoders.encode_base64(part)
622
- safe = fname.replace('"', "").replace("\r", "").replace("\n", "")
623
- part.add_header("Content-Disposition", 'attachment; filename="%s"' % safe)
624
- msg.attach(part)
625
- else:
626
- msg = MIMEText(body or "", "plain", "utf-8")
627
- msg["From"] = acc["username"]
628
- msg["To"] = ", ".join(recipients)
629
- msg["Subject"] = subject or ""
630
- msg["Date"] = formatdate(localtime=True)
631
- msg["Message-ID"] = "<%s@%s>" % (uuid.uuid4().hex, acc["username"].split("@")[-1] or "local")
746
+ msg = build_message(acc, recipients, subject, body, attachments)
632
747
  client = imap_connect(acc)
633
748
  sent_folder = _find_sent_folder(client) or _OUTBOX_FOLDER
634
749
  try:
@@ -665,11 +780,7 @@ def op_send_message(req):
665
780
  recipients = [a.strip() for a in re.split(r"[,;\s]+", str(to)) if a.strip()]
666
781
  if not recipients:
667
782
  return {"ok": False, "error": "收件人不能为空。", "code": "generic"}
668
- msg = MIMEText(body, "plain", "utf-8")
669
- msg["From"] = acc["username"]
670
- msg["To"] = ", ".join(recipients)
671
- msg["Subject"] = subject
672
- msg["Date"] = formatdate(localtime=True)
783
+ msg = build_message(acc, recipients, subject, body, attachments)
673
784
  try:
674
785
  client = smtp_connect(acc)
675
786
  except Exception as exc:
@@ -991,6 +1102,7 @@ OPS = {
991
1102
  "listMessages": op_list_messages,
992
1103
  "getMessage": op_get_message,
993
1104
  "sendMessage": op_send_message,
1105
+ "getAttachment": op_get_attachment,
994
1106
  "listSent": op_list_sent,
995
1107
  "getContacts": op_get_contacts,
996
1108
  "setContacts": op_set_contacts,
package/client.js CHANGED
@@ -38,6 +38,10 @@ window.__ModuleLoader__.load({
38
38
  const known = Object.prototype.hasOwnProperty.call(map, info.code);
39
39
  const head = known ? map[info.code] : t('errGeneric');
40
40
  const raw = String(info.error || '').trim();
41
+ // "unknown op" means the Host half predates this Client half: the plugin
42
+ // was updated on disk but DeepSeek Harness was never restarted, so the
43
+ // running Host has no case for the op the UI just sent.
44
+ if (/unknown op/i.test(raw)) return t('errOutdatedHost');
41
45
  const detail = (!known && raw && raw !== head) ? '\n' + t('errDetail') + raw : '';
42
46
  return stage + head + detail;
43
47
  }
@@ -86,6 +90,8 @@ window.__ModuleLoader__.load({
86
90
  presets: '快速设置',
87
91
  note: 'QQ / 163 需要邮箱授权码,而不是登录密码。授权码保存在凭据保险箱中。',
88
92
  confirmDelete: '确定删除此账号吗?',
93
+ rename: '重命名',
94
+ renameHint: '名称只在本机显示,默认用邮箱前缀。',
89
95
  noSubject: '(无主题)',
90
96
  ok: '成功',
91
97
  failed: '失败',
@@ -100,6 +106,7 @@ window.__ModuleLoader__.load({
100
106
  errNotFound: '未找到这封邮件,它可能已被删除。',
101
107
  errGeneric: '操作失败,请稍后重试。',
102
108
  errDetail: '服务器返回:',
109
+ errOutdatedHost: '插件已更新,但 DeepSeek Harness 仍在运行旧版本。请完全退出并重新启动 DeepSeek Harness(仅刷新页面不够)。',
103
110
  sent: '发件箱',
104
111
  contacts: '联系人',
105
112
  noSent: '还没有已发送的邮件。',
@@ -110,10 +117,24 @@ window.__ModuleLoader__.load({
110
117
  saveContact: '保存联系人',
111
118
  deleteContact: '删除',
112
119
  contactsHint: '手动添加的联系人仅保存在本地,不会上传到邮箱服务器。',
120
+ addSender: '加为联系人',
121
+ addRecipient: '加收件人',
122
+ contactAdded: '已加为联系人。',
123
+ contactExists: '已在联系人中。',
113
124
  emailRequired: '请填写有效的邮箱地址。',
114
125
  saved: '已保存。',
115
126
  selectContact: '用此地址写邮件',
116
127
  attached: '附件',
128
+ attachments: '附件',
129
+ attachmentsHint: '拖拽文件到此处,或点击「添加附件」',
130
+ addAttachment: '添加附件',
131
+ removeAttachment: '移除',
132
+ downloadAttachment: '下载',
133
+ noAttachments: '没有附件',
134
+ attachmentTooLarge: '附件总大小超过 25 MB,请分开发送。',
135
+ attachmentFailed: '附件操作失败:',
136
+ attachmentSaved: '已保存到下载目录:',
137
+ sending: '发送中…',
117
138
  settingsTitle: '邮件',
118
139
  settingsDescription: '配置 AI 助手是否可以读取你的邮箱。',
119
140
  agentMailAccessLabel: '允许 AI 助手查询邮箱',
@@ -211,6 +232,8 @@ window.__ModuleLoader__.load({
211
232
  presets: 'Presets',
212
233
  note: 'QQ / 163 need an app password, not your login password. Stored in the credential vault.',
213
234
  confirmDelete: 'Delete this account?',
235
+ rename: 'Rename',
236
+ renameHint: 'The name is local to this machine; it defaults to the mailbox prefix.',
214
237
  noSubject: '(no subject)',
215
238
  ok: 'OK',
216
239
  failed: 'Failed',
@@ -225,6 +248,7 @@ window.__ModuleLoader__.load({
225
248
  errNotFound: 'This message was not found — it may have been deleted.',
226
249
  errGeneric: 'The operation failed. Please try again later.',
227
250
  errDetail: 'Server said: ',
251
+ 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
252
  sent: 'Sent',
229
253
  contacts: 'Contacts',
230
254
  noSent: 'No sent messages yet.',
@@ -235,10 +259,24 @@ window.__ModuleLoader__.load({
235
259
  saveContact: 'Save contact',
236
260
  deleteContact: 'Delete',
237
261
  contactsHint: 'Contacts you add are saved locally only and are not uploaded to the mail server.',
262
+ addSender: 'Add sender',
263
+ addRecipient: 'Add recipient',
264
+ contactAdded: 'Added to contacts.',
265
+ contactExists: 'Already in contacts.',
238
266
  emailRequired: 'Please enter a valid email address.',
239
267
  saved: 'Saved.',
240
268
  selectContact: 'Compose to this address',
241
269
  attached: 'Attachments',
270
+ attachments: 'Attachments',
271
+ attachmentsHint: 'Drop files here, or click "Add attachment"',
272
+ addAttachment: 'Add attachment',
273
+ removeAttachment: 'Remove',
274
+ downloadAttachment: 'Download',
275
+ noAttachments: 'No attachments',
276
+ attachmentTooLarge: 'Attachments exceed 25 MB in total; please send them separately.',
277
+ attachmentFailed: 'Attachment failed: ',
278
+ attachmentSaved: 'Saved to your downloads folder: ',
279
+ sending: 'Sending…',
242
280
  settingsTitle: 'Mail',
243
281
  settingsDescription: 'Control whether the AI assistant may read your mailbox.',
244
282
  agentMailAccessLabel: 'Allow AI assistant to query mail',
@@ -375,6 +413,16 @@ window.__ModuleLoader__.load({
375
413
  '.dsh-mail-textarea { min-height:200px; resize:vertical; line-height:1.6; }',
376
414
  '.dsh-mail-hint { font-size:11.5px; color:var(--dsw-alias-label-secondary); line-height:1.6; }',
377
415
 
416
+ /* attachments */
417
+ '.dsh-mail-attachbar { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:10px; }',
418
+ '.dsh-mail-attachlist { display:flex; flex-direction:column; gap:6px; margin-bottom:12px; }',
419
+ '.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; }',
420
+ '.dsh-mail-attach-name { font-weight:600; color:var(--dsw-alias-label-primary); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; min-width:0; }',
421
+ '.dsh-mail-attach-size { flex:none; font-size:11px; color:var(--dsw-alias-label-secondary); }',
422
+ '.dsh-mail-attach .dsh-mail-iconbtn { width:26px; height:26px; flex:none; }',
423
+ '.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; }',
424
+ '.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); }',
425
+
378
426
  /* presets */
379
427
  '.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
428
  '.dsh-mail-pill:hover { color:var(--dsw-alias-label-primary); border-color:var(--dsw-alias-brand-primary); }',
@@ -385,6 +433,7 @@ window.__ModuleLoader__.load({
385
433
  '.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
434
  '.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
435
  '.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); }',
436
+ '.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
437
 
389
438
  /* empty & loading */
390
439
  '.dsh-mail-empty { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; padding:64px 28px; text-align:center; }',
@@ -406,6 +455,10 @@ window.__ModuleLoader__.load({
406
455
  '.dsh-mail-detailhead { padding:20px 4px 14px; border-bottom:1px solid var(--dsw-alias-border-l1); margin-bottom:16px; }',
407
456
  '.dsh-mail-detailtitle { margin:0 0 12px; font-size:20px; font-weight:650; line-height:1.4; }',
408
457
  '.dsh-mail-detailfrom { display:flex; align-items:center; gap:10px; }',
458
+ '.dsh-mail-detailfrom > div:nth-child(2) { flex:1; min-width:0; }',
459
+ // A sender already in the address book keeps the button as a quiet state
460
+ // marker instead of an action that would overwrite the saved name.
461
+ '.dsh-mail-btn.is-done { color:var(--dsw-alias-state-success-primary); border-color:var(--dsw-alias-state-success-primary); }',
409
462
  '.dsh-mail-detailmeta { font-size:11.5px; color:var(--dsw-alias-label-secondary); margin-top:2px; }',
410
463
  '.dsh-mail-mailbody { width:100%; padding:18px; border:1px solid var(--dsw-alias-border-l1); border-radius:12px; background:var(--dsw-alias-bg-layer-1); color:var(--dsw-alias-label-primary); line-height:1.75; overflow-wrap:anywhere; word-break:break-word; }',
411
464
 
@@ -511,6 +564,15 @@ window.__ModuleLoader__.load({
511
564
  },
512
565
  };
513
566
 
567
+ // When the background poller detects new mail it publishes the affected
568
+ // account ids here so an open MailPanel can refresh its list in place.
569
+ // Module scope because detection happens outside React, in the poller.
570
+ const MAIL_EVENTS = {
571
+ listeners: new Set(),
572
+ subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); },
573
+ emit(accountIds) { for (const fn of this.listeners) { try { fn(accountIds); } catch { /* dead listener */ } } },
574
+ };
575
+
514
576
  // A mail that arrived while DSH was restarting must not be swallowed by
515
577
  // baseline seeding. On first sight we still alert on unseen messages whose
516
578
  // Date header is within this window.
@@ -678,6 +740,7 @@ window.__ModuleLoader__.load({
678
740
  async function pollNewMail() {
679
741
  if (NOTIFY.busy) return Object.assign({}, NOTIFY.diag);
680
742
  NOTIFY.busy = true;
743
+ const changedAccounts = [];
681
744
  try {
682
745
  const mode = NOTIFY.settings.notifyMode || 'pet';
683
746
  if (mode === 'system' && notifyPermission() !== 'granted') {
@@ -732,6 +795,7 @@ window.__ModuleLoader__.load({
732
795
  NOTIFY.diag.alerts += 1;
733
796
  NOTIFY.diag.lastAlert = Date.now();
734
797
  BADGE.add(recent.length);
798
+ changedAccounts.push(acc.id);
735
799
  if (!res.petOk && !res.sysOk) NOTIFY.diag.error = 'deliver:' + (NOTIFY.lastError || 'no-channel');
736
800
  continue;
737
801
  }
@@ -748,6 +812,7 @@ window.__ModuleLoader__.load({
748
812
  NOTIFY.diag.alerts += 1;
749
813
  NOTIFY.diag.lastAlert = Date.now();
750
814
  BADGE.add(fresh.length);
815
+ changedAccounts.push(acc.id);
751
816
  if (!res.petOk && !res.sysOk) NOTIFY.diag.error = 'deliver:' + (NOTIFY.lastError || 'no-channel');
752
817
  }
753
818
  } catch (e) {
@@ -759,6 +824,7 @@ window.__ModuleLoader__.load({
759
824
  } finally {
760
825
  NOTIFY.busy = false;
761
826
  }
827
+ if (changedAccounts.length) MAIL_EVENTS.emit(changedAccounts);
762
828
  return Object.assign({}, NOTIFY.diag);
763
829
  }
764
830
 
@@ -851,6 +917,8 @@ window.__ModuleLoader__.load({
851
917
  check: 'M4 12l5 5L20 6',
852
918
  warning: 'M12 3L2 20h20L12 3zm0 6v5m0 3v.5',
853
919
  plus: 'M12 5v14M5 12h14',
920
+ 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',
921
+ download: 'M12 4v11m0 0l-4-4m4 4l4-4M4 19h16',
854
922
  };
855
923
  function Ico(props) {
856
924
  // Rendered as a React component via h(Ico, { name, size }); the first
@@ -874,6 +942,27 @@ window.__ModuleLoader__.load({
874
942
  const v = String(s || '').trim();
875
943
  return v ? v.charAt(0).toUpperCase() : '?';
876
944
  }
945
+ // The local label shown for an account defaults to the part before "@", so
946
+ // a fresh mailbox reads as "1101522940" instead of a generic "QQ邮箱" or a
947
+ // guessed display name the user never chose.
948
+ function defaultAccountName(username) {
949
+ const v = String(username || '').trim();
950
+ if (!v) return '';
951
+ const at = v.indexOf('@');
952
+ return at > 0 ? v.slice(0, at) : v;
953
+ }
954
+ // Split a raw address header ("李文" <li@x.com>, "b@y.com") into the parts a
955
+ // contact needs. Accepts the first address only, which is what a sender or a
956
+ // single recipient field carries in practice.
957
+ function parseAddress(raw) {
958
+ const s = String(raw || '').trim();
959
+ if (!s) return null;
960
+ const angled = s.match(/^(.*?)<([^<>]+)>/);
961
+ const name = angled ? String(angled[1] || '').trim().replace(/^["']|["']$/g, '').trim() : '';
962
+ const email = String(angled ? angled[2] : s).trim().replace(/^["']|["']$/g, '');
963
+ if (!email || email.indexOf('@') < 1) return null;
964
+ return { name, email: email.toLowerCase() };
965
+ }
877
966
  function fmtDate(iso) {
878
967
  if (!iso) return '';
879
968
  const d = new Date(iso);
@@ -885,6 +974,47 @@ window.__ModuleLoader__.load({
885
974
  return d.getFullYear() + '.' + (d.getMonth() + 1) + '.' + d.getDate();
886
975
  }
887
976
 
977
+ function fmtSize(bytes) {
978
+ const n = Number(bytes) || 0;
979
+ if (n < 1024) return n + ' B';
980
+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
981
+ return (n / (1024 * 1024)).toFixed(1) + ' MB';
982
+ }
983
+
984
+ // The Host half buffers the whole bridge reply, so keep one attachment under
985
+ // this cap; the send path enforces a 25 MB total for the same reason.
986
+ const MAX_ATTACH_BYTES = 25 * 1024 * 1024;
987
+
988
+ function readFileAsBase64(file) {
989
+ return new Promise((resolve, reject) => {
990
+ const reader = new FileReader();
991
+ reader.onload = () => {
992
+ const result = String(reader.result || '');
993
+ const comma = result.indexOf(',');
994
+ resolve(comma === -1 ? result : result.slice(comma + 1));
995
+ };
996
+ reader.onerror = () => reject(reader.error || new Error('read failed'));
997
+ reader.readAsDataURL(file);
998
+ });
999
+ }
1000
+
1001
+ function saveAttachmentBytes(name, mime, base64) {
1002
+ // Decode base64 to bytes, then hand the browser a Blob download. This keeps
1003
+ // the file binary-exact and never goes through the network again.
1004
+ const bin = atob(base64 || '');
1005
+ const bytes = new Uint8Array(bin.length);
1006
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
1007
+ const blob = new Blob([bytes], { type: mime || 'application/octet-stream' });
1008
+ const url = URL.createObjectURL(blob);
1009
+ const a = document.createElement('a');
1010
+ a.href = url;
1011
+ a.download = name || 'attachment';
1012
+ document.body.appendChild(a);
1013
+ a.click();
1014
+ document.body.removeChild(a);
1015
+ setTimeout(() => URL.revokeObjectURL(url), 10000);
1016
+ }
1017
+
888
1018
  function Loading(props) {
889
1019
  // Rendered as a React component via h(Loading), so the first argument is
890
1020
  // a props object ({} when none is passed) — never treat it as a string.
@@ -919,6 +1049,13 @@ window.__ModuleLoader__.load({
919
1049
  const [flash, setFlash] = useState(null);
920
1050
  const [form, setForm] = usePersistent('form', { preset: 'qq', name: '', username: '', authCode: '', imapHost: PRESETS.qq.imapHost, imapPort: 993, smtpHost: PRESETS.qq.smtpHost, smtpPort: 465 });
921
1051
  const [compose, setCompose] = usePersistent('compose', { to: '', subject: '', body: '' });
1052
+ // Outgoing attachments live in React state (not PERSIST): they hold base64
1053
+ // file bytes, which must not be written to profile storage.
1054
+ const [composeAtts, setComposeAtts] = useState([]);
1055
+ const [attachBusy, setAttachBusy] = useState(false);
1056
+ // Received attachments are fetched on demand from the mail server.
1057
+ const [attachState, setAttachState] = useState({});
1058
+ const [dropOver, setDropOver] = useState(false);
922
1059
  const [sent, setSent] = usePersistent('sent', []);
923
1060
  const [contacts, setContacts] = usePersistent('contacts', []);
924
1061
  const [contactForm, setContactForm] = usePersistent('contactForm', { name: '', email: '' });
@@ -926,10 +1063,27 @@ window.__ModuleLoader__.load({
926
1063
  // Per-account cache of fetched message lists. Survives account switching
927
1064
  // and remounts so we can show cached mail immediately while refreshing.
928
1065
  const [cache, setCache] = usePersistent('mailCache', {});
1066
+ // Inline rename: the account id being edited plus the draft label.
1067
+ const [renameId, setRenameId] = useState('');
1068
+ const [renameDraft, setRenameDraft] = useState('');
1069
+
1070
+ // Keep a fresh handler so the mail-event subscription never sees stale
1071
+ // activeId/view. New mail on the currently open account refreshes the
1072
+ // inbox list in place (silent, no spinner/flash).
1073
+ const onMailRef = useRef(() => {});
1074
+ onMailRef.current = (accountIds) => {
1075
+ if (!activeId || view !== 'inbox') return;
1076
+ if (Array.isArray(accountIds) && accountIds.length && accountIds.indexOf(activeId) === -1) return;
1077
+ void loadMessages(false);
1078
+ };
929
1079
 
930
1080
  useEffect(() => {
931
1081
  if (!PERSIST.accounts) refreshAccounts();
932
- return () => { if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current); };
1082
+ const off = MAIL_EVENTS.subscribe(ids => onMailRef.current(ids));
1083
+ return () => {
1084
+ off();
1085
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
1086
+ };
933
1087
  }, []);
934
1088
 
935
1089
  function notify(kind, text) {
@@ -955,6 +1109,47 @@ window.__ModuleLoader__.load({
955
1109
  return data;
956
1110
  }
957
1111
 
1112
+ // Account labels are set by the user, not guessed from mail headers: a
1113
+ // mailbox's own display name is only visible after signing in to the
1114
+ // provider, so any guess is unreliable. The default label is the mailbox
1115
+ // prefix and this just persists whatever the user prefers.
1116
+ async function renameAccount(id, name) {
1117
+ const next = String(name == null ? '' : name).trim();
1118
+ if (!next) return false;
1119
+ try {
1120
+ const data = await rpc('renameAccount', { id, name: next });
1121
+ if (data && data.account) {
1122
+ setAccounts(prev => (prev || []).map(a => a.id === data.account.id ? Object.assign({}, a, { name: data.account.name }) : a));
1123
+ }
1124
+ return true;
1125
+ } catch (e) {
1126
+ reportError(e);
1127
+ return false;
1128
+ }
1129
+ }
1130
+
1131
+ function startRename(account) {
1132
+ setRenameId(account.id);
1133
+ setRenameDraft(account.name || defaultAccountName(account.username));
1134
+ }
1135
+
1136
+ function cancelRename() {
1137
+ setRenameId('');
1138
+ setRenameDraft('');
1139
+ }
1140
+
1141
+ async function commitRename(id) {
1142
+ const name = String(renameDraft || '').trim();
1143
+ if (!name) { cancelRename(); return; }
1144
+ setBusy(true);
1145
+ try {
1146
+ const ok = await renameAccount(id, name);
1147
+ if (ok) { notify('success', t('saved')); cancelRename(); }
1148
+ } finally {
1149
+ setBusy(false);
1150
+ }
1151
+ }
1152
+
958
1153
  async function refreshAccounts() {
959
1154
  try {
960
1155
  const data = await rpc('listAccounts');
@@ -1050,7 +1245,6 @@ window.__ModuleLoader__.load({
1050
1245
  const p = PRESETS[preset] || PRESETS.custom;
1051
1246
  setForm(Object.assign({}, form, {
1052
1247
  preset,
1053
- name: preset === 'custom' ? '' : t(p.nameKey),
1054
1248
  imapHost: p.imapHost,
1055
1249
  imapPort: p.imapPort,
1056
1250
  smtpHost: p.smtpHost,
@@ -1062,7 +1256,7 @@ window.__ModuleLoader__.load({
1062
1256
  setBusy(true);
1063
1257
  try {
1064
1258
  await rpc('saveAccount', {
1065
- name: form.name || form.username,
1259
+ name: String(form.name || '').trim() || defaultAccountName(form.username),
1066
1260
  username: form.username,
1067
1261
  authCode: form.authCode,
1068
1262
  imapHost: form.imapHost,
@@ -1131,9 +1325,16 @@ window.__ModuleLoader__.load({
1131
1325
  async function sendMail() {
1132
1326
  setBusy(true);
1133
1327
  try {
1134
- await rpc('sendMessage', { id: activeId, to: compose.to, subject: compose.subject, body: compose.body });
1328
+ await rpc('sendMessage', {
1329
+ id: activeId,
1330
+ to: compose.to,
1331
+ subject: compose.subject,
1332
+ body: compose.body,
1333
+ attachments: composeAtts.map(a => ({ name: a.name, mime: a.mime, content: a.content })),
1334
+ });
1135
1335
  notify('success', t('ok'));
1136
1336
  setCompose({ to: '', subject: '', body: '' });
1337
+ setComposeAtts([]);
1137
1338
  await loadSent();
1138
1339
  setView('sent');
1139
1340
  } catch (e) {
@@ -1143,6 +1344,87 @@ window.__ModuleLoader__.load({
1143
1344
  }
1144
1345
  }
1145
1346
 
1347
+ async function addAttachments(fileList) {
1348
+ const files = Array.from(fileList || []);
1349
+ if (!files.length) return;
1350
+ setAttachBusy(true);
1351
+ try {
1352
+ const next = composeAtts.slice();
1353
+ for (const file of files) {
1354
+ if (next.some(a => a.name === file.name && a.size === file.size)) continue; // 去重同一个文件
1355
+ if (file.size > MAX_ATTACH_BYTES) {
1356
+ notify('error', t('attachmentTooLarge'));
1357
+ continue;
1358
+ }
1359
+ const content = await readFileAsBase64(file);
1360
+ next.push({ name: file.name, size: file.size, mime: file.type || '', content });
1361
+ }
1362
+ const total = next.reduce((sum, a) => sum + (Number(a.size) || 0), 0);
1363
+ if (total > MAX_ATTACH_BYTES) {
1364
+ // 超限时整体拒绝,避免用户以为附件已带上却发送失败。
1365
+ notify('error', t('attachmentTooLarge'));
1366
+ } else {
1367
+ setComposeAtts(next);
1368
+ }
1369
+ } catch (e) {
1370
+ notify('error', t('attachmentFailed') + (e && e.message ? e.message : ''));
1371
+ } finally {
1372
+ setAttachBusy(false);
1373
+ }
1374
+ }
1375
+
1376
+ function removeAttachment(index) {
1377
+ setComposeAtts(prev => prev.filter((_, i) => i !== index));
1378
+ }
1379
+
1380
+ async function downloadAttachment(att) {
1381
+ if (!detail || !activeId) return;
1382
+ const key = String(att.index);
1383
+ setAttachState(prev => Object.assign({}, prev, { [key]: 'loading' }));
1384
+ try {
1385
+ const data = await rpc('getAttachment', { id: activeId, uid: detail.uid, index: att.index });
1386
+ saveAttachmentBytes(data.name || att.name, data.mime || att.mime, data.content);
1387
+ setAttachState(prev => Object.assign({}, prev, { [key]: 'ok' }));
1388
+ } catch (e) {
1389
+ setAttachState(prev => Object.assign({}, prev, { [key]: 'error' }));
1390
+ reportError(e);
1391
+ }
1392
+ }
1393
+
1394
+ // Turn a raw address header ("李文" <li@x.com>) into a contact without
1395
+ // leaving the mail. An entry that already exists is reported instead of
1396
+ // being duplicated, since saveContact would otherwise just overwrite it.
1397
+ function contactKnown(email) {
1398
+ const key = String(email || '').toLowerCase();
1399
+ if (!key) return false;
1400
+ return (contacts || []).some(c => String(c.email || '').toLowerCase() === key);
1401
+ }
1402
+
1403
+ async function addAsContact(raw) {
1404
+ const parsed = parseAddress(raw);
1405
+ if (!parsed) {
1406
+ notify('error', t('emailRequired'));
1407
+ return false;
1408
+ }
1409
+ if (!activeId) return false;
1410
+ if (contactKnown(parsed.email)) {
1411
+ notify('info', t('contactExists'));
1412
+ return false;
1413
+ }
1414
+ setBusy(true);
1415
+ try {
1416
+ const data = await rpc('saveContact', { id: activeId, email: parsed.email, name: parsed.name });
1417
+ if (Array.isArray(data.contacts)) setContacts(data.contacts);
1418
+ notify('success', t('contactAdded'));
1419
+ return true;
1420
+ } catch (e) {
1421
+ reportError(e);
1422
+ return false;
1423
+ } finally {
1424
+ setBusy(false);
1425
+ }
1426
+ }
1427
+
1146
1428
  async function saveContact() {
1147
1429
  const email = String(contactForm.email || '').trim();
1148
1430
  if (!email || !email.includes('@')) {
@@ -1260,8 +1542,8 @@ window.__ModuleLoader__.load({
1260
1542
  ))
1261
1543
  ),
1262
1544
 
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 }),
1545
+ 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')) },
1546
+ h(Ico, { name: flash.kind === 'error' ? 'warning' : (flash.kind === 'info' ? 'inbox' : 'check'), size: 15 }),
1265
1547
  h('span', null, flash.text)
1266
1548
  ),
1267
1549
 
@@ -1329,10 +1611,35 @@ window.__ModuleLoader__.load({
1329
1611
  ? h('div', { className: 'dsh-mail-scroll' },
1330
1612
  h('button', { className: 'dsh-mail-btn', onClick: () => setSentDetail(null) }, h(Ico, { name: 'back', size: 15 }), t('back')),
1331
1613
  h('div', { className: 'dsh-mail-detailhead' },
1332
- h('h2', { className: 'dsh-mail-detailtitle' }, sentDetail.subject || t('noSubject')),
1614
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
1615
+ h('h2', { className: 'dsh-mail-detailtitle' }, sentDetail.subject || t('noSubject')),
1616
+ parseAddress(sentDetail.to)
1617
+ ? h('button', {
1618
+ className: 'dsh-mail-btn' + (contactKnown(parseAddress(sentDetail.to).email) ? ' is-done' : ''),
1619
+ 'data-testid': 'add-recipient',
1620
+ onClick: () => addAsContact(sentDetail.to),
1621
+ disabled: busy,
1622
+ title: t('addRecipient'),
1623
+ }, h(Ico, { name: contactKnown(parseAddress(sentDetail.to).email) ? 'check' : 'plus', size: 14 }), t('addRecipient'))
1624
+ : null
1625
+ ),
1333
1626
  h('div', { className: 'dsh-mail-detailmeta' }, t('to') + ': ' + (sentDetail.to || '') + ' · ' + fmtDate(sentDetail.date))
1334
1627
  ),
1335
- h('div', { className: 'dsh-mail-mailbody', style: { whiteSpace: 'pre-wrap' } }, String(sentDetail.body || ''))
1628
+ h('div', { className: 'dsh-mail-mailbody', style: { whiteSpace: 'pre-wrap' } }, String(sentDetail.body || '')),
1629
+ // Sent mail keeps attachment metadata only (names/sizes), which is
1630
+ // enough to confirm what went out with the message.
1631
+ Array.isArray(sentDetail.attachments) && sentDetail.attachments.length > 0
1632
+ ? h('div', { className: 'dsh-mail-field', style: { marginTop: 14 } },
1633
+ h('span', { className: 'dsh-mail-label' }, t('attachments') + ' (' + sentDetail.attachments.length + ')'),
1634
+ h('div', { className: 'dsh-mail-attachlist' }, sentDetail.attachments.map((att, i) =>
1635
+ h('div', { key: String(att.name) + i, className: 'dsh-mail-attach' },
1636
+ h(Ico, { name: 'attach', size: 14 }),
1637
+ h('span', { className: 'dsh-mail-attach-name', title: att.name }, att.name),
1638
+ att.size ? h('span', { className: 'dsh-mail-attach-size' }, fmtSize(att.size)) : null
1639
+ )
1640
+ ))
1641
+ )
1642
+ : null
1336
1643
  )
1337
1644
  : h('div', { className: 'dsh-mail-view' },
1338
1645
  loadingSent && sent.length === 0
@@ -1400,16 +1707,35 @@ window.__ModuleLoader__.load({
1400
1707
  h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 } },
1401
1708
  h('div', { className: 'dsh-mail-avatar', style: { background: avatarColor(a.username) } }, avatarLetter(a.name || a.username)),
1402
1709
  h('div', { style: { flex: 1, minWidth: 0 } },
1403
- h('div', { style: { fontWeight: 650 } }, a.name),
1710
+ renameId === a.id
1711
+ ? h('input', {
1712
+ className: 'dsh-mail-input',
1713
+ 'data-testid': 'rename-input',
1714
+ value: renameDraft,
1715
+ autoFocus: true,
1716
+ placeholder: defaultAccountName(a.username),
1717
+ onChange: e => setRenameDraft(e.target.value),
1718
+ onKeyDown: e => { if (e.key === 'Enter') commitRename(a.id); if (e.key === 'Escape') cancelRename(); },
1719
+ })
1720
+ : h('div', { style: { fontWeight: 650 } }, a.name || a.username),
1404
1721
  h('div', { className: 'dsh-mail-hint' }, a.username)
1405
1722
  )
1406
1723
  ),
1407
1724
  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
- )
1725
+ renameId === a.id
1726
+ ? h('div', null,
1727
+ h('div', { className: 'dsh-mail-hint', style: { marginBottom: 8 } }, t('renameHint')),
1728
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
1729
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-primary', onClick: () => commitRename(a.id), disabled: busy }, h(Ico, { name: 'check', size: 14 }), t('save')),
1730
+ h('button', { className: 'dsh-mail-btn', onClick: cancelRename, disabled: busy }, t('cancel'))
1731
+ )
1732
+ )
1733
+ : h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
1734
+ h('button', { className: 'dsh-mail-btn', onClick: () => testAccount(a.id), disabled: busy }, h(Ico, { name: 'check', size: 14 }), t('test')),
1735
+ h('button', { className: 'dsh-mail-btn', onClick: () => startRename(a), disabled: busy }, h(Ico, { name: 'compose', size: 14 }), t('rename')),
1736
+ h('button', { className: 'dsh-mail-btn', onClick: () => { setActiveId(a.id); navTo('inbox'); } }, h(Ico, { name: 'inbox', size: 14 }), t('inbox')),
1737
+ h('button', { className: 'dsh-mail-btn dsh-mail-btn-danger', onClick: () => deleteAccount(a.id), disabled: busy }, h(Ico, { name: 'trash', size: 14 }), t('delete'))
1738
+ )
1413
1739
  )),
1414
1740
  h('div', { className: 'dsh-mail-card' },
1415
1741
  h('div', { className: 'dsh-mail-cardhead' }, h(Ico, { name: 'plus', size: 16 }), t('addAccount')),
@@ -1424,7 +1750,7 @@ window.__ModuleLoader__.load({
1424
1750
  h('div', { className: 'dsh-mail-grid' },
1425
1751
  h('div', { className: 'dsh-mail-field' },
1426
1752
  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 })) })
1753
+ 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
1754
  ),
1429
1755
  h('div', { className: 'dsh-mail-field' },
1430
1756
  h('span', { className: 'dsh-mail-label' }, t('username')),
@@ -1472,7 +1798,16 @@ window.__ModuleLoader__.load({
1472
1798
  h('div', { style: { minWidth: 0 } },
1473
1799
  h('div', { style: { fontWeight: 600 } }, String(detail.from || '').replace(/<.*>/, '').trim() || detail.from || ''),
1474
1800
  h('div', { className: 'dsh-mail-detailmeta' }, t('to') + ': ' + (detail.to || '') + ' · ' + fmtDate(detail.date))
1475
- )
1801
+ ),
1802
+ parseAddress(detail.from)
1803
+ ? h('button', {
1804
+ className: 'dsh-mail-btn' + (contactKnown(parseAddress(detail.from).email) ? ' is-done' : ''),
1805
+ 'data-testid': 'add-sender',
1806
+ onClick: () => addAsContact(detail.from),
1807
+ disabled: busy,
1808
+ title: t('addSender'),
1809
+ }, h(Ico, { name: contactKnown(parseAddress(detail.from).email) ? 'check' : 'plus', size: 14 }), t('addSender'))
1810
+ : null
1476
1811
  )
1477
1812
  ),
1478
1813
  h('div', {
@@ -1486,7 +1821,29 @@ window.__ModuleLoader__.load({
1486
1821
  if (window.open) window.open(href, '_blank', 'noopener,noreferrer');
1487
1822
  },
1488
1823
  dangerouslySetInnerHTML: { __html: detail.html || ('<div style="white-space:pre-wrap">' + escHtml(detail.body || '') + '</div>') },
1489
- })
1824
+ }),
1825
+ // Attachments are fetched on demand so opening a mail stays fast.
1826
+ Array.isArray(detail.attachments) && detail.attachments.length > 0
1827
+ ? h('div', { className: 'dsh-mail-field', style: { marginTop: 14 } },
1828
+ h('span', { className: 'dsh-mail-label' }, t('attachments') + ' (' + detail.attachments.length + ')'),
1829
+ h('div', { className: 'dsh-mail-attachlist' }, detail.attachments.map(att =>
1830
+ h('div', { key: String(att.index), className: 'dsh-mail-attach' },
1831
+ h(Ico, { name: 'attach', size: 14 }),
1832
+ h('span', { className: 'dsh-mail-attach-name', title: att.name }, att.name),
1833
+ h('span', { className: 'dsh-mail-attach-size' }, fmtSize(att.size)),
1834
+ h('button', {
1835
+ className: 'dsh-mail-btn' + (attachState[String(att.index)] === 'ok' ? ' dsh-mail-refresh-ok' : attachState[String(att.index)] === 'error' ? ' dsh-mail-refresh-err' : ''),
1836
+ type: 'button',
1837
+ disabled: attachState[String(att.index)] === 'loading',
1838
+ onClick: () => downloadAttachment(att),
1839
+ title: t('downloadAttachment'),
1840
+ },
1841
+ h(Ico, { name: attachState[String(att.index)] === 'ok' ? 'check' : attachState[String(att.index)] === 'error' ? 'warning' : 'download', size: 14 }),
1842
+ t('downloadAttachment'))
1843
+ )
1844
+ ))
1845
+ )
1846
+ : null
1490
1847
  )
1491
1848
  )
1492
1849
  ),
@@ -1498,7 +1855,7 @@ window.__ModuleLoader__.load({
1498
1855
  h('div', { className: 'dsh-mail-cardhead' },
1499
1856
  h(Ico, { name: 'compose', size: 16 }), t('compose'),
1500
1857
  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'))
1858
+ 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
1859
  ),
1503
1860
  h('div', { className: 'dsh-mail-hint', style: { marginBottom: 12 } }, account ? account.username : ''),
1504
1861
  h('div', { className: 'dsh-mail-field' },
@@ -1512,6 +1869,49 @@ window.__ModuleLoader__.load({
1512
1869
  h('div', { className: 'dsh-mail-field' },
1513
1870
  h('span', { className: 'dsh-mail-label' }, t('body')),
1514
1871
  h('textarea', { className: 'dsh-mail-textarea', value: compose.body, onChange: e => setCompose(Object.assign({}, compose, { body: e.target.value })) })
1872
+ ),
1873
+ h('div', { className: 'dsh-mail-field' },
1874
+ h('span', { className: 'dsh-mail-label' }, t('attachments')),
1875
+ h('div', { className: 'dsh-mail-attachbar' },
1876
+ h('label', { className: 'dsh-mail-btn', style: { cursor: 'pointer' } },
1877
+ h(Ico, { name: 'attach', size: 15 }),
1878
+ t('addAttachment'),
1879
+ h('input', {
1880
+ type: 'file', multiple: true,
1881
+ 'data-testid': 'attachment-input',
1882
+ style: { display: 'none' },
1883
+ onChange: e => { void addAttachments(e.target.files); e.target.value = ''; },
1884
+ })
1885
+ ),
1886
+ attachBusy ? h('span', { className: 'dsh-mail-hint' }, t('loading')) : null
1887
+ ),
1888
+ // Dropping files anywhere on this card also adds them.
1889
+ h('div', {
1890
+ className: 'dsh-mail-drop' + (dropOver ? ' is-over' : ''),
1891
+ onDragOver: e => { e.preventDefault(); if (!dropOver) setDropOver(true); },
1892
+ onDragLeave: () => setDropOver(false),
1893
+ onDrop: e => {
1894
+ e.preventDefault();
1895
+ setDropOver(false);
1896
+ if (e.dataTransfer && e.dataTransfer.files) void addAttachments(e.dataTransfer.files);
1897
+ },
1898
+ }, dropOver ? t('addAttachment') : t('attachmentsHint')),
1899
+ composeAtts.length > 0
1900
+ ? h('div', { className: 'dsh-mail-attachlist' }, composeAtts.map((a, i) =>
1901
+ h('div', { key: a.name + '-' + i, className: 'dsh-mail-attach' },
1902
+ h(Ico, { name: 'attach', size: 14 }),
1903
+ h('span', { className: 'dsh-mail-attach-name', title: a.name }, a.name),
1904
+ h('span', { className: 'dsh-mail-attach-size' }, fmtSize(a.size)),
1905
+ h('button', {
1906
+ className: 'dsh-mail-btn dsh-mail-iconbtn',
1907
+ type: 'button',
1908
+ onClick: () => removeAttachment(i),
1909
+ title: t('removeAttachment'),
1910
+ 'aria-label': t('removeAttachment'),
1911
+ }, h(Ico, { name: 'trash', size: 14 }))
1912
+ )
1913
+ ))
1914
+ : null
1515
1915
  )
1516
1916
  )
1517
1917
  )
package/docs/DETAIL.md CHANGED
@@ -1 +1 @@
1
- ![Feature result](preview.svg)
1
+ ![Mail panel: a sidebar entry with an unread dot, a read/unread filter bar, and a mail list with a paperclip attachment action](preview.svg)
@@ -0,0 +1 @@
1
+ ![邮件面板:侧边栏入口带未读小圆点,收件箱有已读/未读筛选,邮件列表右侧带附件回形针操作](preview.svg)
package/docs/preview.svg CHANGED
@@ -1,21 +1,51 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 300" width="640" height="300" role="img" aria-label="Mail panel preview">
2
- <rect width="640" height="300" fill="#f4f6fb"/>
3
- <rect x="24" y="24" width="592" height="252" rx="12" fill="#ffffff" stroke="#d9dfeb"/>
4
- <rect x="24" y="24" width="592" height="44" rx="12" fill="#eef3fc"/>
5
- <circle cx="48" cy="46" r="6" fill="#3b82f6"/>
6
- <text x="64" y="51" font-family="system-ui,sans-serif" font-size="16" font-weight="600" fill="#1f2a44">Mail</text>
7
- <rect x="24" y="68" width="160" height="208" fill="#fafbfe"/>
8
- <rect x="40" y="84" width="128" height="30" rx="6" fill="#e6edfb"/>
9
- <text x="52" y="103" font-family="system-ui,sans-serif" font-size="12" fill="#3451a3">Accounts</text>
10
- <rect x="40" y="124" width="128" height="30" rx="6" fill="#ffffff" stroke="#d9dfeb"/>
11
- <text x="52" y="143" font-family="system-ui,sans-serif" font-size="12" fill="#1f2a44">Inbox</text>
12
- <rect x="200" y="84" width="396" height="44" rx="8" fill="#ffffff" stroke="#d9dfeb"/>
13
- <text x="214" y="111" font-family="system-ui,sans-serif" font-size="13" fill="#1f2a44">Project update</text>
14
- <text x="214" y="126" font-family="system-ui,sans-serif" font-size="10" fill="#7b86a0">alice@example.com · today</text>
15
- <rect x="200" y="136" width="396" height="44" rx="8" fill="#ffffff" stroke="#d9dfeb"/>
16
- <text x="214" y="163" font-family="system-ui,sans-serif" font-size="13" fill="#1f2a44">Re: Meeting notes</text>
17
- <text x="214" y="178" font-family="system-ui,sans-serif" font-size="10" fill="#7b86a0">bob@example.com · yesterday</text>
18
- <rect x="200" y="188" width="396" height="72" rx="8" fill="#f8faff" stroke="#d9dfeb"/>
19
- <rect x="528" y="200" width="56" height="24" rx="6" fill="#3b82f6"/>
20
- <text x="540" y="216" font-family="system-ui,sans-serif" font-size="11" fill="#ffffff">Compose</text>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 300" width="640" height="300" role="img" aria-label="Mail panel: a sidebar entry with an unread dot, a filter bar, and a mail list with an envelope action">
2
+ <!-- Text-free illustration: neutral mid-tones so it reads on both light and dark themes. -->
3
+ <rect x="24" y="24" width="592" height="252" rx="14" fill="#7c8ba6" fill-opacity="0.08" stroke="#7c8ba6" stroke-opacity="0.45"/>
4
+
5
+ <!-- Sidebar with the plugin entry and its unread dot -->
6
+ <rect x="40" y="54" width="132" height="30" rx="8" fill="#3b82f6" fill-opacity="0.18"/>
7
+ <path d="M54 63h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H54a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2z" fill="none" stroke="#3b82f6" stroke-width="1.8" stroke-linejoin="round"/>
8
+ <path d="M52.6 65.4 60 70l7.4-4.6" fill="none" stroke="#3b82f6" stroke-width="1.8" stroke-linecap="round"/>
9
+ <rect x="74" y="64" width="52" height="7" rx="3.5" fill="#7c8ba6" fill-opacity="0.7"/>
10
+ <circle cx="166" cy="69" r="5" fill="#ef4444"/>
11
+
12
+ <rect x="40" y="94" width="132" height="26" rx="8" fill="#7c8ba6" fill-opacity="0.14"/>
13
+ <rect x="54" y="104" width="46" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.55"/>
14
+ <rect x="40" y="128" width="132" height="26" rx="8" fill="#7c8ba6" fill-opacity="0.14"/>
15
+ <rect x="54" y="138" width="60" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.55"/>
16
+ <rect x="40" y="162" width="132" height="26" rx="8" fill="#7c8ba6" fill-opacity="0.14"/>
17
+ <rect x="54" y="172" width="52" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.55"/>
18
+
19
+ <!-- Filter bar: all / unread / read, unread selected -->
20
+ <rect x="196" y="54" width="70" height="24" rx="12" fill="#7c8ba6" fill-opacity="0.16"/>
21
+ <rect x="210" y="63" width="30" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.6"/>
22
+ <rect x="274" y="54" width="70" height="24" rx="12" fill="#3b82f6" fill-opacity="0.22"/>
23
+ <rect x="288" y="63" width="30" height="6" rx="3" fill="#3b82f6"/>
24
+ <rect x="352" y="54" width="70" height="24" rx="12" fill="#7c8ba6" fill-opacity="0.16"/>
25
+ <rect x="366" y="63" width="26" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.6"/>
26
+
27
+ <!-- Unread row with accent bar -->
28
+ <rect x="196" y="92" width="404" height="46" rx="10" fill="#3b82f6" fill-opacity="0.10" stroke="#3b82f6" stroke-opacity="0.45"/>
29
+ <rect x="196" y="98" width="3" height="34" rx="1.5" fill="#3b82f6"/>
30
+ <circle cx="224" cy="115" r="11" fill="#3b82f6" fill-opacity="0.28"/>
31
+ <rect x="244" y="104" width="96" height="7" rx="3.5" fill="#7c8ba6" fill-opacity="0.8"/>
32
+ <rect x="516" y="104" width="34" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.5"/>
33
+ <rect x="244" y="118" width="180" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.55"/>
34
+ <rect x="244" y="130" width="120" height="5" rx="2.5" fill="#7c8ba6" fill-opacity="0.4"/>
35
+
36
+ <!-- Read rows -->
37
+ <rect x="196" y="148" width="404" height="46" rx="10" fill="#7c8ba6" fill-opacity="0.08" stroke="#7c8ba6" stroke-opacity="0.35"/>
38
+ <circle cx="224" cy="171" r="11" fill="#7c8ba6" fill-opacity="0.22"/>
39
+ <rect x="244" y="160" width="120" height="7" rx="3.5" fill="#7c8ba6" fill-opacity="0.6"/>
40
+ <rect x="516" y="160" width="34" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.4"/>
41
+ <rect x="244" y="174" width="150" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.4"/>
42
+
43
+ <!-- Mail opened with a paperclip action at the right -->
44
+ <rect x="196" y="204" width="404" height="52" rx="10" fill="#7c8ba6" fill-opacity="0.08" stroke="#7c8ba6" stroke-opacity="0.35"/>
45
+ <circle cx="224" cy="230" r="11" fill="#7c8ba6" fill-opacity="0.22"/>
46
+ <rect x="244" y="218" width="88" height="7" rx="3.5" fill="#7c8ba6" fill-opacity="0.6"/>
47
+ <rect x="244" y="232" width="132" height="6" rx="3" fill="#7c8ba6" fill-opacity="0.4"/>
48
+ <!-- paperclip -->
49
+ <path d="M528 224c-4-4-11-4-15 0l-11 11c-6 6-6 15 0 21s15 6 21 0l9-9" fill="none" stroke="#3b82f6" stroke-width="2.4" stroke-linecap="round"/>
50
+ <path d="M519 233l-10 10c-3 3-3 7 0 10s7 3 10 0l8-8c4-4 4-11 0-15" fill="none" stroke="#3b82f6" stroke-width="2.4" stroke-linecap="round"/>
21
51
  </svg>
package/index.js CHANGED
@@ -220,6 +220,18 @@ async function handleRequest(ctx, request) {
220
220
  }));
221
221
  return json({ ok: true, account: publicAccount(id, payload) });
222
222
  }
223
+ case 'renameAccount': {
224
+ // The account label is user-chosen and local to this machine, so nothing
225
+ // is read from the mailbox or any online profile API.
226
+ const id = String(body.id || '');
227
+ const name = String(body.name || '').trim();
228
+ if (!id) return json({ ok: false, error: 'id is required' }, 400);
229
+ if (!name) return json({ ok: false, error: 'name is required' }, 400);
230
+ const payload = await getAccountPayload(ctx, id);
231
+ const next = Object.assign({}, payload, { name });
232
+ await ctx.credentials.modifyRecord(recordKey(id), async () => ({ kind: 'grant', payload: next }));
233
+ return json({ ok: true, account: publicAccount(id, next) });
234
+ }
223
235
  case 'deleteAccount': {
224
236
  const id = String(body.id || '');
225
237
  if (!id) return json({ ok: false, error: 'id is required' }, 400);
@@ -246,17 +258,38 @@ async function handleRequest(ctx, request) {
246
258
  folder: body.folder || 'INBOX',
247
259
  }));
248
260
  }
261
+ case 'getAttachment': {
262
+ const payload = await getAccountPayload(ctx, String(body.id || ''));
263
+ return json(await runBridge('getAttachment', {
264
+ account: bridgeAccount(payload),
265
+ uid: String(body.uid || ''),
266
+ folder: body.folder || 'INBOX',
267
+ index: Number(body.index) || 0,
268
+ }));
269
+ }
249
270
  case 'sendMessage': {
250
271
  const id = String(body.id || '');
251
272
  const payload = await getAccountPayload(ctx, id);
252
273
  const to = String(body.to || '').trim();
253
274
  if (!to) return json({ ok: false, error: 'to is required' }, 400);
275
+ const attachments = Array.isArray(body.attachments) ? body.attachments : [];
276
+ // Guard the outbound path: each attachment arrives base64-encoded in the
277
+ // request body and is buffered in memory on both sides of the bridge.
278
+ let totalBytes = 0;
279
+ for (const att of attachments) {
280
+ const content = String((att && att.content) || '');
281
+ if (!content) continue;
282
+ totalBytes += Math.floor((content.length * 3) / 4);
283
+ }
284
+ if (totalBytes > 25 * 1024 * 1024) {
285
+ return json({ ok: false, error: '附件总大小超过 25 MB,请分开发送。' }, 400);
286
+ }
254
287
  const result = await runBridge('sendMessage', {
255
288
  account: bridgeAccount(payload),
256
289
  to,
257
290
  subject: String(body.subject || ''),
258
291
  body: String(body.body || ''),
259
- attachments: Array.isArray(body.attachments) ? body.attachments : [],
292
+ attachments,
260
293
  });
261
294
  if (result.ok) {
262
295
  // Keep a local outbox record as an instant, offline-capable mirror of
@@ -270,6 +303,11 @@ async function handleRequest(ctx, request) {
270
303
  subject: String(body.subject || ''),
271
304
  body: String(body.body || ''),
272
305
  date: new Date().toISOString(),
306
+ attachments: attachments.map(a => ({
307
+ name: String((a && a.name) || 'attachment'),
308
+ size: Math.floor((String((a && a.content) || '').length * 3) / 4),
309
+ mime: String((a && a.mime) || ''),
310
+ })),
273
311
  });
274
312
  await writeData(ctx, outboxKey(id), { sent: list.slice(0, 200) });
275
313
  } catch {
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Mail",
4
- "description": "Send and receive email from QQ, 163, Gmail and other IMAP/SMTP accounts.",
4
+ "description": "Send and receive email from QQ, 163, Gmail and other IMAP/SMTP accounts, with attachments, an unread badge, read/unread filters, and new-mail alerts via a desktop pet or system notification. Credentials stay in the local vault.",
5
5
  "detail": "docs/DETAIL.md"
6
6
  },
7
7
  "ui": {
package/locale/zh.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "邮件",
4
- "description": "通过 QQ、163、Gmail 等 IMAP/SMTP 邮箱收发邮件。",
5
- "detail": "docs/DETAIL.md"
4
+ "description": "通过 QQ、163、Gmail 等 IMAP/SMTP 邮箱收发邮件,支持附件、未读角标与已读/未读筛选、新邮件提醒(桌宠播报或系统通知),授权码保存在本机凭据保险箱。",
5
+ "detail": "docs/DETAIL.zh.md"
6
6
  },
7
7
  "ui": {
8
8
  "label": "邮件",
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@mysterycode-liwen/dsh-mail",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "private": false,
5
5
  "type": "module",
6
- "description": "DeepSeek Harness 侧边栏邮件插件:在左侧栏收发 QQ / 163 / Gmail 等邮箱,IMAP 收信 + SMTP 发信,授权码保存在本机凭据保险箱。",
6
+ "description": "DeepSeek Harness 侧边栏邮件插件:在左侧栏收发 QQ / 163 / Gmail 等邮箱,IMAP 收信 + SMTP 发信,支持附件、未读角标与已读/未读筛选、新邮件提醒,授权码保存在本机凭据保险箱。",
7
7
  "license": "MIT",
8
8
  "author": "李文 <59386344+mysterycode-liwen@users.noreply.github.com>",
9
9
  "homepage": "https://github.com/mysterycode-liwen/dsh-email#readme",