A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Mail on Windows: classic Outlook, the Mail section and the chat's mail plans
Claude19d79f40d43f
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex ed962d22..c543a031 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -15,10 +15,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"dependencies = ["cfg-if",- "cipher",+ "cipher 0.4.4","cpufeatures 0.2.17",]+[[package]]+name = "aes"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"+dependencies = [+ "cipher 0.5.2",+ "cpubits",+ "cpufeatures 0.3.1",+]+[[package]]name = "aho-corasick"version = "1.1.5"@@ -28,19 +39,34 @@ dependencies = ["memchr",]+[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"+[[package]]name = "alloc-no-stdlib"version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"+[[package]]+name = "alloc-stdlib"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"+dependencies = [+ "alloc-no-stdlib 2.0.4",+]+[[package]]name = "alloc-stdlib"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"dependencies = [- "alloc-no-stdlib",+ "alloc-no-stdlib 3.0.0",][[package]]@@ -341,6 +367,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]+[[package]]name = "block-padding"version = "0.3.3"@@ -350,6 +385,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-padding"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"+dependencies = [+ "hybrid-array",+]+[[package]]name = "block2"version = "0.6.2"@@ -378,9 +422,19 @@ version = "9.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"dependencies = [- "alloc-no-stdlib",- "alloc-stdlib",- "brotli-decompressor",+ "alloc-no-stdlib 3.0.0",+ "alloc-stdlib 0.3.0",+ "brotli-decompressor 6.0.1",+]++[[package]]+name = "brotli-decompressor"+version = "5.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"+dependencies = [+ "alloc-no-stdlib 2.0.4",+ "alloc-stdlib 0.2.4",][[package]]@@ -389,8 +443,8 @@ version = "6.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"dependencies = [- "alloc-no-stdlib",- "alloc-stdlib",+ "alloc-no-stdlib 3.0.0",+ "alloc-stdlib 0.3.0",][[package]]@@ -532,7 +586,16 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"dependencies = [- "cipher",+ "cipher 0.4.4",+]++[[package]]+name = "cbc"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"+dependencies = [+ "cipher 0.5.2",][[package]]@@ -615,8 +678,18 @@ version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = [- "crypto-common",- "inout",+ "crypto-common 0.1.7",+ "inout 0.1.4",+]++[[package]]+name = "cipher"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"+dependencies = [+ "crypto-common 0.2.2",+ "inout 0.2.5",][[package]]@@ -647,6 +720,12 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "const-oid"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"+[[package]]name = "constant_time_eq"version = "0.3.1"@@ -703,6 +782,12 @@ dependencies = ["libc",]+[[package]]+name = "core_detect"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"+[[package]]name = "coreaudio-rs"version = "0.14.2"@@ -728,6 +813,7 @@ dependencies = ["gtk","keyring","libc",+ "lopdf","mdns-sd","miniz_oxide 0.8.9","qrcode",@@ -795,6 +881,12 @@ dependencies = ["windows-core 0.62.2",]+[[package]]+name = "cpubits"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -862,6 +954,15 @@ dependencies = ["typenum",]+[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]+[[package]]name = "cssparser"version = "0.37.0"@@ -954,15 +1055,15 @@ version = "4.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"dependencies = [- "aes",- "block-padding",- "cbc",+ "aes 0.8.4",+ "block-padding 0.3.3",+ "cbc 0.1.2","dbus","fastrand","hkdf","num","once_cell",- "sha2",+ "sha2 0.10.9","zeroize",]@@ -1050,11 +1151,22 @@ version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = [- "block-buffer",- "crypto-common",+ "block-buffer 0.10.4",+ "crypto-common 0.1.7","subtle",]+[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.1",+ "const-oid",+ "crypto-common 0.2.2",+]+[[package]]name = "dirs"version = "4.0.0"@@ -1199,6 +1311,15 @@ version = "1.0.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]+name = "ecb"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac"+dependencies = [+ "cipher 0.5.2",+]+[[package]]name = "embed-resource"version = "3.0.11"@@ -1219,6 +1340,20 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "encoding_rs"+version = "0.8.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "844dfa6d76a4e6b9d98e03ae5ead89fbedd02cbd1206b7817d6d3dca62326967"+dependencies = [+ "cfg-if",+ "core_detect",+ "multiversion_no_op",+ "rustversion",+ "scopeguard",+ "simdutf8",+]+[[package]]name = "endi"version = "1.1.1"@@ -1918,7 +2053,7 @@ version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"dependencies = [- "digest",+ "digest 0.10.7",][[package]]@@ -1970,6 +2105,15 @@ version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+[[package]]+name = "hybrid-array"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"+dependencies = [+ "typenum",+]+[[package]]name = "hyper"version = "1.11.1"@@ -2222,10 +2366,20 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"dependencies = [- "block-padding",+ "block-padding 0.3.3","generic-array",]+[[package]]+name = "inout"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"+dependencies = [+ "block-padding 0.4.2",+ "hybrid-array",+]+[[package]]name = "ipnet"version = "2.12.2"@@ -2552,6 +2706,33 @@ version = "0.4.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"+[[package]]+name = "lopdf"+version = "0.46.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d43f64cb8c0d673ff84245a6de9e0172c0cc05dc5dd9d263660b5b4a02b6c4ae"+dependencies = [+ "aes 0.9.3",+ "bitflags 2.13.2",+ "brotli-decompressor 5.0.3",+ "cbc 0.2.1",+ "ecb",+ "encoding_rs",+ "flate2",+ "getrandom 0.4.3",+ "indexmap 2.14.2",+ "itoa",+ "log",+ "md-5",+ "nom",+ "rand 0.10.3",+ "rangemap",+ "sha2 0.11.1",+ "stringprep",+ "thiserror 2.0.21",+ "weezl",+]+[[package]]name = "lru-slab"version = "0.1.3"@@ -2596,6 +2777,16 @@ dependencies = ["web_atoms",]+[[package]]+name = "md-5"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"+dependencies = [+ "cfg-if",+ "digest 0.11.3",+]+[[package]]name = "mdns-sd"version = "0.21.5"@@ -2684,6 +2875,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "multiversion_no_op"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"+[[package]]name = "ndk"version = "0.9.0"@@ -3194,7 +3391,7 @@ version = "0.12.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"dependencies = [- "digest",+ "digest 0.10.7","hmac",]@@ -3653,6 +3850,12 @@ dependencies = ["rand_core 0.10.1",]+[[package]]+name = "rangemap"+version = "1.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"+[[package]]name = "raw-window-handle"version = "0.6.2"@@ -3984,8 +4187,8 @@ version = "4.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4"dependencies = [- "aes",- "cbc",+ "aes 0.8.4",+ "cbc 0.1.2","futures-util","generic-array","hkdf",@@ -3993,7 +4196,7 @@ dependencies = ["once_cell","rand 0.8.8","serde",- "sha2",+ "sha2 0.10.9","zbus 4.4.0",]@@ -4206,7 +4409,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",][[package]]@@ -4217,7 +4420,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",+]++[[package]]+name = "sha2"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.1",+ "digest 0.11.3",][[package]]@@ -4413,6 +4627,17 @@ dependencies = ["quote",]+[[package]]+name = "stringprep"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"+dependencies = [+ "unicode-bidi",+ "unicode-normalization",+ "unicode-properties",+]+[[package]]name = "strsim"version = "0.11.1"@@ -4658,7 +4883,7 @@ dependencies = ["semver","serde","serde_json",- "sha2",+ "sha2 0.10.9","syn 2.0.119","tauri-utils","thiserror 2.0.21",@@ -5264,12 +5489,33 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"+[[package]]name = "unicode-ident"version = "1.0.26"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"+[[package]]+name = "unicode-normalization"+version = "0.1.26"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"+dependencies = [+ "tinyvec",+]++[[package]]+name = "unicode-properties"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"+[[package]]name = "unicode-segmentation"version = "1.13.3"@@ -5680,6 +5926,12 @@ dependencies = ["windows-core 0.62.2",]+[[package]]+name = "weezl"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2"+[[package]]name = "winapi"version = "0.3.9"@@ -6263,7 +6515,7 @@ dependencies = ["once_cell","percent-encoding","raw-window-handle",- "sha2",+ "sha2 0.10.9","soup3","tao-macros","thiserror 2.0.21",@@ -6608,7 +6860,7 @@ version = "2.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"dependencies = [- "aes",+ "aes 0.8.4","arbitrary","bzip2 0.5.2","constant_time_eq",diff --git a/windows/README.md b/windows/README.mdindex a3f80fad..2fca954d 100644--- a/windows/README.md+++ b/windows/README.md@@ -320,6 +320,27 @@ minute while a CI is running, and as soon as you open the card on data olderthan a minute; contributions every 30 minutes. Nothing is fetched while the pillis off or Coucou is paused.+## Mail (classic Outlook, Windows)++Turn the **Mail** pill on in Notch → Active pills. Coucou reads the Outlook already open on+your PC — the classic Outlook of Microsoft 365, through its own COM objects — with no sign-in,+no app to register at Microsoft and no admin consent. It never starts Outlook, and a closed+Outlook costs nothing. The new Outlook for Windows has no COM objects, so it is not reached+this way. Linux has no Outlook: the pill is Windows only.++| What you do | What happens |+|---|---|+| Open the Mail pill | Your newest messages, unread ones tinted, a ⚑ on the flagged ones. The magnifier searches every inbox: free words, `from:anne`, `subject:"May quote"`. Filters: All, Unread, Important, Today |+| Click a message | Its sender, subject and the start of its text. **Open in Outlook**, **Reply** (Outlook's own window: nothing is sent from Coucou), **Mark as read**, **Important**, **Junk**, and in ⋯ **Always important (VIP)** or **Always ignore this sender** |+| Coucou → Mail → Overview | **Sort new messages automatically** (off by default): only what arrives after you turn it on, each message once. VIPs are flagged, banned words send to Junk, then the first rule that matches acts. A journal of every action, each with **Undo** |+| Coucou → Mail → Rules, Banned words, VIP | "If the sender / domain / subject / text / account contains … then Junk / important / read / move to a folder". Banned words are whole words: "sale" does not catch "Salesforce". A VIP is an address or a whole domain (`@client.com`) |+| Turn on **Mail** next to the model in the chat | The AI gets your 40 newest messages (text and attachments for the newest and for the ones you name) and may answer with a plan: sort, reply drafts, sends, a mail merge that gives each recipient their page of a PDF, saving attachments. The plan shows as a card: the mails to send, the ones that can't be sent in red, **Send me a test**, and **Run**, which waits 5 seconds (Cancel) before anything happens |++Coucou never deletes a message, and never sends one without your click on Run. Your mail+goes only to the chat's AI you picked (your key or your subscription), and only while the+chat's Mail switch is on. On some company PCs, Outlook may ask whether to let a program use+it: that is Outlook's own security prompt, set by your IT department.+## WhatsApp (experimental)The same as on the Mac. Your WhatsApp messages in the island, through adiff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.tomlindex c11d92ca..049fd0fc 100644--- a/windows/src-tauri/Cargo.toml+++ b/windows/src-tauri/Cargo.toml@@ -53,6 +53,10 @@ cpal = "0.18"# the raw DEFLATE decoder only, already in the tree through png (the same 0.8.9), so nothing new is# downloaded or compiled. MIT/Zlib/Apache-2.0.miniz_oxide = "0.8"+# The chat's mail merge cuts a PDF into one page per recipient and reads each page's text+# (mail/pdf.rs), as the Mac does with PDFKit; Windows has no PDF library of its own. MIT, pure+# Rust, default features (clock, rayon) off.+lopdf = { version = "0.46", default-features = false }[target.'cfg(windows)'.dependencies]keyring = { version = "3", features = ["windows-native"] }diff --git a/windows/src-tauri/src/chat.rs b/windows/src-tauri/src/chat.rsindex a681e05e..1ca5d44b 100644--- a/windows/src-tauri/src/chat.rs+++ b/windows/src-tauri/src/chat.rs@@ -115,7 +115,12 @@ impl Chat {/// has one worth using (identity.rs), and only claims web search where the/// provider runs it (Claude).pub fn system_prompt(web_search: bool) -> String {- system_prompt_for(crate::identity::first_name(), web_search)+ let base = system_prompt_for(crate::identity::first_name(), web_search);+ // The chat's Mail switch is on for this turn: how to write a mail plan.+ if crate::mail::MAIL_TURN.load(std::sync::atomic::Ordering::Relaxed) {+ return base + crate::mail::plan::INSTRUCTIONS;+ }+ base}fn system_prompt_for(first_name: Option<&str>, web_search: bool) -> String {diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex 765772de..8c216498 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -19,6 +19,7 @@ mod integrations;mod island;mod local_chat;mod log;+mod mail;mod net;mod notes;mod openai_compat;@@ -535,8 +536,18 @@ async fn chat_send(chat: State<'_, Chat>,query: String,context: Option<ChatContext>,+ mail: Option<bool>,) -> Result<ChatReply, String> {let settings = shared.settings.lock().unwrap().clone();+ // The chat's Mail switch: the latest Outlook messages ride under the request, and the+ // system prompt says how to write a plan (mail/plan.rs) that runs only after a click.+ if mail == Some(true) {+ let query = mail::decorate(&query).await;+ mail::MAIL_TURN.store(true, std::sync::atomic::Ordering::Relaxed);+ let reply = chat::send(&app, &chat, &settings, query, context).await;+ mail::MAIL_TURN.store(false, std::sync::atomic::Ordering::Relaxed);+ return reply;+ }chat::send(&app, &chat, &settings, query, context).await}@@ -850,6 +861,20 @@ pub fn run() {.manage(recap::load()).invoke_handler(tauri::generate_handler![boot,+ mail::mail_refresh,+ mail::mail_more,+ mail::mail_search,+ mail::mail_detail,+ mail::mail_open,+ mail::mail_act,+ mail::mail_triage,+ mail::mail_triage_set,+ mail::mail_journal_clear,+ mail::mail_undo,+ mail::mail_plan_show,+ mail::mail_plan_test,+ mail::mail_plan_start,+ mail::mail_plan_cancel,save_settings,set_system_languages,set_collapsed,@@ -1052,6 +1077,7 @@ pub fn run() {pipe::start(handle.clone());phone_link::start_if_enabled(&handle);integrations::start(handle.clone());+ mail::start(handle.clone());spotify::sync(&handle, &loaded.active_integrations);// WhatsApp (experimental): nothing runs unless it is turned on and its pill is active.whatsapp::start(&handle, &loaded.active_integrations);diff --git a/windows/src-tauri/src/mail/mod.rs b/windows/src-tauri/src/mail/mod.rsnew file mode 100644index 00000000..b8f638d0--- /dev/null+++ b/windows/src-tauri/src/mail/mod.rs@@ -0,0 +1,833 @@+// The Mail pill on Windows: classic Outlook, driven through its COM objects (outlook.rs).+// Port of MailController / MailTriageStore / MailAgent from the Mac, where Apple Mail plays+// Outlook's part.+//+// - The pill: the latest messages of every inbox, a search and quick filters, and actions+// on a message (each one the user's click).+// - The Mail section of the Coucou window: automatic sorting (off by default), rules, banned+// words, VIPs, a journal with Undo, and what Coucou sent.+// - The chat's Mail switch: the AI gets the latest messages and may answer with a plan+// (plan.rs) that runs only after the user clicks Run on its card.+//+// Outlook is read every 60 s only while the pill is on or the sorting is, and only when+// OUTLOOK.EXE runs: Coucou never starts Outlook, and a closed Outlook costs nothing.+// Coucou never deletes a message.++pub mod outlook;+pub mod pdf;+pub mod plan;+pub mod store;+pub mod triage;++use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Mutex, MutexGuard, OnceLock};+use std::time::Duration;++use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use tauri::{AppHandle, Emitter, Manager};++use outlook::{Message, RunError};+use plan::{Plan, Step};+use store::{JournalEntry, SentEntry, Store};+use triage::{Action, Facts, Filter, Query, Reason, Settings};++pub const PILL: &str = "integration_mail";+const OUTLOOK_EXE: &str = "OUTLOOK.EXE";+const TIMEOUT: Duration = Duration::from_secs(40);+const KEEP: usize = 12;+const MAX_SHOWN: usize = 60;++/// Set around a chat turn sent with the Mail switch on: chat::system_prompt adds the+/// mail instructions while it is.+pub static MAIL_TURN: AtomicBool = AtomicBool::new(false);++static BUSY: AtomicBool = AtomicBool::new(false);+static COUNTER: AtomicU64 = AtomicU64::new(0);++struct Runtime {+ store: Store,+ shown: usize,+ /// The card's list and unread count, as last read.+ last: Vec<Message>,+ last_unread: i64,+ /// The messages of the last list sent to the AI, by their number.+ numbered: HashMap<usize, Message>,+ accounts: Vec<(String, String)>,+ plans: HashMap<String, PlanRun>,+ cancelled: HashSet<String>,+}++fn rt() -> MutexGuard<'static, Runtime> {+ static RT: OnceLock<Mutex<Runtime>> = OnceLock::new();+ RT.get_or_init(|| {+ Mutex::new(Runtime {+ store: Store::load(crate::platform::config_dir().join("mail")),+ shown: KEEP,+ last: Vec::new(),+ last_unread: 0,+ numbered: HashMap::new(),+ accounts: Vec::new(),+ plans: HashMap::new(),+ cancelled: HashSet::new(),+ })+ })+ .lock()+ .unwrap_or_else(|e| e.into_inner())+}++fn now_ms() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as i64)+ .unwrap_or(0)+}++fn new_id() -> String {+ format!("{:x}-{:x}", now_ms(), COUNTER.fetch_add(1, Ordering::Relaxed))+}++fn sender_of(m: &Message) -> String {+ if m.sender_name.is_empty() { m.address.clone() } else { format!("{} <{}>", m.sender_name, m.address) }+}++fn pill_on(app: &AppHandle) -> bool {+ app.try_state::<crate::Shared>()+ .map(|shared| shared.settings.lock().unwrap().active_integrations.iter().any(|x| x == PILL))+ .unwrap_or(false)+}++fn outlook_open() -> bool {+ cfg!(windows) && crate::platform::process_running(OUTLOOK_EXE)+}++fn emit_card(app: &AppHandle, running: bool) {+ let data = {+ let r = rt();+ json!({+ "running": running,+ "windows": cfg!(windows),+ "unread": r.last_unread,+ "messages": r.last,+ "shown": r.shown,+ "maxShown": MAX_SHOWN,+ })+ };+ let _ = app.emit_to(crate::island::WINDOW_LABEL, "integration", json!({+ "id": PILL, "data": data, "error": Value::Null, "event": Value::Null,+ }));+}++// ── Polling ──────────────────────────────────────────────────────────────────++pub fn start(app: AppHandle) {+ let _ = std::fs::remove_dir_all(work_dir());+ tauri::async_runtime::spawn(async move {+ tokio::time::sleep(Duration::from_secs(8)).await;+ let mut ticker = tokio::time::interval(Duration::from_secs(60));+ loop {+ ticker.tick().await;+ poll(&app).await;+ }+ });+}++/// Reads the inboxes (the card, and the sorting) when the pill or the sorting is on.+pub async fn poll(app: &AppHandle) {+ if crate::integrations::PAUSED.load(Ordering::Relaxed) {+ return;+ }+ let pill = pill_on(app);+ let auto = rt().store.settings.auto_sort;+ if !pill && !auto {+ return;+ }+ if !outlook_open() {+ if pill {+ emit_card(app, false);+ }+ return;+ }+ if BUSY.swap(true, Ordering::AcqRel) {+ return;+ }+ let per_inbox = { rt().shown.max(if auto { 30 } else { 0 }) };+ let result = outlook::run(outlook::list_script(per_inbox), TIMEOUT).await;+ BUSY.store(false, Ordering::Release);+ match result {+ Ok(v) => {+ let listing: outlook::Listing = serde_json::from_value(v).unwrap_or_default();+ let mut all = listing.messages;+ all.sort_by(|a, b| b.date.cmp(&a.date));+ {+ let mut r = rt();+ r.last_unread = listing.unread;+ r.last = all.iter().take(r.shown).cloned().collect();+ }+ if pill {+ emit_card(app, true);+ }+ triage(app, &all).await;+ }+ Err(RunError::NotRunning) if pill => emit_card(app, false),+ Err(e) => crate::log::line(format!("[mail] Outlook: {e}")),+ }+}++/// The automatic sorting: each message that arrived since it was turned on is looked at once+/// (VIPs, banned words, rules), and what it does goes in the journal.+async fn triage(app: &AppHandle, list: &[Message]) {+ let settings = rt().store.settings.clone();+ let (true, Some(since)) = (settings.auto_sort, settings.auto_sort_since) else { return };+ let mut fresh: Vec<Message> = {+ let r = rt();+ list.iter().filter(|m| m.date >= since && !r.store.is_seen(&m.id())).cloned().collect()+ };+ if fresh.is_empty() {+ return;+ }+ fresh.sort_by_key(|m| m.date);+ rt().store.mark_seen(&fresh.iter().map(Message::id).collect::<Vec<_>>());+ let needs_text = triage::needs_text(&settings);+ let mut changed = false;+ for m in &fresh {+ let mut facts = Facts {+ sender_name: m.sender_name.clone(),+ address: m.address.clone(),+ subject: m.subject.clone(),+ account: m.account.clone(),+ text: None,+ };+ if needs_text {+ facts.text = detail(m, 4000).await.map(|d| d.text);+ }+ if let Some(d) = triage::decide(&facts, &settings) {+ changed |= perform(&d.action, m, d.reason).await.is_ok();+ }+ }+ if changed && pill_on(app) {+ emit_card(app, true);+ }+}++/// Applies `action` to a message in Outlook, writes it in the journal and updates the card.+async fn perform(action: &Action, m: &Message, reason: Reason) -> Result<(), String> {+ let v = outlook::run(outlook::apply_script(&m.entry_id, &m.store_id, action), TIMEOUT)+ .await+ .map_err(|e| e.to_string())?;+ let after = v.get("entryId").and_then(Value::as_str).unwrap_or(&m.entry_id).to_string();+ let mut r = rt();+ r.store.record(JournalEntry {+ id: new_id(),+ date: now_ms(),+ account: m.account.clone(),+ store_id: m.store_id.clone(),+ entry_id: after,+ sender: sender_of(m),+ subject: m.subject.clone(),+ action: action.clone(),+ reason,+ undone: false,+ });+ let id = m.id();+ match action {+ Action::Junk | Action::Move(_) => {+ if r.last.iter().any(|x| x.id() == id && x.unread) {+ r.last_unread = (r.last_unread - 1).max(0);+ }+ r.last.retain(|x| x.id() != id);+ }+ Action::Important => r.last.iter_mut().filter(|x| x.id() == id).for_each(|x| x.flagged = true),+ Action::MarkRead => r.last.iter_mut().filter(|x| x.id() == id).for_each(|x| x.unread = false),+ }+ Ok(())+}++#[derive(Serialize, Deserialize, Default, Clone)]+pub struct Detail {+ #[serde(default)]+ pub text: String,+ #[serde(default)]+ pub attachments: Vec<String>,+}++async fn detail(m: &Message, limit: usize) -> Option<Detail> {+ let v = outlook::run(outlook::detail_script(&m.entry_id, &m.store_id, limit), TIMEOUT).await.ok()?;+ serde_json::from_value(v).ok()+}++// ── The pill's commands ──────────────────────────────────────────────────────++/// Reads Outlook now (the card opened, Refresh).+#[tauri::command]+pub async fn mail_refresh(app: AppHandle) {+ poll(&app).await;+}++/// The card shows 12 more messages.+#[tauri::command]+pub async fn mail_more(app: AppHandle) {+ {+ let mut r = rt();+ r.shown = (r.shown + KEEP).min(MAX_SHOWN);+ }+ poll(&app).await;+}++/// Searches every inbox; nothing to search: the card's list.+#[tauri::command]+pub async fn mail_search(query: String, filter: Filter) -> Result<Vec<Message>, String> {+ let Some(dasl) = outlook::dasl(&Query::parse(&query), filter) else { return Ok(rt().last.clone()) };+ let v = outlook::run(outlook::search_script(&dasl, MAX_SHOWN), TIMEOUT).await.map_err(|e| e.to_string())?;+ let mut list = serde_json::from_value::<outlook::Listing>(v).unwrap_or_default().messages;+ list.sort_by(|a, b| b.date.cmp(&a.date));+ list.truncate(MAX_SHOWN);+ Ok(list)+}++/// A message's text (1,200 characters) and attachments, for the card.+#[tauri::command]+pub async fn mail_detail(message: Message) -> Result<Detail, String> {+ detail(&message, 1200).await.ok_or_else(|| "Outlook did not answer".to_string())+}++/// Opens the message (or a reply to it) in Outlook's own window. Nothing is sent.+#[tauri::command]+pub async fn mail_open(message: Message, reply: bool) -> Result<(), String> {+ let body = reply.then_some("");+ outlook::run(outlook::open_script(&message.entry_id, &message.store_id, body), TIMEOUT)+ .await+ .map(|_| ())+ .map_err(|e| e.to_string())+}++/// An action on a message, from the user's click in the card.+#[tauri::command]+pub async fn mail_act(app: AppHandle, message: Message, kind: String) -> Result<(), String> {+ match kind.as_str() {+ "read" => perform(&Action::MarkRead, &message, Reason::Manual).await?,+ "flag" => perform(&Action::Important, &message, Reason::Manual).await?,+ "unflag" => {+ outlook::run(outlook::unflag_script(&message.entry_id, &message.store_id), TIMEOUT)+ .await+ .map_err(|e| e.to_string())?;+ rt().last.iter_mut().filter(|x| x.id() == message.id()).for_each(|x| x.flagged = false);+ }+ "junk" => perform(&Action::Junk, &message, Reason::Manual).await?,+ "ignore" => {+ rt().store.add_banned(&message.address);+ perform(&Action::Junk, &message, Reason::Manual).await?;+ }+ "vip" => {+ rt().store.add_vip(&message.address);+ if !message.flagged {+ perform(&Action::Important, &message, Reason::Manual).await?;+ }+ }+ other => return Err(format!("unknown action {other}")),+ }+ emit_card(&app, true);+ Ok(())+}++// ── The Mail section's commands ──────────────────────────────────────────────++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+pub struct TriageView {+ settings: Settings,+ journal: Vec<JournalEntry>,+ sent: Vec<SentEntry>,+ today: Value,+ windows: bool,+ outlook_open: bool,+}++#[tauri::command]+pub fn mail_triage() -> TriageView {+ let r = rt();+ let start_of_day = {+ let t = crate::platform::local_time();+ let secs_today = (t.hour * 3600 + t.minute * 60 + t.second) as i64;+ now_ms() - secs_today * 1000+ };+ let today: Vec<&JournalEntry> = r.store.journal.iter().filter(|e| e.date >= start_of_day && !e.undone).collect();+ TriageView {+ settings: r.store.settings.clone(),+ journal: r.store.journal.iter().take(100).cloned().collect(),+ sent: r.store.sent.iter().take(50).cloned().collect(),+ today: json!({+ "sorted": today.len(),+ "junk": today.iter().filter(|e| e.action == Action::Junk).count(),+ "important": today.iter().filter(|e| e.action == Action::Important).count(),+ }),+ windows: cfg!(windows),+ outlook_open: outlook_open(),+ }+}++#[tauri::command]+pub async fn mail_triage_set(app: AppHandle, settings: Settings) {+ rt().store.set_settings(settings, now_ms());+ poll(&app).await;+}++#[tauri::command]+pub fn mail_journal_clear() {+ rt().store.clear_journal();+}++/// Puts back a message the journal shows as sorted.+#[tauri::command]+pub async fn mail_undo(app: AppHandle, id: String) -> Result<(), String> {+ let entry = rt().store.journal.iter().find(|e| e.id == id && !e.undone).cloned().ok_or("not found")?;+ outlook::run(outlook::undo_script(&entry.entry_id, &entry.store_id, &entry.action), TIMEOUT)+ .await+ .map_err(|e| e.to_string())?;+ rt().store.mark_undone(&id);+ poll(&app).await;+ Ok(())+}++// ── The chat's Mail switch ───────────────────────────────────────────────────++/// The user's request with the latest messages under it, for the AI.+pub async fn decorate(query: &str) -> String {+ if !cfg!(windows) {+ return format!("{query}\n\n<mail>Outlook is only reached on Windows: say so.</mail>");+ }+ if !outlook_open() {+ return format!("{query}\n\n<mail>Outlook is closed: ask the user to open the classic Outlook, then to ask again.</mail>");+ }+ if let Ok(v) = outlook::run(outlook::accounts_script(), TIMEOUT).await {+ let accounts: Vec<(String, String)> = v["accounts"]+ .as_array()+ .map(|a| {+ a.iter()+ .map(|x| (x["name"].as_str().unwrap_or("").to_string(), x["address"].as_str().unwrap_or("").to_string()))+ .collect()+ })+ .unwrap_or_default();+ rt().accounts = accounts;+ }+ let mut list = match outlook::run(outlook::list_script(20), TIMEOUT).await {+ Ok(v) => serde_json::from_value::<outlook::Listing>(v).unwrap_or_default().messages,+ Err(e) => return format!("{query}\n\n<mail>Coucou could not read Outlook ({e}).</mail>"),+ };+ list.sort_by(|a, b| b.date.cmp(&a.date));+ list.truncate(40);+ rt().numbered = list.iter().enumerate().map(|(i, m)| (i + 1, m.clone())).collect();+ let senders: Vec<String> = list.iter().map(sender_of).collect();+ let subjects: Vec<String> = list.iter().map(|m| m.subject.clone()).collect();+ let named: HashSet<usize> = plan::mentioned(query, &senders, &subjects, 3).into_iter().collect();+ let mut lines = Vec::new();+ for (i, m) in list.iter().enumerate() {+ let mut line = plan::Line {+ number: i + 1,+ sender: senders[i].clone(),+ subject: m.subject.clone(),+ date: m.local.clone(),+ unread: m.unread,+ account: m.account.clone(),+ attachments: Vec::new(),+ text: None,+ };+ // The messages the request names get their text; the newest ones their attachments.+ if named.contains(&i) || i < 8 {+ if let Some(d) = detail(m, if named.contains(&i) { 3000 } else { 300 }).await {+ line.attachments = d.attachments;+ line.text = Some(d.text);+ }+ }+ lines.push(line);+ }+ let accounts = rt().accounts.clone();+ format!("{query}{}", plan::snapshot(&lines, &accounts))+}++/// One mail a plan will send.+#[derive(Serialize, Clone, PartialEq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct PreparedMail {+ to: Vec<String>,+ cc: Vec<String>,+ subject: String,+ body: String,+ /// Paths on this computer.+ attachments: Vec<String>,+ /// Why it can't be sent ("noPage", "badAddress"): shown in red, skipped.+ problem: Option<&'static str>,+}++#[derive(Serialize, Clone, Debug)]+#[serde(tag = "kind", rename_all = "camelCase")]+pub enum Phase {+ Preparing,+ Ready,+ Countdown { seconds: u32 },+ Running { done: usize, total: usize },+ Done { ok: usize, failed: usize },+ Cancelled,+}++#[derive(Serialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct SortStep {+ action: Action,+ messages: Vec<Message>,+}++#[derive(Serialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct PlanNote {+ /// "missing" (a message number not in the list), "noPdf", "fileMissing".+ kind: &'static str,+ value: String,+}++#[derive(Serialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct PlanRun {+ phase: Phase,+ summary: String,+ sorts: Vec<SortStep>,+ replies: Vec<(Message, String)>,+ saves: Vec<(Message, String)>,+ mails: Vec<PreparedMail>,+ notes: Vec<PlanNote>,+ test_sent_to: Option<String>,+ my_address: Option<String>,+ step_count: usize,+}++impl PlanRun {+ fn new(summary: String) -> PlanRun {+ PlanRun {+ phase: Phase::Preparing,+ summary,+ sorts: Vec::new(),+ replies: Vec::new(),+ saves: Vec::new(),+ mails: Vec::new(),+ notes: Vec::new(),+ test_sent_to: None,+ my_address: None,+ step_count: 0,+ }+ }++ fn count(&self) -> usize {+ self.sorts.iter().map(|s| s.messages.len()).sum::<usize>()+ + self.replies.len()+ + self.saves.len()+ + self.mails.iter().filter(|m| m.problem.is_none()).count()+ }+}++fn emit_plan(app: &AppHandle, id: &str) {+ let run = rt().plans.get(id).cloned();+ if let Some(run) = run {+ let _ = app.emit_to(crate::island::WINDOW_LABEL, "mail-plan", json!({ "id": id, "run": run }));+ }+}++fn set_phase(app: &AppHandle, id: &str, phase: Phase) {+ if let Some(run) = rt().plans.get_mut(id) {+ run.phase = phase;+ }+ emit_plan(app, id);+}++fn work_dir() -> std::path::PathBuf {+ std::env::temp_dir().join("coucou-mail-plans")+}++/// The card of a chat answer holding a plan: prepared once, then its state.+#[tauri::command]+pub async fn mail_plan_show(app: AppHandle, id: String, text: String) -> Result<PlanRun, String> {+ if let Some(run) = rt().plans.get(&id).cloned() {+ return Ok(run);+ }+ let (_, plan, error) = plan::extract(&text);+ let plan = plan.ok_or(error.unwrap_or_else(|| "no plan".into()))?;+ let run = PlanRun::new(plan.summary.clone());+ rt().plans.insert(id.clone(), run.clone());+ let app2 = app.clone();+ let id2 = id.clone();+ tauri::async_runtime::spawn(async move {+ let mut run = prepare(plan).await;+ run.phase = Phase::Ready;+ run.step_count = run.count();+ run.my_address = rt().accounts.iter().map(|a| a.1.clone()).find(|a| !a.is_empty());+ rt().plans.insert(id2.clone(), run);+ emit_plan(&app2, &id2);+ });+ Ok(run)+}++async fn save_attachments(m: &Message, only: Option<&str>) -> Vec<String> {+ let dir = work_dir().join(new_id());+ let folder = dir.to_string_lossy().to_string();+ match outlook::run(outlook::save_attachments_script(&m.entry_id, &m.store_id, &folder, only), TIMEOUT).await {+ Ok(v) => v["saved"]+ .as_array()+ .map(|a| a.iter().filter_map(Value::as_str).map(|n| dir.join(n).to_string_lossy().to_string()).collect())+ .unwrap_or_default(),+ Err(_) => Vec::new(),+ }+}++fn expand(path: &str) -> String {+ match path.strip_prefix('~') {+ Some(rest) => format!("{}{}", crate::platform::home_dir().to_string_lossy(), rest),+ None => path.to_string(),+ }+}++async fn prepare(plan: Plan) -> PlanRun {+ let mut run = PlanRun::new(plan.summary.clone());+ let numbered = rt().numbered.clone();+ let message = |n: usize, run: &mut PlanRun| -> Option<Message> {+ let m = numbered.get(&n).cloned();+ if m.is_none() {+ run.notes.push(PlanNote { kind: "missing", value: n.to_string() });+ }+ m+ };+ for step in plan.steps {+ match step {+ Step::Sort(action, numbers) => {+ let messages: Vec<Message> = numbers.into_iter().filter_map(|n| message(n, &mut run)).collect();+ if !messages.is_empty() {+ run.sorts.push(SortStep { action, messages });+ }+ }+ Step::Reply(n, body) => {+ if let Some(m) = message(n, &mut run) {+ run.replies.push((m, body));+ }+ }+ Step::SaveAttachments(n, folder) => {+ if let Some(m) = message(n, &mut run) {+ run.saves.push((m, expand(&folder)));+ }+ }+ Step::Send(out) => {+ let mut files = Vec::new();+ if let Some(m) = out.attachments_from.and_then(|n| message(n, &mut run)) {+ files.extend(save_attachments(&m, None).await);+ }+ for f in &out.files {+ let p = expand(f);+ if std::path::Path::new(&p).is_file() {+ files.push(p);+ } else {+ run.notes.push(PlanNote { kind: "fileMissing", value: f.clone() });+ }+ }+ let bad = out.to.iter().chain(&out.cc).any(|a| !plan::valid_address(a));+ run.mails.push(PreparedMail {+ to: out.to,+ cc: out.cc,+ subject: out.subject,+ body: out.body,+ attachments: files,+ problem: bad.then_some("badAddress"),+ });+ }+ Step::Merge(merge) => {+ let source = merge.from_message.and_then(|n| message(n, &mut run));+ prepare_merge(merge, source, &mut run).await;+ }+ }+ }+ run+}++async fn prepare_merge(merge: plan::Merge, source: Option<Message>, run: &mut PlanRun) {+ // The PDF: a file on this computer, or one of a message's attachments.+ let mut pdf: Option<String> = None;+ if let Some(file) = &merge.file {+ let p = expand(file);+ if std::path::Path::new(&p).is_file() {+ pdf = Some(p);+ } else {+ run.notes.push(PlanNote { kind: "fileMissing", value: file.clone() });+ }+ } else if let Some(m) = &source {+ let mut name = merge.attachment.clone();+ if name.is_none() {+ name = detail(m, 1).await.and_then(|d| d.attachments.into_iter().find(|a| a.to_lowercase().ends_with(".pdf")));+ }+ if let Some(name) = name {+ pdf = save_attachments(m, Some(&name)).await.into_iter().next();+ }+ if pdf.is_none() {+ run.notes.push(PlanNote { kind: "noPdf", value: String::new() });+ }+ }+ let mut pages = pdf::Pages { files: Vec::new(), texts: Vec::new() };+ if let (Some(path), true) = (&pdf, merge.split_pages) {+ let path = std::path::PathBuf::from(path);+ let dir = work_dir().join(new_id());+ match tauri::async_runtime::spawn_blocking(move || pdf::split(&path, &dir)).await {+ Ok(Ok(p)) => pages = p,+ _ => run.notes.push(PlanNote { kind: "noPdf", value: String::new() }),+ }+ }+ let assignments = if merge.split_pages {+ plan::assign(&pages.texts, &merge.recipients, merge.match_by_key)+ } else {+ merge.recipients.iter().map(|r| plan::Assignment { recipient: r.clone(), page: None, ambiguous: false }).collect()+ };+ let base = pdf+ .as_deref()+ .and_then(|p| std::path::Path::new(p).file_name())+ .map(|n| n.to_string_lossy().to_string())+ .unwrap_or_else(|| "Plan.pdf".into());+ for a in assignments {+ let mut files = Vec::new();+ let mut problem = None;+ if merge.split_pages {+ match a.page.and_then(|p| pages.files.get(p).map(|f| (p, f))) {+ Some((p, file)) => {+ // The recipient gets "Plans - Bordeaux.pdf", not "p3.pdf".+ let named = file.with_file_name(plan::page_file_name(&base, &a.recipient.key, p));+ let _ = std::fs::copy(file, &named);+ files.push(named.to_string_lossy().to_string());+ }+ None => problem = Some("noPage"),+ }+ } else if let Some(p) = &pdf {+ files.push(p.clone());+ }+ if !plan::valid_address(&a.recipient.email) {+ problem = Some("badAddress");+ }+ run.mails.push(PreparedMail {+ to: vec![a.recipient.email.clone()],+ cc: Vec::new(),+ subject: plan::fill(&merge.subject, &a.recipient),+ body: plan::fill(&merge.body, &a.recipient),+ attachments: files,+ problem,+ });+ }+}++/// Sends the plan's first mail to the user's own address, "[Test]" in front.+#[tauri::command]+pub async fn mail_plan_test(app: AppHandle, id: String) -> Result<(), String> {+ let (first, me) = {+ let r = rt();+ let run = r.plans.get(&id).ok_or("no plan")?;+ let first = run.mails.iter().find(|m| m.problem.is_none()).cloned().ok_or("no mail")?;+ (first, run.my_address.clone().ok_or("no address")?)+ };+ let script = outlook::send_script(&[me.clone()], &[], &format!("[Test] {}", first.subject), &first.body, &first.attachments);+ outlook::run(script, TIMEOUT).await.map_err(|e| e.to_string())?;+ if let Some(run) = rt().plans.get_mut(&id) {+ run.test_sent_to = Some(me);+ }+ emit_plan(&app, &id);+ Ok(())+}++/// Run: 5 seconds to change one's mind, then every step in order.+#[tauri::command]+pub async fn mail_plan_start(app: AppHandle, id: String) -> Result<(), String> {+ let run = {+ let mut r = rt();+ r.cancelled.remove(&id);+ r.plans.get(&id).cloned().ok_or("no plan")?+ };+ if !matches!(run.phase, Phase::Ready | Phase::Cancelled) {+ return Ok(());+ }+ tauri::async_runtime::spawn(async move {+ for s in (1..=5).rev() {+ if rt().cancelled.contains(&id) {+ set_phase(&app, &id, Phase::Cancelled);+ return;+ }+ set_phase(&app, &id, Phase::Countdown { seconds: s });+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+ if rt().cancelled.contains(&id) {+ set_phase(&app, &id, Phase::Cancelled);+ return;+ }+ execute(&app, &id, run).await;+ });+ Ok(())+}++#[tauri::command]+pub fn mail_plan_cancel(app: AppHandle, id: String) {+ let countdown = {+ let mut r = rt();+ r.cancelled.insert(id.clone());+ matches!(r.plans.get(&id).map(|p| &p.phase), Some(Phase::Countdown { .. }))+ };+ if countdown {+ set_phase(&app, &id, Phase::Cancelled);+ }+}++async fn execute(app: &AppHandle, id: &str, run: PlanRun) {+ let total = run.count();+ let (mut ok, mut failed) = (0, 0);+ let step = |success: bool, ok: &mut usize, failed: &mut usize| {+ if success { *ok += 1 } else { *failed += 1 }+ set_phase(app, id, Phase::Running { done: *ok + *failed, total });+ };+ set_phase(app, id, Phase::Running { done: 0, total });+ let stopped = || rt().cancelled.contains(id);+ for s in &run.sorts {+ for m in &s.messages {+ if stopped() {+ break;+ }+ step(perform(&s.action, m, Reason::Manual).await.is_ok(), &mut ok, &mut failed);+ }+ }+ for (m, body) in &run.replies {+ let r = outlook::run(outlook::open_script(&m.entry_id, &m.store_id, Some(body)), TIMEOUT).await;+ step(r.is_ok(), &mut ok, &mut failed);+ }+ for (m, folder) in &run.saves {+ let r = outlook::run(outlook::save_attachments_script(&m.entry_id, &m.store_id, folder, None), TIMEOUT).await;+ step(r.is_ok(), &mut ok, &mut failed);+ }+ let mails: Vec<&PreparedMail> = run.mails.iter().filter(|m| m.problem.is_none()).collect();+ for (i, mail) in mails.iter().enumerate() {+ if stopped() {+ break;+ }+ let script = outlook::send_script(&mail.to, &mail.cc, &mail.subject, &mail.body, &mail.attachments);+ let sent = outlook::run(script, TIMEOUT).await.is_ok();+ if sent {+ rt().store.record_sent(SentEntry {+ id: new_id(),+ date: now_ms(),+ to: mail.to.clone(),+ subject: mail.subject.clone(),+ attachments: mail+ .attachments+ .iter()+ .filter_map(|p| std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().to_string()))+ .collect(),+ });+ }+ step(sent, &mut ok, &mut failed);+ // A pause between mails: the provider sees a person, not a burst.+ if i + 1 < mails.len() {+ tokio::time::sleep(Duration::from_millis(1200)).await;+ }+ }+ set_phase(app, id, Phase::Done { ok, failed });+ if pill_on(app) {+ emit_card(app, true);+ }+}diff --git a/windows/src-tauri/src/mail/outlook.rs b/windows/src-tauri/src/mail/outlook.rsnew file mode 100644index 00000000..58ec3e30--- /dev/null+++ b/windows/src-tauri/src/mail/outlook.rs@@ -0,0 +1,460 @@+// Classic Outlook on Windows, driven through its own COM objects by a small PowerShell+// script: the Windows counterpart of Apple Mail's AppleScript on the Mac (MailController.swift).+//+// Coucou attaches to the Outlook already open (GetActiveObject) and never starts it. No+// sign-in, no app registration, no admin consent: it is the user's Outlook, on the user's PC.+// The new Outlook for Windows has no COM objects, so it is not reached this way.+//+// The script builders are pure and tested; `run` (Windows only) writes the script to a+// temporary .ps1 and runs Windows PowerShell on it, without a console window.++use serde::{Deserialize, Serialize};++use super::triage::{Action, Filter, Query};++/// One message of an inbox, as the list script reports it.+#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Message {+ /// Outlook's EntryID: with the store's id, finds the message again.+ pub entry_id: String,+ pub store_id: String,+ /// The store's name ("[email protected]"): what the rules call the account.+ pub account: String,+ #[serde(default)]+ pub sender_name: String,+ #[serde(default)]+ pub address: String,+ #[serde(default)]+ pub subject: String,+ /// Milliseconds since 1970.+ pub date: i64,+ #[serde(default)]+ pub unread: bool,+ #[serde(default)]+ pub flagged: bool,+ /// The date in the computer's time, for the AI ("2026-10-30 14:05").+ #[serde(default)]+ pub local: String,+}++impl Message {+ pub fn id(&self) -> String {+ format!("{}/{}", self.store_id, self.entry_id)+ }+}++#[derive(Deserialize, Debug, Default)]+#[serde(rename_all = "camelCase")]+pub struct Listing {+ #[serde(default)]+ pub unread: i64,+ #[serde(default)]+ pub messages: Vec<Message>,+}++/// A string inside PowerShell single quotes (nothing is expanded there; ' is doubled).+pub fn ps(s: &str) -> String {+ format!("'{}'", s.replace('\'', "''"))+}++/// Attaches to the running Outlook, or prints {"error":"notRunning"} and stops. JSON goes+/// out as UTF-8 so names and subjects keep their accents.+const PRELUDE: &str = r#"$ErrorActionPreference = 'Stop'+[Console]::OutputEncoding = [System.Text.Encoding]::UTF8+try { $ol = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Outlook.Application') }+catch { Write-Output '{"error":"notRunning"}'; exit 0 }+$ns = $ol.GetNamespace('MAPI')+function Coucou-Address($i) {+ try {+ if ($i.SenderEmailType -eq 'EX') {+ $u = $i.Sender.GetExchangeUser()+ if ($u) { return $u.PrimarySmtpAddress }+ }+ } catch {}+ return [string]$i.SenderEmailAddress+}+function Coucou-Row($i, $store) {+ [pscustomobject]@{+ entryId = $i.EntryID; storeId = $store.StoreID; account = $store.DisplayName+ senderName = [string]$i.SenderName; address = (Coucou-Address $i); subject = [string]$i.Subject+ date = [long](([DateTimeOffset]$i.ReceivedTime).ToUnixTimeMilliseconds())+ unread = [bool]$i.UnRead; flagged = ($i.FlagStatus -eq 2)+ local = $i.ReceivedTime.ToString('yyyy-MM-dd HH:mm')+ }+}+function Coucou-Inboxes {+ foreach ($s in $ns.Stores) {+ try { $f = $s.GetDefaultFolder(6); if ($f) { [pscustomobject]@{ store = $s; inbox = $f } } } catch {}+ }+}+function Coucou-Item($entryId, $storeId) { $ns.GetItemFromID($entryId, $storeId) }+"#;++fn script(body: &str) -> String {+ format!("{PRELUDE}\n{body}\n")+}++/// The unread count and the newest `per_inbox` messages of every account's inbox.+pub fn list_script(per_inbox: usize) -> String {+ script(&format!(+ r#"$rows = @(); $unread = 0+foreach ($b in (Coucou-Inboxes)) {{+ try {{ $unread += $b.inbox.UnReadItemCount }} catch {{}}+ $items = $b.inbox.Items+ $items.Sort('[ReceivedTime]', $true)+ $n = 0; $i = $items.GetFirst()+ while ($i -ne $null -and $n -lt {per_inbox}) {{+ if ($i.Class -eq 43) {{ $rows += (Coucou-Row $i $b.store); $n++ }}+ $i = $items.GetNext()+ }}+}}+[pscustomobject]@{{ unread = $unread; messages = @($rows) }} | ConvertTo-Json -Depth 4 -Compress"#+ ))+}++/// A DASL text test: `field LIKE '%value%'` (' doubled, % removed from the value).+fn like(field: &str, value: &str) -> String {+ let v = value.replace('%', "").replace('\'', "''");+ format!("\"{field}\" LIKE '%{v}%'")+}++const SUBJECT: &str = "urn:schemas:httpmail:subject";+const FROM_NAME: &str = "urn:schemas:httpmail:fromname";+const FROM_EMAIL: &str = "urn:schemas:httpmail:fromemail";++/// The `@SQL=` filter for a search and a quick filter, None when there is nothing to test.+pub fn dasl(q: &Query, filter: Filter) -> Option<String> {+ let mut parts = Vec::new();+ for w in &q.words {+ parts.push(format!("({} OR {} OR {})", like(SUBJECT, w), like(FROM_NAME, w), like(FROM_EMAIL, w)));+ }+ for f in &q.from {+ parts.push(format!("({} OR {})", like(FROM_NAME, f), like(FROM_EMAIL, f)));+ }+ for s in &q.subject {+ parts.push(like(SUBJECT, s));+ }+ match filter {+ Filter::All => {}+ Filter::Unread => parts.push("\"urn:schemas:httpmail:read\" = 0".into()),+ Filter::Flagged => parts.push("\"http://schemas.microsoft.com/mapi/proptag/0x10900003\" = 2".into()),+ Filter::Today => parts.push("%today(\"urn:schemas:httpmail:datereceived\")%".into()),+ }+ (!parts.is_empty()).then(|| format!("@SQL={}", parts.join(" AND ")))+}++/// Messages of every inbox matching a `dasl` filter, newest first, `limit` per inbox.+pub fn search_script(filter: &str, limit: usize) -> String {+ script(&format!(+ r#"$rows = @()+foreach ($b in (Coucou-Inboxes)) {{+ try {{+ $found = $b.inbox.Items.Restrict({filter})+ $found.Sort('[ReceivedTime]', $true)+ $n = 0; $i = $found.GetFirst()+ while ($i -ne $null -and $n -lt {limit}) {{+ if ($i.Class -eq 43) {{ $rows += (Coucou-Row $i $b.store); $n++ }}+ $i = $found.GetNext()+ }}+ }} catch {{}}+}}+[pscustomobject]@{{ unread = 0; messages = @($rows) }} | ConvertTo-Json -Depth 4 -Compress"#,+ filter = ps(filter)+ ))+}++/// What the action does to `$i` in its store `$st`. Moving returns the message's new+/// EntryID (Outlook gives a moved message a new one), which the journal keeps for Undo.+fn apply(action: &Action) -> String {+ match action {+ Action::Junk => "$m = $i.Move($st.GetDefaultFolder(23)); $new = $m.EntryID".into(),+ Action::Important => "$i.MarkAsTask(4); $i.Save(); $new = $i.EntryID".into(),+ Action::MarkRead => "$i.UnRead = $false; $i.Save(); $new = $i.EntryID".into(),+ Action::Move(name) => format!(+ r#"$inbox = $st.GetDefaultFolder(6); $dest = $null+try {{ $dest = $inbox.Folders.Item({n}) }} catch {{}}+if (-not $dest) {{ try {{ $dest = $st.GetRootFolder().Folders.Item({n}) }} catch {{}} }}+if (-not $dest) {{ $dest = $inbox.Folders.Add({n}) }}+$m = $i.Move($dest); $new = $m.EntryID"#,+ n = ps(name)+ ),+ }+}++/// Sorts one message; prints {"entryId": its id afterwards}.+pub fn apply_script(entry_id: &str, store_id: &str, action: &Action) -> String {+ script(&format!(+ r#"$i = Coucou-Item {e} {s}+$st = $ns.GetStoreFromID({s})+{body}+[pscustomobject]@{{ entryId = $new }} | ConvertTo-Json -Compress"#,+ e = ps(entry_id),+ s = ps(store_id),+ body = apply(action)+ ))+}++/// Puts back a message the journal shows as sorted (by the EntryID it had afterwards).+pub fn undo_script(entry_id: &str, store_id: &str, action: &Action) -> String {+ let body = match action {+ Action::Junk | Action::Move(_) => "$null = $i.Move($st.GetDefaultFolder(6))",+ Action::Important => "$i.ClearTaskFlag(); $i.Save()",+ Action::MarkRead => "$i.UnRead = $true; $i.Save()",+ };+ script(&format!(+ r#"$i = Coucou-Item {e} {s}+$st = $ns.GetStoreFromID({s})+{body}+Write-Output '{{"ok":true}}'"#,+ e = ps(entry_id),+ s = ps(store_id)+ ))+}++pub fn unflag_script(entry_id: &str, store_id: &str) -> String {+ script(&format!(+ "$i = Coucou-Item {} {}\n$i.ClearTaskFlag(); $i.Save()\nWrite-Output '{{\"ok\":true}}'",+ ps(entry_id),+ ps(store_id)+ ))+}++/// The message's text (`limit` characters) and its attachments' names.+pub fn detail_script(entry_id: &str, store_id: &str, limit: usize) -> String {+ script(&format!(+ r#"$i = Coucou-Item {e} {s}+$body = [string]$i.Body+if ($body.Length -gt {limit}) {{ $body = $body.Substring(0, {limit}) }}+$names = @(); foreach ($a in $i.Attachments) {{ $names += [string]$a.FileName }}+[pscustomobject]@{{ text = $body; attachments = @($names) }} | ConvertTo-Json -Depth 3 -Compress"#,+ e = ps(entry_id),+ s = ps(store_id)+ ))+}++/// Opens the message, or a reply to it with `body` on top, in Outlook's own window. Nothing+/// is sent: the user sends from Outlook.+pub fn open_script(entry_id: &str, store_id: &str, reply_body: Option<&str>) -> String {+ let body = match reply_body {+ None => "$i.Display()".to_string(),+ Some("") => "$r = $i.Reply(); $r.Display()".to_string(),+ Some(text) => format!("$r = $i.Reply(); $r.Body = {} + \"`r`n`r`n\" + $r.Body; $r.Display()", ps(text)),+ };+ script(&format!(+ "$i = Coucou-Item {} {}\n{body}\nWrite-Output '{{\"ok\":true}}'",+ ps(entry_id),+ ps(store_id)+ ))+}++/// Saves a message's attachments (only `only` when given) in `folder`; prints their names.+pub fn save_attachments_script(entry_id: &str, store_id: &str, folder: &str, only: Option<&str>) -> String {+ let test = only.map_or("$true".to_string(), |n| format!("$a.FileName -eq {}", ps(n)));+ script(&format!(+ r#"$i = Coucou-Item {e} {s}+$dir = {d}+$null = New-Item -ItemType Directory -Force -Path $dir+$saved = @()+foreach ($a in $i.Attachments) {{+ if ({test}) {{ $a.SaveAsFile((Join-Path $dir $a.FileName)); $saved += [string]$a.FileName }}+}}+[pscustomobject]@{{ saved = @($saved) }} | ConvertTo-Json -Depth 3 -Compress"#,+ e = ps(entry_id),+ s = ps(store_id),+ d = ps(folder)+ ))+}++/// Sends one message from Outlook (the default account), attachments as file paths.+pub fn send_script(to: &[String], cc: &[String], subject: &str, body: &str, attachments: &[String]) -> String {+ let mut s = String::from("$m = $ol.CreateItem(0)\n");+ s += &format!("$m.To = {}\n", ps(&to.join("; ")));+ if !cc.is_empty() {+ s += &format!("$m.CC = {}\n", ps(&cc.join("; ")));+ }+ s += &format!("$m.Subject = {}\n$m.Body = {}\n", ps(subject), ps(body));+ for a in attachments {+ s += &format!("$null = $m.Attachments.Add({})\n", ps(a));+ }+ s += "$m.Send()\nWrite-Output '{\"ok\":true}'";+ script(&s)+}++/// Every account: its name and address.+pub fn accounts_script() -> String {+ script(+ r#"$rows = @()+foreach ($a in $ns.Accounts) { $rows += [pscustomobject]@{ name = [string]$a.DisplayName; address = [string]$a.SmtpAddress } }+[pscustomobject]@{ accounts = @($rows) } | ConvertTo-Json -Depth 3 -Compress"#,+ )+}++#[derive(Debug, PartialEq, Eq)]+#[cfg_attr(not(windows), allow(dead_code))]+pub enum RunError {+ /// Outlook is not open (or is the new Outlook, which has no COM objects).+ NotRunning,+ /// Not on Windows.+ Unsupported,+ Failed(String),+}++impl std::fmt::Display for RunError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ RunError::NotRunning => write!(f, "Outlook is not open"),+ RunError::Unsupported => write!(f, "Outlook is only reached on Windows"),+ RunError::Failed(e) => write!(f, "{e}"),+ }+ }+}++/// Reads a script's output: its JSON, or why it failed.+#[cfg_attr(not(windows), allow(dead_code))]+pub fn parse_output(stdout: &str, stderr: &str, ok: bool) -> Result<serde_json::Value, RunError> {+ let text = stdout.trim().trim_start_matches('\u{feff}');+ if let Some(line) = text.lines().rev().find(|l| l.trim_start().starts_with('{')) {+ if let Ok(v) = serde_json::from_str::<serde_json::Value>(line.trim()) {+ if v.get("error").and_then(|e| e.as_str()) == Some("notRunning") {+ return Err(RunError::NotRunning);+ }+ return Ok(v);+ }+ }+ let why = stderr.lines().find(|l| !l.trim().is_empty()).unwrap_or(if ok { "no answer" } else { "failed" });+ Err(RunError::Failed(why.trim().to_string()))+}++/// Runs a script with Windows PowerShell, `timeout` at most.+#[cfg(windows)]+pub async fn run(source: String, timeout: std::time::Duration) -> Result<serde_json::Value, RunError> {+ tauri::async_runtime::spawn_blocking(move || {+ use std::io::Write;+ use std::process::{Command, Stdio};+ let path = std::env::temp_dir().join(format!("coucou-outlook-{}.ps1", std::process::id() as u64 * 1000 + rand_suffix()));+ let mut file = std::fs::File::create(&path).map_err(|e| RunError::Failed(e.to_string()))?;+ // A BOM so Windows PowerShell 5.1 reads the script as UTF-8 (names, accents).+ file.write_all(b"\xEF\xBB\xBF").and_then(|_| file.write_all(source.as_bytes()))+ .map_err(|e| RunError::Failed(e.to_string()))?;+ drop(file);+ let mut cmd = Command::new("powershell.exe");+ cmd.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File"])+ .arg(&path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ crate::platform::no_console(&mut cmd);+ let child = cmd.spawn().map_err(|e| RunError::Failed(e.to_string()));+ let result = child.and_then(|child| wait(child, timeout));+ let _ = std::fs::remove_file(&path);+ let out = result?;+ parse_output(&String::from_utf8_lossy(&out.stdout), &String::from_utf8_lossy(&out.stderr), out.status.success())+ })+ .await+ .unwrap_or_else(|e| Err(RunError::Failed(e.to_string())))+}++#[cfg(windows)]+fn rand_suffix() -> u64 {+ use std::time::{SystemTime, UNIX_EPOCH};+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.subsec_nanos() as u64 % 1000).unwrap_or(0)+}++#[cfg(windows)]+fn wait(mut child: std::process::Child, timeout: std::time::Duration) -> Result<std::process::Output, RunError> {+ let start = std::time::Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(_)) => return child.wait_with_output().map_err(|e| RunError::Failed(e.to_string())),+ Ok(None) if start.elapsed() < timeout => std::thread::sleep(std::time::Duration::from_millis(50)),+ Ok(None) => {+ let _ = child.kill();+ return Err(RunError::Failed("Outlook did not answer in time".into()));+ }+ Err(e) => return Err(RunError::Failed(e.to_string())),+ }+ }+}++#[cfg(not(windows))]+pub async fn run(_source: String, _timeout: std::time::Duration) -> Result<serde_json::Value, RunError> {+ Err(RunError::Unsupported)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn quotes_never_break_out() {+ assert_eq!(ps("it's"), "'it''s'");+ assert_eq!(ps("$env:x `n"), "'$env:x `n'", "single quotes expand nothing");+ }++ #[test]+ fn the_list_attaches_and_never_starts_outlook() {+ let s = list_script(12);+ assert!(s.contains("GetActiveObject('Outlook.Application')"));+ assert!(!s.contains("New-Object -ComObject"), "never starts Outlook");+ assert!(s.contains("$n -lt 12") && s.contains("GetDefaultFolder(6)") && s.contains("ConvertTo-Json"));+ }++ #[test]+ fn search_filters_are_dasl() {+ let q = Query::parse("de:dupont objet:\"devis mai\" facture");+ let f = dasl(&q, Filter::Unread).unwrap();+ assert!(f.starts_with("@SQL="));+ assert!(f.contains("\"urn:schemas:httpmail:subject\" LIKE '%facture%'"));+ assert!(f.contains("\"urn:schemas:httpmail:fromname\" LIKE '%dupont%'"));+ assert!(f.contains("\"urn:schemas:httpmail:subject\" LIKE '%devis mai%'"));+ assert!(f.ends_with("\"urn:schemas:httpmail:read\" = 0"));+ assert_eq!(dasl(&Query::default(), Filter::All), None);+ assert!(dasl(&Query::default(), Filter::Today).unwrap().contains("%today("));+ let tricky = dasl(&Query::parse("l'été"), Filter::All).unwrap();+ assert!(tricky.contains("'%l''été%'"));+ // The filter goes into the script as a PowerShell string: quotes doubled again.+ assert!(search_script(&tricky, 30).contains("Restrict('@SQL="));+ assert!(search_script(&tricky, 30).contains("l''''été"));+ }++ #[test]+ fn actions_move_flag_and_never_delete() {+ let junk = apply_script("E1", "S1", &Action::Junk);+ assert!(junk.contains("GetItemFromID($entryId, $storeId)") || junk.contains("Coucou-Item 'E1' 'S1'"));+ assert!(junk.contains("GetDefaultFolder(23)") && junk.contains("$new = $m.EntryID"));+ assert!(apply_script("E", "S", &Action::Important).contains("MarkAsTask(4)"));+ let mv = apply_script("E", "S", &Action::Move("Compta".into()));+ assert!(mv.contains("Folders.Item('Compta')") && mv.contains("Folders.Add('Compta')"));+ for a in [Action::Junk, Action::Important, Action::MarkRead, Action::Move("X".into())] {+ let s = apply_script("E", "S", &a) + &undo_script("E", "S", &a);+ assert!(!s.contains(".Delete("), "Coucou never deletes a message");+ }+ assert!(undo_script("E", "S", &Action::Junk).contains("Move($st.GetDefaultFolder(6))"));+ assert!(undo_script("E", "S", &Action::Important).contains("ClearTaskFlag()"));+ }++ #[test]+ fn sending_and_drafts() {+ let s = send_script(&["[email protected]".into(), "[email protected]".into()], &[], "Plan 'Lyon'", "Bonjour", &["C:\\p 1.pdf".into()]);+ assert!(s.contains("$m.To = '[email protected]; [email protected]'"));+ assert!(s.contains("$m.Subject = 'Plan ''Lyon'''"));+ assert!(s.contains("$m.Attachments.Add('C:\\p 1.pdf')") && s.contains("$m.Send()"));+ let r = open_script("E", "S", Some("Merci"));+ assert!(r.contains("$i.Reply()") && r.contains("Display()") && !r.contains("Send()"));+ assert!(save_attachments_script("E", "S", "C:\\t", Some("plans.pdf")).contains("$a.FileName -eq 'plans.pdf'"));+ }++ #[test]+ fn outputs_are_read() {+ assert_eq!(parse_output("{\"error\":\"notRunning\"}", "", true), Err(RunError::NotRunning));+ let v = parse_output("\u{feff}WARNING x\n{\"unread\":3,\"messages\":[]}\n", "", true).unwrap();+ assert_eq!(v["unread"], 3);+ assert_eq!(parse_output("", "Exception: boom\n", false), Err(RunError::Failed("Exception: boom".into())));+ let listing: Listing = serde_json::from_str(+ r#"{"unread":2,"messages":[{"entryId":"E","storeId":"S","account":"[email protected]","senderName":"Paul","address":"[email protected]","subject":"Hi","date":1700000000000,"unread":true,"flagged":false}]}"#,+ ).unwrap();+ assert_eq!(listing.messages[0].id(), "S/E");+ assert!(listing.messages[0].unread);+ }+}diff --git a/windows/src-tauri/src/mail/pdf.rs b/windows/src-tauri/src/mail/pdf.rsnew file mode 100644index 00000000..9e09cf7e--- /dev/null+++ b/windows/src-tauri/src/mail/pdf.rs@@ -0,0 +1,87 @@+// A PDF cut into one-page files, with each page's text: what the mail merge needs to give+// each recipient their page (the Mac does this with PDFKit). lopdf, pure Rust, MIT.++use std::path::{Path, PathBuf};++pub struct Pages {+ /// One file per page, in order.+ pub files: Vec<PathBuf>,+ /// The text of each page ("" for a scanned page, which has none).+ pub texts: Vec<String>,+}++/// Cuts `pdf` into `dir/p1.pdf`, `dir/p2.pdf`…+pub fn split(pdf: &Path, dir: &Path) -> Result<Pages, String> {+ let doc = lopdf::Document::load(pdf).map_err(|e| e.to_string())?;+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;+ let numbers: Vec<u32> = doc.get_pages().keys().copied().collect();+ let mut files = Vec::new();+ let mut texts = Vec::new();+ for &n in &numbers {+ texts.push(doc.extract_text(&[n]).unwrap_or_default());+ let mut single = doc.clone();+ let others: Vec<u32> = numbers.iter().copied().filter(|&m| m != n).collect();+ single.delete_pages(&others);+ single.prune_objects();+ let path = dir.join(format!("p{n}.pdf"));+ single.save(&path).map_err(|e| e.to_string())?;+ files.push(path);+ }+ Ok(Pages { files, texts })+}++#[cfg(test)]+mod tests {+ use super::*;+ use lopdf::content::{Content, Operation};+ use lopdf::{dictionary, Document, Object, Stream};++ /// A PDF with one line of text per page.+ fn sample(lines: &[&str], path: &Path) {+ let mut doc = Document::with_version("1.5");+ let pages_id = doc.new_object_id();+ let font_id = doc.add_object(dictionary! {+ "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica",+ });+ let resources_id = doc.add_object(dictionary! { "Font" => dictionary! { "F1" => font_id } });+ let mut kids = Vec::new();+ for line in lines {+ let content = Content {+ operations: vec![+ Operation::new("BT", vec![]),+ Operation::new("Tf", vec!["F1".into(), 24.into()]),+ Operation::new("Td", vec![100.into(), 600.into()]),+ Operation::new("Tj", vec![Object::string_literal(*line)]),+ Operation::new("ET", vec![]),+ ],+ };+ let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap()));+ let page_id = doc.add_object(dictionary! {+ "Type" => "Page", "Parent" => pages_id, "Contents" => content_id,+ "Resources" => resources_id, "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()],+ });+ kids.push(page_id.into());+ }+ let count = kids.len() as i64;+ doc.objects.insert(pages_id, Object::Dictionary(dictionary! { "Type" => "Pages", "Kids" => kids, "Count" => count }));+ let catalog_id = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });+ doc.trailer.set("Root", catalog_id);+ doc.save(path).unwrap();+ }++ #[test]+ fn a_pdf_is_cut_into_pages_with_their_text() {+ let dir = std::env::temp_dir().join(format!("coucou-pdf-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let source = dir.join("plans.pdf");+ sample(&["Plan Bordeaux", "Plan Lyon", "Plan Nice"], &source);+ let pages = split(&source, &dir.join("out")).unwrap();+ assert_eq!(pages.files.len(), 3);+ assert!(pages.texts[1].contains("Lyon"), "{:?}", pages.texts);+ let one = lopdf::Document::load(&pages.files[2]).unwrap();+ assert_eq!(one.get_pages().len(), 1);+ assert!(one.extract_text(&[1]).unwrap().contains("Nice"));+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/windows/src-tauri/src/mail/plan.rs b/windows/src-tauri/src/mail/plan.rsnew file mode 100644index 00000000..c1cbde33--- /dev/null+++ b/windows/src-tauri/src/mail/plan.rs@@ -0,0 +1,401 @@+// The chat's mail actions: the plan the AI writes (a ```coucou-mail JSON block in its+// answer), what Coucou tells the AI, and the matching of PDF pages to recipients. Port of+// MailPlan.swift; pure, tested on any machine. Nothing in a plan happens until the user+// clicks Run on its card (mod.rs).++use serde::Serialize;+use serde_json::Value;++use super::triage::{contains_word, normalize, Action};++#[derive(Serialize, Clone, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Outgoing {+ pub to: Vec<String>,+ pub cc: Vec<String>,+ pub subject: String,+ pub body: String,+ /// Forward the attachments of this message (its number in the list sent to the AI).+ pub attachments_from: Option<usize>,+ /// Files on this computer.+ pub files: Vec<String>,+}++#[derive(Serialize, Clone, PartialEq, Eq, Debug)]+pub struct Recipient {+ pub email: String,+ pub name: String,+ /// What the recipient's page holds ("Bordeaux"), and the {key} of the templates.+ pub key: String,+}++/// One message per recipient, each with its own page of a PDF.+#[derive(Serialize, Clone, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Merge {+ pub from_message: Option<usize>,+ /// The PDF among that message's attachments (None: the first PDF).+ pub attachment: Option<String>,+ pub split_pages: bool,+ /// Pages go to the recipient whose key they contain; false: in order.+ pub match_by_key: bool,+ pub recipients: Vec<Recipient>,+ pub subject: String,+ pub body: String,+ /// A PDF on this computer, instead of a message's.+ pub file: Option<String>,+}++#[derive(Clone, PartialEq, Eq, Debug)]+pub enum Step {+ Sort(Action, Vec<usize>),+ Reply(usize, String),+ Send(Outgoing),+ Merge(Merge),+ SaveAttachments(usize, String),+}++#[derive(Clone, PartialEq, Eq, Debug)]+pub struct Plan {+ pub summary: String,+ pub steps: Vec<Step>,+}++pub const FENCE: &str = "```coucou-mail";++/// The answer without its plan block, the plan, and why the block could not be read.+pub fn extract(text: &str) -> (String, Option<Plan>, Option<String>) {+ let Some(start) = text.find(FENCE) else { return (text.to_string(), None, None) };+ let after = &text[start + FENCE.len()..];+ let end = after.find("```");+ let json = end.map_or(after, |e| &after[..e]);+ let mut prose = text[..start].to_string();+ if let Some(e) = end {+ prose.push_str(&after[e + 3..]);+ }+ let prose = prose.trim().to_string();+ if end.is_none() {+ return (prose, None, None); // still streaming+ }+ match decode(json) {+ Ok(plan) => (prose, Some(plan), None),+ Err(e) => (prose, None, Some(e)),+ }+}++fn int(v: Option<&Value>) -> Option<usize> {+ match v? {+ Value::Number(n) => n.as_u64().map(|n| n as usize).or_else(|| n.as_f64().map(|f| f as usize)),+ Value::String(s) => s.trim_matches(|c: char| c == '[' || c == ']' || c == ' ').parse().ok(),+ _ => None,+ }+}++fn ints(v: Option<&Value>) -> Vec<usize> {+ match v {+ Some(Value::Array(a)) => a.iter().filter_map(|x| int(Some(x))).collect(),+ other => int(other).into_iter().collect(),+ }+}++fn strings(v: Option<&Value>) -> Vec<String> {+ match v {+ Some(Value::String(s)) => s.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect(),+ Some(Value::Array(a)) => a.iter().filter_map(|x| x.as_str()).filter(|x| !x.is_empty()).map(String::from).collect(),+ _ => Vec::new(),+ }+}++fn text(a: &Value, key: &str) -> String {+ a.get(key).and_then(Value::as_str).unwrap_or("").to_string()+}++pub fn decode(json: &str) -> Result<Plan, String> {+ let root: Value = serde_json::from_str(json.trim()).map_err(|_| "not a JSON object".to_string())?;+ let list = root.get("actions").and_then(Value::as_array).cloned().unwrap_or_default();+ let mut steps = Vec::new();+ for (i, a) in list.iter().enumerate() {+ let index = i + 1;+ let kind = a.get("type").and_then(Value::as_str).ok_or(format!("action {index} has no type"))?.to_lowercase();+ let need = |key: &str| -> Result<String, String> {+ let v = text(a, key);+ if v.trim().is_empty() { Err(format!("action {index} ({kind}) needs \"{key}\"")) } else { Ok(v) }+ };+ let message = || int(a.get("message")).ok_or(format!("action {index} ({kind}) needs \"message\""));+ let step = match kind.as_str() {+ "flag" | "important" | "junk" | "read" | "mark_read" | "move" => {+ let messages = ints(a.get("messages").or_else(|| a.get("message")));+ if messages.is_empty() {+ return Err(format!("action {index} ({kind}) needs \"messages\""));+ }+ let action = match kind.as_str() {+ "junk" => Action::Junk,+ "read" | "mark_read" => Action::MarkRead,+ "move" => Action::Move(need("mailbox")?),+ _ => Action::Important,+ };+ Step::Sort(action, messages)+ }+ "reply" => Step::Reply(message()?, need("body")?),+ "send" => {+ let to = strings(a.get("to"));+ if to.is_empty() {+ return Err(format!("action {index} (send) needs \"to\""));+ }+ Step::Send(Outgoing {+ to,+ cc: strings(a.get("cc")),+ subject: text(a, "subject"),+ body: text(a, "body"),+ attachments_from: int(a.get("attachments_from")),+ files: strings(a.get("files")),+ })+ }+ "merge" | "mail_merge" => {+ let recipients: Vec<Recipient> = a.get("recipients").and_then(Value::as_array).cloned().unwrap_or_default()+ .iter()+ .filter_map(|r| {+ let email = r.get("email")?.as_str()?.to_string();+ (!email.is_empty()).then(|| Recipient {+ email,+ name: text(r, "name"),+ key: r.get("key").or_else(|| r.get("city")).and_then(Value::as_str).unwrap_or("").to_string(),+ })+ })+ .collect();+ if recipients.is_empty() {+ return Err(format!("action {index} (merge) needs \"recipients\""));+ }+ Step::Merge(Merge {+ from_message: int(a.get("from_message").or_else(|| a.get("message"))),+ attachment: a.get("attachment").and_then(Value::as_str).map(String::from),+ split_pages: a.get("split_pages").and_then(Value::as_bool).unwrap_or(true),+ match_by_key: a.get("match").and_then(Value::as_str).unwrap_or("key").to_lowercase() != "order",+ recipients,+ subject: text(a, "subject"),+ body: text(a, "body"),+ file: a.get("file").and_then(Value::as_str).map(String::from),+ })+ }+ "save_attachments" | "save" => Step::SaveAttachments(message()?, need("folder")?),+ other => return Err(format!("action {index} has an unknown type \"{other}\"")),+ };+ steps.push(step);+ }+ if steps.is_empty() {+ return Err("no actions".into());+ }+ Ok(Plan { summary: text(&root, "summary"), steps })+}++// ── Mail merge ───────────────────────────────────────────────────────────────++#[derive(Clone, PartialEq, Eq, Debug)]+pub struct Assignment {+ pub recipient: Recipient,+ /// The page (0-based) for this recipient, None when none was found.+ pub page: Option<usize>,+ /// More than one page held the key: the first free one was taken.+ pub ambiguous: bool,+}++/// Gives each recipient a page: the one whose text holds its key as a whole word, or the+/// page in the same order. A page goes to one recipient only.+pub fn assign(pages: &[String], recipients: &[Recipient], by_key: bool) -> Vec<Assignment> {+ if !by_key {+ return recipients+ .iter()+ .enumerate()+ .map(|(i, r)| Assignment { recipient: r.clone(), page: (i < pages.len()).then_some(i), ambiguous: false })+ .collect();+ }+ let mut taken = std::collections::HashSet::new();+ recipients+ .iter()+ .map(|r| {+ let key = r.key.trim();+ if key.is_empty() {+ return Assignment { recipient: r.clone(), page: None, ambiguous: false };+ }+ let hits: Vec<usize> = (0..pages.len()).filter(|&p| contains_word(&pages[p], key)).collect();+ let page = hits.iter().copied().find(|p| !taken.contains(p));+ if let Some(p) = page {+ taken.insert(p);+ }+ Assignment { recipient: r.clone(), page, ambiguous: page.is_some() && hits.len() > 1 }+ })+ .collect()+}++/// {name}, {key} (and {city}, {email}) filled in.+pub fn fill(template: &str, r: &Recipient) -> String {+ template+ .replace("{name}", &r.name)+ .replace("{key}", &r.key)+ .replace("{city}", &r.key)+ .replace("{email}", &r.email)+}++/// A file name for a recipient's page: "Plans - Bordeaux.pdf".+pub fn page_file_name(base: &str, key: &str, page: usize) -> String {+ let stem = base.strip_suffix(".pdf").or_else(|| base.strip_suffix(".PDF")).unwrap_or(base);+ let label = if key.is_empty() { format!("p{}", page + 1) } else { key.to_string() };+ let name: String = format!("{stem} - {label}")+ .chars()+ .map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '-' } else { c })+ .collect();+ format!("{name}.pdf")+}++/// A plain address check: [email protected], no spaces.+pub fn valid_address(s: &str) -> bool {+ let t = s.trim();+ let Some(at) = t.find('@') else { return false };+ let domain = &t[at + 1..];+ at > 0 && !t.contains(' ') && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.') && !domain.contains('@')+}++// ── What the AI is told ──────────────────────────────────────────────────────++/// Added to the chat's system prompt while the chat's Mail switch is on (same text as the Mac's).+pub const INSTRUCTIONS: &str = "++The user turned on Mail: you can act on their Outlook through Coucou. Their latest messages are listed under their request, each with a number [n]; some come with their text and attachments.+When they ask you to DO something with their mail, answer in one or two short sentences, then give ONE plan in a fenced code block tagged coucou-mail, holding JSON:+{\"summary\": \"what the plan does, in the user's language\", \"actions\": [ ... ]}+Actions:+- {\"type\": \"flag\" | \"junk\" | \"read\" | \"move\", \"messages\": [n, ...], \"mailbox\": \"only for move\"}+- {\"type\": \"reply\", \"message\": n, \"body\": \"...\"} : a reply draft opened in Outlook, not sent+- {\"type\": \"send\", \"to\": [\"address\"], \"cc\": [], \"subject\": \"...\", \"body\": \"...\", \"attachments_from\": n (optional: that message's attachments), \"files\": [\"C:\\\\path\"] (optional)}+- {\"type\": \"merge\", \"from_message\": n, \"attachment\": \"name of a PDF in that message\", \"split_pages\": true, \"match\": \"key\" or \"order\", \"recipients\": [{\"email\": \"...\", \"name\": \"...\", \"key\": \"what is written on their page, like a city\"}], \"subject\": \"... {key} ...\", \"body\": \"Hello {name}, ...\"} : one mail per recipient, each with the PDF page that contains their key (or the page in the same order)+- {\"type\": \"save_attachments\", \"message\": n, \"folder\": \"C:\\\\Users\\\\...\"}+Rules: nothing happens until the user clicks Run under your plan, so never say it is done. Never invent an address: use only addresses the user gave, found in their messages, or in a file they shared. If something is missing (the recipients' addresses, which message), ask instead of writing a plan. A question about their mail gets an answer, without a plan. Plain text bodies, in the user's language.";++pub struct Line {+ pub number: usize,+ pub sender: String,+ pub subject: String,+ /// "2026-10-30 14:05", the computer's local time.+ pub date: String,+ pub unread: bool,+ pub account: String,+ pub attachments: Vec<String>,+ pub text: Option<String>,+}++/// The list sent under the user's request.+pub fn snapshot(lines: &[Line], accounts: &[(String, String)]) -> String {+ let mut out = String::from("\n\n<mail>\n");+ if !accounts.is_empty() {+ let list: Vec<String> = accounts.iter().map(|(n, a)| format!("{n} <{a}>")).collect();+ out += &format!("Accounts: {}\n", list.join(", "));+ }+ for l in lines {+ out += &format!(+ "[{}] {} · {} · {} · from {} · \"{}\"",+ l.number, l.date, if l.unread { "unread" } else { "read" }, l.account, l.sender, l.subject+ );+ if !l.attachments.is_empty() {+ out += &format!(" · attachments: {}", l.attachments.join(", "));+ }+ out.push('\n');+ if let Some(t) = l.text.as_deref().filter(|t| !t.trim().is_empty()) {+ let one: String = t.replace(['\r', '\n'], " ").chars().take(3000).collect();+ out += &format!(" text: {one}\n");+ }+ }+ out += "</mail>";+ out+}++/// The messages a request names (a sender or a subject word of four letters or more),+/// best first: their text goes to the AI.+pub fn mentioned(query: &str, senders: &[String], subjects: &[String], limit: usize) -> Vec<usize> {+ let words: Vec<String> = query+ .split(|c: char| !c.is_alphanumeric() && c != '@' && c != '.')+ .map(normalize)+ .filter(|w| w.chars().count() >= 4)+ .collect();+ if words.is_empty() {+ return Vec::new();+ }+ let mut scored: Vec<(usize, usize)> = senders+ .iter()+ .zip(subjects)+ .enumerate()+ .filter_map(|(i, (s, sub))| {+ let (s, sub) = (normalize(s), normalize(sub));+ let score: usize = words.iter().map(|w| (if s.contains(w) { 2 } else { 0 }) + usize::from(sub.contains(w))).sum();+ (score > 0).then_some((i, score))+ })+ .collect();+ scored.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));+ scored.into_iter().take(limit).map(|(i, _)| i).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn plans_are_read_from_the_answer() {+ let answer = "Je prépare les envois.\n\n```coucou-mail\n{\"summary\": \"3 mails\", \"actions\": [\n\+ {\"type\": \"junk\", \"messages\": [2, 3]},\n\+ {\"type\": \"move\", \"messages\": 4, \"mailbox\": \"Compta\"},\n\+ {\"type\": \"reply\", \"message\": 1, \"body\": \"Merci !\"},\n\+ {\"type\": \"send\", \"to\": \"[email protected], [email protected]\", \"subject\": \"Hi\", \"body\": \"Yo\", \"attachments_from\": \"5\"},\n\+ {\"type\": \"merge\", \"from_message\": 1, \"attachment\": \"plans.pdf\", \"recipients\": [{\"email\": \"[email protected]\", \"name\": \"Léa\", \"key\": \"Bordeaux\"}, {\"email\": \"[email protected]\", \"city\": \"Lyon\"}], \"subject\": \"Plan {key}\", \"body\": \"Bonjour {name}\"},\n\+ {\"type\": \"save_attachments\", \"message\": 1, \"folder\": \"C:\\\\Plans\"}\n]}\n```\nClique sur Lancer.";+ let (prose, plan, error) = extract(answer);+ assert_eq!(error, None);+ assert!(prose.starts_with("Je prépare") && prose.ends_with("Clique sur Lancer.") && !prose.contains("coucou-mail"));+ let plan = plan.unwrap();+ assert_eq!(plan.summary, "3 mails");+ assert_eq!(plan.steps[0], Step::Sort(Action::Junk, vec![2, 3]));+ assert_eq!(plan.steps[1], Step::Sort(Action::Move("Compta".into()), vec![4]));+ assert_eq!(plan.steps[2], Step::Reply(1, "Merci !".into()));+ let Step::Send(s) = &plan.steps[3] else { panic!() };+ assert_eq!(s.to, vec!["[email protected]", "[email protected]"]);+ assert_eq!(s.attachments_from, Some(5));+ let Step::Merge(m) = &plan.steps[4] else { panic!() };+ assert_eq!(m.recipients[1].key, "Lyon");+ assert!(m.match_by_key && m.split_pages);+ assert_eq!(plan.steps[5], Step::SaveAttachments(1, "C:\\Plans".into()));+ // Still streaming, broken, and an action that does not exist.+ assert_eq!(extract("Ok\n```coucou-mail\n{\"actions\": ["), ("Ok".into(), None, None));+ assert!(extract("```coucou-mail\n{\"actions\": [{\"type\": \"send\"}]}\n```").2.unwrap().contains("needs \"to\""));+ assert!(extract("```coucou-mail\n{\"actions\": [{\"type\": \"delete\", \"messages\": [1]}]}\n```").2.unwrap().contains("unknown type"));+ }++ #[test]+ fn each_recipient_gets_its_page() {+ let pages: Vec<String> = ["Plan — BORDEAUX — RDC", "Plan Lyon 3e", "Plan Bordeaux annexe", "Marseille"].map(String::from).to_vec();+ let r = |e: &str, k: &str| Recipient { email: e.into(), name: e.into(), key: k.into() };+ let rs = vec![r("[email protected]", "Bordeaux"), r("[email protected]", "Lyon"), r("[email protected]", "Nice"), r("[email protected]", "Bordeaux")];+ let a = assign(&pages, &rs, true);+ assert_eq!(a.iter().map(|x| x.page).collect::<Vec<_>>(), vec![Some(0), Some(1), None, Some(2)]);+ assert!(a[0].ambiguous && !a[1].ambiguous);+ let o = assign(&pages, &[rs.clone(), rs.clone()].concat(), false);+ assert_eq!(o.iter().map(|x| x.page).collect::<Vec<_>>(), vec![Some(0), Some(1), Some(2), Some(3), None, None, None, None]);+ assert_eq!(fill("Plan {key} pour {name}", &rs[0]), "Plan Bordeaux pour [email protected]");+ assert_eq!(page_file_name("Plans.pdf", "Lyon", 1), "Plans - Lyon.pdf");+ assert_eq!(page_file_name("a:b.pdf", "", 4), "a-b - p5.pdf");+ assert!(valid_address("[email protected]"));+ for bad in ["lea", "lea@", "@x.fr", "lea@x", "le [email protected]", "[email protected]."] {+ assert!(!valid_address(bad), "{bad}");+ }+ }++ #[test]+ fn the_ai_gets_a_numbered_list() {+ let lines = vec![Line { number: 1, sender: "Martin <[email protected]>".into(), subject: "Plans".into(), date: "2026-10-30 09:00".into(),+ unread: true, account: "Pro".into(), attachments: vec!["plans.pdf".into()], text: Some("Voici\nles plans".into()) }];+ let s = snapshot(&lines, &[("Pro".into(), "[email protected]".into())]);+ assert!(s.contains("Accounts: Pro <[email protected]>") && s.contains("[1] 2026-10-30 09:00 · unread"));+ assert!(s.contains("attachments: plans.pdf") && s.contains("text: Voici les plans") && s.ends_with("</mail>"));+ assert!(INSTRUCTIONS.contains("coucou-mail") && INSTRUCTIONS.contains("Never invent an address"));+ let hits = mentioned("le mail de Martin avec les plans", &["Anne <[email protected]>".into(), "Martin <[email protected]>".into(), "Paul".into()],+ &["Plans".into(), "Plans franchisés".into(), "Hello".into()], 3);+ assert_eq!(hits, vec![1, 0]);+ }+}diff --git a/windows/src-tauri/src/mail/store.rs b/windows/src-tauri/src/mail/store.rsnew file mode 100644index 00000000..299a3625--- /dev/null+++ b/windows/src-tauri/src/mail/store.rs@@ -0,0 +1,181 @@+// The Mail section's settings, the journal of what Coucou sorted, what it sent for the chat,+// and the messages the automatic sorting already looked at. Small JSON files in+// %APPDATA%\Coucou\mail, on this computer only (MailTriageStore.swift on the Mac).++use std::path::PathBuf;++use serde::{de::DeserializeOwned, Deserialize, Serialize};++use super::triage::{Action, Reason, Settings};++/// One thing Coucou did to a message: shown in the Mail section, with its Undo.+#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct JournalEntry {+ pub id: String,+ pub date: i64,+ pub account: String,+ pub store_id: String,+ /// The message's EntryID after the action (a moved message gets a new one).+ pub entry_id: String,+ pub sender: String,+ pub subject: String,+ pub action: Action,+ pub reason: Reason,+ #[serde(default)]+ pub undone: bool,+}++/// A mail Coucou sent for the chat (a plan the user ran).+#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct SentEntry {+ pub id: String,+ pub date: i64,+ pub to: Vec<String>,+ pub subject: String,+ pub attachments: Vec<String>,+}++#[derive(Default)]+pub struct Store {+ pub settings: Settings,+ pub journal: Vec<JournalEntry>,+ pub sent: Vec<SentEntry>,+ seen: Vec<String>,+ seen_set: std::collections::HashSet<String>,+ dir: Option<PathBuf>,+}++const KEEP: usize = 500;+const SEEN: usize = 4000;++impl Store {+ pub fn load(dir: PathBuf) -> Store {+ let seen: Vec<String> = read(&dir, "seen.json").unwrap_or_default();+ Store {+ settings: read(&dir, "settings.json").unwrap_or_default(),+ journal: read(&dir, "journal.json").unwrap_or_default(),+ sent: read(&dir, "sent.json").unwrap_or_default(),+ seen_set: seen.iter().cloned().collect(),+ seen,+ dir: Some(dir),+ }+ }++ pub fn set_settings(&mut self, mut s: Settings, now: i64) {+ // Only what arrives from now on: Coucou never goes through the old messages.+ if s.auto_sort && !self.settings.auto_sort {+ s.auto_sort_since = Some(now);+ }+ self.settings = s;+ self.write("settings.json", &self.settings);+ }++ pub fn add_banned(&mut self, word: &str) {+ let w = word.trim();+ if w.is_empty() || self.settings.banned.iter().any(|b| super::triage::normalize(b) == super::triage::normalize(w)) {+ return;+ }+ self.settings.banned.push(w.to_string());+ self.write("settings.json", &self.settings);+ }++ pub fn add_vip(&mut self, entry: &str) {+ let e = entry.trim();+ if e.is_empty() || self.settings.vip.iter().any(|v| super::triage::normalize(v) == super::triage::normalize(e)) {+ return;+ }+ self.settings.vip.push(e.to_string());+ self.write("settings.json", &self.settings);+ }++ pub fn is_seen(&self, id: &str) -> bool {+ self.seen_set.contains(id)+ }++ pub fn mark_seen(&mut self, ids: &[String]) {+ let fresh: Vec<String> = ids.iter().filter(|i| !self.seen_set.contains(*i)).cloned().collect();+ if fresh.is_empty() {+ return;+ }+ for id in &fresh {+ self.seen_set.insert(id.clone());+ }+ self.seen.extend(fresh);+ if self.seen.len() > SEEN {+ let drop = self.seen.len() - SEEN;+ self.seen.drain(..drop);+ self.seen_set = self.seen.iter().cloned().collect();+ }+ self.write("seen.json", &self.seen);+ }++ pub fn record(&mut self, entry: JournalEntry) {+ self.journal.insert(0, entry);+ self.journal.truncate(KEEP);+ self.write("journal.json", &self.journal);+ }++ pub fn mark_undone(&mut self, id: &str) {+ if let Some(e) = self.journal.iter_mut().find(|e| e.id == id) {+ e.undone = true;+ self.write("journal.json", &self.journal);+ }+ }++ pub fn clear_journal(&mut self) {+ self.journal.clear();+ self.write("journal.json", &self.journal);+ }++ pub fn record_sent(&mut self, entry: SentEntry) {+ self.sent.insert(0, entry);+ self.sent.truncate(KEEP);+ self.write("sent.json", &self.sent);+ }++ fn write<T: Serialize>(&self, name: &str, value: &T) {+ let Some(dir) = &self.dir else { return };+ let result = std::fs::create_dir_all(dir)+ .and_then(|_| serde_json::to_vec_pretty(value).map_err(std::io::Error::other))+ .and_then(|bytes| {+ let tmp = dir.join(format!("{name}.tmp"));+ std::fs::write(&tmp, bytes)?;+ std::fs::rename(&tmp, dir.join(name))+ });+ if let Err(e) = result {+ crate::log::line(format!("[mail] could not save {name}: {e}"));+ }+ }+}++fn read<T: DeserializeOwned>(dir: &std::path::Path, name: &str) -> Option<T> {+ serde_json::from_slice(&std::fs::read(dir.join(name)).ok()?).ok()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn turning_sorting_on_starts_from_now_and_files_survive() {+ let dir = std::env::temp_dir().join(format!("coucou-mail-store-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let mut s = Store::load(dir.clone());+ s.set_settings(Settings { auto_sort: true, ..Default::default() }, 1234);+ assert_eq!(s.settings.auto_sort_since, Some(1234));+ s.set_settings(Settings { auto_sort: true, auto_sort_since: Some(1234), banned: vec!["promo".into()], ..Default::default() }, 9999);+ assert_eq!(s.settings.auto_sort_since, Some(1234), "already on: the start stays");+ s.add_banned("PROMO");+ assert_eq!(s.settings.banned.len(), 1, "no duplicate, whatever the case");+ s.mark_seen(&["a".into(), "b".into()]);+ s.record(JournalEntry { id: "j".into(), date: 1, account: "a".into(), store_id: "s".into(), entry_id: "e".into(),+ sender: "x".into(), subject: "y".into(), action: Action::Junk, reason: Reason::Manual, undone: false });+ let again = Store::load(dir.clone());+ assert!(again.is_seen("a") && !again.is_seen("c"));+ assert_eq!(again.journal.len(), 1);+ assert_eq!(again.settings.banned, vec!["promo"]);+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/windows/src-tauri/src/mail/triage.rs b/windows/src-tauri/src/mail/triage.rsnew file mode 100644index 00000000..fd8ac202--- /dev/null+++ b/windows/src-tauri/src/mail/triage.rs@@ -0,0 +1,379 @@+// Mail triage: the rules, the banned words and the VIPs of the Mail section, and the+// search of the Mail pill. Port of MailTriage.swift; pure, so it is tested on any machine.++use serde::{Deserialize, Serialize};++/// What a rule looks at. `contains` everywhere, ignoring case and accents; `domain` is the+/// end of the sender's address.+#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub enum Field {+ Sender,+ Domain,+ Subject,+ Text,+ Account,+}++#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]+pub struct Condition {+ pub field: Field,+ pub value: String,+}++/// What a rule does to a message. Coucou never deletes a message.+#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug)]+#[serde(tag = "kind", content = "mailbox", rename_all = "camelCase")]+pub enum Action {+ Junk,+ Important,+ MarkRead,+ Move(String),+}++#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Rule {+ pub id: String,+ pub name: String,+ #[serde(default = "yes")]+ pub enabled: bool,+ pub conditions: Vec<Condition>,+ pub action: Action,+}++fn yes() -> bool {+ true+}++/// Everything the Mail section lets the user set for the triage.+#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug, Default)]+#[serde(rename_all = "camelCase", default)]+pub struct Settings {+ /// Sort the messages that arrive from now on.+ pub auto_sort: bool,+ /// When the automatic sorting was turned on (ms since 1970): older messages are never touched.+ pub auto_sort_since: Option<i64>,+ /// Words, phrases or addresses: a message holding one goes to Junk.+ pub banned: Vec<String>,+ /// Addresses or domains ("@client.fr"): always important, never moved by a rule.+ pub vip: Vec<String>,+ pub rules: Vec<Rule>,+}++/// What the triage knows about a message when it decides.+#[derive(Clone, Debug, Default)]+pub struct Facts {+ pub sender_name: String,+ pub address: String,+ pub subject: String,+ pub account: String,+ /// The text, when it was read (banned words and text rules need it).+ pub text: Option<String>,+}++impl Facts {+ /// "Name <address>", what the sender rules look at.+ pub fn sender(&self) -> String {+ if self.sender_name.is_empty() {+ self.address.clone()+ } else {+ format!("{} <{}>", self.sender_name, self.address)+ }+ }+}++/// Why a message was sorted the way it was: shown in the journal.+#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]+#[serde(tag = "kind", content = "value", rename_all = "camelCase")]+pub enum Reason {+ Vip(String),+ Banned(String),+ Rule(String),+ /// The user's own click in the Mail pill or the chat.+ Manual,+}++#[derive(Clone, PartialEq, Eq, Debug)]+pub struct Decision {+ pub action: Action,+ pub reason: Reason,+}++/// Lowercased, without accents: "Réunion" and "reunion" are the same word.+pub fn normalize(s: &str) -> String {+ s.trim().chars().flat_map(|c| c.to_lowercase()).map(fold).collect()+}++/// The accented Latin letters most mail is written with, without their accent.+fn fold(c: char) -> char {+ match c {+ 'à' | 'á' | 'â' | 'ã' | 'ä' | 'å' | 'ā' | 'ă' | 'ą' => 'a',+ 'ç' | 'ć' | 'č' => 'c',+ 'ď' | 'đ' => 'd',+ 'è' | 'é' | 'ê' | 'ë' | 'ē' | 'ė' | 'ę' | 'ě' => 'e',+ 'ğ' => 'g',+ 'ì' | 'í' | 'î' | 'ï' | 'ī' | 'į' | 'ı' => 'i',+ 'ł' | 'ľ' => 'l',+ 'ñ' | 'ń' | 'ň' => 'n',+ 'ò' | 'ó' | 'ô' | 'õ' | 'ö' | 'ø' | 'ō' | 'ő' => 'o',+ 'ř' => 'r',+ 'ś' | 'š' | 'ş' | 'ș' => 's',+ 'ť' | 'ţ' | 'ț' => 't',+ 'ù' | 'ú' | 'û' | 'ü' | 'ū' | 'ů' | 'ű' | 'ų' => 'u',+ 'ý' | 'ÿ' => 'y',+ 'ź' | 'ż' | 'ž' => 'z',+ other => other,+ }+}++/// `needle` in `haystack` as a whole word or phrase ("sale" is not found in "salesforce").+/// An address or anything with "@" or "." is matched as plain text.+pub fn contains_word(haystack: &str, needle: &str) -> bool {+ let h = normalize(haystack);+ let n = normalize(needle);+ if n.is_empty() {+ return false;+ }+ if n.contains('@') || n.contains('.') {+ return h.contains(&n);+ }+ let edge = |c: Option<char>| c.map_or(true, |c| !c.is_alphanumeric());+ let mut start = 0;+ while let Some(pos) = h[start..].find(&n) {+ let at = start + pos;+ let before = h[..at].chars().next_back();+ let after = h[at + n.len()..].chars().next();+ if edge(before) && edge(after) {+ return true;+ }+ start = at + h[at..].chars().next().map_or(1, char::len_utf8);+ }+ false+}++fn domain_matches(address: &str, domain: &str) -> bool {+ let domain = domain.strip_prefix('@').unwrap_or(domain);+ address.ends_with(&format!("@{domain}")) || address.ends_with(&format!(".{domain}"))+}++pub fn matches(c: &Condition, f: &Facts) -> bool {+ let v = normalize(&c.value);+ if v.is_empty() {+ return false;+ }+ match c.field {+ Field::Sender => normalize(&f.sender()).contains(&v),+ Field::Domain => domain_matches(&normalize(&f.address), &v),+ Field::Subject => normalize(&f.subject).contains(&v),+ Field::Text => f.text.as_deref().is_some_and(|t| normalize(t).contains(&v)),+ Field::Account => normalize(&f.account).contains(&v),+ }+}++/// A VIP entry: a whole address, or a domain ("@client.fr" or "client.fr").+pub fn vip_hit(f: &Facts, vip: &[String]) -> Option<String> {+ let address = normalize(&f.address);+ vip.iter()+ .find(|entry| {+ let e = normalize(entry);+ if e.is_empty() {+ false+ } else if e.contains('@') && !e.starts_with('@') {+ address == e+ } else {+ domain_matches(&address, &e)+ }+ })+ .cloned()+}++/// The first banned word found in the sender, the subject or the text.+pub fn banned_hit(f: &Facts, banned: &[String]) -> Option<String> {+ let sender = f.sender();+ banned+ .iter()+ .filter(|w| !normalize(w).is_empty())+ .find(|w| {+ contains_word(&sender, w)+ || contains_word(&f.subject, w)+ || f.text.as_deref().is_some_and(|t| contains_word(t, w))+ })+ .cloned()+}++/// Whether deciding needs the message's text (a banned word or a text rule).+pub fn needs_text(s: &Settings) -> bool {+ !s.banned.is_empty()+ || s.rules.iter().any(|r| r.enabled && r.conditions.iter().any(|c| c.field == Field::Text))+}++/// VIPs first (never moved), then banned words, then the rules in order. None: left alone.+pub fn decide(f: &Facts, s: &Settings) -> Option<Decision> {+ if let Some(v) = vip_hit(f, &s.vip) {+ return Some(Decision { action: Action::Important, reason: Reason::Vip(v) });+ }+ if let Some(w) = banned_hit(f, &s.banned) {+ return Some(Decision { action: Action::Junk, reason: Reason::Banned(w) });+ }+ s.rules+ .iter()+ .filter(|r| r.enabled && !r.conditions.is_empty())+ .find(|r| r.conditions.iter().all(|c| matches(c, f)))+ .map(|r| Decision { action: r.action.clone(), reason: Reason::Rule(r.name.clone()) })+}++// ── Search ───────────────────────────────────────────────────────────────────++/// The search of the Mail pill: free words, plus "de:" / "from:" and "objet:" / "subject:".+#[derive(Clone, PartialEq, Eq, Debug, Default)]+pub struct Query {+ pub from: Vec<String>,+ pub subject: Vec<String>,+ pub words: Vec<String>,+}++const FROM_KEYS: [&str; 4] = ["de:", "from:", "von:", "da:"];+const SUBJECT_KEYS: [&str; 6] = ["objet:", "subject:", "asunto:", "betreff:", "assunto:", "oggetto:"];++impl Query {+ #[allow(dead_code)]+ pub fn is_empty(&self) -> bool {+ self.from.is_empty() && self.subject.is_empty() && self.words.is_empty()+ }++ /// `de:dupont objet:"devis mai" facture` → from dupont, subject "devis mai", word facture.+ pub fn parse(text: &str) -> Query {+ let mut tokens = Vec::new();+ let (mut current, mut quoted) = (String::new(), false);+ for c in text.chars() {+ if c == '"' {+ quoted = !quoted;+ } else if c.is_whitespace() && !quoted {+ if !current.is_empty() {+ tokens.push(std::mem::take(&mut current));+ }+ } else {+ current.push(c);+ }+ }+ if !current.is_empty() {+ tokens.push(current);+ }+ let mut q = Query::default();+ let mut pending: Option<bool> = None; // Some(true) = from, Some(false) = subject+ for token in tokens {+ let lower = token.to_lowercase();+ let key = FROM_KEYS.iter().map(|k| (k, true)).chain(SUBJECT_KEYS.iter().map(|k| (k, false)))+ .find(|(k, _)| lower.starts_with(**k));+ if let Some((k, is_from)) = key {+ let rest: String = token.chars().skip(k.chars().count()).collect();+ if rest.is_empty() {+ pending = Some(is_from);+ } else if is_from {+ q.from.push(rest);+ } else {+ q.subject.push(rest);+ }+ continue;+ }+ match pending.take() {+ Some(true) => q.from.push(token),+ Some(false) => q.subject.push(token),+ None => q.words.push(token),+ }+ }+ q+ }+}++/// The quick filters of the Mail pill.+#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]+#[serde(rename_all = "camelCase")]+pub enum Filter {+ #[default]+ All,+ Unread,+ Flagged,+ Today,+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts(address: &str, subject: &str, text: Option<&str>) -> Facts {+ Facts {+ sender_name: "Paul".into(),+ address: address.into(),+ subject: subject.into(),+ account: "Pro".into(),+ text: text.map(String::from),+ }+ }++ #[test]+ fn words_are_whole_and_without_accents() {+ assert_eq!(normalize(" Réunion ÉTÉ "), "reunion ete");+ assert!(contains_word("Big SALE today", "sale"));+ assert!(!contains_word("Salesforce update", "sale"));+ assert!(contains_word("Promo d'été -50%", "promo"));+ assert!(contains_word("Votre facture du mois", "facture du mois"));+ assert!(contains_word("from [email protected]", "[email protected]"));+ assert!(contains_word("bonjour, réunion demain", "reunion"));+ assert!(!contains_word("anything", " "));+ }++ #[test]+ fn vips_then_banned_words_then_rules() {+ let mut s = Settings::default();+ let paul = facts("[email protected]", "Devis mai", None);+ assert_eq!(decide(&paul, &s), None);+ s.vip = vec!["@client.fr".into()];+ s.banned = vec!["devis".into()];+ assert_eq!(decide(&paul, &s).unwrap().reason, Reason::Vip("@client.fr".into()));+ s.vip = vec!["client.fr".into()];+ assert_eq!(decide(&facts("[email protected]", "Devis", None), &s).unwrap().action, Action::Important);+ assert_eq!(decide(&facts("[email protected]", "Devis", None), &s).unwrap().reason, Reason::Banned("devis".into()));+ s.vip = vec![];+ s.banned = vec!["unsubscribe".into()];+ assert_eq!(decide(&facts("[email protected]", "Hi", Some("Click to UNSUBSCRIBE")), &s).unwrap().action, Action::Junk);+ assert_eq!(decide(&facts("[email protected]", "Hi", None), &s), None);+ assert!(needs_text(&s));+ s.banned = vec![];+ s.rules = vec![+ Rule { id: "1".into(), name: "Off".into(), enabled: false,+ conditions: vec![Condition { field: Field::Sender, value: "paul".into() }], action: Action::Junk },+ Rule { id: "2".into(), name: "Clients".into(), enabled: true,+ conditions: vec![Condition { field: Field::Domain, value: "@client.fr".into() },+ Condition { field: Field::Subject, value: "devis".into() }],+ action: Action::Move("Clients".into()) },+ ];+ let d = decide(&paul, &s).unwrap();+ assert_eq!(d.action, Action::Move("Clients".into()));+ assert_eq!(d.reason, Reason::Rule("Clients".into()));+ assert_eq!(decide(&facts("[email protected]", "Bonjour", None), &s), None);+ }++ #[test]+ fn settings_and_actions_round_trip_as_the_island_reads_them() {+ let s = Settings { auto_sort: true, rules: vec![Rule { id: "a".into(), name: "n".into(), enabled: true,+ conditions: vec![], action: Action::Move("X".into()) }], ..Default::default() };+ let json = serde_json::to_string(&s).unwrap();+ assert!(json.contains("\"autoSort\":true"));+ assert!(json.contains("{\"kind\":\"move\",\"mailbox\":\"X\"}"));+ assert_eq!(serde_json::to_string(&Action::Junk).unwrap(), "{\"kind\":\"junk\"}");+ assert_eq!(serde_json::from_str::<Settings>(&json).unwrap(), s);+ assert_eq!(serde_json::from_str::<Settings>("{}").unwrap(), Settings::default());+ }++ #[test]+ fn search_reads_from_and_subject() {+ let q = Query::parse("de:dupont objet:\"devis mai\" facture urgent");+ assert_eq!(q.from, vec!["dupont"]);+ assert_eq!(q.subject, vec!["devis mai"]);+ assert_eq!(q.words, vec!["facture", "urgent"]);+ assert_eq!(Query::parse("from: anne").from, vec!["anne"]);+ assert!(Query::parse(" ").is_empty());+ }+}diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rsindex f451eefa..aac6ba42 100644--- a/windows/src-tauri/src/platform/linux.rs+++ b/windows/src-tauri/src/platform/linux.rs@@ -235,6 +235,11 @@ pub fn user_full_name() -> Option<String> {// ── Processes ─────────────────────────────────────────────────────────────────/// Nothing to hide: a spawned process only gets a terminal if it asks for one.+/// Outlook (the Mail pill) is a Windows program: nothing to look for here.+pub fn process_running(_exe: &str) -> bool {+ false+}+pub fn no_console(cmd: &mut Command) -> &mut Command {cmd}diff --git a/windows/src-tauri/src/platform/windows.rs b/windows/src-tauri/src/platform/windows.rsindex e850ae55..0d90b1cd 100644--- a/windows/src-tauri/src/platform/windows.rs+++ b/windows/src-tauri/src/platform/windows.rs@@ -371,6 +371,12 @@ pub fn pipe_client_pid(handle: RawHandle) -> Option<u32> {(pid != 0).then_some(pid)}+/// Whether a program runs (by its executable's name, any case): the Mail pill asks for+/// OUTLOOK.EXE before it starts PowerShell, so a closed Outlook costs nothing.+pub fn process_running(exe: &str) -> bool {+ process_table().values().any(|p| p.exe.eq_ignore_ascii_case(exe))+}+/// Every process, by ID: its parent and its executable's name.fn process_table() -> HashMap<u32, Proc> {let mut out = HashMap::new();diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex c8868a08..66289868 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -362,8 +362,8 @@ export const Bridge = {// ── Chat, files, secrets ──────────────────────────────────────────────────/** One chat turn. The API key and any file bytes never leave Rust. */- chatSend: (query: string, context: ChatContext | null) =>- callOrThrow<{ text: string }>("chat_send", { query, context }),+ chatSend: (query: string, context: ChatContext | null, mail = false) =>+ callOrThrow<{ text: string }>("chat_send", { query, context, mail }),chatReset: () => call<void>("chat_reset"),/*** The models a provider offers, for the picker in the chat view. Rust asksdiff --git a/windows/src/core/mail.ts b/windows/src/core/mail.tsnew file mode 100644index 00000000..f856cad8--- /dev/null+++ b/windows/src/core/mail.ts@@ -0,0 +1,239 @@+// The Mail pill on Windows (classic Outlook, src-tauri/src/mail): the types the island and+// the Coucou window read, and the calls to Rust. Port of MailController / MailTriageStore /+// MailAgent's shapes; the wording is the Mac's (MailViews.swift, MailHubPages.swift).++import { invoke } from "@tauri-apps/api/core";+import { IS_TAURI } from "./bridge";+import { t } from "../i18n/i18n";++export const MAIL_ID = "integration_mail";+export const MAIL_BLUE = "#2F8CFF";++export interface MailMessage {+ entryId: string;+ storeId: string;+ account: string;+ senderName: string;+ address: string;+ subject: string;+ /** Milliseconds since 1970. */+ date: number;+ unread: boolean;+ flagged: boolean;+ local: string;+}++export type MailFilter = "all" | "unread" | "flagged" | "today";+export const MAIL_FILTERS: MailFilter[] = ["all", "unread", "flagged", "today"];++export type MailAction =+ | { kind: "junk" }+ | { kind: "important" }+ | { kind: "markRead" }+ | { kind: "move"; mailbox: string };++export type MailField = "sender" | "domain" | "subject" | "text" | "account";+export const MAIL_FIELDS: MailField[] = ["sender", "domain", "subject", "text", "account"];++export interface MailRule {+ id: string;+ name: string;+ enabled: boolean;+ conditions: { field: MailField; value: string }[];+ action: MailAction;+}++export interface MailSettings {+ autoSort: boolean;+ autoSortSince: number | null;+ banned: string[];+ vip: string[];+ rules: MailRule[];+}++export type MailReason =+ | { kind: "vip"; value: string }+ | { kind: "banned"; value: string }+ | { kind: "rule"; value: string }+ | { kind: "manual" };++export interface JournalEntry {+ id: string;+ date: number;+ account: string;+ storeId: string;+ entryId: string;+ sender: string;+ subject: string;+ action: MailAction;+ reason: MailReason;+ undone: boolean;+}++export interface SentEntry {+ id: string;+ date: number;+ to: string[];+ subject: string;+ attachments: string[];+}++export interface TriageView {+ settings: MailSettings;+ journal: JournalEntry[];+ sent: SentEntry[];+ today: { sorted: number; junk: number; important: number };+ windows: boolean;+ outlookOpen: boolean;+}++export interface PreparedMail {+ to: string[];+ cc: string[];+ subject: string;+ body: string;+ attachments: string[];+ problem: "noPage" | "badAddress" | null;+}++export type PlanPhase =+ | { kind: "preparing" }+ | { kind: "ready" }+ | { kind: "countdown"; seconds: number }+ | { kind: "running"; done: number; total: number }+ | { kind: "done"; ok: number; failed: number }+ | { kind: "cancelled" };++export interface PlanRun {+ phase: PlanPhase;+ summary: string;+ sorts: { action: MailAction; messages: MailMessage[] }[];+ replies: [MailMessage, string][];+ saves: [MailMessage, string][];+ mails: PreparedMail[];+ notes: { kind: "missing" | "noPdf" | "fileMissing"; value: string }[];+ testSentTo: string | null;+ myAddress: string | null;+ stepCount: number;+}++/** What the card shows, as Rust sends it in the pill's `integration` data. */+export interface MailCardData {+ running: boolean;+ windows: boolean;+ unread: number;+ messages: MailMessage[];+ shown: number;+ maxShown: number;+}++async function call<T>(cmd: string, args?: Record<string, unknown>): Promise<T | null> {+ if (!IS_TAURI) return null;+ try {+ return await invoke<T>(cmd, args);+ } catch (err) {+ console.error(`[coucou] ${cmd} failed`, err);+ return null;+ }+}++export const MailBridge = {+ refresh: () => call<void>("mail_refresh"),+ more: () => call<void>("mail_more"),+ search: (query: string, filter: MailFilter) => call<MailMessage[]>("mail_search", { query, filter }),+ detail: (message: MailMessage) => call<{ text: string; attachments: string[] }>("mail_detail", { message }),+ open: (message: MailMessage, reply: boolean) => call<void>("mail_open", { message, reply }),+ act: (message: MailMessage, kind: "read" | "flag" | "unflag" | "junk" | "ignore" | "vip") =>+ call<void>("mail_act", { message, kind }),+ triage: () => call<TriageView>("mail_triage"),+ setTriage: (settings: MailSettings) => call<void>("mail_triage_set", { settings }),+ clearJournal: () => call<void>("mail_journal_clear"),+ undo: (id: string) => call<void>("mail_undo", { id }),+ planShow: (id: string, text: string) => call<PlanRun>("mail_plan_show", { id, text }),+ planTest: (id: string) => call<void>("mail_plan_test", { id }),+ planStart: (id: string) => call<void>("mail_plan_start", { id }),+ planCancel: (id: string) => call<void>("mail_plan_cancel", { id }),+};++/** The chat's Mail switch: off at each start, like the Mac's. */+export const MailChat = { on: false };++export function messageId(m: MailMessage): string {+ return `${m.storeId}/${m.entryId}`;+}++/** "Name" from the message, else the address before "@". */+export function senderName(m: { senderName: string; address: string }): string {+ return m.senderName.trim() || m.address.split("@")[0] || m.address;+}++/** "Name" from "Name <address>" (the journal keeps the sender that way). */+export function nameOf(sender: string): string {+ const lt = sender.indexOf("<");+ const name = (lt >= 0 ? sender.slice(0, lt) : sender).trim().replace(/^"|"$/g, "");+ return name || sender.replace(/[<>]/g, "").split("@")[0];+}++export function filterTitle(f: MailFilter): string {+ switch (f) {+ case "all": return t("All");+ case "unread": return t("Unread");+ case "flagged": return t("Important");+ case "today": return t("Today");+ }+}++export function fieldTitle(f: MailField): string {+ switch (f) {+ case "sender": return t("Sender");+ case "domain": return t("Sender’s domain");+ case "subject": return t("Subject");+ case "text": return t("Text");+ case "account": return t("Account");+ }+}++/** "Move to Junk", in a rule. */+export function ruleLine(a: MailAction): string {+ switch (a.kind) {+ case "junk": return t("Move to Junk");+ case "important": return t("Mark important");+ case "markRead": return t("Mark as read");+ case "move": return t("Move to {0}", { 0: a.mailbox });+ }+}++/** "Moved to Junk", in the journal. */+export function journalLine(a: MailAction): string {+ switch (a.kind) {+ case "junk": return t("Moved to Junk");+ case "important": return t("Marked important");+ case "markRead": return t("Marked as read");+ case "move": return t("Moved to {0}", { 0: a.mailbox });+ }+}++export function reasonLine(r: MailReason): string {+ switch (r.kind) {+ case "vip": return t("VIP {0}", { 0: r.value });+ case "banned": return t("banned word “{0}”", { 0: r.value });+ case "rule": return t("rule “{0}”", { 0: r.value });+ case "manual": return t("by hand");+ }+}++/** The answer without its ```coucou-mail block, and whether it held one (mail/plan.rs). */+export function splitPlan(text: string): { prose: string; plan: boolean } {+ const fence = "```coucou-mail";+ const start = text.indexOf(fence);+ if (start < 0) return { prose: text, plan: false };+ const after = text.slice(start + fence.length);+ const end = after.indexOf("```");+ const prose = (text.slice(0, start) + (end >= 0 ? after.slice(end + 3) : "")).trim();+ return { prose, plan: end >= 0 };+}++/** A new rule's name: "Sender contains “newsletter” → Move to Junk". */+export function ruleName(field: MailField, value: string, action: MailAction): string {+ return t("{0} contains “{1}” → {2}", { 0: fieldTitle(field), 1: value, 2: ruleLine(action) });+}diff --git a/windows/src/core/pills.ts b/windows/src/core/pills.tsindex fa222fef..ad79d97c 100644--- a/windows/src/core/pills.ts+++ b/windows/src/core/pills.ts@@ -138,6 +138,10 @@ export const PILL_CATALOG: readonly PillDefinition[] = [// (src-tauri/src/spotify.rs).{ id: "integration_spotify", name: "Spotify", color: "#1DB954", category: "service",subtitle: N_("Integration"), source: "n8n", support: "yes", connect: none },+ // Mail: classic Outlook on Windows, driven on this computer through its COM objects+ // (src-tauri/src/mail). The new Outlook has none, and Linux has no Outlook.+ { id: "integration_mail", name: "Mail", color: "#2F8CFF", category: "service",+ subtitle: N_("Integration"), source: "n8n", support: "windows", connect: none },// WhatsApp (experimental) through a gateway on this computer (src-tauri/src/whatsapp): set up,// linked and turned on in Settings → Integrations → WhatsApp, off until then.{ id: "integration_whatsapp", name: "WhatsApp", color: "#25D366", category: "service",diff --git a/windows/src/hub/hero.ts b/windows/src/hub/hero.tsindex b0dce33f..528197f9 100644--- a/windows/src/hub/hero.ts+++ b/windows/src/hub/hero.ts@@ -401,6 +401,10 @@ export const THEMES: Record<string, Theme> = {phone: { color: "#3DDC84", cast: [m("#3DDC84", 56, 0.25), m("#F5F6F8", 46, 0.8, { outfit: "beanie" })] },voice: { color: "#F97316", cast: [m("#F97316", 60, 0.3), m("#F5F6F8", 48, 0.85, { outfit: "roundGlasses" })] },shortcuts: { color: "#6366F1", cast: [m("#6366F1", 56, 0.2, { outfit: "sunglasses" }), m("#F5F6F8", 46, 0.8)] },+ mailOverview: { color: "#2F8CFF", cast: [m("#2F8CFF", 58, 0.2, { state: "working" }), m("#F5F6F8", 46, 0.7), m("#F5A524", 40, 1)] },+ mailRules: { color: "#34D399", cast: [m("#34D399", 56, 0.3, { outfit: "roundGlasses" }), m("#8E939C", 46, 0.85)] },+ mailBanned: { color: "#FF453A", cast: [m("#FF453A", 54, 0.25, { outfit: "sunglasses" }), m("#F5F6F8", 44, 0.8, { state: "sleeping", roams: false })] },+ mailVIP: { color: "#F5A524", cast: [m("#F5A524", 60, 0.3, { outfit: "crown" }), m("#2F8CFF", 46, 0.85)] },};/** The band itself: title, line, actions, and the Mochis. */diff --git a/windows/src/hub/hub.css b/windows/src/hub/hub.cssindex a4327c0f..13a7873a 100644--- a/windows/src/hub/hub.css+++ b/windows/src/hub/hub.css@@ -921,3 +921,45 @@ button.hub-icon svg {.hub-note-detail > button {align-self: flex-start;}++/* ── Mail (classic Outlook) — MailHubPages.swift ──────────────────────────── */+.mail-stats {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 12px;+}++.mail-stat {+ font: 700 28px var(--font);+ font-variant-numeric: tabular-nums;+}++.mail-journal {+ gap: 12px;+ align-items: center;+}++.mail-journal b {+ font-weight: 600;+}++.mail-dim {+ color: #8e939c;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.mail-dim.small {+ font-size: 11.5px;+ color: #6b7079;+}++.mail-rule-line {+ gap: 8px;+}++.mail-if {+ width: 44px;+ flex: 0 0 auto;+}diff --git a/windows/src/hub/pages.ts b/windows/src/hub/pages.tsindex 469ca204..431cfa59 100644--- a/windows/src/hub/pages.ts+++ b/windows/src/hub/pages.ts@@ -9,6 +9,7 @@ import { dictionaryPage, snippetsPage } from "./pages/words";import { stylesPage } from "./pages/styles";import { flowSettingsPage } from "./pages/flowsettings";import { voicePage } from "./pages/voice";+import { mailBannedPage, mailOverviewPage, mailRulesPage, mailVIPPage } from "./pages/mail";export const FLOW_PAGE_RENDERERS: Partial<Record<PageId, FlowPageRenderer>> = {dictation: dictationPage,@@ -19,4 +20,8 @@ export const FLOW_PAGE_RENDERERS: Partial<Record<PageId, FlowPageRenderer>> = {styles: stylesPage,flowsettings: flowSettingsPage,voice: voicePage,+ mailOverview: mailOverviewPage,+ mailRules: mailRulesPage,+ mailBanned: mailBannedPage,+ mailVIP: mailVIPPage,};diff --git a/windows/src/hub/pages/mail.ts b/windows/src/hub/pages/mail.tsnew file mode 100644index 00000000..e62b66db--- /dev/null+++ b/windows/src/hub/pages/mail.ts@@ -0,0 +1,263 @@+// The Mail section of the Coucou window (classic Outlook): the automatic sorting and its+// journal, the rules, the banned words and the VIPs. Port of MailHubPages.swift; what they+// decide lives in src-tauri/src/mail/triage.rs.++import { h, clear } from "../../views/dom";+import { t } from "../../i18n/i18n";+import {+ MAIL_BLUE, MAIL_FIELDS, MailBridge, fieldTitle, journalLine, nameOf, reasonLine, ruleLine, ruleName,+ type MailAction, type MailField, type MailSettings, type TriageView,+} from "../../core/mail";+import type { HubContext } from "../shell";+import { emptyState } from "../hero";+import { button, card, divider, icon, iconButton, label, row, select, toggle } from "../ui";++const EMPTY: TriageView = {+ settings: { autoSort: false, autoSortSince: null, banned: [], vip: [], rules: [] },+ journal: [], sent: [], today: { sorted: 0, junk: 0, important: 0 }, windows: true, outlookOpen: false,+};++async function load(): Promise<TriageView> {+ return (await MailBridge.triage()) ?? EMPTY;+}++function save(settings: MailSettings) {+ void MailBridge.setTriage(settings);+}++function input(placeholder: string, onEnter?: () => void): HTMLInputElement {+ const el = h("input", { class: "hub-input", placeholder }) as HTMLInputElement;+ if (onEnter) el.addEventListener("keydown", (e) => e.key === "Enter" && onEnter());+ el.style.flex = "1";+ return el;+}++function time(ms: number, withDay = false): string {+ try {+ return new Intl.DateTimeFormat(document.documentElement.lang || undefined, withDay+ ? { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }+ : { hour: "2-digit", minute: "2-digit" }).format(new Date(ms));+ } catch {+ return new Date(ms).toLocaleTimeString();+ }+}++/** When the automatic sorting is off, the pages that feed it say so, with the switch. */+function autoSortHint(view: TriageView, redraw: () => void): HTMLElement | null {+ if (view.settings.autoSort) return null;+ return card(row(t("Automatic sorting is off: these settings do nothing until it is on."), null,+ button(t("Turn on"), () => {+ save({ ...view.settings, autoSort: true });+ window.setTimeout(redraw, 300);+ }, "primary")));+}++// ── Overview ─────────────────────────────────────────────────────────────────++export async function mailOverviewPage(page: HTMLElement, ctx: HubContext) {+ const view = await load();+ page.append(ctx.hero("mailOverview", t("Overview"),+ t("Coucou sorts your Outlook inboxes: VIPs first, then banned words, then your rules. It never deletes a message.")));+ const redraw = () => ctx.navigate("mailOverview");++ const sortCard = card(row(t("Sort new messages automatically"),+ t("Only messages that arrive from now on, in every Outlook account. The classic Outlook must be open."),+ toggle(view.settings.autoSort, (on) => {+ save({ ...view.settings, autoSort: on });+ view.settings.autoSort = on;+ })));+ if (!view.windows) {+ sortCard.append(divider(), h("div", { class: "hub-note", text: t("Outlook is only reached on Windows.") }));+ } else if (!view.outlookOpen) {+ sortCard.append(divider(), h("div", { class: "hub-note", text: t("Outlook is closed: nothing is sorted until it is open.") }));+ }+ page.append(sortCard);++ const stat = (value: number, text: string, color: string) =>+ card(h("div", { class: "mail-stat", style: `color:${color}`, text: String(value) }), h("div", { class: "hub-note", text }));+ page.append(h("div", { class: "mail-stats" },+ stat(view.today.sorted, t("sorted today"), MAIL_BLUE),+ stat(view.today.junk, t("sent to Junk"), "#8E939C"),+ stat(view.today.important, t("marked important"), "#F5A524"),+ ));++ if (view.sent.length > 0) {+ page.append(label(t("Sent by Coucou")));+ const list = card();+ view.sent.forEach((e, i) => {+ if (i > 0) list.append(divider());+ list.append(h("div", { class: "hub-list-row mail-journal" },+ h("b", { text: e.to.join(", ") }),+ h("span", { class: "grow mail-dim", text: e.subject }),+ e.attachments.length > 0 ? h("span", { class: "mail-dim", text: `📎 ${e.attachments.join(", ")}` }) : h("span"),+ h("span", { class: "mail-dim", text: time(e.date, true) }),+ ));+ });+ page.append(list);+ }++ const journalHead = h("div", { class: "hub-row" }, label(t("Journal")));+ if (view.journal.length > 0) {+ journalHead.append(button(t("Clear"), () => {+ void MailBridge.clearJournal().then(redraw);+ }, "", true));+ }+ page.append(journalHead);+ const journal = card();+ if (view.journal.length === 0) {+ journal.append(emptyState(t("Nothing sorted yet. What Coucou does to your messages shows up here, with an Undo."), "idle", MAIL_BLUE));+ }+ view.journal.forEach((e, i) => {+ if (i > 0) journal.append(divider());+ const undo = e.undone+ ? h("span", { class: "mail-dim", text: t("Undone") })+ : button(t("Undo"), () => void MailBridge.undo(e.id).then(redraw), "", true);+ journal.append(h("div", { class: "hub-list-row mail-journal" },+ h("div", { class: "grow" },+ h("div", {}, h("b", { text: nameOf(e.sender) }), h("span", { class: "mail-dim", text: ` ${e.subject}` })),+ h("div", { class: "mail-dim small", text: `${journalLine(e.action)} · ${reasonLine(e.reason)}` }),+ ),+ h("span", { class: "mail-dim", text: time(e.date) }),+ undo,+ ));+ });+ page.append(journal);+}++// ── Rules ────────────────────────────────────────────────────────────────────++type Kind = "junk" | "important" | "read" | "move";++export async function mailRulesPage(page: HTMLElement, ctx: HubContext) {+ const view = await load();+ const redraw = () => ctx.navigate("mailRules");+ page.append(ctx.hero("mailRules", t("Rules"),+ t("If a message matches, Coucou does the action. The first rule that matches wins; VIPs and banned words come before.")));+ const hint = autoSortHint(view, redraw);+ if (hint) page.append(hint);++ let field: MailField = "sender";+ let kind: Kind = "junk";+ const value = input(t("newsletter, @shop.com, invoice…"), () => add());+ const mailbox = input(t("Mailbox name"), () => add());+ mailbox.style.display = "none";+ const action = (): MailAction | null => {+ switch (kind) {+ case "junk": return { kind: "junk" };+ case "important": return { kind: "important" };+ case "read": return { kind: "markRead" };+ case "move": return mailbox.value.trim() ? { kind: "move", mailbox: mailbox.value.trim() } : null;+ }+ };+ const add = () => {+ const v = value.value.trim();+ const a = action();+ if (!v || !a) return;+ const rules = [...view.settings.rules, {+ id: `${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 8)}`,+ name: ruleName(field, v, a), enabled: true, conditions: [{ field, value: v }], action: a,+ }];+ view.settings = { ...view.settings, rules };+ save(view.settings);+ value.value = "";+ mailbox.value = "";+ drawRules();+ };+ const fields = select(MAIL_FIELDS.map((f) => [f, fieldTitle(f)] as [MailField, string]), field, (f) => (field = f));+ const kinds = select<Kind>([+ ["junk", ruleLine({ kind: "junk" })],+ ["important", ruleLine({ kind: "important" })],+ ["read", ruleLine({ kind: "markRead" })],+ ["move", t("Move to mailbox…")],+ ], kind, (k) => {+ kind = k;+ mailbox.style.display = k === "move" ? "" : "none";+ });+ page.append(card(+ h("div", { class: "hub-row mail-rule-line" }, h("b", { class: "mail-if", text: t("If") }), fields, h("span", { class: "mail-dim", text: t("contains") }), value),+ h("div", { class: "hub-row mail-rule-line" }, h("b", { class: "mail-if", text: t("Then") }), kinds, mailbox, h("span", { class: "grow" }), button(t("Add"), add, "primary")),+ ));++ const list = card();+ page.append(list);+ const drawRules = () => {+ clear(list);+ if (view.settings.rules.length === 0) {+ list.append(emptyState(t("No rules yet. Example: if the sender contains “newsletter”, move to Junk."), "idle", "#34D399"));+ return;+ }+ view.settings.rules.forEach((r, i) => {+ if (i > 0) list.append(divider());+ list.append(h("div", { class: "hub-list-row" },+ toggle(r.enabled, (on) => {+ view.settings = { ...view.settings, rules: view.settings.rules.map((x) => (x.id === r.id ? { ...x, enabled: on } : x)) };+ save(view.settings);+ }),+ h("span", { class: "grow", text: r.name }),+ iconButton("trash", t("Delete"), () => {+ view.settings = { ...view.settings, rules: view.settings.rules.filter((x) => x.id !== r.id) };+ save(view.settings);+ drawRules();+ }),+ ));+ });+ };+ drawRules();+}++// ── Banned words and VIPs ────────────────────────────────────────────────────++function chipsPage(+ page: HTMLElement, ctx: HubContext, view: TriageView, id: "mailBanned" | "mailVIP",+ key: "banned" | "vip", placeholder: string, empty: string, color: string,+) {+ const hint = autoSortHint(view, () => ctx.navigate(id));+ if (hint) page.append(hint);+ const chips = h("div", { class: "hub-chips" });+ const field = input(placeholder, () => add());+ const add = () => {+ const w = field.value.trim();+ const list = view.settings[key];+ if (!w || list.some((x) => x.toLowerCase() === w.toLowerCase())) return;+ view.settings = { ...view.settings, [key]: [...list, w] };+ save(view.settings);+ field.value = "";+ draw();+ };+ const draw = () => {+ clear(chips);+ const list = view.settings[key];+ if (list.length === 0) {+ chips.append(emptyState(empty, "idle", color));+ return;+ }+ for (const w of list) {+ const remove = h("button", { title: t("Delete"), "aria-label": t("Delete") });+ remove.append(icon("x"));+ remove.addEventListener("click", () => {+ view.settings = { ...view.settings, [key]: view.settings[key].filter((x) => x !== w) };+ save(view.settings);+ draw();+ });+ chips.append(h("span", { class: "hub-chip" }, h("span", { text: w }), remove));+ }+ };+ page.append(card(h("div", { class: "hub-row" }, field, button(t("Add"), add, "primary")), chips));+ draw();+}++export async function mailBannedPage(page: HTMLElement, ctx: HubContext) {+ const view = await load();+ page.append(ctx.hero("mailBanned", t("Banned words"),+ t("A message whose sender, subject or text holds one of these words or addresses goes straight to Junk. Whole words only: “sale” does not catch “Salesforce”.")));+ chipsPage(page, ctx, view, "mailBanned", "banned", t("A word, a phrase or an address"),+ t("No banned words. Add a word, or click “Always ignore this sender” on a message in the island."), "#FF453A");+}++export async function mailVIPPage(page: HTMLElement, ctx: HubContext) {+ const view = await load();+ page.append(ctx.hero("mailVIP", t("VIP"),+ t("Messages from these addresses or domains are always flagged important, and no rule ever moves them.")));+ chipsPage(page, ctx, view, "mailVIP", "vip", t("[email protected] or @client.com"),+ t("No VIPs yet. Add an address, or a whole domain with @."), "#F5A524");+}diff --git a/windows/src/hub/shell.ts b/windows/src/hub/shell.tsindex 252a0f10..693d9082 100644--- a/windows/src/hub/shell.ts+++ b/windows/src/hub/shell.ts@@ -13,7 +13,8 @@ import { icon, keyLabel } from "./ui";export type PageId =| "dictation" | "notes" | "insights" | "dictionary" | "snippets" | "styles" | "flowsettings"- | "general" | "pills" | "agents" | "chat" | "voice" | "integrations" | "phone" | "shortcuts";+ | "general" | "pills" | "agents" | "chat" | "voice" | "integrations" | "phone" | "shortcuts"+ | "mailOverview" | "mailRules" | "mailBanned" | "mailVIP";interface PageDef {id: PageId;@@ -44,7 +45,15 @@ export const NOTCH_PAGES: PageDef[] = [{ id: "shortcuts", icon: "keyboard", title: () => t("Shortcuts"), subtitle: () => t("The keys that open the island and its actions.") },];-const ALL = [...FLOW_PAGES, ...NOTCH_PAGES];+/** Mail (classic Outlook): Windows only, Linux has no Outlook. */+export const MAIL_PAGES: PageDef[] = [+ { id: "mailOverview", icon: "tray", title: () => t("Overview") },+ { id: "mailRules", icon: "filter", title: () => t("Rules") },+ { id: "mailBanned", icon: "nosign", title: () => t("Banned words") },+ { id: "mailVIP", icon: "star", title: () => t("VIP") },+];++const ALL = [...FLOW_PAGES, ...NOTCH_PAGES, ...MAIL_PAGES];/** What a page gets to draw itself and reach the rest of the window. */export interface HubContext {@@ -175,6 +184,7 @@ export async function startHub(root: HTMLElement, opts: HubOptions) {};group("Flow", FLOW_PAGES);group(t("Notch"), NOTCH_PAGES);+ if (status.platform === "windows") group("Mail", MAIL_PAGES);side.append(h("div", { class: "spacer" }), statusLine, h("div", { class: "hub-version", text: `Coucou ${opts.version}` }));clear(root);diff --git a/windows/src/hub/ui.ts b/windows/src/hub/ui.tsindex 07330d45..47d715ae 100644--- a/windows/src/hub/ui.ts+++ b/windows/src/hub/ui.ts@@ -32,6 +32,10 @@ export const HUB_ICONS: Record<string, string> = {dots: "M6 12h.01M12 12h.01M18 12h.01",lock: "M6.5 11h11v9h-11zM8.5 11V8a3.5 3.5 0 0 1 7 0v3",window: "M3.5 5h17v14h-17zM3.5 9h17",+ tray: "M3.5 13.5 6 5h12l2.5 8.5V19h-17zM3.5 13.5h5a3.5 3.5 0 0 0 7 0h5",+ filter: "M4 7h16M7 12h10M10 17h4",+ nosign: "M12 3.5a8.5 8.5 0 1 0 0 17 8.5 8.5 0 0 0 0-17zM6 6l12 12",+ star: "M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.9l-5.2 2.7 1-5.8-4.3-4.1 5.9-.9z",};export function icon(name: string): SVGSVGElement {diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.jsonindex d765066d..4b34c64e 100644--- a/windows/src/i18n/extra.json+++ b/windows/src/i18n/extra.json@@ -676,6 +676,21 @@"ko": "Coucou가 Claude Code 세션에 연결됐어요. 도구 실행, 질문, 권한 요청이 아일랜드에 뜨고, 거기서 바로 답할 수 있어요.","ja": "Coucou は Claude Code のセッションにつながっています。ツールの呼び出し、質問、許可のリクエストがアイランドに表示され、そこで答えられます。"},+ "Coucou sorts your Outlook inboxes: VIPs first, then banned words, then your rules. It never deletes a message.": {+ "zh-Hans": "Coucou 会整理你的 Outlook 收件箱:先看 VIP,再看屏蔽词,最后是你的规则。它从不删除邮件。",+ "hi": "Coucou आपके Outlook इनबॉक्स छाँटता है: पहले VIP, फिर प्रतिबंधित शब्द, फिर आपके नियम। यह कभी कोई मेल नहीं हटाता।",+ "es": "Coucou ordena tus buzones de Outlook: primero los VIP, luego las palabras prohibidas y después tus reglas. Nunca borra un correo.",+ "ar": "يفرز Coucou صناديق Outlook لديك: كبار الشخصيات أولًا، ثم الكلمات المحظورة، ثم قواعدك. لا يحذف أي رسالة أبدًا.",+ "fr": "Coucou trie tes boîtes Outlook : les VIP d’abord, puis les mots bannis, puis tes règles. Il ne supprime jamais un mail.",+ "bn": "Coucou আপনার Outlook ইনবক্স সাজায়: আগে VIP, তারপর নিষিদ্ধ শব্দ, তারপর আপনার নিয়ম। এটি কখনো কোনো মেল মুছে না।",+ "pt-BR": "O Coucou organiza suas caixas do Outlook: primeiro os VIPs, depois as palavras proibidas, depois suas regras. Ele nunca apaga um e-mail.",+ "ru": "Coucou сортирует ящики Outlook: сначала VIP, затем запрещённые слова, затем ваши правила. Он никогда не удаляет письма.",+ "id": "Coucou memilah kotak masuk Outlook-mu: VIP dulu, lalu kata terlarang, lalu aturanmu. Coucou tidak pernah menghapus email.",+ "de": "Coucou sortiert deine Outlook-Postfächer: zuerst VIPs, dann verbotene Wörter, dann deine Regeln. Es löscht nie eine E-Mail.",+ "tr": "Coucou, Outlook gelen kutularını düzenler: önce VIP’ler, sonra yasaklı kelimeler, sonra kuralların. Hiçbir e-postayı silmez.",+ "ko": "Coucou가 Outlook 받은편지함을 정리합니다. VIP가 먼저, 다음은 금지어, 그다음은 내 규칙입니다. 메일을 삭제하지는 않습니다.",+ "ja": "Coucou は Outlook の受信トレイを整理します。まず VIP、次に禁止ワード、最後にあなたのルール。メールを削除することはありません。"+ },"Could not remove {path}: {error}": {"zh-Hans": "无法删除 {path}:{error}","hi": "{path} हटाया नहीं जा सका: {error}",@@ -1636,6 +1651,21 @@"ko": "저장할 사진이나 다운로드 폴더가 없어요.","ja": "保存先のピクチャやダウンロードフォルダがありません。"},+ "No banned words. Add a word, or click “Always ignore this sender” on a message in the island.": {+ "zh-Hans": "没有屏蔽词。添加一个词,或在灵动岛里的邮件上点击“始终忽略此发件人”。",+ "hi": "कोई प्रतिबंधित शब्द नहीं। कोई शब्द जोड़ें, या आइलैंड में किसी मेल पर “इस प्रेषक को हमेशा अनदेखा करें” क्लिक करें।",+ "es": "No hay palabras prohibidas. Añade una o haz clic en «Ignorar siempre a este remitente» en un correo de la isla.",+ "ar": "لا كلمات محظورة. أضف كلمة، أو انقر «تجاهل هذا المرسل دائمًا» على رسالة في الجزيرة.",+ "fr": "Aucun mot banni. Ajoute un mot, ou clique sur « Toujours ignorer cet expéditeur » sur un mail dans l’île.",+ "bn": "কোনো নিষিদ্ধ শব্দ নেই। একটি শব্দ যোগ করুন, অথবা আইল্যান্ডে কোনো মেলে “এই প্রেরককে সবসময় উপেক্ষা করুন” ক্লিক করুন।",+ "pt-BR": "Nenhuma palavra proibida. Adicione uma, ou clique em “Sempre ignorar este remetente” num e-mail na ilha.",+ "ru": "Запрещённых слов нет. Добавьте слово или нажмите «Всегда игнорировать этого отправителя» у письма на острове.",+ "id": "Belum ada kata terlarang. Tambahkan kata, atau klik “Selalu abaikan pengirim ini” pada email di pulau.",+ "de": "Keine verbotenen Wörter. Füge ein Wort hinzu oder klicke bei einer E-Mail auf der Insel auf „Diesen Absender immer ignorieren“.",+ "tr": "Yasaklı kelime yok. Bir kelime ekle ya da adadaki bir e-postada “Bu göndereni her zaman yok say”a tıkla.",+ "ko": "금지어가 없습니다. 단어를 추가하거나 아일랜드의 메일에서 ‘이 보낸 사람 항상 무시’를 누르세요.",+ "ja": "禁止ワードはありません。語句を追加するか、アイランドのメールで「この差出人を常に無視」をクリックしてください。"+ },"No change.": {"zh-Hans": "没有改动。","hi": "कोई बदलाव नहीं।",@@ -1861,6 +1891,51 @@"ko": "아일랜드에 놓은 파일만 추가할 수 있어요.","ja": "アイランドにドロップしたファイルだけを追加できます。"},+ "Only messages that arrive from now on, in every Outlook account. The classic Outlook must be open.": {+ "zh-Hans": "仅限从现在起收到的邮件,涵盖所有 Outlook 账户。经典版 Outlook 必须保持打开。",+ "hi": "सिर्फ़ अब से आने वाले मेल, हर Outlook खाते में। क्लासिक Outlook खुला होना चाहिए।",+ "es": "Solo los correos que lleguen a partir de ahora, en todas las cuentas de Outlook. El Outlook clásico debe estar abierto.",+ "ar": "الرسائل التي تصل من الآن فقط، في كل حسابات Outlook. يجب أن يكون Outlook الكلاسيكي مفتوحًا.",+ "fr": "Seulement les mails qui arrivent à partir de maintenant, dans tous les comptes Outlook. L’Outlook classique doit être ouvert.",+ "bn": "শুধু এখন থেকে আসা মেল, সব Outlook অ্যাকাউন্টে। ক্লাসিক Outlook খোলা থাকতে হবে।",+ "pt-BR": "Só os e-mails que chegarem a partir de agora, em todas as contas do Outlook. O Outlook clássico precisa estar aberto.",+ "ru": "Только письма, которые придут с этого момента, во всех учётных записях Outlook. Классический Outlook должен быть открыт.",+ "id": "Hanya email yang masuk mulai sekarang, di semua akun Outlook. Outlook klasik harus terbuka.",+ "de": "Nur E-Mails, die ab jetzt ankommen, in allen Outlook-Konten. Das klassische Outlook muss geöffnet sein.",+ "tr": "Yalnızca bundan sonra gelen e-postalar, tüm Outlook hesaplarında. Klasik Outlook açık olmalı.",+ "ko": "지금부터 도착하는 메일만, 모든 Outlook 계정에서 정리합니다. 클래식 Outlook이 열려 있어야 합니다.",+ "ja": "今から届くメールのみ、すべての Outlook アカウントが対象です。クラシック版 Outlook を開いておく必要があります。"+ },+ "Open Outlook (the classic one) to see your mail here.": {+ "zh-Hans": "打开 Outlook(经典版),即可在这里看到你的邮件。",+ "hi": "अपने मेल यहाँ देखने के लिए Outlook (क्लासिक) खोलें।",+ "es": "Abre Outlook (el clásico) para ver tus correos aquí.",+ "ar": "افتح Outlook (الكلاسيكي) لترى بريدك هنا.",+ "fr": "Ouvre Outlook (le classique) pour voir tes mails ici.",+ "bn": "আপনার মেল এখানে দেখতে Outlook (ক্লাসিক) খুলুন।",+ "pt-BR": "Abra o Outlook (o clássico) para ver seus e-mails aqui.",+ "ru": "Откройте Outlook (классический), чтобы видеть почту здесь.",+ "id": "Buka Outlook (yang klasik) untuk melihat email-mu di sini.",+ "de": "Öffne Outlook (das klassische), um deine E-Mails hier zu sehen.",+ "tr": "E-postalarını burada görmek için Outlook’u (klasik olanı) aç.",+ "ko": "여기에서 메일을 보려면 Outlook(클래식)을 여세요.",+ "ja": "ここでメールを見るには Outlook(クラシック版)を開いてください。"+ },+ "Open in Outlook": {+ "zh-Hans": "在 Outlook 中打开",+ "hi": "Outlook में खोलें",+ "es": "Abrir en Outlook",+ "ar": "فتح في Outlook",+ "fr": "Ouvrir dans Outlook",+ "bn": "Outlook-এ খুলুন",+ "pt-BR": "Abrir no Outlook",+ "ru": "Открыть в Outlook",+ "id": "Buka di Outlook",+ "de": "In Outlook öffnen",+ "tr": "Outlook’ta aç",+ "ko": "Outlook에서 열기",+ "ja": "Outlook で開く"+ },"Open in VS Code": {"zh-Hans": "在 VS Code 中打开","hi": "VS Code में खोलें",@@ -1966,6 +2041,36 @@"ko": "OpenAI 호환 서버","ja": "OpenAI 互換サーバー"},+ "Outlook is closed: nothing is sorted until it is open.": {+ "zh-Hans": "Outlook 已关闭:打开之前不会整理任何邮件。",+ "hi": "Outlook बंद है: खुलने तक कुछ भी नहीं छाँटा जाएगा।",+ "es": "Outlook está cerrado: no se ordena nada hasta que se abra.",+ "ar": "Outlook مغلق: لن يُفرز شيء حتى يُفتح.",+ "fr": "Outlook est fermé : rien n’est trié tant qu’il n’est pas ouvert.",+ "bn": "Outlook বন্ধ: খোলা না হওয়া পর্যন্ত কিছুই সাজানো হবে না।",+ "pt-BR": "O Outlook está fechado: nada é organizado até ele ser aberto.",+ "ru": "Outlook закрыт: пока он не открыт, ничего не сортируется.",+ "id": "Outlook tertutup: tidak ada yang dipilah sampai dibuka.",+ "de": "Outlook ist geschlossen: Nichts wird sortiert, bis es geöffnet ist.",+ "tr": "Outlook kapalı: açılana kadar hiçbir şey düzenlenmez.",+ "ko": "Outlook이 닫혀 있습니다. 열 때까지 아무것도 정리되지 않습니다.",+ "ja": "Outlook が閉じています。開くまで何も整理されません。"+ },+ "Outlook is only reached on Windows.": {+ "zh-Hans": "Outlook 只能在 Windows 上使用。",+ "hi": "Outlook सिर्फ़ Windows पर उपलब्ध है।",+ "es": "Outlook solo se puede usar en Windows.",+ "ar": "لا يمكن الوصول إلى Outlook إلا على Windows.",+ "fr": "Outlook n’est accessible que sur Windows.",+ "bn": "Outlook শুধু Windows-এ ব্যবহার করা যায়।",+ "pt-BR": "O Outlook só é acessível no Windows.",+ "ru": "Outlook доступен только в Windows.",+ "id": "Outlook hanya bisa dijangkau di Windows.",+ "de": "Outlook ist nur unter Windows erreichbar.",+ "tr": "Outlook’a yalnızca Windows’ta erişilebilir.",+ "ko": "Outlook은 Windows에서만 사용할 수 있습니다.",+ "ja": "Outlook は Windows でのみ利用できます。"+ },"PDF": {"zh-Hans": "PDF","hi": "PDF",diff --git a/windows/src/style.css b/windows/src/style.cssindex ebc40932..4eb1f63e 100644--- a/windows/src/style.css+++ b/windows/src/style.css@@ -3026,3 +3026,442 @@ html[data-dir="rtl"] #views :is(.bubble, .reply .md-p, .reply .md-h, .reply .md-unicode-bidi: plaintext;text-align: start;}++/* ── Mail (classic Outlook) — MailViews.swift ─────────────────────────────── */+.mail-card {+ height: 100%;+ box-sizing: border-box;+}++.mail-list,+.mail-detail {+ display: flex;+ flex-direction: column;+ min-height: 0;+ height: 100%;+}++.mail-card.detail-open .mail-list,+.mail-card:not(.detail-open) .mail-detail {+ display: none;+}++.mail-head {+ padding-right: 36px;+}++.mail-unread {+ font: 600 10px var(--font);+ color: #2f8cff;+ font-variant-numeric: tabular-nums;+ padding: 1px 6px;+ border-radius: 999px;+ background: rgba(47, 140, 255, 0.14);+}++.mail-spacer {+ flex: 1 1 0;+}++.mail-icon {+ border: 0;+ background: transparent;+ color: #8e939c;+ width: 18px;+ height: 16px;+ display: grid;+ place-items: center;+ cursor: default;+ flex: 0 0 auto;+}++.mail-icon:hover {+ color: var(--ink);+}++.mail-search {+ flex: 1 1 auto;+ min-width: 0;+ border: 0;+ outline: 0;+ background: transparent;+ font: 400 11px var(--font);+ color: #e8e9ec;+}++.mail-filters {+ display: flex;+ align-items: center;+ gap: 4px;+ padding-top: 4px;+}++.mail-chip {+ border: 0;+ border-radius: 999px;+ padding: 2px 7px;+ background: transparent;+ font: 400 9.5px var(--font);+ color: #6b7079;+ cursor: default;+}++.mail-chip:hover {+ color: #b0b5be;+ background: rgba(255, 255, 255, 0.06);+}++.mail-chip.on {+ font-weight: 600;+ color: #e8e9ec;+ background: rgba(47, 140, 255, 0.22);+}++.mail-searching {+ font: 400 9.5px var(--font);+ color: #6b7079;+ padding-left: 4px;+}++.mail-rows {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 5px 12px 6px 0;+ overflow-y: auto;+ min-height: 0;+ scrollbar-width: none;+}++.mail-row {+ border: 0;+ background: transparent;+ text-align: start;+ width: 100%;+ cursor: default;+ flex: 0 0 auto;+}++.mail-row:hover {+ background: rgba(255, 255, 255, 0.05);+}++.mail-row.unread {+ background: rgba(47, 140, 255, 0.08);+}++.mail-row.unread:hover {+ background: rgba(47, 140, 255, 0.14);+}++.mail-row.unread .mail-name {+ font-weight: 600;+ color: #e8e9ec;+}++.mail-row.unread .mail-subject {+ color: #8e939c;+}++.mail-name {+ max-width: 82px;+ flex: 0 1 auto;+}++.mail-dot {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ border: 1px solid #4d5159;+ box-sizing: border-box;+ flex: 0 0 auto;+}++.mail-dot.on {+ border: 0;+ background: #2f8cff;+}++.mail-flag {+ font-size: 8px;+ color: #f5a524;+ flex: 0 0 auto;+}++.mail-empty {+ font: 400 11px var(--font);+ color: var(--dim-3);+ padding: 8px 0 0 8px;+}++.mail-more {+ color: rgba(47, 140, 255, 0.9);+ align-self: flex-start;+ padding: 3px 8px;+}++.mail-detail {+ gap: 4px;+ padding-right: 12px;+}++.mail-detail-head {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ padding-right: 24px;+ margin-left: -6px;+}++.mail-back {+ width: 20px;+ height: 20px;+}++.mail-from {+ font: 600 11px var(--font);+ color: var(--ink);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.mail-detail-subject {+ font: 500 11px var(--font);+ color: #c5c8cd;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.mail-detail-text {+ font: 400 10.5px var(--font);+ color: #9398a1;+ height: 28px;+ overflow-y: auto;+ white-space: pre-wrap;+ user-select: text;+ scrollbar-width: none;+}++.mail-actions {+ display: flex;+ align-items: center;+ gap: 12px;+}++.mail-actions .link-btn {+ padding: 0;+ color: #c5c8cd;+}++.mail-actions .link-btn.accent {+ color: rgba(47, 140, 255, 0.9);+}++.mail-actions .link-btn.amber {+ color: rgba(245, 165, 36, 0.9);+}++.mail-actions .link-btn.dim {+ color: #8e939c;+}++.mail-dots-wrap {+ position: relative;+}++.mail-more-menu {+ display: none;+ position: absolute;+ bottom: 18px;+ right: 0;+ flex-direction: column;+ background: #1d1f23;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ padding: 4px;+ z-index: 5;+ white-space: nowrap;+}++.mail-more-menu.on {+ display: flex;+}++.mail-more-menu button {+ border: 0;+ background: transparent;+ text-align: start;+ font: 400 11px var(--font);+ color: #e8e9ec;+ padding: 4px 8px;+ border-radius: 5px;+ cursor: default;+}++.mail-more-menu button:hover {+ background: rgba(47, 140, 255, 0.3);+}++/* The chat's Mail switch and a plan's card (MailAgentViews.swift). */+.model-row {+ gap: 6px;+}++.mail-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 4px 8px;+ border: 0;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.06);+ font: 500 10.5px var(--font);+ color: #7b8089;+ cursor: default;+}++.mail-toggle.on {+ background: rgba(47, 140, 255, 0.85);+ color: #fff;+}++.plan-card {+ margin-top: 6px;+ display: flex;+ flex-direction: column;+ gap: 5px;+ padding: 7px 9px;+ border-radius: 8px;+ background: rgba(47, 140, 255, 0.08);+ border: 1px solid rgba(47, 140, 255, 0.25);+}++.plan-title {+ display: flex;+ align-items: center;+ gap: 6px;+ font: 600 11.5px var(--font);+ color: #f1f2f4;+}++.plan-icon {+ font-style: normal;+ color: #2f8cff;+}++.plan-line {+ display: flex;+ gap: 5px;+ font: 400 10.5px var(--font);+ color: #c5c8cd;+}++.plan-arrow {+ color: #2f8cff;+}++.plan-rows {+ display: flex;+ flex-direction: column;+ gap: 2px;+ max-height: 90px;+ overflow-y: auto;+ scrollbar-width: none;+}++.plan-row {+ display: flex;+ gap: 6px;+ font: 400 10px var(--font);+ min-width: 0;+}++.plan-to {+ width: 150px;+ flex: 0 0 auto;+ color: #c5c8cd;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.plan-row.bad .plan-to,+.plan-problem {+ color: #f4505e;+}++.plan-subject {+ flex: 1 1 auto;+ min-width: 0;+ color: #8e939c;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.plan-file {+ max-width: 150px;+ color: #8e939c;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.plan-note {+ font: 400 10px var(--font);+ color: #f5a524;+}++.plan-controls {+ display: flex;+ align-items: center;+ gap: 10px;+ padding-top: 2px;+}++.plan-btn {+ border: 0;+ border-radius: 999px;+ padding: 4px 9px;+ font: 600 10.5px var(--font);+ color: #c5c8cd;+ background: rgba(255, 255, 255, 0.08);+ cursor: default;+}++.plan-btn.primary {+ color: #fff;+ background: #2f8cff;+}++.plan-status {+ font: 400 10.5px var(--font);+ color: #8e939c;+ font-variant-numeric: tabular-nums;+}++.plan-status.ok {+ color: #34d399;+}++.plan-status.amber {+ color: #f5a524;+ font-weight: 600;+}++.plan-bar {+ width: 140px;+ height: 4px;+ border-radius: 2px;+ background: rgba(255, 255, 255, 0.08);+ overflow: hidden;+}++.plan-bar i {+ display: block;+ height: 100%;+}diff --git a/windows/src/views/chat.ts b/windows/src/views/chat.tsindex cc9b950d..4ddde198 100644--- a/windows/src/views/chat.ts+++ b/windows/src/views/chat.ts@@ -18,6 +18,9 @@ import { chipLabel, loadSubscriptions, subscribedProviders, subscription } fromimport { State, type ChatMessage } from "../core/state";import type { ViewHost } from "./views";import { N_, t, tl } from "../i18n/i18n";+import { HOST_OS } from "../core/pills";+import { MailChat, splitPlan } from "../core/mail";+import { mailPlanCard } from "./mailplan";const STRINGS = {placeholderFirst: N_("Ask me anything…"),@@ -41,7 +44,10 @@ function bubble(message: ChatMessage): HTMLElement {);}const reply = h("div", { class: "reply" });- renderMarkdown(reply, message.content);+ // A mail plan (```coucou-mail) is never shown as raw JSON: its card goes under the answer.+ const { prose, plan } = splitPlan(message.content);+ renderMarkdown(reply, prose);+ if (plan) reply.append(mailPlanCard(`chat-${message.id}-${message.content.length}`, "", message.content));return h("div", { class: "chat-row" }, reply);}@@ -234,7 +240,16 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {modelName,svg(ICONS.chevronUpDown, 9, { stroke: 2 }),);+ // The Mail switch (classic Outlook, Windows): on, the AI sees the latest messages and may+ // prepare actions on them, which run only after a click on the plan's card.+ const mailBtn = h("button", { class: "mail-toggle", title: tl("Lets the AI see your latest messages and prepare actions on them. Nothing happens until you click Run.") },+ h("span", { text: "✉" }), h("span", { text: tl("Mail") }));+ mailBtn.addEventListener("click", () => {+ MailChat.on = !MailChat.on;+ mailBtn.classList.toggle("on", MailChat.on);+ });const modelRow = h("div", { class: "model-row" }, modelBtn);+ if (HOST_OS === "windows") modelRow.prepend(mailBtn);const body = h("div", { class: "chat-body" });const picker = buildPicker(() => {@@ -273,7 +288,7 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {log.querySelector(".typing")?.parentElement?.remove();log.append(h("div", { class: "chat-row" }, live));}- renderMarkdown(live, text);+ renderMarkdown(live, splitPlan(text).prose);log.scrollTop = log.scrollHeight;});@@ -296,7 +311,7 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {State.chatHistory.length === 1 && file ? { kind: "file", name: file.name, path: file.path } : null;try {- const reply = await Bridge.chatSend(query, context);+ const reply = await Bridge.chatSend(query, context, MailChat.on && HOST_OS === "windows");State.chatHistory.push({ id: nextId++, role: "assistant", content: reply.text });State.stateOverride = null;Sound.play("finish");diff --git a/windows/src/views/icons.ts b/windows/src/views/icons.tsindex 86394d75..254ac92e 100644--- a/windows/src/views/icons.ts+++ b/windows/src/views/icons.ts@@ -31,6 +31,8 @@ export const ICONS = {// exclamationmarkbang: "M11 4h2v10h-2V4zm0 12.2h2v2.2h-2v-2.2z",// xmark+ // magnifyingglass (fill)+ magnifier: "M10.5 3a7.5 7.5 0 0 1 5.96 12.06l4.24 4.24-1.4 1.4-4.24-4.24A7.5 7.5 0 1 1 10.5 3zm0 2a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11z",xmark: "M6.4 5 12 10.6 17.6 5 19 6.4 13.4 12 19 17.6 17.6 19 12 13.4 6.4 19 5 17.6 10.6 12 5 6.4 6.4 5z",// timertimer: "M12 4.2a7.8 7.8 0 1 0 0 15.6 7.8 7.8 0 0 0 0-15.6zm0 1.9a5.9 5.9 0 1 1 0 11.8 5.9 5.9 0 0 1 0-11.8zm-.95 2.3v4.2l3.3 2 .95-1.55-2.4-1.45V8.4h-1.85zM9.2 2h5.6v1.7H9.2V2z",diff --git a/windows/src/views/mail.ts b/windows/src/views/mail.tsnew file mode 100644index 00000000..8332116b--- /dev/null+++ b/windows/src/views/mail.ts@@ -0,0 +1,297 @@+// The Mail card (classic Outlook) — a DOM port of MailCardView / MailRow / MailDetailView+// (MailViews.swift). Sizes, colours and wording are the Mac's.+//+// The list: the newest messages of every inbox, unread ones tinted, a flag on the important+// ones; a search (free words, from:, subject:) and quick filters (All, Unread, Important,+// Today); Load more. A click opens the message: its sender, subject and the start of its text,+// with Open in Outlook, Reply (Outlook's own window: nothing is sent from Coucou), Mark as read,+// Important, Junk, and in ⋯ Always important (VIP) and Always ignore this sender.+//+// Built once and synced in place: the search field keeps its text and the keyboard.++import { h, svg, clear, dot } from "./dom";+import { ICONS } from "./icons";+import { State } from "../core/state";+import {+ MAIL_BLUE, MAIL_FILTERS, MAIL_ID, MailBridge, filterTitle, messageId, senderName,+ type MailCardData, type MailFilter, type MailMessage,+} from "../core/mail";+import { timeAgo } from "./integrations";+import { language, t, tl } from "../i18n/i18n";++export interface MailCardHost {+ /** The island takes the keyboard for the search field, and gives it back. */+ keyboard(on: boolean): void;+}++export interface MailCard {+ el: HTMLElement;+ sync(): void;+}++function data(): MailCardData {+ const d = (State.integrations[MAIL_ID]?.data ?? {}) as Partial<MailCardData>;+ return {+ running: d.running ?? false,+ windows: d.windows ?? true,+ unread: d.unread ?? 0,+ messages: Array.isArray(d.messages) ? d.messages : [],+ shown: d.shown ?? 12,+ maxShown: d.maxShown ?? 60,+ };+}++export function buildMailCard(host: MailCardHost): MailCard {+ const unreadTag = h("span", { class: "mail-unread" });+ const field = h("input", { class: "mail-search", type: "text", spellcheck: "false", placeholder: t("from:anne invoice") }) as HTMLInputElement;+ const closeSearch = h("button", { class: "mail-icon", title: tl("Close") }, svg(ICONS.xmark, 9));+ const searchBtn = h("button", { class: "mail-icon", title: tl("Search") }, svg(ICONS.magnifier, 10));+ const head = h("div", { class: "int-head mail-head" }, dot(MAIL_BLUE, 7), h("b", { text: "Outlook" }));+ const filters = h("div", { class: "mail-filters" });+ const listBody = h("div", { class: "mail-rows" });+ const listView = h("div", { class: "mail-list" }, head, filters, listBody);+ const detailView = h("div", { class: "mail-detail" });+ const el = h("div", { class: "int-card mail-card" }, listView, detailView);++ let searchOpen = false;+ let filter: MailFilter = "all";+ let results: MailMessage[] | null = null;+ let searching = false;+ let token = 0;+ let open: MailMessage | null = null;+ const previews = new Map<string, { text: string; attachments: string[] } | null>();+ let listKey = "";+ let refreshed = 0;++ const displayed = (): MailMessage[] => results ?? data().messages;++ async function runSearch() {+ const q = field.value.trim();+ if (!q && filter === "all") {+ results = null;+ searching = false;+ listKey = "";+ sync();+ return;+ }+ const mine = ++token;+ searching = true;+ listKey = "";+ sync();+ const found = await MailBridge.search(q, filter);+ if (mine !== token) return;+ searching = false;+ results = found ?? [];+ listKey = "";+ sync();+ }++ function setSearch(on: boolean) {+ searchOpen = on;+ if (on) {+ host.keyboard(true);+ window.setTimeout(() => field.focus(), 80);+ } else {+ field.value = "";+ filter = "all";+ results = null;+ token++;+ searching = false;+ host.keyboard(false);+ }+ listKey = "";+ sync();+ }++ searchBtn.addEventListener("click", () => setSearch(true));+ closeSearch.addEventListener("click", () => setSearch(false));+ field.addEventListener("keydown", (e) => {+ const key = (e as KeyboardEvent).key;+ if (key === "Enter") {+ e.preventDefault();+ void runSearch();+ } else if (key === "Escape") {+ e.preventDefault();+ setSearch(false);+ }+ e.stopPropagation();+ });++ function openMessage(m: MailMessage) {+ open = m;+ const id = messageId(m);+ if (!previews.has(id)) {+ previews.set(id, null);+ void MailBridge.detail(m).then((d) => {+ previews.set(id, d ?? { text: "", attachments: [] });+ drawDetail();+ });+ }+ drawDetail();+ sync();+ }++ function closeMessage() {+ open = null;+ listKey = "";+ sync();+ }++ async function act(m: MailMessage, kind: "read" | "flag" | "unflag" | "junk" | "ignore" | "vip") {+ // Shown at once; Outlook catches up.+ const id = messageId(m);+ const change = (list: MailMessage[] | null) =>+ list?.flatMap((x) => {+ if (messageId(x) !== id) return [x];+ if (kind === "junk" || kind === "ignore") return [];+ return [{ ...x, unread: kind === "read" ? false : x.unread, flagged: kind === "flag" || kind === "vip" ? true : kind === "unflag" ? false : x.flagged }];+ }) ?? null;+ results = change(results);+ if (open && messageId(open) === id) {+ open = kind === "junk" || kind === "ignore" ? null : change([open])?.[0] ?? null;+ }+ listKey = "";+ sync();+ await MailBridge.act(m, kind);+ }++ function row(m: MailMessage): HTMLElement {+ const r = h("button", { class: m.unread ? "int-row mail-row unread" : "int-row mail-row" },+ h("i", { class: m.unread ? "mail-dot on" : "mail-dot" }),+ h("span", { class: "int-name mail-name", text: senderName(m) }),+ );+ if (m.flagged) r.append(h("span", { class: "mail-flag", text: "⚑" }));+ r.append(+ h("span", { class: "int-ago", text: timeAgo(m.date) }),+ h("span", { class: "int-sub mail-subject", text: m.subject }),+ );+ r.addEventListener("click", () => openMessage(m));+ return r;+ }++ function syncList() {+ const d = data();+ const list = displayed();+ const key = [+ language(), d.running, d.windows, d.unread, searchOpen, filter, searching, results === null, d.shown,+ Math.floor(Date.now() / 60_000),+ ...list.map((m) => `${messageId(m)}|${m.unread}|${m.flagged}`),+ ].join("~");+ if (key === listKey) return;+ listKey = key;++ // The head: the unread count and the magnifier, or the search field.+ clear(head);+ head.append(dot(MAIL_BLUE, 7), h("b", { text: "Outlook" }));+ if (searchOpen) {+ head.append(field, closeSearch);+ } else {+ head.append(h("span", { text: t("Inbox") }));+ unreadTag.textContent = d.unread > 0 ? t("{0} unread", { 0: d.unread }) : "";+ unreadTag.style.display = d.unread > 0 ? "" : "none";+ head.append(unreadTag, h("span", { class: "mail-spacer" }), searchBtn);+ }++ clear(filters);+ for (const f of MAIL_FILTERS) {+ filters.append(h("button", {+ class: f === filter ? "mail-chip on" : "mail-chip",+ text: filterTitle(f),+ onclick: () => {+ filter = f;+ void runSearch();+ },+ }));+ }+ if (searching) filters.append(h("span", { class: "mail-searching", text: t("Searching…") }));+ filters.style.display = d.running ? "" : "none";++ clear(listBody);+ if (!d.windows) {+ listBody.append(h("div", { class: "mail-empty", text: t("Outlook is only reached on Windows.") }));+ return;+ }+ if (!d.running) {+ listBody.append(h("div", { class: "mail-empty", text: t("Open Outlook (the classic one) to see your mail here.") }));+ return;+ }+ if (list.length === 0) {+ listBody.append(h("div", { class: "mail-empty", text: results !== null ? t("Nothing found") : t("No messages") }));+ return;+ }+ for (const m of list) listBody.append(row(m));+ if (results === null && d.messages.length >= d.shown && d.shown < d.maxShown) {+ listBody.append(h("button", { class: "link-btn mail-more", text: t("Load more"), onclick: () => void MailBridge.more() }));+ }+ }++ function drawDetail() {+ clear(detailView);+ const m = open;+ if (!m) return;+ const back = h("button", { class: "int-back mail-back", title: tl("Back") }, svg(ICONS.chevronLeft, 10, { stroke: 2.4 }));+ back.addEventListener("click", closeMessage);+ const preview = previews.get(messageId(m));+ const text = preview === undefined || preview === null ? t("Loading…") : preview.text.trim() || " ";+ const actions = h("div", { class: "mail-actions" },+ h("button", { class: "link-btn accent", text: t("Open in Outlook"), onclick: () => void MailBridge.open(m, false) }),+ h("button", { class: "link-btn", text: t("Reply"), onclick: () => void MailBridge.open(m, true) }),+ );+ if (m.unread) actions.append(h("button", { class: "link-btn dim", text: t("Mark as read"), onclick: () => void act(m, "read") }));+ actions.append(+ h("button", {+ class: "link-btn amber",+ text: m.flagged ? t("Not important") : t("Important"),+ onclick: () => void act(m, m.flagged ? "unflag" : "flag"),+ }),+ h("button", { class: "link-btn dim", text: t("Junk"), onclick: () => void act(m, "junk") }),+ );+ // ⋯: Always important (VIP), Always ignore this sender.+ const more = h("div", { class: "mail-more-menu" });+ const dots = h("button", { class: "link-btn dim mail-dots", text: "⋯" });+ dots.addEventListener("click", () => more.classList.toggle("on"));+ more.append(+ h("button", { text: t("Always important (VIP)"), onclick: () => void act(m, "vip") }),+ h("button", { text: t("Always ignore this sender"), onclick: () => void act(m, "ignore") }),+ );+ actions.append(h("span", { class: "mail-dots-wrap" }, dots, more));+ detailView.append(+ h("div", { class: "mail-detail-head" },+ back,+ h("i", { class: m.unread ? "mail-dot on" : "mail-dot" }),+ h("b", { class: "mail-from", text: senderName(m), title: m.address }),+ h("span", { class: "mail-spacer" }),+ h("span", { class: "int-ago", text: timeAgo(m.date) }),+ ),+ h("div", { class: "mail-detail-subject", text: m.subject || " " }),+ h("div", { class: "mail-detail-text", text }),+ actions,+ );+ }++ function sync() {+ el.classList.toggle("detail-open", open !== null);+ if (open) {+ // The open message, kept up to date when a refresh changes it.+ const fresh = displayed().find((x) => messageId(x) === messageId(open!));+ if (fresh && (fresh.unread !== open.unread || fresh.flagged !== open.flagged)) {+ open = fresh;+ drawDetail();+ }+ }+ syncList();+ // Opening the card reads Outlook again (at most every 15 s).+ if (State.focusTask?.id === MAIL_ID && State.mode === "expanded" && Date.now() - refreshed > 15_000) {+ refreshed = Date.now();+ void MailBridge.refresh();+ }+ }++ // Leaving the card gives the keyboard back.+ State.subscribe(() => {+ if (!searchOpen) return;+ if (State.mode !== "expanded" || State.view !== "overview" || State.focusTask?.id !== MAIL_ID) setSearch(false);+ });++ return { el, sync };+}diff --git a/windows/src/views/mailplan.ts b/windows/src/views/mailplan.tsnew file mode 100644index 00000000..bee41b39--- /dev/null+++ b/windows/src/views/mailplan.ts@@ -0,0 +1,122 @@+// A plan of the chat, under the answer that wrote it: what it will do, the mails it will send+// (the ones that can't be sent in red), Send me a test, and Run, which starts a 5-second+// countdown before anything happens. Port of MailPlanCard (MailAgentViews.swift).+//+// The plan is prepared and run by Rust (src-tauri/src/mail): the PDF saved from Outlook and+// cut page by page, each page given to its recipient. Rust tells the card as it goes+// (`mail-plan` events).++import { h, clear } from "./dom";+import { onEvent } from "../core/bridge";+import { MAIL_BLUE, MailBridge, nameOf, ruleLine, senderName, type PlanRun } from "../core/mail";+import { t } from "../i18n/i18n";++const runs = new Map<string, PlanRun>();+const cards = new Map<string, Set<() => void>>();++void onEvent<{ id: string; run: PlanRun }>("mail-plan", ({ id, run }) => {+ runs.set(id, run);+ cards.get(id)?.forEach((redraw) => redraw());+});++function fileName(path: string): string {+ return path.split(/[\\/]/).pop() ?? path;+}++function noteText(n: PlanRun["notes"][number]): string {+ switch (n.kind) {+ case "missing": return t("Message {0} is not in the list", { 0: n.value });+ case "noPdf": return t("No PDF found in that message");+ case "fileMissing": return t("File not found: {0}", { 0: n.value });+ }+}++/** The card of the chat message `id`, whose answer is `text`. */+export function mailPlanCard(id: string, summary: string, text: string): HTMLElement {+ const el = h("div", { class: "plan-card" });+ const redraw = () => draw(el, id, summary);+ if (!cards.has(id)) cards.set(id, new Set());+ cards.get(id)!.add(redraw);+ if (!runs.has(id)) {+ void MailBridge.planShow(id, text).then((run) => {+ if (run && !runs.has(id)) {+ runs.set(id, run);+ redraw();+ }+ });+ }+ redraw();+ return el;+}++function line(text: string): HTMLElement {+ return h("div", { class: "plan-line" }, h("span", { class: "plan-arrow", text: "→" }), h("span", { text }));+}++function button(text: string, primary: boolean, onclick: () => void): HTMLElement {+ return h("button", { class: primary ? "plan-btn primary" : "plan-btn", text, onclick });+}++function draw(el: HTMLElement, id: string, summary: string) {+ clear(el);+ const run = runs.get(id);+ el.append(h("div", { class: "plan-title" },+ h("i", { class: "plan-icon", text: "✉" }),+ h("b", { text: run?.summary || summary || t("Mail plan") }),+ ));+ if (!run) return;+ for (const s of run.sorts) el.append(line(t("{0}: {1} messages", { 0: ruleLine(s.action), 1: s.messages.length })));+ for (const [m] of run.replies) el.append(line(t("Reply draft to {0}", { 0: senderName(m) })));+ for (const [m, folder] of run.saves) el.append(line(t("Save the attachments of {0} in {1}", { 0: nameOf(senderName(m)), 1: folder })));+ if (run.mails.length > 0) {+ el.append(line(t("{0} mails to send", { 0: run.mails.filter((m) => !m.problem).length })));+ const rows = h("div", { class: "plan-rows" });+ for (const m of run.mails) {+ const r = h("div", { class: m.problem ? "plan-row bad" : "plan-row" },+ h("span", { class: "plan-to", text: m.to.join(", ") }),+ h("span", { class: "plan-subject", text: m.subject }),+ );+ if (m.problem) {+ r.append(h("span", { class: "plan-problem", text: m.problem === "noPage" ? t("no page found") : t("invalid address") }));+ } else if (m.attachments.length > 0) {+ const extra = m.attachments.length > 1 ? ` +${m.attachments.length - 1}` : "";+ r.append(h("span", { class: "plan-file", text: `📎 ${fileName(m.attachments[0])}${extra}` }));+ }+ rows.append(r);+ }+ el.append(rows);+ }+ for (const n of run.notes) el.append(h("div", { class: "plan-note", text: noteText(n) }));++ const controls = h("div", { class: "plan-controls" });+ const p = run.phase;+ switch (p.kind) {+ case "preparing":+ controls.append(h("span", { class: "plan-status", text: t("Preparing…") }));+ break;+ case "ready":+ case "cancelled":+ if (run.stepCount > 0) controls.append(button(t("Run ({0})", { 0: run.stepCount }), true, () => void MailBridge.planStart(id)));+ if (run.mails.length > 0 && run.myAddress) controls.append(button(t("Send me a test"), false, () => void MailBridge.planTest(id)));+ if (p.kind === "cancelled") controls.append(h("span", { class: "plan-status", text: t("Cancelled") }));+ else if (run.testSentTo) controls.append(h("span", { class: "plan-status ok", text: t("Test sent to {0}", { 0: run.testSentTo }) }));+ break;+ case "countdown":+ controls.append(+ h("span", { class: "plan-status amber", text: t("Starting in {0} s", { 0: p.seconds }) }),+ button(t("Cancel"), false, () => void MailBridge.planCancel(id)),+ );+ break;+ case "running": {+ const bar = h("div", { class: "plan-bar" }, h("i", { style: `width:${Math.round((100 * p.done) / Math.max(1, p.total))}%;background:${MAIL_BLUE}` }));+ controls.append(bar, h("span", { class: "plan-status", text: `${p.done}/${p.total}` }),+ button(t("Cancel"), false, () => void MailBridge.planCancel(id)));+ break;+ }+ case "done":+ controls.append(h("span", { class: p.failed === 0 ? "plan-status ok" : "plan-status amber",+ text: (p.failed === 0 ? "✓ " : "⚠ ") + t("{0} done · {1} failed", { 0: p.ok, 1: p.failed }) }));+ break;+ }+ el.append(controls);+}diff --git a/windows/src/views/views.ts b/windows/src/views/views.tsindex 491bc9b2..d9f3b3aa 100644--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@ -27,6 +27,8 @@ import { buildSpotifyCard, buildSpotifyPill, type SpotifyPillHost } from "./spotimport { SPOTIFY_ID } from "../core/spotify";import { buildWhatsAppCard } from "./whatsapp";import { WHATSAPP_ID } from "../core/whatsapp";+import { MAIL_ID } from "../core/mail";+import { buildMailCard } from "./mail";import type { Outfit, OutfitSelection } from "../mochi/wardrobe";import { language, t, tl, type Msg } from "../i18n/i18n";import type { ViewCommand } from "../island/shortcuts";@@ -208,6 +210,8 @@ function buildOverview(actions: ViewActions): ViewHost {const spotifyCard = buildSpotifyCard();let spotifyPill: SpotifyPillHost | null = null;// WhatsApp's card too: its reply field keeps the draft and the keyboard while messages arrive.+ // Mail's card too (classic Outlook): the search field keeps its text and the keyboard.+ const mailCard = buildMailCard({ keyboard: (on) => actions.keyboard(on) });const whatsappCard = buildWhatsAppCard({openSettings: () => actions.openSettingsWindow(),keyboard: (on) => actions.keyboard(on),@@ -222,7 +226,7 @@ function buildOverview(actions: ViewActions): ViewHost {let pillIds = "";let detailOpen = false;let lastFocus: string | null = null;- let mode: "ticker" | "card" | "plan" | "diff" | "spotify" | "whatsapp" | null = null;+ let mode: "ticker" | "card" | "plan" | "diff" | "spotify" | "whatsapp" | "mail" | null = null;let cardKey = "";/** The list row highlighted at the last sync, to scroll only when it moves. */let shownSelection: number | null = null;@@ -379,6 +383,14 @@ function buildOverview(actions: ViewActions): ViewHost {cardKey = "";}spotifyCard.sync();+ } else if (task && task.id === MAIL_ID) {+ if (mode !== "mail") {+ clear(leftBody);+ leftBody.append(mailCard.el);+ mode = "mail";+ cardKey = "";+ }+ mailCard.sync();} else if (task && task.id === WHATSAPP_ID) {// Its own card in every state: not linked, no message, conversations, one open.if (mode !== "whatsapp") {diff --git a/windows/tests/i18n.test.mjs b/windows/tests/i18n.test.mjsindex 2ed1b920..33401a1d 100644--- a/windows/tests/i18n.test.mjs+++ b/windows/tests/i18n.test.mjs@@ -459,6 +459,7 @@ const NOT_TEXT = new Set(["unknown", // a CI state"Resend", // the service's name (the Mac's "Resend" is a button: send again)"Stop", // Claude Code's hook event (the Mac's "Stop" is a button)+ "running", // the phase of a mail plan (src/views/mailplan.ts)]);test("no known user-facing English literal outside t() in the views and settings", () => {diff --git a/windows/tests/pills.test.mjs b/windows/tests/pills.test.mjsindex aab49072..37b90819 100644--- a/windows/tests/pills.test.mjs+++ b/windows/tests/pills.test.mjs@@ -45,6 +45,7 @@ test("the catalog holds the Mac's pills with the Claude Code label for Windows a["integration_stripe", "Stripe", "#0570DE", "service", "Integration"],["integration_music", "Apple Music", "#FA2D48", "service", "Integration"],["integration_spotify", "Spotify", "#1DB954", "service", "Integration"],+ ["integration_mail", "Mail", "#2F8CFF", "service", "Integration"],["integration_whatsapp", "WhatsApp", "#25D366", "service", "Integration"],];assert.deepEqual(@@ -108,11 +109,14 @@ test("this build leaves out what only macOS has, and Claude Desktop on Linux", (assert.ok(linux.includes(id), id);}assert.ok(windows.includes("agent_claude-desktop"));+ // Mail is Outlook's, and Outlook is a Windows program.+ assert.ok(windows.includes("integration_mail"));+ assert.ok(!linux.includes("integration_mail"));assert.ok(!linux.includes("agent_claude-desktop"));// Spotify: MPRIS on Linux, the system media controls on Windows.assert.ok(linux.includes("integration_spotify"));assert.ok(windows.includes("integration_spotify"));- assert.deepEqual(linux, windows.filter((id) => id !== "agent_claude-desktop"));+ assert.deepEqual(linux, windows.filter((id) => id !== "agent_claude-desktop" && id !== "integration_mail"));});test("Spotify: a service on both systems with nothing to set up", () => {