@bobfrankston/rmfmail 1.0.467

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.
Files changed (330) hide show
  1. package/README.md +429 -0
  2. package/bin/build-icon-ico.js +283 -0
  3. package/bin/lean-accounts.js +172 -0
  4. package/bin/mailx.js +1580 -0
  5. package/bin/mailx.js.map +1 -0
  6. package/bin/mailx.ts +1549 -0
  7. package/bin/postinstall.js +39 -0
  8. package/bin/postinstall.js.map +1 -0
  9. package/bin/postinstall.ts +41 -0
  10. package/bin/tsconfig.json +10 -0
  11. package/client/.gitattributes +10 -0
  12. package/client/.msger-window.json +1 -0
  13. package/client/android.html +226 -0
  14. package/client/app.js +3400 -0
  15. package/client/app.js.map +1 -0
  16. package/client/app.ts +3190 -0
  17. package/client/components/address-book.js +199 -0
  18. package/client/components/address-book.js.map +1 -0
  19. package/client/components/address-book.ts +204 -0
  20. package/client/components/alarms.js +299 -0
  21. package/client/components/alarms.js.map +1 -0
  22. package/client/components/alarms.ts +276 -0
  23. package/client/components/calendar-sidebar.js +508 -0
  24. package/client/components/calendar-sidebar.js.map +1 -0
  25. package/client/components/calendar-sidebar.ts +474 -0
  26. package/client/components/calendar.js +217 -0
  27. package/client/components/calendar.js.map +1 -0
  28. package/client/components/calendar.ts +211 -0
  29. package/client/components/context-menu.js +80 -0
  30. package/client/components/context-menu.js.map +1 -0
  31. package/client/components/context-menu.ts +95 -0
  32. package/client/components/folder-picker.js +119 -0
  33. package/client/components/folder-picker.js.map +1 -0
  34. package/client/components/folder-picker.ts +127 -0
  35. package/client/components/folder-tree.js +1093 -0
  36. package/client/components/folder-tree.js.map +1 -0
  37. package/client/components/folder-tree.ts +1069 -0
  38. package/client/components/message-list.js +1140 -0
  39. package/client/components/message-list.js.map +1 -0
  40. package/client/components/message-list.ts +1129 -0
  41. package/client/components/message-viewer.js +1291 -0
  42. package/client/components/message-viewer.js.map +1 -0
  43. package/client/components/message-viewer.ts +1257 -0
  44. package/client/components/outbox-view.js +104 -0
  45. package/client/components/outbox-view.js.map +1 -0
  46. package/client/components/outbox-view.ts +102 -0
  47. package/client/components/tasks.js +261 -0
  48. package/client/components/tasks.js.map +1 -0
  49. package/client/components/tasks.ts +234 -0
  50. package/client/compose/compose.css +560 -0
  51. package/client/compose/compose.html +52 -0
  52. package/client/compose/compose.js +1289 -0
  53. package/client/compose/compose.js.map +1 -0
  54. package/client/compose/compose.ts +1231 -0
  55. package/client/compose/editor.js +616 -0
  56. package/client/compose/editor.js.map +1 -0
  57. package/client/compose/editor.ts +599 -0
  58. package/client/compose/ghost-text.js +122 -0
  59. package/client/compose/ghost-text.js.map +1 -0
  60. package/client/compose/ghost-text.ts +140 -0
  61. package/client/favicon.svg +11 -0
  62. package/client/icon.ico +0 -0
  63. package/client/icon.png +0 -0
  64. package/client/index.html +230 -0
  65. package/client/lib/android-bootstrap.js +9 -0
  66. package/client/lib/android-bootstrap.js.map +1 -0
  67. package/client/lib/android-bootstrap.ts +9 -0
  68. package/client/lib/api-client.js +378 -0
  69. package/client/lib/api-client.js.map +1 -0
  70. package/client/lib/api-client.ts +439 -0
  71. package/client/lib/local-service.js +603 -0
  72. package/client/lib/local-service.js.map +1 -0
  73. package/client/lib/local-service.ts +646 -0
  74. package/client/lib/local-store.js +214 -0
  75. package/client/lib/local-store.js.map +1 -0
  76. package/client/lib/local-store.ts +283 -0
  77. package/client/lib/mailxapi.js +304 -0
  78. package/client/lib/message-state.js +132 -0
  79. package/client/lib/message-state.js.map +1 -0
  80. package/client/lib/message-state.ts +160 -0
  81. package/client/package.json +16 -0
  82. package/client/styles/components.css +2049 -0
  83. package/client/styles/layout.css +332 -0
  84. package/client/styles/variables.css +85 -0
  85. package/client/tsconfig.json +19 -0
  86. package/package.json +124 -0
  87. package/packages/mailx-api/.gitattributes +10 -0
  88. package/packages/mailx-api/index.d.ts +10 -0
  89. package/packages/mailx-api/index.d.ts.map +1 -0
  90. package/packages/mailx-api/index.js +322 -0
  91. package/packages/mailx-api/index.js.map +1 -0
  92. package/packages/mailx-api/index.ts +283 -0
  93. package/packages/mailx-api/package.json +27 -0
  94. package/packages/mailx-api/tsconfig.json +9 -0
  95. package/packages/mailx-api/tsconfig.tsbuildinfo +1 -0
  96. package/packages/mailx-compose/.gitattributes +10 -0
  97. package/packages/mailx-compose/index.d.ts +21 -0
  98. package/packages/mailx-compose/index.d.ts.map +1 -0
  99. package/packages/mailx-compose/index.js +61 -0
  100. package/packages/mailx-compose/index.js.map +1 -0
  101. package/packages/mailx-compose/index.ts +85 -0
  102. package/packages/mailx-compose/package.json +18 -0
  103. package/packages/mailx-compose/tsconfig.json +9 -0
  104. package/packages/mailx-core/index.d.ts +139 -0
  105. package/packages/mailx-core/index.d.ts.map +1 -0
  106. package/packages/mailx-core/index.js +403 -0
  107. package/packages/mailx-core/index.js.map +1 -0
  108. package/packages/mailx-core/index.ts +424 -0
  109. package/packages/mailx-core/ipc.d.ts +13 -0
  110. package/packages/mailx-core/ipc.d.ts.map +1 -0
  111. package/packages/mailx-core/ipc.js +56 -0
  112. package/packages/mailx-core/ipc.js.map +1 -0
  113. package/packages/mailx-core/ipc.ts +62 -0
  114. package/packages/mailx-core/package.json +18 -0
  115. package/packages/mailx-core/tsconfig.json +9 -0
  116. package/packages/mailx-host/.gitattributes +10 -0
  117. package/packages/mailx-host/index.d.ts +21 -0
  118. package/packages/mailx-host/index.d.ts.map +1 -0
  119. package/packages/mailx-host/index.js +29 -0
  120. package/packages/mailx-host/index.js.map +1 -0
  121. package/packages/mailx-host/index.ts +38 -0
  122. package/packages/mailx-host/package.json +23 -0
  123. package/packages/mailx-host/tsconfig.json +9 -0
  124. package/packages/mailx-host/types-shim.d.ts +14 -0
  125. package/packages/mailx-imap/.gitattributes +10 -0
  126. package/packages/mailx-imap/index.d.ts +442 -0
  127. package/packages/mailx-imap/index.d.ts.map +1 -0
  128. package/packages/mailx-imap/index.js +3684 -0
  129. package/packages/mailx-imap/index.js.map +1 -0
  130. package/packages/mailx-imap/index.ts +3652 -0
  131. package/packages/mailx-imap/package-lock.json +131 -0
  132. package/packages/mailx-imap/package.json +28 -0
  133. package/packages/mailx-imap/providers/gmail-api.d.ts +8 -0
  134. package/packages/mailx-imap/providers/gmail-api.d.ts.map +1 -0
  135. package/packages/mailx-imap/providers/gmail-api.js +8 -0
  136. package/packages/mailx-imap/providers/gmail-api.js.map +1 -0
  137. package/packages/mailx-imap/providers/gmail-api.ts +8 -0
  138. package/packages/mailx-imap/providers/outlook-api.ts +7 -0
  139. package/packages/mailx-imap/providers/types.d.ts +9 -0
  140. package/packages/mailx-imap/providers/types.d.ts.map +1 -0
  141. package/packages/mailx-imap/providers/types.js +9 -0
  142. package/packages/mailx-imap/providers/types.js.map +1 -0
  143. package/packages/mailx-imap/providers/types.ts +9 -0
  144. package/packages/mailx-imap/tsconfig.json +9 -0
  145. package/packages/mailx-imap/tsconfig.tsbuildinfo +1 -0
  146. package/packages/mailx-send/.gitattributes +10 -0
  147. package/packages/mailx-send/README.md +217 -0
  148. package/packages/mailx-send/cli-queue.d.ts +11 -0
  149. package/packages/mailx-send/cli-queue.d.ts.map +1 -0
  150. package/packages/mailx-send/cli-queue.js +59 -0
  151. package/packages/mailx-send/cli-queue.js.map +1 -0
  152. package/packages/mailx-send/cli-queue.ts +62 -0
  153. package/packages/mailx-send/cli-send.d.ts +17 -0
  154. package/packages/mailx-send/cli-send.d.ts.map +1 -0
  155. package/packages/mailx-send/cli-send.js +75 -0
  156. package/packages/mailx-send/cli-send.js.map +1 -0
  157. package/packages/mailx-send/cli-send.ts +83 -0
  158. package/packages/mailx-send/cli.d.ts +22 -0
  159. package/packages/mailx-send/cli.d.ts.map +1 -0
  160. package/packages/mailx-send/cli.js +115 -0
  161. package/packages/mailx-send/cli.js.map +1 -0
  162. package/packages/mailx-send/cli.ts +126 -0
  163. package/packages/mailx-send/index.d.ts +77 -0
  164. package/packages/mailx-send/index.d.ts.map +1 -0
  165. package/packages/mailx-send/index.js +264 -0
  166. package/packages/mailx-send/index.js.map +1 -0
  167. package/packages/mailx-send/index.ts +333 -0
  168. package/packages/mailx-send/mailsend/README.md +133 -0
  169. package/packages/mailx-send/mailsend/cli.d.ts +12 -0
  170. package/packages/mailx-send/mailsend/cli.d.ts.map +1 -0
  171. package/packages/mailx-send/mailsend/cli.js +70 -0
  172. package/packages/mailx-send/mailsend/cli.js.map +1 -0
  173. package/packages/mailx-send/mailsend/cli.ts +81 -0
  174. package/packages/mailx-send/mailsend/index.d.ts +77 -0
  175. package/packages/mailx-send/mailsend/index.d.ts.map +1 -0
  176. package/packages/mailx-send/mailsend/index.js +264 -0
  177. package/packages/mailx-send/mailsend/index.js.map +1 -0
  178. package/packages/mailx-send/mailsend/index.ts +333 -0
  179. package/packages/mailx-send/mailsend/package-lock.json +65 -0
  180. package/packages/mailx-send/mailsend/package.json +26 -0
  181. package/packages/mailx-send/mailsend/tsconfig.json +21 -0
  182. package/packages/mailx-send/package-lock.json +65 -0
  183. package/packages/mailx-send/package.json +37 -0
  184. package/packages/mailx-send/tsconfig.json +21 -0
  185. package/packages/mailx-server/.gitattributes +10 -0
  186. package/packages/mailx-server/index.d.ts +8 -0
  187. package/packages/mailx-server/index.d.ts.map +1 -0
  188. package/packages/mailx-server/index.js +397 -0
  189. package/packages/mailx-server/index.js.map +1 -0
  190. package/packages/mailx-server/index.ts +429 -0
  191. package/packages/mailx-server/package.json +28 -0
  192. package/packages/mailx-server/tsconfig.json +9 -0
  193. package/packages/mailx-server/tsconfig.tsbuildinfo +1 -0
  194. package/packages/mailx-service/google-sync.d.ts +96 -0
  195. package/packages/mailx-service/google-sync.d.ts.map +1 -0
  196. package/packages/mailx-service/google-sync.js +153 -0
  197. package/packages/mailx-service/google-sync.js.map +1 -0
  198. package/packages/mailx-service/google-sync.ts +238 -0
  199. package/packages/mailx-service/index.d.ts +366 -0
  200. package/packages/mailx-service/index.d.ts.map +1 -0
  201. package/packages/mailx-service/index.js +2589 -0
  202. package/packages/mailx-service/index.js.map +1 -0
  203. package/packages/mailx-service/index.ts +2512 -0
  204. package/packages/mailx-service/jsonrpc.d.ts +25 -0
  205. package/packages/mailx-service/jsonrpc.d.ts.map +1 -0
  206. package/packages/mailx-service/jsonrpc.js +238 -0
  207. package/packages/mailx-service/jsonrpc.js.map +1 -0
  208. package/packages/mailx-service/jsonrpc.ts +268 -0
  209. package/packages/mailx-service/package.json +22 -0
  210. package/packages/mailx-service/tsconfig.json +9 -0
  211. package/packages/mailx-settings/.gitattributes +10 -0
  212. package/packages/mailx-settings/cloud.d.ts +47 -0
  213. package/packages/mailx-settings/cloud.d.ts.map +1 -0
  214. package/packages/mailx-settings/cloud.js +408 -0
  215. package/packages/mailx-settings/cloud.js.map +1 -0
  216. package/packages/mailx-settings/cloud.ts +393 -0
  217. package/packages/mailx-settings/index.d.ts +140 -0
  218. package/packages/mailx-settings/index.d.ts.map +1 -0
  219. package/packages/mailx-settings/index.js +872 -0
  220. package/packages/mailx-settings/index.js.map +1 -0
  221. package/packages/mailx-settings/index.ts +908 -0
  222. package/packages/mailx-settings/package.json +20 -0
  223. package/packages/mailx-settings/tsconfig.json +9 -0
  224. package/packages/mailx-settings/tsconfig.tsbuildinfo +1 -0
  225. package/packages/mailx-store/.gitattributes +10 -0
  226. package/packages/mailx-store/db.d.ts +346 -0
  227. package/packages/mailx-store/db.d.ts.map +1 -0
  228. package/packages/mailx-store/db.js +1796 -0
  229. package/packages/mailx-store/db.js.map +1 -0
  230. package/packages/mailx-store/db.ts +2007 -0
  231. package/packages/mailx-store/file-store.d.ts +36 -0
  232. package/packages/mailx-store/file-store.d.ts.map +1 -0
  233. package/packages/mailx-store/file-store.js +80 -0
  234. package/packages/mailx-store/file-store.js.map +1 -0
  235. package/packages/mailx-store/file-store.ts +82 -0
  236. package/packages/mailx-store/index.d.ts +7 -0
  237. package/packages/mailx-store/index.d.ts.map +1 -0
  238. package/packages/mailx-store/index.js +7 -0
  239. package/packages/mailx-store/index.js.map +1 -0
  240. package/packages/mailx-store/index.ts +7 -0
  241. package/packages/mailx-store/package.json +19 -0
  242. package/packages/mailx-store/tsconfig.json +9 -0
  243. package/packages/mailx-store/tsconfig.tsbuildinfo +1 -0
  244. package/packages/mailx-store-web/android-bootstrap.d.ts +16 -0
  245. package/packages/mailx-store-web/android-bootstrap.d.ts.map +1 -0
  246. package/packages/mailx-store-web/android-bootstrap.js +1247 -0
  247. package/packages/mailx-store-web/android-bootstrap.js.map +1 -0
  248. package/packages/mailx-store-web/android-bootstrap.ts +1262 -0
  249. package/packages/mailx-store-web/db.d.ts +132 -0
  250. package/packages/mailx-store-web/db.d.ts.map +1 -0
  251. package/packages/mailx-store-web/db.js +642 -0
  252. package/packages/mailx-store-web/db.js.map +1 -0
  253. package/packages/mailx-store-web/db.ts +756 -0
  254. package/packages/mailx-store-web/gmail-api-web.d.ts +11 -0
  255. package/packages/mailx-store-web/gmail-api-web.d.ts.map +1 -0
  256. package/packages/mailx-store-web/gmail-api-web.js +11 -0
  257. package/packages/mailx-store-web/gmail-api-web.js.map +1 -0
  258. package/packages/mailx-store-web/gmail-api-web.ts +11 -0
  259. package/packages/mailx-store-web/imap-web-provider.d.ts +33 -0
  260. package/packages/mailx-store-web/imap-web-provider.d.ts.map +1 -0
  261. package/packages/mailx-store-web/imap-web-provider.js +140 -0
  262. package/packages/mailx-store-web/imap-web-provider.js.map +1 -0
  263. package/packages/mailx-store-web/imap-web-provider.ts +156 -0
  264. package/packages/mailx-store-web/index.d.ts +10 -0
  265. package/packages/mailx-store-web/index.d.ts.map +1 -0
  266. package/packages/mailx-store-web/index.js +10 -0
  267. package/packages/mailx-store-web/index.js.map +1 -0
  268. package/packages/mailx-store-web/index.ts +10 -0
  269. package/packages/mailx-store-web/main-thread-host.d.ts +15 -0
  270. package/packages/mailx-store-web/main-thread-host.d.ts.map +1 -0
  271. package/packages/mailx-store-web/main-thread-host.js +292 -0
  272. package/packages/mailx-store-web/main-thread-host.js.map +1 -0
  273. package/packages/mailx-store-web/main-thread-host.ts +322 -0
  274. package/packages/mailx-store-web/package.json +23 -0
  275. package/packages/mailx-store-web/provider-types.d.ts +7 -0
  276. package/packages/mailx-store-web/provider-types.d.ts.map +1 -0
  277. package/packages/mailx-store-web/provider-types.js +7 -0
  278. package/packages/mailx-store-web/provider-types.js.map +1 -0
  279. package/packages/mailx-store-web/provider-types.ts +7 -0
  280. package/packages/mailx-store-web/sql-wasm-esm.js +10 -0
  281. package/packages/mailx-store-web/sql.js.d.ts +29 -0
  282. package/packages/mailx-store-web/sync-manager.d.ts +68 -0
  283. package/packages/mailx-store-web/sync-manager.d.ts.map +1 -0
  284. package/packages/mailx-store-web/sync-manager.js +506 -0
  285. package/packages/mailx-store-web/sync-manager.js.map +1 -0
  286. package/packages/mailx-store-web/sync-manager.ts +508 -0
  287. package/packages/mailx-store-web/tsconfig.json +10 -0
  288. package/packages/mailx-store-web/web-jsonrpc.d.ts +20 -0
  289. package/packages/mailx-store-web/web-jsonrpc.d.ts.map +1 -0
  290. package/packages/mailx-store-web/web-jsonrpc.js +102 -0
  291. package/packages/mailx-store-web/web-jsonrpc.js.map +1 -0
  292. package/packages/mailx-store-web/web-jsonrpc.ts +116 -0
  293. package/packages/mailx-store-web/web-message-store.d.ts +16 -0
  294. package/packages/mailx-store-web/web-message-store.d.ts.map +1 -0
  295. package/packages/mailx-store-web/web-message-store.js +89 -0
  296. package/packages/mailx-store-web/web-message-store.js.map +1 -0
  297. package/packages/mailx-store-web/web-message-store.ts +97 -0
  298. package/packages/mailx-store-web/web-service.d.ts +111 -0
  299. package/packages/mailx-store-web/web-service.d.ts.map +1 -0
  300. package/packages/mailx-store-web/web-service.js +542 -0
  301. package/packages/mailx-store-web/web-service.js.map +1 -0
  302. package/packages/mailx-store-web/web-service.ts +616 -0
  303. package/packages/mailx-store-web/web-settings.d.ts +83 -0
  304. package/packages/mailx-store-web/web-settings.d.ts.map +1 -0
  305. package/packages/mailx-store-web/web-settings.js +491 -0
  306. package/packages/mailx-store-web/web-settings.js.map +1 -0
  307. package/packages/mailx-store-web/web-settings.ts +522 -0
  308. package/packages/mailx-store-web/worker-bundle.js +6838 -0
  309. package/packages/mailx-store-web/worker-entry.d.ts +8 -0
  310. package/packages/mailx-store-web/worker-entry.d.ts.map +1 -0
  311. package/packages/mailx-store-web/worker-entry.js +187 -0
  312. package/packages/mailx-store-web/worker-entry.js.map +1 -0
  313. package/packages/mailx-store-web/worker-entry.ts +215 -0
  314. package/packages/mailx-store-web/worker-tcp-transport.d.ts +28 -0
  315. package/packages/mailx-store-web/worker-tcp-transport.d.ts.map +1 -0
  316. package/packages/mailx-store-web/worker-tcp-transport.js +98 -0
  317. package/packages/mailx-store-web/worker-tcp-transport.js.map +1 -0
  318. package/packages/mailx-store-web/worker-tcp-transport.ts +101 -0
  319. package/packages/mailx-types/.gitattributes +10 -0
  320. package/packages/mailx-types/index.d.ts +319 -0
  321. package/packages/mailx-types/index.d.ts.map +1 -0
  322. package/packages/mailx-types/index.js +243 -0
  323. package/packages/mailx-types/index.js.map +1 -0
  324. package/packages/mailx-types/index.ts +498 -0
  325. package/packages/mailx-types/package.json +16 -0
  326. package/packages/mailx-types/tsconfig.json +9 -0
  327. package/packages/mailx-types/tsconfig.tsbuildinfo +1 -0
  328. package/todo.json +13 -0
  329. package/tsconfig.base.json +31 -0
  330. package/tsconfig.json +9 -0
package/bin/mailx.ts ADDED
@@ -0,0 +1,1549 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * rmfmail -- email client
4
+ *
5
+ * Usage:
6
+ * rmfmail Start service + open in msger (IPC, no TCP)
7
+ * rmfmail --server Start Express HTTP server (dev/remote)
8
+ * rmfmail --no-browser Start server only (headless)
9
+ * rmfmail --verbose Show console output (default: log file only)
10
+ * rmfmail --email <addr> First-time setup with email (skips prompt)
11
+ * rmfmail --import <file> Import accounts.jsonc into GDrive and merge
12
+ * rmfmail -v / --version Show version and exit
13
+ * rmfmail -kill Kill running rmfmail processes
14
+ * rmfmail -setup Interactive first-time setup (CLI)
15
+ * rmfmail -test Test IMAP/SMTP connectivity
16
+ * rmfmail -rebuild Wipe local cache, re-sync from IMAP
17
+ * rmfmail -repair Re-sync metadata (fix corrupt subjects) keeping .eml files
18
+ * rmfmail -reauth Clear cached OAuth tokens; next start re-consents
19
+ * (use when new Google scopes have been added)
20
+ */
21
+
22
+ import fs from "node:fs";
23
+ import path from "node:path";
24
+ import os from "node:os";
25
+ import net from "node:net";
26
+ import { ports } from "@bobfrankston/miscinfo";
27
+ import { showMessageBox, showService, setAppName, setAppIcon } from "@bobfrankston/mailx-host";
28
+
29
+ setAppName("rmfmail");
30
+ // Prefer the .ico (Windows Explorer / taskbar-pin shortcut uses the embedded
31
+ // icon resource of the pinned exe, or a Windows icon resource referenced
32
+ // via PKEY_AppUserModel_RelaunchIconResource — PNG can't play either role).
33
+ // Fall back to PNG for the in-window / tao-level icon on non-Windows.
34
+ {
35
+ const icoPath = path.resolve(import.meta.dirname, "..", "client", "icon.ico");
36
+ const pngPath = path.resolve(import.meta.dirname, "..", "client", "icon.png");
37
+ setAppIcon(fs.existsSync(icoPath) ? icoPath : pngPath);
38
+ }
39
+ const PORT = ports.mailx;
40
+ const args = process.argv.slice(2);
41
+
42
+ // Normalize: accept both -flag and --flag
43
+ function hasFlag(name: string): boolean { return args.includes(`-${name}`) || args.includes(`--${name}`); }
44
+
45
+ const verbose = hasFlag("verbose");
46
+ const isDaemon = hasFlag("daemon"); // internal: re-spawned detached process
47
+
48
+ // Read our own version once — used for the instance file + upgrade check below.
49
+ const __selfRoot = path.join(import.meta.dirname, "..");
50
+ const __selfVersion: string = (() => {
51
+ try { return JSON.parse(fs.readFileSync(path.join(__selfRoot, "package.json"), "utf-8")).version || "unknown"; }
52
+ catch { return "unknown"; }
53
+ })();
54
+ const __instanceFile = path.join(process.env.USERPROFILE || process.env.HOME || ".", ".rmfmail", "instance.json");
55
+
56
+ function readInstanceFile(): { pid: number; version: string; startedAt: number } | null {
57
+ try {
58
+ const raw = fs.readFileSync(__instanceFile, "utf-8");
59
+ const inst = JSON.parse(raw);
60
+ if (typeof inst.pid === "number" && typeof inst.version === "string") return inst;
61
+ } catch { /* missing or unreadable — treated as no instance */ }
62
+ return null;
63
+ }
64
+ function writeInstanceFile(pid: number): void {
65
+ try {
66
+ fs.mkdirSync(path.dirname(__instanceFile), { recursive: true });
67
+ fs.writeFileSync(__instanceFile, JSON.stringify({ pid, version: __selfVersion, startedAt: Date.now() }, null, 2));
68
+ } catch { /* non-fatal */ }
69
+ }
70
+ function clearInstanceFile(): void {
71
+ try { fs.unlinkSync(__instanceFile); } catch { /* ignore */ }
72
+ }
73
+ function pidAlive(pid: number): boolean {
74
+ try { process.kill(pid, 0); return true; } catch { return false; }
75
+ }
76
+ /** True only if `pid` is alive AND its command line looks like a rmfmail node
77
+ * process. Windows reuses PIDs aggressively — a rmfmail that exited without
78
+ * running its cleanup handler can leave behind an instance.json whose PID
79
+ * has since been recycled by some other app (e.g. Creative Cloud UI Helper),
80
+ * making bare pidAlive() return true and wedging every subsequent `mailx`
81
+ * with "already running". Verify it's actually us. Non-Windows: fall back
82
+ * to pidAlive — POSIX PID reuse is rare enough that we don't bother. */
83
+ function pidIsMailx(pid: number): boolean {
84
+ if (!pidAlive(pid)) return false;
85
+ if (process.platform !== "win32") return true;
86
+ try {
87
+ const { execSync } = require("node:child_process");
88
+ const out = execSync(
89
+ `powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId=${pid}\\").CommandLine"`,
90
+ { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true },
91
+ ).toString();
92
+ return /(?:rmfmail|mailx)[\\\/](?:bin|packages|app)|mailx-server/i.test(out);
93
+ } catch { return false; }
94
+ }
95
+
96
+ // Version-mismatch upgrade: if a daemon from an older version is running when
97
+ // the user types `mailx`, kill it so the new one can take over. Without this,
98
+ // a second invocation would silently no-op (daemon exists), leaving the user
99
+ // on an old UI with no indication that the install has been upgraded.
100
+ // Skip this logic for command-only flags (kill, rebuild, setup, ...) and for
101
+ // the internal --daemon respawn.
102
+ const __commandFlags = ["kill", "v", "version", "setup", "add", "test", "rebuild", "repair", "import", "log", "reauth"];
103
+ const __isCommandInvocation = process.argv.slice(2).some(a => __commandFlags.includes(a.replace(/^--?/, "")));
104
+ if (!isDaemon && !__isCommandInvocation) {
105
+ const inst = readInstanceFile();
106
+ if (inst && pidIsMailx(inst.pid)) {
107
+ if (inst.version !== __selfVersion) {
108
+ console.log(`rmfmail: upgrading running daemon (PID ${inst.pid}) from v${inst.version} → v${__selfVersion}`);
109
+ try { process.kill(inst.pid, "SIGTERM"); } catch { /* already gone */ }
110
+ // Give it ~1.5s to exit gracefully, then verify
111
+ const deadline = Date.now() + 2000;
112
+ while (Date.now() < deadline && pidAlive(inst.pid)) {
113
+ const sab = new SharedArrayBuffer(4);
114
+ Atomics.wait(new Int32Array(sab), 0, 0, 100); // 100ms nap
115
+ }
116
+ if (pidAlive(inst.pid)) {
117
+ try { process.kill(inst.pid, "SIGKILL"); } catch { /* */ }
118
+ }
119
+ clearInstanceFile();
120
+ } else {
121
+ // Same version already running — nothing to do. Print so the user
122
+ // knows why `mailx` seems to have done nothing.
123
+ console.log(`rmfmail v${__selfVersion} is already running (PID ${inst.pid}). Use rmfmail -kill to stop it.`);
124
+ process.exit(0);
125
+ }
126
+ } else if (inst) {
127
+ // Stale instance file — PID is dead. Clean up.
128
+ clearInstanceFile();
129
+ }
130
+ }
131
+
132
+ // Auto-detach: re-spawn as background process so terminal returns immediately
133
+ // Skip for: --verbose (want console), --daemon (already detached),
134
+ // and any command flags (setup, kill, test, etc.)
135
+ if (!verbose && !isDaemon && !process.argv.slice(2).some(a => /^-/.test(a))) {
136
+ const { spawn } = await import("node:child_process");
137
+ const child = spawn(process.execPath, [...process.argv.slice(1), "--daemon"], {
138
+ // windowsHide on the spawn options below — prevents the brief
139
+ // console-window flash when the daemon launches.
140
+ detached: true,
141
+ stdio: "ignore",
142
+ windowsHide: true,
143
+ });
144
+ child.unref();
145
+ process.exit(0);
146
+ }
147
+
148
+ const setupMode = hasFlag("setup");
149
+ const addMode = hasFlag("add");
150
+ const testMode = hasFlag("test");
151
+ const rebuildMode = hasFlag("rebuild");
152
+ const repairMode = hasFlag("repair");
153
+ const importMode = hasFlag("import");
154
+
155
+ // Validate arguments
156
+ const knownFlags = ["verbose", "kill", "v", "version", "setup", "add", "test", "rebuild", "repair", "log", "import", "email", "mail", "daemon"];
157
+ for (const arg of args) {
158
+ const flag = arg.replace(/^--?/, "");
159
+ if (arg.startsWith("-") && !knownFlags.includes(flag)) {
160
+ console.error(`Unknown option: ${arg}`);
161
+ console.error("Usage: rmfmail [-verbose] [-kill] [-rebuild] [-v] [-setup]");
162
+ process.exit(1);
163
+ }
164
+ }
165
+
166
+ function log(...msg: any[]): void { if (verbose) console.log("[rmfmail]", ...msg); }
167
+
168
+ /** Detect whether we're running with administrator / root privileges.
169
+ * Windows: `net session` requires admin — succeeds silently when elevated,
170
+ * errors "Access is denied" otherwise. Linux/Mac: check process uid.
171
+ * Returns true only when positively detected as elevated; on ambiguity
172
+ * (e.g. child_process spawn failed for non-privilege reasons), returns
173
+ * false so we don't block users on false positives. */
174
+ function isElevated(): boolean {
175
+ try {
176
+ if (process.platform === "win32") {
177
+ const { execSync } = require("node:child_process");
178
+ execSync("net session >nul 2>&1", { stdio: "ignore", windowsHide: true });
179
+ return true;
180
+ }
181
+ if (typeof (process as any).getuid === "function") {
182
+ return (process as any).getuid() === 0;
183
+ }
184
+ } catch { /* non-admin → net session fails */ }
185
+ return false;
186
+ }
187
+
188
+ /** Put up a blocking warning dialog via showMessageBox. Returns the label
189
+ * the user clicked. The default (Quit) is first so Enter dismisses to
190
+ * safety. Caller decides what to do with "Continue anyway". */
191
+ async function warnElevated(): Promise<string> {
192
+ const res = await showMessageBox({
193
+ title: "rmfmail — elevated run not recommended",
194
+ message:
195
+ "rmfmail is running with Administrator privileges.\n\n" +
196
+ "This can corrupt the per-user WebView2 profile at\n" +
197
+ "%LOCALAPPDATA%\\msger\\webview2\\ and create admin-owned files\n" +
198
+ "under ~/.rmfmail/ that later non-admin runs can't write to\n" +
199
+ "(SQLite db, tokens, config).\n\n" +
200
+ "Quit, relaunch from a normal shell, and only use admin if\n" +
201
+ "you specifically know you need it. To bypass this warning\n" +
202
+ "(for scripted admin use), pass --allow-elevated.",
203
+ buttons: ["Quit", "Continue anyway"],
204
+ size: { width: 540, height: 340 },
205
+ escapeCloses: true,
206
+ });
207
+ return res.button;
208
+ }
209
+
210
+ // Kill any running rmfmail server
211
+ if (hasFlag("kill")) {
212
+ log("Killing rmfmail processes...");
213
+ const { execSync } = await import("node:child_process");
214
+ let killed = 0;
215
+
216
+ // Try graceful exit first
217
+ try {
218
+ execSync(`curl -s -m 2 http://localhost:${PORT}/api/exit`, { stdio: "pipe" });
219
+ log("Sent graceful exit");
220
+ execSync("timeout /t 1 /nobreak", { stdio: "pipe" });
221
+ } catch { /* server may not be responding */ }
222
+
223
+ if (process.platform === "win32") {
224
+ // Kill by port
225
+ try {
226
+ const out = execSync(`netstat -ano | findstr :${PORT} | findstr LISTENING`, { encoding: "utf-8" }).trim();
227
+ const pids = [...new Set(out.split("\n").map(l => l.trim().split(/\s+/).pop()).filter(Boolean))];
228
+ for (const pid of pids) {
229
+ try { execSync(`taskkill /F /PID ${pid}`, { stdio: "pipe" }); console.log(`Killed PID ${pid} (port ${PORT})`); killed++; } catch { /* */ }
230
+ }
231
+ } catch { /* no process on port */ }
232
+
233
+ // Kill any node.exe running rmfmail (server or IPC service). Match
234
+ // the legacy `mailx` path too — source tree dir is still
235
+ // `Y:\dev\email\mailx\` and per-app exes from older installs are
236
+ // under `%LOCALAPPDATA%\mailx\` until those get cleaned up.
237
+ try {
238
+ const ps = execSync(
239
+ `powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='node.exe'\\" | Where-Object { $_.CommandLine -match '(rmfmail|mailx)-server|(rmfmail|mailx)\\\\packages|(rmfmail|mailx)\\\\bin' } | Select-Object -ExpandProperty ProcessId"`,
240
+ { encoding: "utf-8" }
241
+ ).trim();
242
+ for (const pid of ps.split("\n").map(s => s.trim()).filter(s => /^\d+$/.test(s))) {
243
+ try { execSync(`taskkill /F /PID ${pid}`, { stdio: "pipe" }); console.log(`Killed PID ${pid} (rmfmail node process)`); killed++; } catch { /* */ }
244
+ }
245
+ } catch { /* */ }
246
+
247
+ // Kill orphaned msgernative.exe windows. When the node process dies
248
+ // without cascade-killing its WebView child (old crash, forced
249
+ // taskkill, etc.), the msgernative.exe stays on screen and looks
250
+ // like a live rmfmail. rmfmail -kill should leave no trace.
251
+ // Scoped to exes launched for rmfmail by filtering CommandLine —
252
+ // don't touch msger windows started by other apps (msga, bbs, etc.).
253
+ try {
254
+ const ps = execSync(
255
+ `powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='msgernative.exe'\\" | Where-Object { $_.CommandLine -match 'rmfmail|mailx' -or $_.Path -match 'rmfmail|mailx' } | Select-Object -ExpandProperty ProcessId"`,
256
+ { encoding: "utf-8" }
257
+ ).trim();
258
+ for (const pid of ps.split("\n").map(s => s.trim()).filter(s => /^\d+$/.test(s))) {
259
+ try { execSync(`taskkill /F /PID ${pid}`, { stdio: "pipe" }); console.log(`Killed PID ${pid} (rmfmail msgernative/WebView)`); killed++; } catch { /* */ }
260
+ }
261
+ } catch { /* */ }
262
+ } else {
263
+ try { execSync(`fuser -k ${PORT}/tcp`, { stdio: "pipe" }); console.log(`Killed process on port ${PORT}`); killed++; } catch { /* */ }
264
+ }
265
+
266
+ // Clean up stale SQLite WAL/SHM files
267
+ const mailxDir = path.join(process.env.USERPROFILE || process.env.HOME || ".", ".rmfmail");
268
+ for (const ext of ["mailx.db-shm", "mailx.db-wal"]) {
269
+ const p = path.join(mailxDir, ext);
270
+ try { fs.unlinkSync(p); log(`Cleaned ${ext}`); } catch { /* */ }
271
+ }
272
+
273
+ // Always clear instance.json — the daemon's exit handler does this on a
274
+ // clean shutdown, but if it crashed (or was force-killed before the
275
+ // handler ran) the file lingers and wedges every future `mailx` with
276
+ // "already running" because Windows recycles PIDs aggressively. -kill
277
+ // is the user's escape hatch; leave no lock behind.
278
+ clearInstanceFile();
279
+
280
+ if (killed === 0) console.log("No rmfmail processes found");
281
+ process.exit(0);
282
+ }
283
+
284
+ // Re-auth: clear cached OAuth tokens so the next start forces a fresh
285
+ // consent flow. Needed when scopes change (e.g. Google Tasks was added
286
+ // 2026-04-23 but existing tokens were issued against the older scope
287
+ // set, so tasks API calls 403ed with "insufficient authentication
288
+ // scopes"). Safe — tokens are only a cache; fresh consent re-issues.
289
+ if (hasFlag("reauth")) {
290
+ const { getConfigDir } = await import("@bobfrankston/mailx-settings");
291
+ const tokensDir = path.join(getConfigDir(), "tokens");
292
+ if (!fs.existsSync(tokensDir)) {
293
+ console.log("No tokens directory — nothing to clear.");
294
+ process.exit(0);
295
+ }
296
+ let cleared = 0;
297
+ for (const entry of fs.readdirSync(tokensDir)) {
298
+ const userDir = path.join(tokensDir, entry);
299
+ try {
300
+ const stat = fs.statSync(userDir);
301
+ if (!stat.isDirectory()) continue;
302
+ const tokenFile = path.join(userDir, "oauth-token.json");
303
+ if (fs.existsSync(tokenFile)) {
304
+ fs.unlinkSync(tokenFile);
305
+ console.log(` Cleared token for ${entry}`);
306
+ cleared++;
307
+ }
308
+ } catch { /* skip */ }
309
+ }
310
+ console.log(cleared === 0
311
+ ? "No cached tokens found."
312
+ : `Cleared ${cleared} cached token(s). Next 'rmfmail' start will open a browser OAuth consent so the new scopes (tasks, full contacts) get granted.`);
313
+ process.exit(0);
314
+ }
315
+
316
+ // Rebuild: wipe DB + message store, keep accounts/settings
317
+ if (rebuildMode) {
318
+ const { getConfigDir, getStorePath } = await import("@bobfrankston/mailx-settings");
319
+ const dbDir = getConfigDir();
320
+ const storePath = getStorePath();
321
+
322
+ console.log("Rebuilding rmfmail local cache...");
323
+ console.log(" Accounts and settings will be preserved.");
324
+
325
+ // Remove DB files
326
+ for (const f of ["mailx.db", "mailx.db-wal", "mailx.db-shm"]) {
327
+ const p = path.join(dbDir, f);
328
+ if (fs.existsSync(p)) { fs.unlinkSync(p); console.log(` Deleted ${f}`); }
329
+ }
330
+
331
+ // Remove message store
332
+ if (fs.existsSync(storePath)) {
333
+ fs.rmSync(storePath, { recursive: true });
334
+ console.log(` Deleted message store`);
335
+ }
336
+
337
+ console.log(" Rebuild complete. Run 'rmfmail' to start fresh.");
338
+ process.exit(0);
339
+ }
340
+
341
+ // Repair: re-sync metadata (subjects, flags, envelopes) without deleting stored .eml files
342
+ if (repairMode) {
343
+ const { getConfigDir } = await import("@bobfrankston/mailx-settings");
344
+ const dbDir = getConfigDir();
345
+ const dbPath = path.join(dbDir, "mailx.db");
346
+
347
+ if (!fs.existsSync(dbPath)) {
348
+ console.error("No database found. Run 'rmfmail' first to create one.");
349
+ process.exit(1);
350
+ }
351
+
352
+ console.log("Repairing rmfmail metadata...");
353
+ console.log(" Message bodies (.eml files) will be preserved.");
354
+ console.log(" Clearing message metadata for re-sync...");
355
+
356
+ // Dynamic require — better-sqlite3 is a native module, not typed in bin/
357
+ const mod = "better-sqlite3";
358
+ const Database = (await import(/* webpackIgnore: true */ mod) as any).default;
359
+ const db = Database(dbPath);
360
+ db.pragma("journal_mode = WAL");
361
+
362
+ const count = (db.prepare("SELECT COUNT(*) as cnt FROM messages").get() as any).cnt;
363
+ db.exec("DELETE FROM messages");
364
+ db.exec("DELETE FROM messages_fts");
365
+ // Reset folder sync state so IMAP re-syncs all envelopes
366
+ db.exec("UPDATE folders SET total = 0, unread = 0");
367
+ db.close();
368
+
369
+ console.log(` Cleared ${count} message entries. Folder sync state reset.`);
370
+ console.log(" Run 'rmfmail' to re-sync from IMAP with correct encoding.");
371
+ process.exit(0);
372
+ }
373
+
374
+ // Import accounts from a local file into GDrive
375
+ if (importMode) {
376
+ const importPath = args.find(a => !a.startsWith("-"));
377
+ if (!importPath) {
378
+ console.error("Usage: rmfmail --import <path-to-accounts.jsonc>");
379
+ console.error(" Reads accounts from a local file and saves to Google Drive.");
380
+ console.error(" Example: rmfmail --import ~/OneDrive/home/.rmfmail/accounts.jsonc");
381
+ process.exit(1);
382
+ }
383
+ const { parse: parseJsonc } = await import("jsonc-parser");
384
+ const absPath = path.resolve(importPath);
385
+ if (!fs.existsSync(absPath)) {
386
+ console.error(`File not found: ${absPath}`);
387
+ process.exit(1);
388
+ }
389
+ const content = fs.readFileSync(absPath, "utf-8").replace(/\r/g, "");
390
+ const data = parseJsonc(content);
391
+ const accounts = data?.accounts || (Array.isArray(data) ? data : null);
392
+ if (!accounts || accounts.length === 0) {
393
+ console.error("No accounts found in file. Expected { accounts: [...] } or [...]");
394
+ process.exit(1);
395
+ }
396
+ console.log(`Found ${accounts.length} account(s) in ${absPath}`);
397
+
398
+ // Initialize cloud config (GDrive) and save
399
+ const { initCloudConfig, loadAccounts, saveAccounts } = await import("@bobfrankston/mailx-settings");
400
+ await initCloudConfig("gdrive");
401
+
402
+ // Merge: existing cloud accounts + imported, deduplicate by email
403
+ const existing = loadAccounts();
404
+ const merged = [...existing];
405
+ for (const acct of accounts) {
406
+ if (!merged.some(e => e.email === acct.email)) {
407
+ merged.push(acct);
408
+ console.log(` + ${acct.label || acct.email}`);
409
+ } else {
410
+ console.log(` = ${acct.label || acct.email} (already exists)`);
411
+ }
412
+ }
413
+ // Wrap with name if the source had one
414
+ const wrapper: any = { accounts: merged };
415
+ if (data?.name) wrapper.name = data.name;
416
+ await saveAccounts(merged);
417
+ console.log(`Saved ${merged.length} account(s). Run 'rmfmail' to start.`);
418
+ process.exit(0);
419
+ }
420
+
421
+ // Version
422
+ if (hasFlag("v") || hasFlag("version")) {
423
+ const root = path.join(import.meta.dirname, "..");
424
+ const ver = (pkg: string): string => {
425
+ for (const dir of [`${root}/node_modules/${pkg}`, `${root}/node_modules/@bobfrankston/${pkg.replace("@bobfrankston/","")}`]) {
426
+ try { return JSON.parse(fs.readFileSync(`${dir}/package.json`, "utf-8")).version; } catch { /* */ }
427
+ }
428
+ // Check workspace packages
429
+ const short = pkg.replace("@bobfrankston/","");
430
+ try { return JSON.parse(fs.readFileSync(`${root}/packages/${short}/package.json`, "utf-8")).version; } catch { /* */ }
431
+ return "not found";
432
+ };
433
+ try {
434
+ const pkg = JSON.parse(fs.readFileSync(`${root}/package.json`, "utf-8"));
435
+ console.log(`\x1b[1;97;44m rmfmail v${pkg.version} \x1b[0m`);
436
+ } catch { console.log("rmfmail (version unknown)"); }
437
+ console.log(` node ${process.version}`);
438
+ console.log(` iflow-direct ${ver("@bobfrankston/iflow-direct")}`);
439
+ console.log(` miscinfo ${ver("@bobfrankston/miscinfo")}`);
440
+ console.log(` oauth ${ver("@bobfrankston/oauthsupport")}`);
441
+ console.log(` store ${ver("@bobfrankston/mailx-store")}`);
442
+ console.log(` server ${ver("@bobfrankston/mailx-server")}`);
443
+ console.log(` api ${ver("@bobfrankston/mailx-api")}`);
444
+ console.log(` platform ${process.platform} ${process.arch}`);
445
+ process.exit(0);
446
+ }
447
+
448
+ function isPortInUse(port: number): Promise<boolean> {
449
+ return new Promise((resolve) => {
450
+ const socket = net.createConnection({ port, host: "127.0.0.1" });
451
+ socket.once("connect", () => { socket.destroy(); resolve(true); });
452
+ socket.once("error", () => resolve(false));
453
+ });
454
+ }
455
+
456
+ /** Launch msger pointing at the server URL */
457
+ function launchMsger(url: string): void {
458
+ showMessageBox({ url, detach: true, size: { width: 1400, height: 900 } });
459
+ }
460
+
461
+ async function prompt(question: string): Promise<string> {
462
+ const readline = await import("readline");
463
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
464
+ return new Promise(resolve => rl.question(question, (ans: string) => { rl.close(); resolve(ans.trim()); }));
465
+ }
466
+
467
+ interface DiscoveredServer {
468
+ imap: { host: string; port: number; auth: string };
469
+ smtp: { host: string; port: number; auth: string };
470
+ source: string;
471
+ }
472
+
473
+ interface AccountInput {
474
+ email: string;
475
+ password?: string;
476
+ imap?: { host: string; port?: number };
477
+ smtp?: { host: string; port?: number };
478
+ }
479
+
480
+ /** Check if rmfmail is configured (has local config or accounts) */
481
+ function hasConfig(): boolean {
482
+ const home = process.env.USERPROFILE || process.env.HOME || "";
483
+ const mailxDir = path.join(home, ".rmfmail");
484
+ for (const f of ["config.jsonc", "accounts.jsonc", "settings.jsonc"]) {
485
+ if (fs.existsSync(path.join(mailxDir, f))) return true;
486
+ }
487
+ return false;
488
+ }
489
+
490
+ /** Try to auto-discover mail server settings from email domain */
491
+ async function autoDiscover(domain: string): Promise<DiscoveredServer | null> {
492
+ // 1. Try Thunderbird ISPDB
493
+ try {
494
+ const res = await fetch(`https://autoconfig.thunderbird.net/v1.1/${domain}`, { signal: AbortSignal.timeout(5000) });
495
+ if (res.ok) {
496
+ const xml = await res.text();
497
+ const imap = xml.match(/<incomingServer type="imap">[\s\S]*?<hostname>(.*?)<\/hostname>[\s\S]*?<port>(\d+)<\/port>[\s\S]*?<authentication>(.*?)<\/authentication>/);
498
+ const smtp = xml.match(/<outgoingServer type="smtp">[\s\S]*?<hostname>(.*?)<\/hostname>[\s\S]*?<port>(\d+)<\/port>[\s\S]*?<authentication>(.*?)<\/authentication>/);
499
+ if (imap && smtp) {
500
+ return {
501
+ imap: { host: imap[1], port: parseInt(imap[2]), auth: imap[3].includes("OAuth2") ? "oauth2" : "password" },
502
+ smtp: { host: smtp[1], port: parseInt(smtp[2]), auth: smtp[3].includes("OAuth2") ? "oauth2" : "password" },
503
+ source: "ISPDB",
504
+ };
505
+ }
506
+ }
507
+ } catch { /* timeout or not found */ }
508
+
509
+ // 2. Try DNS SRV records
510
+ try {
511
+ const dns = await import("node:dns/promises");
512
+ const imapSrv = await dns.resolveSrv(`_imaps._tcp.${domain}`).catch((): null => null);
513
+ const smtpSrv = await dns.resolveSrv(`_submission._tcp.${domain}`).catch((): null => null);
514
+ if (imapSrv?.[0] && smtpSrv?.[0]) {
515
+ return {
516
+ imap: { host: imapSrv[0].name, port: imapSrv[0].port, auth: "password" },
517
+ smtp: { host: smtpSrv[0].name, port: smtpSrv[0].port, auth: "password" },
518
+ source: "DNS SRV",
519
+ };
520
+ }
521
+ } catch { /* DNS failed */ }
522
+
523
+ // 3. Try MX-based detection (Google Workspace, Microsoft 365)
524
+ try {
525
+ const dns = await import("node:dns/promises");
526
+ const records = await dns.resolveMx(domain);
527
+ for (const mx of records) {
528
+ const host = mx.exchange.toLowerCase();
529
+ if (host.endsWith(".google.com") || host.endsWith(".googlemail.com")) {
530
+ return {
531
+ imap: { host: "imap.gmail.com", port: 993, auth: "oauth2" },
532
+ smtp: { host: "smtp.gmail.com", port: 587, auth: "oauth2" },
533
+ source: `MX → Google (${host})`,
534
+ };
535
+ }
536
+ if (host.endsWith(".outlook.com") || host.endsWith(".protection.outlook.com")) {
537
+ return {
538
+ imap: { host: "outlook.office365.com", port: 993, auth: "oauth2" },
539
+ smtp: { host: "smtp.office365.com", port: 587, auth: "oauth2" },
540
+ source: `MX → Microsoft (${host})`,
541
+ };
542
+ }
543
+ }
544
+ } catch { /* DNS failed */ }
545
+
546
+ return null;
547
+ }
548
+
549
+ /** Prompt user for account details, auto-discover where possible */
550
+ async function promptForAccount(intro?: string): Promise<AccountInput | null> {
551
+ if (intro) console.log(intro);
552
+ const email = await prompt("Email address (or 'skip'): ");
553
+ if (!email || email.toLowerCase() === "skip") return null;
554
+
555
+ const domain = email.split("@")[1]?.toLowerCase() || "";
556
+ const knownOAuth = ["gmail.com", "googlemail.com", "outlook.com", "hotmail.com"];
557
+
558
+ if (knownOAuth.includes(domain)) {
559
+ console.log(` ${domain}: OAuth2 — no password needed. Browser will prompt for authorization.`);
560
+ return { email };
561
+ }
562
+
563
+ // Try auto-discovery
564
+ console.log(` Looking up mail servers for ${domain}...`);
565
+ const discovered = await autoDiscover(domain);
566
+
567
+ if (discovered) {
568
+ console.log(` Found via ${discovered.source}: IMAP ${discovered.imap.host}:${discovered.imap.port}, SMTP ${discovered.smtp.host}:${discovered.smtp.port}`);
569
+ if (discovered.imap.auth === "oauth2") {
570
+ console.log(" OAuth2 authentication — browser will prompt for authorization.");
571
+ return { email };
572
+ }
573
+ const password = await prompt("Password: ");
574
+ return {
575
+ email, password,
576
+ imap: { host: discovered.imap.host, port: discovered.imap.port },
577
+ smtp: { host: discovered.smtp.host, port: discovered.smtp.port },
578
+ };
579
+ }
580
+
581
+ // Manual fallback
582
+ console.log(" Could not auto-detect servers. Enter manually:");
583
+ const password = await prompt("Password: ");
584
+ const imapHost = await prompt(`IMAP host [imap.${domain}]: `) || `imap.${domain}`;
585
+ const smtpHost = await prompt(`SMTP host [smtp.${domain}]: `) || `smtp.${domain}`;
586
+ return {
587
+ email, password,
588
+ imap: { host: imapHost },
589
+ smtp: { host: smtpHost },
590
+ };
591
+ }
592
+
593
+ /** Interactive first-time setup — GDrive API for cloud storage.
594
+ * Returns true if an account was added (caller should proceed to launch UI),
595
+ * false if the user skipped (UI's in-browser setup form will take over). */
596
+ async function runSetup(providedEmail?: string): Promise<boolean> {
597
+ console.log("\nrmfmail— first-time setup\n");
598
+
599
+ const home = process.env.USERPROFILE || process.env.HOME || "";
600
+ const mailxDir = path.join(home, ".rmfmail");
601
+ fs.mkdirSync(mailxDir, { recursive: true });
602
+
603
+ // Use --email flag or prompt interactively
604
+ const email = providedEmail || await prompt("Email address (Gmail recommended): ");
605
+ if (!email || !email.includes("@")) {
606
+ console.log(`\nNo account added. The UI will show a setup form.`);
607
+ return false;
608
+ }
609
+ if (providedEmail) console.log(`Using email: ${email}`);
610
+
611
+ const domain = email.split("@")[1]?.toLowerCase() || "";
612
+ let isGoogle = ["gmail.com", "googlemail.com"].includes(domain);
613
+ if (!isGoogle) {
614
+ try {
615
+ const dnsmod = await import("node:dns/promises");
616
+ const records = await dnsmod.resolveMx(domain);
617
+ isGoogle = records.some(mx => {
618
+ const host = mx.exchange.toLowerCase();
619
+ return host.endsWith(".google.com") || host.endsWith(".googlemail.com");
620
+ });
621
+ if (isGoogle) console.log(` ${domain} is hosted on Google (detected via MX)`);
622
+ } catch { /* DNS lookup failed */ }
623
+ }
624
+
625
+ // For Google-hosted accounts, check Drive for existing settings first
626
+ let driveFolderId: string | null = null;
627
+ if (isGoogle) {
628
+ console.log("\nChecking Google Drive for existing rmfmail settings...");
629
+ try {
630
+ const { gDriveFindOrCreateFolder, getCloudProvider } = await import("@bobfrankston/mailx-settings/cloud.js");
631
+ driveFolderId = await gDriveFindOrCreateFolder();
632
+ if (driveFolderId) {
633
+ console.log(` Drive folder: My Drive/rmfmail/ (${driveFolderId})`);
634
+ const gdrive = getCloudProvider("gdrive", driveFolderId);
635
+ if (gdrive) {
636
+ // Read accounts.jsonc (canonical) — ignore legacy settings.jsonc
637
+ const existing = await gdrive.read("accounts.jsonc");
638
+ if (existing) {
639
+ const { parse: parseJsonc } = await import("jsonc-parser");
640
+ const data = parseJsonc(existing);
641
+ const accts = data?.accounts || (Array.isArray(data) ? data : []);
642
+ if (accts.length > 0) {
643
+ console.log(`\nFound ${accts.length} existing account(s) on Google Drive (My Drive/rmfmail/accounts.jsonc):`);
644
+ for (const a of accts) console.log(` • ${a.label || a.name || a.email}`);
645
+ // Save config pointing to Drive — no prompts needed
646
+ const config = { sharedDir: { provider: "gdrive", path: "rmfmail", folderId: driveFolderId } };
647
+ fs.writeFileSync(path.join(mailxDir, "config.jsonc"), JSON.stringify(config, null, 2));
648
+ console.log("Local config created. Starting rmfmail...\n");
649
+ return true;
650
+ }
651
+ }
652
+ }
653
+ // No existing accounts — save Drive config for later
654
+ const config = { sharedDir: { provider: "gdrive", path: "rmfmail", folderId: driveFolderId } };
655
+ fs.writeFileSync(path.join(mailxDir, "config.jsonc"), JSON.stringify(config, null, 2));
656
+ } else {
657
+ console.log(" Could not access Google Drive (OAuth not granted or token expired).");
658
+ console.log(" Account will be saved locally; the UI will retry the cloud sync when you fix Drive access.");
659
+ }
660
+ } catch (e: any) {
661
+ console.log(` Drive check failed: ${e.message} — will save locally and retry from UI.`);
662
+ }
663
+ }
664
+
665
+ // No existing accounts found — build a new account
666
+ const account = { email } as any;
667
+ const isOAuth = ["gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com"].includes(domain);
668
+ if (!isOAuth) {
669
+ account.password = await prompt("Password (app password for Yahoo/AOL/iCloud): ");
670
+ }
671
+
672
+ // Display name: leave empty for Google accounts so MailxService.setupAccount
673
+ // (or the next launch's IMAP auth) can resolve it from the People API once
674
+ // the Gmail OAuth token exists. The Drive token alone doesn't have the
675
+ // contacts.readonly scope, so we can't fetch it here at CLI-prompt time.
676
+ const defaultName = email.split("@")[0];
677
+ const name = await prompt(`Your name (for From: header) [auto-detect from Google, or '${defaultName}']: `) || (isGoogle ? "" : defaultName);
678
+
679
+ // ALWAYS write a local copy first so the data is never lost. The cloud
680
+ // write below is the sync, not the source of truth on this machine.
681
+ const accountsData = { name, accounts: [account] };
682
+ const localAccountsPath = path.join(mailxDir, "accounts.jsonc");
683
+ fs.writeFileSync(localAccountsPath, JSON.stringify(accountsData, null, 2));
684
+
685
+ if (isGoogle && driveFolderId) {
686
+ // Save to Google Drive via API
687
+ console.log("\nSaving account to Google Drive...");
688
+ try {
689
+ const { getCloudProvider } = await import("@bobfrankston/mailx-settings/cloud.js");
690
+ const gdrive = getCloudProvider("gdrive", driveFolderId);
691
+ if (!gdrive) throw new Error("getCloudProvider returned null");
692
+ await gdrive.write("accounts.jsonc", JSON.stringify(accountsData, null, 2));
693
+ console.log(" Account saved to Google Drive.");
694
+ } catch (e: any) {
695
+ console.log(` Drive write failed: ${e.message}`);
696
+ console.log(` Local copy saved at ${localAccountsPath} — UI will retry cloud sync.`);
697
+ }
698
+ } else if (isGoogle && !driveFolderId) {
699
+ console.log(` Skipping Drive sync (no folder ID). Local copy at ${localAccountsPath}.`);
700
+ }
701
+
702
+ console.log("Setup complete. Starting rmfmail...\n");
703
+ return true;
704
+ }
705
+
706
+ /** Test account connectivity — IMAP connect, SMTP send, sync round-trip */
707
+ async function runTest(): Promise<void> {
708
+ console.log("\nrmfmail— connection test\n");
709
+
710
+ // Start server in-process to access settings
711
+ console.log("Loading settings...");
712
+ const { loadSettings, getSharedDir, initLocalConfig } = await import("@bobfrankston/mailx-settings");
713
+ initLocalConfig();
714
+ const settings = loadSettings();
715
+
716
+ if (settings.accounts.length === 0) {
717
+ console.log("No accounts configured. Run: rmfmail -setup");
718
+ process.exit(1);
719
+ }
720
+
721
+ console.log(`Shared dir: ${getSharedDir()}`);
722
+ console.log(`Accounts: ${settings.accounts.map((a: any) => `${a.label || a.name} <${a.email}>`).join(", ")}\n`);
723
+
724
+ for (const account of settings.accounts) {
725
+ if (!account.enabled) { console.log(` ${account.label || account.id}: SKIPPED (disabled)\n`); continue; }
726
+
727
+ console.log(`Testing ${account.label || account.id} (${account.email}):`);
728
+
729
+ // Test IMAP
730
+ try {
731
+ const { createAutoImapConfig, CompatImapClient } = await import("@bobfrankston/iflow-direct");
732
+ const { NodeTcpTransport } = await import("@bobfrankston/node-tcp-transport");
733
+ const config = createAutoImapConfig({
734
+ server: account.imap.host,
735
+ port: account.imap.port,
736
+ username: account.imap.user,
737
+ password: account.imap.password
738
+ });
739
+ const client = new CompatImapClient(config, () => new NodeTcpTransport());
740
+ const folders = await client.getFolderList();
741
+ await client.logout();
742
+ console.log(` IMAP: OK (${folders.length} folders)`);
743
+ } catch (e: any) {
744
+ console.log(` IMAP: FAILED — ${e.message}`);
745
+ }
746
+
747
+ // Test SMTP
748
+ try {
749
+ const { createTransport } = await import("nodemailer");
750
+ let smtpAuth: any;
751
+ if (account.smtp.auth === "password") {
752
+ smtpAuth = { user: account.smtp.user, pass: account.smtp.password };
753
+ } else if (account.smtp.auth === "oauth2") {
754
+ // Try to get OAuth token
755
+ const { createAutoImapConfig } = await import("@bobfrankston/iflow-direct");
756
+ const config = createAutoImapConfig({
757
+ server: account.imap.host,
758
+ port: account.imap.port,
759
+ username: account.imap.user,
760
+ });
761
+ if (config.tokenProvider) {
762
+ const accessToken = await config.tokenProvider();
763
+ smtpAuth = { type: "OAuth2", user: account.smtp.user, accessToken };
764
+ }
765
+ }
766
+ const transport = createTransport({
767
+ host: account.smtp.host,
768
+ port: account.smtp.port,
769
+ secure: account.smtp.port === 465,
770
+ auth: smtpAuth,
771
+ tls: { rejectUnauthorized: false },
772
+ });
773
+ await transport.verify();
774
+ console.log(` SMTP: OK`);
775
+
776
+ // Send test message to self
777
+ const testSubject = `rmfmail test — ${new Date().toLocaleString()}`;
778
+ await transport.sendMail({
779
+ from: `${account.name} <${account.email}>`,
780
+ to: account.email,
781
+ subject: testSubject,
782
+ text: `This is a test message from rmfmail -test.\nSent: ${new Date().toISOString()}\nAccount: ${account.id}`,
783
+ });
784
+ console.log(` SEND: OK — test message sent to ${account.email}`);
785
+ console.log(` Subject: "${testSubject}"`);
786
+ } catch (e: any) {
787
+ console.log(` SMTP: FAILED — ${e.message}`);
788
+ }
789
+
790
+ console.log();
791
+ }
792
+
793
+ console.log("Test complete. Check your inbox for the test message(s).");
794
+ process.exit(0);
795
+ }
796
+
797
+ /** Register this client on GDrive — writes/updates clients.jsonc with device info.
798
+ * Best-effort: silently skips when cloud isn't ready (fresh install, expired
799
+ * token). The scary "No cloud configured" banner must NOT fire for this. */
800
+ async function registerClient(settings: any): Promise<void> {
801
+ const { cloudRead, cloudWrite, getStorageInfo } = await import("@bobfrankston/mailx-settings");
802
+ // Check if cloud is actually ready before attempting a write — cloudWrite
803
+ // calls setCloudError which pushes an error banner to the UI. We'd rather
804
+ // silently skip than show "No cloud configured" at startup.
805
+ const info = getStorageInfo();
806
+ if (info.mode === "local" || !info.provider || info.provider === "local") return;
807
+
808
+ // Device ID: stable per machine, stored locally
809
+ const deviceIdPath = path.join(os.homedir(), ".rmfmail", "device-id");
810
+ let deviceId: string;
811
+ if (fs.existsSync(deviceIdPath)) {
812
+ deviceId = fs.readFileSync(deviceIdPath, "utf-8").trim();
813
+ } else {
814
+ deviceId = `${os.hostname()}-${Date.now().toString(36)}`;
815
+ fs.mkdirSync(path.dirname(deviceIdPath), { recursive: true });
816
+ fs.writeFileSync(deviceIdPath, deviceId);
817
+ }
818
+
819
+ // Get local IP
820
+ let localIp = "";
821
+ try {
822
+ const nets = os.networkInterfaces();
823
+ for (const addrs of Object.values(nets) as (os.NetworkInterfaceInfo[] | undefined)[]) {
824
+ for (const addr of addrs || []) {
825
+ if (addr.family === "IPv4" && !addr.internal) { localIp = addr.address; break; }
826
+ }
827
+ if (localIp) break;
828
+ }
829
+ } catch { /* ignore */ }
830
+
831
+ // Read existing clients.jsonc from cloud (may not exist yet — that's fine)
832
+ let clients: Record<string, any> = {};
833
+ try {
834
+ const content = await cloudRead("clients.jsonc");
835
+ if (content) clients = JSON.parse(content);
836
+ } catch { /* start fresh */ }
837
+
838
+ // Update this device's entry
839
+ clients[deviceId] = {
840
+ hostname: os.hostname(),
841
+ platform: `${process.platform} ${process.arch}`,
842
+ accounts: settings.accounts.map((a: any) => a.id),
843
+ lastSeen: new Date().toISOString(),
844
+ ip: localIp,
845
+ version: JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "package.json"), "utf-8")).version,
846
+ };
847
+
848
+ // Write back. cloudWrite now throws on failure (and sets lastCloudError),
849
+ // so swallow here — registerClient is fire-and-forget from the caller.
850
+ try {
851
+ await cloudWrite("clients.jsonc", JSON.stringify(clients, null, 2));
852
+ console.log(` [client] Registered device: ${deviceId}`);
853
+ } catch (e: any) {
854
+ console.error(` [client] Failed to register device: ${e.message}`);
855
+ }
856
+ }
857
+
858
+ async function main(): Promise<void> {
859
+ log(`Platform: ${process.platform} ${process.arch}`);
860
+ log(`Node: ${process.version}`);
861
+ log(`Mode: ${setupMode ? "setup" : "auto"}`);
862
+
863
+ // Refuse to run elevated unless explicitly opted in. An elevated mailx
864
+ // can poison %LOCALAPPDATA%\msger\webview2\ (see msger/notes.md WebView2
865
+ // profile playbook) and create admin-owned files under ~/.rmfmail/ that
866
+ // later non-admin runs can't write to. `net session` requires admin on
867
+ // Windows; succeeds → admin, fails → non-admin. Linux/Mac use process
868
+ // uid (0 = root). --allow-elevated bypasses for scripted admin use.
869
+ if (!hasFlag("allow-elevated") && !isDaemon && isElevated()) {
870
+ const button = await warnElevated();
871
+ if (button !== "Continue anyway") {
872
+ log("User chose Quit on elevated-run warning. Exiting.");
873
+ process.exit(0);
874
+ }
875
+ log("User chose Continue anyway on elevated-run warning. Proceeding (will likely poison local state).");
876
+ }
877
+
878
+ // Test connectivity
879
+ if (testMode) {
880
+ await runTest();
881
+ return;
882
+ }
883
+
884
+ // Add account to existing config
885
+ if (addMode) {
886
+ const account = await promptForAccount();
887
+ if (account) {
888
+ const home = process.env.USERPROFILE || process.env.HOME || "";
889
+ const mailxDir = path.join(home, ".rmfmail");
890
+ const settingsPath = path.join(mailxDir, "settings.jsonc");
891
+ let settings: any;
892
+ try { settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8").replace(/\r/g, "").replace(/\/\/.*/g, "")); } catch { settings = { accounts: [] }; }
893
+ if (!settings.accounts) settings.accounts = [];
894
+ settings.accounts.push(account);
895
+ fs.mkdirSync(mailxDir, { recursive: true });
896
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
897
+ console.log(`Added ${account.email} to settings. Restart rmfmail to connect.`);
898
+ }
899
+ process.exit(0);
900
+ }
901
+
902
+ // Auto-detect first run — enter setup if no config exists.
903
+ // Skip CLI prompts entirely when stdin isn't a TTY (auto-detached daemon
904
+ // has stdio:"ignore", so prompt() returns "" instantly and the user never
905
+ // gets to type their email — silent no-setup). The in-browser setup form
906
+ // takes over in that case.
907
+ const hasTty = setupMode ? !!process.stdin.isTTY : (process.stdin.isTTY === true);
908
+ if (setupMode || !hasConfig()) {
909
+ if (!setupMode) console.log("No rmfmail configuration found.");
910
+ // -email or -mail flag skips the interactive prompt
911
+ const emailFlag = args.findIndex(a => a === "-email" || a === "--email" || a === "-mail" || a === "--mail");
912
+ const emailArg = args.find(a => a.startsWith("-email=") || a.startsWith("--email=") || a.startsWith("-mail=") || a.startsWith("--mail="))?.split("=")[1]
913
+ || (emailFlag >= 0 ? args[emailFlag + 1] : undefined);
914
+ if (hasTty || emailArg) {
915
+ await runSetup(emailArg);
916
+ } else {
917
+ console.log("No TTY and no -email flag — skipping CLI setup; in-browser setup form will appear.");
918
+ // Ensure the data dir exists so the UI can write its config.
919
+ const home = process.env.USERPROFILE || process.env.HOME || "";
920
+ fs.mkdirSync(path.join(home, ".rmfmail"), { recursive: true });
921
+ }
922
+ }
923
+
924
+ // Redirect console to log file — keep terminal clean
925
+ if (!verbose) {
926
+ const home = process.env.USERPROFILE || process.env.HOME || ".";
927
+ const logDir = path.join(home, ".rmfmail", "logs");
928
+ fs.mkdirSync(logDir, { recursive: true });
929
+ // Prune logs older than LOG_RETENTION_DAYS on startup. Keep it simple:
930
+ // scan the dir, stat, delete. Cheap even with years of history.
931
+ // Bumped 7 → 30 days so "where did my letter go?" reports can still
932
+ // reach the `[reconcile-delete]` log entry weeks after the fact.
933
+ const LOG_RETENTION_DAYS = 30;
934
+ const cutoff = Date.now() - LOG_RETENTION_DAYS * 86400000;
935
+ try {
936
+ for (const name of fs.readdirSync(logDir)) {
937
+ if (!/^mailx-\d{4}-\d{2}-\d{2}\.log$/.test(name)) continue;
938
+ const full = path.join(logDir, name);
939
+ try {
940
+ const st = fs.statSync(full);
941
+ if (st.mtimeMs < cutoff) fs.unlinkSync(full);
942
+ } catch { /* ignore per-file error */ }
943
+ }
944
+ } catch { /* ignore — log pruning is best-effort */ }
945
+ const logDate = new Date().toISOString().slice(0, 10);
946
+ const logPath = path.join(logDir, `mailx-${logDate}.log`);
947
+ const logStream = fs.createWriteStream(logPath, { flags: "a" });
948
+ const ts = () => new Date().toISOString().slice(11, 23);
949
+ console.log = (...a: any[]) => { logStream.write(`${ts()} ${a.join(" ")}\n`); };
950
+ console.error = (...a: any[]) => { logStream.write(`${ts()} ERROR ${a.join(" ")}\n`); };
951
+ // Redirect daemon's process.stderr to the log too. msger forwards its
952
+ // Rust child's stderr to our process.stderr; in daemon mode that's
953
+ // stdio:"ignore" → /dev/null, which buries diagnostics like
954
+ // "Failed to load icon ..." that we need to debug taskbar-icon
955
+ // problems. Wire it through here.
956
+ const origStderrWrite = process.stderr.write.bind(process.stderr);
957
+ process.stderr.write = ((chunk: any, ...rest: any[]): boolean => {
958
+ try {
959
+ const s = typeof chunk === "string" ? chunk : chunk.toString();
960
+ logStream.write(`${ts()} STDERR ${s}${s.endsWith("\n") ? "" : "\n"}`);
961
+ } catch { /* ignore — best-effort logging */ }
962
+ return origStderrWrite(chunk, ...rest);
963
+ }) as typeof process.stderr.write;
964
+ }
965
+
966
+ // IPC service mode — no HTTP server
967
+ console.log("Starting rmfmail service...");
968
+ const { MailxDB } = await import("@bobfrankston/mailx-store");
969
+ const { ImapManager } = await import("@bobfrankston/mailx-imap");
970
+ const { MailxService } = await import("@bobfrankston/mailx-service");
971
+ const { dispatch } = await import("@bobfrankston/mailx-service/jsonrpc.js");
972
+ const { loadSettings, loadAccountsAsync, getConfigDir, getStorageInfo } = await import("@bobfrankston/mailx-settings");
973
+
974
+ let settings = loadSettings();
975
+ if (settings.accounts.length === 0) {
976
+ const cloudAccounts = await loadAccountsAsync();
977
+ if (cloudAccounts.length > 0) {
978
+ settings = { ...settings, accounts: cloudAccounts };
979
+ console.log(` Loaded ${cloudAccounts.length} account(s) from cloud`);
980
+ }
981
+ }
982
+
983
+ const db = new MailxDB(getConfigDir());
984
+
985
+ // Auto-create the sending/ recovery README on every startup. Stays in
986
+ // sync with the running version of mailx; user can ignore once the
987
+ // disk-staging fallback is no longer needed.
988
+ try {
989
+ const sendingDir = path.join(getConfigDir(), "sending");
990
+ fs.mkdirSync(sendingDir, { recursive: true });
991
+ const readmePath = path.join(sendingDir, "README.md");
992
+ const readmeBody = `# \`~/.rmfmail/sending/\` and \`~/.rmfmail/outbox/\` — outgoing-mail staging
993
+
994
+ Auto-generated by rmfmail on startup. Manual recovery reference for when rmfmail is broken or you need to feed an outgoing message into another mail program.
995
+
996
+ ## Layout
997
+
998
+ \`\`\`
999
+ ~/.rmfmail/
1000
+ ├── outbox/<account>/
1001
+ │ └── *.ltr ← THE QUEUE. Worker scans every 10s, sends, deletes on success.
1002
+ └── sending/<account>/
1003
+ ├── editing/ ← Last 3 draft autosaves while composing.
1004
+ ├── queued/ ← Manual drop-in / crash-recovery copies.
1005
+ └── sent/ ← Audit trail of successfully sent messages.
1006
+ \`\`\`
1007
+
1008
+ In-flight files are atomically renamed to \`<file>.sending-<host>-<pid>\` while the worker is processing them — same-machine claim so two rmfmail instances don't double-send. Stale claims (dead PIDs on this host) are recovered on the next tick.
1009
+
1010
+ ## Manual fallback
1011
+
1012
+ - **rmfmail is dead, need to send a draft** — most recent file in \`sending/<account>/editing/\` is a complete RFC 822 message; copy the body into another mail client and resend.
1013
+ - **Feed a raw .eml to mailx** — drop into \`sending/<account>/queued/\`. Picked up within 10s.
1014
+ - **rmfmail says queued but server doesn't have it** — look in \`outbox/<account>/\`. \`.ltr\` still there → worker hasn't sent yet (check \`~/.rmfmail/logs/\`). \`.sending-<host>-<pid>\` → in flight. Gone → success.
1015
+
1016
+ ## Format
1017
+
1018
+ RFC 5322 with CRLF line endings. Bodies are quoted-printable encoded (readable in a text editor). Every message carries \`Message-ID:\` for cross-device dedup; \`X-Mailx-Retry\` marks retry attempts.
1019
+ `;
1020
+ // Only rewrite if content drifted (avoids gratuitous mtime updates).
1021
+ let existing = "";
1022
+ try { existing = fs.readFileSync(readmePath, "utf-8"); } catch { /* missing */ }
1023
+ if (existing !== readmeBody) fs.writeFileSync(readmePath, readmeBody);
1024
+ } catch (e: any) {
1025
+ console.error(` [readme] Could not write sending README: ${e?.message || e}`);
1026
+ }
1027
+
1028
+ // `--server` mode — hand off to the Express HTTP server package (self-
1029
+ // contained; initializes its own DB / IMAP manager / MailxService). No
1030
+ // WebView2, no IPC bridge. Useful for remote access (phone before MAUI
1031
+ // was a thing) and for JSON-RPC debugging from devtools. Loopback by
1032
+ // default; passes --external through if the user asked for it. See C34.
1033
+ if (hasFlag("server")) {
1034
+ writeInstanceFile(process.pid);
1035
+ await import("@bobfrankston/mailx-server");
1036
+ // mailx-server's index.ts self-invokes `start()` — once imported,
1037
+ // Express owns the event loop. Don't fall through to showService.
1038
+ return;
1039
+ }
1040
+
1041
+ const { NodeTcpTransport } = await import("@bobfrankston/node-tcp-transport");
1042
+ const imapManager = new ImapManager(db, () => new NodeTcpTransport());
1043
+ // Native client is the only option (iflow-direct)
1044
+ const svc = new MailxService(db, imapManager);
1045
+
1046
+ // Open msger in service mode — custom protocol serves files from client dir
1047
+ const clientDir = path.join(import.meta.dirname, "..", "client");
1048
+ const mailxapiPath = path.join(clientDir, "lib", "mailxapi.js");
1049
+ const mailxapiScript = fs.readFileSync(mailxapiPath, "utf-8");
1050
+
1051
+ // Restore saved window geometry (position + size) from previous session
1052
+ const windowJsonPath = path.join(getConfigDir(), "window.json");
1053
+ interface WindowGeometry { x: number; y: number; width: number; height: number }
1054
+ let savedGeometry: WindowGeometry | null = null;
1055
+ try {
1056
+ const raw = JSON.parse(fs.readFileSync(windowJsonPath, "utf-8"));
1057
+ if (typeof raw.width === "number" && raw.width > 200 &&
1058
+ typeof raw.height === "number" && raw.height > 200) {
1059
+ savedGeometry = raw as WindowGeometry;
1060
+ }
1061
+ } catch { /* no saved geometry — use defaults */ }
1062
+
1063
+ const rootPkgVersion = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "package.json"), "utf-8")).version;
1064
+ // Pass the .png as the window-decode icon: msger uses the `image` crate
1065
+ // to decode `options.icon` for the Tao window icon, and PNG-in-ICO files
1066
+ // round-trip unreliably through the image-0.24 ICO decoder, which leaves
1067
+ // the taskbar entry showing the empty msgernative.exe default. PNG always
1068
+ // decodes cleanly. The .ico path is forwarded separately as
1069
+ // `relaunchIcon`, which msger uses for `PKEY_AppUserModel_RelaunchIconResource`
1070
+ // (the path is consumed verbatim — no decode — so PNG-in-ICO is fine
1071
+ // there). Falls back if either file is missing.
1072
+ const __iconIco = path.join(clientDir, "icon.ico");
1073
+ const __iconPng = path.join(clientDir, "icon.png");
1074
+ const __iconPathRuntime = fs.existsSync(__iconPng) ? __iconPng : __iconIco;
1075
+ const __iconPathPin = fs.existsSync(__iconIco) ? __iconIco : undefined;
1076
+ console.log(`[icon] runtime=${__iconPathRuntime} (exists=${fs.existsSync(__iconPathRuntime)}) pin=${__iconPathPin ?? "none"} (exists=${__iconPathPin ? fs.existsSync(__iconPathPin) : false})`);
1077
+ // Pinned-shortcut launch command. Windows captures the running exe at
1078
+ // pin time by default, but the running exe is `mailx.exe` — actually
1079
+ // msgernative.exe expecting JSON options on stdin. Click that bare and
1080
+ // it dies on `serde_json::from_str("")`. Override with an explicit
1081
+ // node + script invocation so the pin re-enters through bin/mailx.js
1082
+ // the same way the `mailx` CLI does.
1083
+ const __mailxJs = path.join(import.meta.dirname, "mailx.js");
1084
+ const __relaunchCommand = `"${process.execPath}" "${__mailxJs}"`;
1085
+ const handle = showService({
1086
+ title: `rmfmail v${rootPkgVersion}`,
1087
+ url: "index.html",
1088
+ contentDir: clientDir,
1089
+ initScript: mailxapiScript,
1090
+ icon: __iconPathRuntime,
1091
+ relaunchIcon: __iconPathPin,
1092
+ relaunchCommand: __relaunchCommand,
1093
+ relaunchDisplayName: "rmfmail",
1094
+ aumid: "com.frankston.rmfmail",
1095
+ size: savedGeometry
1096
+ ? { width: savedGeometry.width, height: savedGeometry.height }
1097
+ : { width: 1400, height: 900 },
1098
+ pos: savedGeometry
1099
+ ? { x: savedGeometry.x, y: savedGeometry.y }
1100
+ : undefined,
1101
+ escapeCloses: false,
1102
+ });
1103
+
1104
+ // Register ourselves as the live instance so subsequent `mailx` invocations
1105
+ // can detect version-mismatch and upgrade us (see top of file). Clear on
1106
+ // any of: SIGINT, SIGTERM, normal exit.
1107
+ //
1108
+ // Critical: the SIGTERM handler must *close the WebView child process*
1109
+ // (handle.close() → kills msgernative.exe) before Node exits. Without
1110
+ // this, the auto-upgrade leaves the old WebView orphaned on screen and
1111
+ // the user sees an apparently frozen "old mailx" while the new Node is
1112
+ // trying to spawn a second one. Cascade-killing the child makes the
1113
+ // version-mismatch auto-upgrade actually transparent to the user.
1114
+ writeInstanceFile(process.pid);
1115
+ const __cleanupInstance = () => {
1116
+ // Only clear if WE are still the registered instance. Prevents the
1117
+ // restart-daemon sequence (clear → spawn → new daemon writes its
1118
+ // own entry → we exit) from deleting the replacement's claim on
1119
+ // the way out.
1120
+ const inst = readInstanceFile();
1121
+ if (inst && inst.pid === process.pid) clearInstanceFile();
1122
+ try { handle.close(); } catch { /* already gone */ }
1123
+ };
1124
+ process.once("exit", __cleanupInstance);
1125
+ process.once("SIGINT", () => { __cleanupInstance(); process.exit(0); });
1126
+ process.once("SIGTERM", () => { __cleanupInstance(); process.exit(0); });
1127
+
1128
+ // Handle requests from WebView → dispatch to MailxService
1129
+ // Pass server version to dispatch so getVersion returns it
1130
+ const rootPkg = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "package.json"), "utf-8"));
1131
+
1132
+ handle.onRequest(async (req) => {
1133
+ if (!req._action) {
1134
+ // msger sends {"button":"OK","closed":true} on navigation — ignore it, don't exit
1135
+ if (req.closed || req.button) {
1136
+ console.log(`[ipc] ← ignored close signal during navigation: ${JSON.stringify(req).substring(0, 100)}`);
1137
+ return;
1138
+ }
1139
+ console.log(`[ipc] ← ignored (no _action): ${JSON.stringify(req).substring(0, 100)}`);
1140
+ return;
1141
+ }
1142
+ console.log(`[ipc] ← ${req._action} (${req._cbid})`);
1143
+ // Save window position+size for next launch (handled here, not in MailxService)
1144
+ if (req._action === "saveWindowGeometry") {
1145
+ try {
1146
+ const geom: WindowGeometry = {
1147
+ x: Number(req.x) || 0,
1148
+ y: Number(req.y) || 0,
1149
+ width: Math.max(400, Number(req.width) || 1400),
1150
+ height: Math.max(300, Number(req.height) || 900),
1151
+ };
1152
+ fs.writeFileSync(windowJsonPath, JSON.stringify(geom, null, 2));
1153
+ } catch (e: any) {
1154
+ console.error(`[window] Failed to save geometry: ${e.message}`);
1155
+ }
1156
+ handle.send({ _cbid: req._cbid, result: { ok: true } });
1157
+ return;
1158
+ }
1159
+ // Restart the daemon in-place without npm install. Subtle: the new
1160
+ // mailx's startup-time instance check sees the instance.json we
1161
+ // wrote and bails with "already running" if versions match —
1162
+ // skipping the new process entirely. Clear the instance file
1163
+ // FIRST so the replacement can claim the slot, THEN spawn, THEN
1164
+ // gracefully shut this process down. The exit handler guards
1165
+ // against clobbering the replacement's entry (see __cleanupInstance
1166
+ // below — only clears if instance.json's PID still matches ours).
1167
+ if (req._action === "restartDaemon") {
1168
+ handle.send({ _cbid: req._cbid, ok: true, status: "restarting" });
1169
+ try {
1170
+ clearInstanceFile();
1171
+ const { spawn: spawnChild } = await import("child_process");
1172
+ const child = spawnChild("rmfmail", [], { detached: true, stdio: "ignore", shell: true, windowsHide: true });
1173
+ child.unref();
1174
+ console.log(" [restart] Spawned fresh daemon; shutting down current");
1175
+ // Give the spawn a moment to take hold before we start
1176
+ // tearing things down — otherwise IMAP disconnects could
1177
+ // race with the new process's startup handshake.
1178
+ await new Promise(r => setTimeout(r, 800));
1179
+ } catch (e: any) {
1180
+ console.error(` [restart] Spawn failed: ${e.message}`);
1181
+ }
1182
+ gracefulShutdown("User requested restart");
1183
+ return;
1184
+ }
1185
+ // Auto-update action: run npm install then restart
1186
+ if (req._action === "performUpdate") {
1187
+ handle.send({ _cbid: req._cbid, ok: true, status: "updating" });
1188
+ try {
1189
+ const { execSync, spawn: spawnChild } = await import("child_process");
1190
+ console.log(" [update] Installing latest version...");
1191
+ execSync("npm install -g @bobfrankston/rmfmail", { encoding: "utf-8", timeout: 120_000, stdio: "inherit", windowsHide: true });
1192
+ console.log(" [update] Install complete — relaunching");
1193
+ // Spawn the new version detached so it outlives this process
1194
+ const child = spawnChild("rmfmail", [], { detached: true, stdio: "ignore", shell: true, windowsHide: true });
1195
+ child.unref();
1196
+ gracefulShutdown("Update applied");
1197
+ } catch (e: any) {
1198
+ // Don't shut down on a failed install — the user is still in
1199
+ // the middle of a session, an offline-time "Update now" tap
1200
+ // shouldn't kill the running app. Surface the failure so the
1201
+ // banner can offer a retry instead of leaving "Updating..."
1202
+ // pinned forever.
1203
+ const msg = e?.message || String(e);
1204
+ console.error(` [update] Install failed: ${msg}`);
1205
+ const offline = /ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|getaddrinfo|network|registry/i.test(msg);
1206
+ handle.send({ _event: "updateFailed", type: "updateFailed", offline, message: msg });
1207
+ }
1208
+ return;
1209
+ }
1210
+ // Per-action wall-clock timing so a "took N seconds" report tells us
1211
+ // where between Rust→stdin→dispatch→service the time actually went.
1212
+ const ipcT0 = Date.now();
1213
+ try {
1214
+ const response = await dispatch(svc as any, req);
1215
+ const elapsed = Date.now() - ipcT0;
1216
+ console.log(`[ipc] → ${req._action} (${req._cbid}) ok in ${elapsed}ms`);
1217
+ handle.send(response);
1218
+ } catch (e: any) {
1219
+ const elapsed = Date.now() - ipcT0;
1220
+ console.error(`[ipc] → ${req._action} (${req._cbid}) error in ${elapsed}ms: ${e.message}`);
1221
+ handle.send({ _cbid: req._cbid, error: e.message });
1222
+ }
1223
+ });
1224
+
1225
+ // Wire IMAP events → push to WebView (throttled to avoid flooding stdin)
1226
+ let pendingSyncProgress: Record<string, { phase: string; progress: number }> = {};
1227
+ let syncProgressTimer: ReturnType<typeof setTimeout> | null = null;
1228
+ imapManager.on("syncProgress", (accountId: string, phase: string, progress: number) => {
1229
+ pendingSyncProgress[accountId] = { phase, progress };
1230
+ if (!syncProgressTimer) {
1231
+ syncProgressTimer = setTimeout(() => {
1232
+ syncProgressTimer = null;
1233
+ for (const [id, p] of Object.entries(pendingSyncProgress)) {
1234
+ handle.send({ _event: "syncProgress", type: "syncProgress", accountId: id, phase: p.phase, progress: p.progress });
1235
+ }
1236
+ pendingSyncProgress = {};
1237
+ }, 500); // batch sync events every 500ms
1238
+ }
1239
+ });
1240
+ let pendingCounts: Record<string, any> = {};
1241
+ let countsTimer: ReturnType<typeof setTimeout> | null = null;
1242
+ imapManager.on("folderCountsChanged", (accountId: string, counts: any) => {
1243
+ pendingCounts[accountId] = counts;
1244
+ if (!countsTimer) {
1245
+ countsTimer = setTimeout(() => {
1246
+ countsTimer = null;
1247
+ for (const [id, c] of Object.entries(pendingCounts)) {
1248
+ handle.send({ _event: "folderCountsChanged", type: "folderCountsChanged", accountId: id, ...c });
1249
+ }
1250
+ pendingCounts = {};
1251
+ }, 1000); // batch count updates every 1s
1252
+ }
1253
+ });
1254
+ // Batch folderSynced events (same cadence as counts) so a sync-all burst
1255
+ // doesn't flood the WebView with one stdin write per folder.
1256
+ let pendingSynced: Record<string, { folderId: number; syncedAt: number }[]> = {};
1257
+ let syncedTimer: ReturnType<typeof setTimeout> | null = null;
1258
+ imapManager.on("folderSynced", (accountId: string, folderId: number, syncedAt: number) => {
1259
+ (pendingSynced[accountId] ||= []).push({ folderId, syncedAt });
1260
+ if (!syncedTimer) {
1261
+ syncedTimer = setTimeout(() => {
1262
+ syncedTimer = null;
1263
+ for (const [id, entries] of Object.entries(pendingSynced)) {
1264
+ handle.send({ _event: "folderSynced", type: "folderSynced", accountId: id, entries });
1265
+ }
1266
+ pendingSynced = {};
1267
+ }, 1000);
1268
+ }
1269
+ });
1270
+ imapManager.on("syncError", (accountId: string, error: string) => {
1271
+ handle.send({ _event: "error", type: "error", message: `${accountId}: ${error}` });
1272
+ });
1273
+ imapManager.on("accountError", (accountId: string, error: string, hint: string, isOAuth: boolean) => {
1274
+ handle.send({ _event: "accountError", type: "accountError", accountId, error, hint, isOAuth });
1275
+ });
1276
+ imapManager.on("configChanged", (filename: string) => {
1277
+ handle.send({ _event: "configChanged", type: "configChanged", filename });
1278
+ });
1279
+ imapManager.on("outboxStatus", (status: any) => {
1280
+ handle.send({ _event: "outboxStatus", type: "outboxStatus", ...status });
1281
+ });
1282
+ // syncComplete drives the folder-tree refresh that picks up newly-discovered
1283
+ // folders on first run (Gmail accounts have no folders in the DB until the
1284
+ // first sync fetches the labels). Without this forward, the UI shows the
1285
+ // account but no folders, and never auto-selects the inbox.
1286
+ imapManager.on("syncComplete", (accountId: string) => {
1287
+ handle.send({ _event: "syncComplete", type: "syncComplete", accountId });
1288
+ });
1289
+ imapManager.on("syncActionFailed", (accountId: string, action: string, uid: number, error: string) => {
1290
+ handle.send({ _event: "syncActionFailed", type: "syncActionFailed", accountId, action, uid, error });
1291
+ });
1292
+ // External-edit (Word) save events. The service watches the temp file
1293
+ // and emits this when Word writes; compose.ts listens and reloads Quill.
1294
+ imapManager.on("wordEditUpdated", (payload: { editId: string; html: string }) => {
1295
+ handle.send({ _event: "wordEditUpdated", type: "wordEditUpdated", ...payload });
1296
+ });
1297
+ // Cloud-write/read failures from mailx-settings → push to UI as a banner so
1298
+ // silent fall-back-to-local can no longer swallow Drive errors.
1299
+ const { onCloudError } = await import("@bobfrankston/mailx-settings");
1300
+ onCloudError((error, ctx) => {
1301
+ if (error) {
1302
+ handle.send({ _event: "cloudError", type: "cloudError", error, op: ctx?.op, filename: ctx?.filename });
1303
+ } else {
1304
+ handle.send({ _event: "cloudError", type: "cloudError", error: null });
1305
+ }
1306
+ });
1307
+ // Coalesce bodyCached into batches so a prefetch storm doesn't flood stdin
1308
+ // with one IPC write per message — lets the UI flip many rows at once.
1309
+ let pendingCached: { accountId: string; uid: number }[] = [];
1310
+ let cachedTimer: ReturnType<typeof setTimeout> | null = null;
1311
+ // Calendar/tasks refresh completion — service emits when a pull merged
1312
+ // new rows or reconciled a server-side delete. Client re-renders its
1313
+ // sidebar on receipt. No payload beyond accountId.
1314
+ imapManager.on("calendarUpdated", (payload: any) => {
1315
+ handle.send({ _event: "calendarUpdated", type: "calendarUpdated", ...payload });
1316
+ });
1317
+ imapManager.on("tasksUpdated", (payload: any) => {
1318
+ handle.send({ _event: "tasksUpdated", type: "tasksUpdated", ...payload });
1319
+ });
1320
+ imapManager.on("authScopeError", (payload: any) => {
1321
+ handle.send({ _event: "authScopeError", type: "authScopeError", ...payload });
1322
+ });
1323
+ imapManager.on("bodyCached", (accountId: string, uid: number) => {
1324
+ pendingCached.push({ accountId, uid });
1325
+ if (!cachedTimer) {
1326
+ cachedTimer = setTimeout(() => {
1327
+ cachedTimer = null;
1328
+ const batch = pendingCached;
1329
+ pendingCached = [];
1330
+ handle.send({ _event: "bodyCached", type: "bodyCached", items: batch });
1331
+ }, 500);
1332
+ }
1333
+ });
1334
+
1335
+ // Brief pause for WebView2 to initialize before starting IMAP (avoids stdin writes during init)
1336
+ await new Promise(r => setTimeout(r, 500));
1337
+
1338
+ // Register all accounts (OAuth may open browser for Gmail — event loop stays free for IPC)
1339
+ for (const account of settings.accounts) {
1340
+ if (!account.enabled) continue;
1341
+ try {
1342
+ await imapManager.addAccount(account);
1343
+ console.log(` Account: ${account.label || account.name} (${account.id})`);
1344
+ } catch (e: any) {
1345
+ console.error(` Failed: ${account.id}: ${e.message}`);
1346
+ }
1347
+ }
1348
+ // After OAuth has completed, resolve missing display names for Google
1349
+ // accounts via the People API (contacts.readonly is in the Gmail scope).
1350
+ // "Missing" = empty or matches the email local-part default.
1351
+ try {
1352
+ const { getGoogleProfile } = await import("@bobfrankston/mailx-settings/cloud.js");
1353
+ const { saveAccounts } = await import("@bobfrankston/mailx-settings");
1354
+ let updated = false;
1355
+ for (const acct of settings.accounts) {
1356
+ if (!acct.enabled) continue;
1357
+ const isGoogle = acct.email.endsWith("@gmail.com")
1358
+ || acct.email.endsWith("@googlemail.com")
1359
+ || acct.imap?.host?.includes("gmail");
1360
+ if (!isGoogle) continue;
1361
+ const local = acct.email.split("@")[0];
1362
+ const looksDefault = !acct.name || acct.name === local;
1363
+ if (!looksDefault) continue;
1364
+ try {
1365
+ const tok = await imapManager.getOAuthToken(acct.id);
1366
+ if (!tok) continue;
1367
+ const profile = await getGoogleProfile(tok);
1368
+ if (profile?.name && profile.name !== acct.name) {
1369
+ console.log(` [name-resolve] ${acct.id}: '${acct.name || "(empty)"}' → '${profile.name}'`);
1370
+ acct.name = profile.name;
1371
+ updated = true;
1372
+ }
1373
+ } catch (e: any) {
1374
+ console.error(` [name-resolve] ${acct.id}: ${e.message}`);
1375
+ }
1376
+ }
1377
+ if (updated) {
1378
+ try { await saveAccounts(settings.accounts); } catch (e: any) {
1379
+ console.error(` [name-resolve] saveAccounts failed: ${e.message}`);
1380
+ }
1381
+ }
1382
+ } catch (e: any) {
1383
+ console.error(` [name-resolve] init failed: ${e.message}`);
1384
+ }
1385
+ // Register this client device on GDrive (fire-and-forget).
1386
+ // Skip when no accounts — cloud isn't configured yet on fresh installs,
1387
+ // so the write fails with "No cloud configured" and flashes a scary banner.
1388
+ if (settings.accounts.length > 0) {
1389
+ registerClient(settings).catch(() => {});
1390
+ }
1391
+
1392
+ // Start sync in background — don't block. Kick off IDLE watchers once the
1393
+ // initial sync finishes so IMAP accounts get instant-push new-mail (the
1394
+ // 5-min STATUS poll is only a safety net).
1395
+ if (settings.accounts.some(a => a.enabled)) {
1396
+ // Fast-path: fire a quick INBOX check on every account IMMEDIATELY,
1397
+ // parallel to the full syncAll. quickInboxCheckAccount uses a fresh
1398
+ // client + a cached folder list from the DB, so it skips the
1399
+ // folder-list fetch that syncAll's step 1 does. On a cold Dovecot
1400
+ // session that folder LIST can take several seconds on big trees
1401
+ // (bobma = ~105 folders) — no reason the user should wait for it
1402
+ // before seeing mail that arrived overnight in INBOX.
1403
+ for (const acct of settings.accounts) {
1404
+ if (!acct.enabled) continue;
1405
+ imapManager.quickInboxCheckAccount(acct.id).catch(e =>
1406
+ console.error(` [startup-check] ${acct.id}: ${e?.message || e}`)
1407
+ );
1408
+ }
1409
+ imapManager.syncAll()
1410
+ .then(() => imapManager.startWatching())
1411
+ .then(() => {
1412
+ // Seed the contacts table from received messages so address
1413
+ // autocomplete works on the first compose without waiting for
1414
+ // the user to manually trigger it. Cheap — one grouped SELECT
1415
+ // + one INSERT per new sender. No-op if contact already exists.
1416
+ const added = db.seedContactsFromMessages();
1417
+ if (added > 0) console.log(` [contacts] seeded ${added} from message senders`);
1418
+ })
1419
+ .catch(e => console.error(` Sync error: ${e.message}`));
1420
+ }
1421
+ imapManager.startPeriodicSync(settings.sync.intervalMinutes);
1422
+ imapManager.startOutboxWorker();
1423
+ imapManager.watchConfigFiles();
1424
+ // Re-seed contacts every 30 min so newly-received senders surface in
1425
+ // autocomplete without restarting mailx. Cheap; idempotent.
1426
+ setInterval(() => {
1427
+ try {
1428
+ const added = db.seedContactsFromMessages();
1429
+ if (added > 0) console.log(` [contacts] periodic seed added ${added} new senders`);
1430
+ } catch (e: any) { console.error(` [contacts] periodic seed error: ${e.message}`); }
1431
+ }, 30 * 60_000);
1432
+ // Drain store_sync (calendar / tasks / contacts two-way pushes) every
1433
+ // 30s. Local edits also drain immediately; this picks up rows that
1434
+ // failed their first attempt (network blip, token refresh, 5xx).
1435
+ setInterval(() => {
1436
+ svc.drainStoreSync().catch((e: any) =>
1437
+ console.error(` [store_sync] periodic drain error: ${e?.message || e}`));
1438
+ }, 30_000);
1439
+ // Calendar + Tasks poll — pulls server-side changes so the sidebar
1440
+ // reflects events added/edited/deleted on another device without
1441
+ // needing a sidebar nav click. 5-minute cadence is well under the
1442
+ // per-user rate limit and the 1M/day project quota. Webhooks would
1443
+ // be cheaper in theory but need a public HTTPS endpoint; poll is
1444
+ // the pragmatic choice (confirmed 2026-04-23). getCalendarEvents /
1445
+ // getTasks emit the refresh event via imapManager, so the sidebar
1446
+ // re-renders automatically.
1447
+ const CAL_POLL_MS = 5 * 60_000;
1448
+ const horizonDays = 90; // larger than sidebar's default so background
1449
+ // poll catches upcoming-week events the sidebar hasn't asked for yet.
1450
+ setInterval(() => {
1451
+ const now = Date.now();
1452
+ svc.getCalendarEvents(now, now + horizonDays * 86400_000)
1453
+ .catch((e: any) => console.error(` [calendar] poll error: ${e?.message || e}`));
1454
+ svc.getTasks(false)
1455
+ .catch((e: any) => console.error(` [tasks] poll error: ${e?.message || e}`));
1456
+ }, CAL_POLL_MS);
1457
+
1458
+ // Contacts poll — incremental sync via People API syncToken (persisted
1459
+ // per-account in the kv table). Cheap after the first run because only
1460
+ // changed/deleted contacts come back. 15-minute cadence picks up new
1461
+ // contacts added on phone / web without restart while staying well
1462
+ // under the People API rate limit.
1463
+ const CONTACTS_POLL_MS = 15 * 60_000;
1464
+ setInterval(() => {
1465
+ svc.syncGoogleContacts()
1466
+ .catch((e: any) => console.error(` [contacts] poll error: ${e?.message || e}`));
1467
+ }, CONTACTS_POLL_MS);
1468
+
1469
+ // Auto-update: periodically check npm for a newer version and push a
1470
+ // notification to the WebView so the user can update with one click.
1471
+ const UPDATE_CHECK_MS = 30 * 60_000; // 30 minutes
1472
+ async function checkForUpdate(): Promise<void> {
1473
+ try {
1474
+ // spawn with windowsHide:true — execSync briefly flashes a cmd
1475
+ // window on Windows every time the periodic check fires.
1476
+ const { spawn } = await import("child_process");
1477
+ const latest = await new Promise<string>((resolve, reject) => {
1478
+ const child = spawn("npm", ["view", "@bobfrankston/mailx", "version"], {
1479
+ windowsHide: true,
1480
+ shell: true,
1481
+ });
1482
+ let out = "";
1483
+ let err = "";
1484
+ child.stdout.on("data", (d: Buffer) => { out += d.toString(); });
1485
+ child.stderr.on("data", (d: Buffer) => { err += d.toString(); });
1486
+ const killer = setTimeout(() => { try { child.kill(); } catch { /* */ } reject(new Error("npm view timed out")); }, 15_000);
1487
+ child.on("error", (e) => { clearTimeout(killer); reject(e); });
1488
+ child.on("exit", (code) => {
1489
+ clearTimeout(killer);
1490
+ if (code === 0) resolve(out.trim());
1491
+ else reject(new Error(err.trim() || `npm view exit ${code}`));
1492
+ });
1493
+ });
1494
+ const current = rootPkgVersion;
1495
+ if (latest && latest !== current) {
1496
+ console.log(` [update] New version available: ${current} → ${latest}`);
1497
+ handle.send({ _event: "updateAvailable", type: "updateAvailable", current, latest });
1498
+ }
1499
+ } catch (e: any) {
1500
+ // Silent — network down, npm not reachable, etc.
1501
+ console.log(` [update] Check failed: ${e.message}`);
1502
+ }
1503
+ }
1504
+ // First check after 2 minutes (don't slow down startup), then every 30 min
1505
+ setTimeout(() => {
1506
+ checkForUpdate();
1507
+ setInterval(checkForUpdate, UPDATE_CHECK_MS);
1508
+ }, 120_000);
1509
+
1510
+ // Graceful shutdown — close IMAP connections, stop timers, close DB
1511
+ let shuttingDown = false;
1512
+ async function gracefulShutdown(reason: string): Promise<void> {
1513
+ if (shuttingDown) return;
1514
+ shuttingDown = true;
1515
+ console.log(`${reason} — shutting down`);
1516
+ imapManager.stopPeriodicSync();
1517
+ imapManager.stopOutboxWorker();
1518
+ // 3s hard timeout — don't hang on broken IMAP connections
1519
+ const forceExit = setTimeout(() => { console.log("Forced exit"); process.exit(0); }, 3000);
1520
+ try { await imapManager.shutdown(); } catch { /* proceed */ }
1521
+ clearTimeout(forceExit);
1522
+ db.close();
1523
+ process.exit(0);
1524
+ }
1525
+
1526
+ process.on("SIGINT", () => gracefulShutdown("SIGINT"));
1527
+ process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
1528
+ process.on("uncaughtException", (err) => {
1529
+ console.error(`UNCAUGHT EXCEPTION: ${err.stack || err.message}`);
1530
+ gracefulShutdown("uncaughtException");
1531
+ });
1532
+ process.on("unhandledRejection", (reason: any) => {
1533
+ console.error(`UNHANDLED REJECTION: ${reason?.stack || reason?.message || reason}`);
1534
+ });
1535
+ process.on("exit", (code) => {
1536
+ console.log(`Process exit (code ${code})`);
1537
+ if (!shuttingDown) {
1538
+ imapManager.stopPeriodicSync();
1539
+ imapManager.stopOutboxWorker();
1540
+ db.close();
1541
+ }
1542
+ });
1543
+
1544
+ // Wait for window close, then shut down
1545
+ await handle.closed;
1546
+ await gracefulShutdown("Window closed");
1547
+ }
1548
+
1549
+ main().catch(console.error);