tauri-plugin-deeprespond-im 1.0.0-alpha

深应智能 IM 的 Tauri 插件:本地存储、安全存储、窗口间的锁与消息、系统事件、通知、角标、文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! 系统通知(《2.功能概述文档》第 8.3、10 节,《4.实现与测试》第 3.5 节):显示、替换、清除、权限,以及点击的分发。
//!
//! 点击(含通知上的按钮)的分发与平台无关:插件向全部页面广播 notification_click,第一个 notify_claim 的页面认领;
//! 300 毫秒内没有认领的交给 App 的 on_notification_click,没有注册的显示主窗口。来电通知的“拒绝”直接交给引擎。
//! 应用退出后点击通知中心里的通知会重新启动应用:点击记为“启动点击”,第一个 hello 的界面窗口拿到一次,
//! 引擎就绪后再照常广播(已被认领的不再广播)。

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use base64::Engine as _;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use tauri::{AppHandle, Manager, Runtime};

use crate::error::{Error, Result};
use crate::{CallAction, Callbacks, EngineState, NotificationClick, Shared};

pub mod commands;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;

#[cfg(target_os = "linux")]
use linux::Backend;
#[cfg(target_os = "macos")]
use macos::Backend;
#[cfg(target_os = "windows")]
use self::windows::Backend;

/// 点击后等待页面认领的时间。
const CLAIM_WAIT: Duration = Duration::from_millis(300);
/// 启动点击最多等引擎这么久,之后不论引擎状态照常交出。
const LAUNCH_WAIT: Duration = Duration::from_secs(30);
/// Windows 通知的启动参数(也可以嵌在 App 自己的 URI 协议地址中,见 decode_arg)。
pub const LAUNCH_ARG: &str = "--drim-notification=";
/// data 的上限(《3.接口设计》第 5 节):随通知交给系统,Windows 还要放进启动参数。
const MAX_DATA_BYTES: usize = 1024;
const KINDS: [&str; 5] = ["message", "notice", "call", "session", "custom"];

/// notify_show 的参数。
#[derive(Clone, Debug, Default)]
pub struct Request {
    pub id: String,
    pub title: String,
    pub body: String,
    pub kind: String,
    pub conversation_id: Option<String>,
    pub seq: Option<i64>,
    pub data: Option<Map<String, Value>>,
    pub sound: bool,
    pub actions: Option<Vec<Action>>,
    /// 归组(Windows 的 group、macOS 的 threadIdentifier),默认按会话、没有会话的按 kind。
    #[cfg_attr(target_os = "linux", allow(dead_code))]
    pub group: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Action {
    pub id: String,
    pub title: String,
}

impl Request {
    pub fn validate(&self) -> Result<()> {
        if self.id.is_empty() || self.id.len() > 256 {
            return Err(Error::validation("invalid_id", "通知的 id 不能为空,最长 256 个字符"));
        }
        if !KINDS.contains(&self.kind.as_str()) {
            return Err(Error::validation("invalid_kind", format!("不认识的通知类型 {}", self.kind)));
        }
        if self.actions.as_ref().is_some_and(|a| a.len() > 2) {
            return Err(Error::validation("too_many_actions", "通知上最多 2 个按钮"));
        }
        if let Some(data) = &self.data {
            if serde_json::to_vec(data).map(|v| v.len()).unwrap_or(0) > MAX_DATA_BYTES {
                return Err(Error::validation("data_too_large", "通知的 data 最多 1 KB"));
            }
        }
        Ok(())
    }

    /// 实际显示的按钮:来电通知没有给出按钮的,加上“接听”“拒绝”。
    pub fn effective_actions(&self) -> Vec<Action> {
        match &self.actions {
            Some(actions) => actions.clone(),
            None if self.kind == "call" => vec![
                Action { id: "accept".into(), title: "接听".into() },
                Action { id: "decline".into(), title: "拒绝".into() },
            ],
            None => Vec::new(),
        }
    }

    /// 归组的名称(未经散列)。Linux 的通知服务没有归组,不用它。
    #[cfg_attr(target_os = "linux", allow(dead_code))]
    pub fn group_key(&self) -> &str {
        self.group.as_deref().or(self.conversation_id.as_deref()).unwrap_or(&self.kind)
    }

    pub fn payload(&self) -> Payload {
        Payload {
            id: self.id.clone(),
            kind: self.kind.clone(),
            conversation_id: self.conversation_id.clone(),
            seq: self.seq,
            data: self.data.clone(),
            action: None,
        }
    }
}

/// 随通知交给系统、点击时交回的内容(Windows 的启动参数、macOS 的 userInfo、Linux 的内存表)。
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Payload {
    pub id: String,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conversation_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<Map<String, Value>>,
    /// 点击的按钮;点击通知本身时为空。
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
}

impl Payload {
    pub fn with_action(&self, action: Option<String>) -> Payload {
        Payload { action, ..self.clone() }
    }

    fn into_click(self, launched: bool) -> NotificationClick {
        NotificationClick {
            id: self.id,
            kind: self.kind,
            conversation_id: self.conversation_id,
            seq: self.seq,
            action: self.action,
            data: self.data,
            launched,
        }
    }
}

/// 编码为启动参数:`--drim-notification=<base64url(JSON)>`。
pub fn encode_arg(payload: &Payload) -> String {
    let json = serde_json::to_vec(payload).unwrap_or_default();
    format!("{LAUNCH_ARG}{}", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json))
}

/// 从一个命令行参数中取出点击的内容:参数本身是 `--drim-notification=...`,或嵌在 App 的 URI 中(`...drim-notification=...`)。
pub fn decode_arg(arg: &str) -> Option<Payload> {
    let start = arg.find("drim-notification=")? + "drim-notification=".len();
    let rest = &arg[start..];
    let end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '=')).unwrap_or(rest.len());
    let encoded = rest[..end].trim_end_matches('=');
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(encoded).ok()?;
    serde_json::from_slice(&bytes).ok()
}

/// notify_clear 的对象。
#[derive(Clone, Debug, PartialEq)]
pub enum Clear {
    Id(String),
    Conversation(String),
    All,
}

/// 平台把点击交给插件:内容和“是否由这次点击启动”。
pub(crate) type Sink = Arc<dyn Fn(Payload, bool) + Send + Sync>;

/// 等待认领的点击。
#[derive(Default)]
pub(crate) struct Clicks {
    next: u64,
    pending: HashMap<String, Pending>,
}

struct Pending {
    click: NotificationClick,
    claimed: bool,
    /// 没有认领时是否交给 App 或显示主窗口(来电的“接听”已经处理过,不再兜底)。
    fallback: bool,
    created: Instant,
}

impl Clicks {
    /// 登记一次点击,返回 click_id。
    pub fn register(&mut self, click: NotificationClick, fallback: bool) -> String {
        // 不会无限增长:正常情况下 300 毫秒后就删除;异常残留的超过 1 分钟清掉
        self.pending.retain(|_, p| p.created.elapsed() < Duration::from_secs(60));
        self.next += 1;
        let id = format!("c{}", self.next);
        self.pending.insert(id.clone(), Pending { click, claimed: false, fallback, created: Instant::now() });
        id
    }

    /// 页面认领:第一个认领的返回 true。
    pub fn claim(&mut self, click_id: &str) -> bool {
        match self.pending.get_mut(click_id) {
            Some(p) if !p.claimed => {
                p.claimed = true;
                true
            }
            _ => false,
        }
    }

    pub fn is_claimed(&self, click_id: &str) -> bool {
        self.pending.get(click_id).is_some_and(|p| p.claimed)
    }

    /// 等待结束:删除登记;没有被认领、需要兜底的返回点击的内容。
    pub fn expire(&mut self, click_id: &str) -> Option<NotificationClick> {
        let p = self.pending.remove(click_id)?;
        (!p.claimed && p.fallback).then_some(p.click)
    }
}

pub(crate) struct Core {
    clicks: Mutex<Clicks>,
    /// 启动点击的事件(含 click_id):第一个 hello 的界面窗口拿走。
    launch: Mutex<Option<Value>>,
}

pub struct Notifier {
    core: Arc<Core>,
    backend: Backend,
}

impl Notifier {
    pub fn new<R: Runtime>(app: &AppHandle<R>, identifier: &str) -> Self {
        let core = Arc::new(Core { clicks: Mutex::new(Clicks::default()), launch: Mutex::new(None) });
        let (handle, sink_core) = (app.clone(), core.clone());
        let sink: Sink = Arc::new(move |payload, launched| activated(&handle, &sink_core, payload, launched));
        let backend = Backend::new(app, identifier, sink.clone());
        // Windows:应用退出后点击通知(登记了激活方式时)以启动参数带来点击的内容
        for arg in std::env::args().skip(1) {
            if let Some(payload) = decode_arg(&arg) {
                sink(payload, true);
            }
        }
        Self { core, backend }
    }

    /// 启动应用的那次点击(只交给第一个 hello 的界面窗口),格式与 notification_click 事件相同。
    pub fn launch_click(&self) -> Option<Value> {
        self.core.launch.lock().unwrap().take()
    }

    pub fn claim(&self, click_id: &str) -> bool {
        self.core.clicks.lock().unwrap().claim(click_id)
    }

    pub async fn show(&self, req: &Request) -> Result<()> {
        req.validate()?;
        self.backend.show(req, &req.payload()).await
    }

    pub async fn clear(&self, target: Clear) -> Result<()> {
        self.backend.clear(&target).await
    }

    pub async fn permission(&self) -> &'static str {
        self.backend.permission().await
    }

    pub async fn request_permission(&self) -> &'static str {
        self.backend.request_permission().await
    }
}

/// 单实例插件转来的命令行中的通知点击(应用已在运行)。
pub(crate) fn handle_args<R: Runtime>(app: &AppHandle<R>, argv: &[String]) {
    let Some(shared) = app.try_state::<Arc<Shared>>() else { return };
    let shared = shared.inner().clone();
    for arg in argv {
        if let Some(payload) = decode_arg(arg) {
            activated(app, &shared.notify.core, payload, false);
        }
    }
}

fn click_event(click_id: &str, click: &NotificationClick) -> Value {
    json!({
        "t": "notification_click",
        "click_id": click_id,
        "id": click.id,
        "kind": click.kind,
        "conversation_id": click.conversation_id,
        "seq": click.seq,
        "action": click.action,
        "data": click.data,
        "launched": click.launched,
    })
}

/// 平台交来一次点击(可能在任意线程)。
fn activated<R: Runtime>(app: &AppHandle<R>, core: &Arc<Core>, payload: Payload, launched: bool) {
    let shared = app.try_state::<Arc<Shared>>().map(|s| s.inner().clone());
    match shared {
        Some(shared) if !launched => dispatch(app, &shared, core, payload.into_click(false)),
        // 启动时(插件还没初始化完、引擎还没就绪):先存下,引擎就绪后交出
        _ => {
            let click = payload.into_click(true);
            let click_id = core.clicks.lock().unwrap().register(click.clone(), true);
            *core.launch.lock().unwrap() = Some(click_event(&click_id, &click));
            deliver_launch(app.clone(), core.clone(), click_id, click);
        }
    }
}

/// 引擎就绪(或失败、或等了 30 秒)后交出启动点击;已被 hello 拿到并认领的不再广播。
fn deliver_launch<R: Runtime>(app: AppHandle<R>, core: Arc<Core>, click_id: String, click: NotificationClick) {
    tauri::async_runtime::spawn(async move {
        let started = Instant::now();
        let shared = loop {
            if let Some(shared) = app.try_state::<Arc<Shared>>() {
                let state = shared.engine.state();
                if state == EngineState::Ready || state == EngineState::Failed || started.elapsed() >= LAUNCH_WAIT {
                    break shared.inner().clone();
                }
            } else if started.elapsed() >= LAUNCH_WAIT {
                return;
            }
            tokio::time::sleep(Duration::from_millis(200)).await;
        };
        // 还没被 hello 拿走的也不再交给后来的窗口:从这里起按普通点击处理
        core.launch.lock().unwrap().take();
        if core.clicks.lock().unwrap().is_claimed(&click_id) {
            core.clicks.lock().unwrap().expire(&click_id);
            return;
        }
        if decline_call(&app, &shared, &click) {
            core.clicks.lock().unwrap().expire(&click_id);
            return;
        }
        shared.hub.broadcast(click_event(&click_id, &click));
        wait_claim(app, shared, core, click_id);
    });
}

/// 应用运行中的点击。
fn dispatch<R: Runtime>(app: &AppHandle<R>, shared: &Arc<Shared>, core: &Arc<Core>, click: NotificationClick) {
    if decline_call(app, shared, &click) {
        return;
    }
    let mut fallback = true;
    if click.kind == "call" && click.action.as_deref() == Some("accept") {
        // 接听:App 打开窗口接听;没有注册的显示主窗口。照常广播,已打开的窗口可以直接接听
        if !call_action(app, "accept", &click) {
            crate::engine::show_main_window(app, shared);
        }
        fallback = false;
    }
    let click_id = core.clicks.lock().unwrap().register(click.clone(), fallback);
    shared.hub.broadcast(click_event(&click_id, &click));
    wait_claim(app.clone(), shared.clone(), core.clone(), click_id);
}

/// 来电通知上的“拒绝”:直接交给引擎执行(不需要窗口),并告诉 App。返回是否已处理。
fn decline_call<R: Runtime>(app: &AppHandle<R>, shared: &Shared, click: &NotificationClick) -> bool {
    if click.kind != "call" || click.action.as_deref() != Some("decline") {
        return false;
    }
    let Some(call_id) = call_id_of(click) else {
        shared.logs.plugin("warn", "来电通知的“拒绝”没有 data.call_id,按普通点击处理");
        return false;
    };
    shared.hub.send_engine(json!({ "t": "call_action", "action": "decline", "call_id": call_id }));
    call_action(app, "decline", click);
    true
}

fn call_id_of(click: &NotificationClick) -> Option<String> {
    click.data.as_ref()?.get("call_id")?.as_str().map(str::to_string)
}

/// 调用 App 的 on_call_action;没有注册时返回 false。
fn call_action<R: Runtime>(app: &AppHandle<R>, action: &str, click: &NotificationClick) -> bool {
    let Some(callbacks) = app.try_state::<Callbacks<R>>() else { return false };
    let Some(f) = &callbacks.on_call_action else { return false };
    f(app, CallAction { action: action.to_string(), call_id: call_id_of(click).unwrap_or_default(), data: click.data.clone() });
    true
}

/// 300 毫秒内没有页面认领的:交给 App 的 on_notification_click,没有注册的显示主窗口。
fn wait_claim<R: Runtime>(app: AppHandle<R>, shared: Arc<Shared>, core: Arc<Core>, click_id: String) {
    tauri::async_runtime::spawn(async move {
        tokio::time::sleep(CLAIM_WAIT).await;
        let Some(click) = core.clicks.lock().unwrap().expire(&click_id) else { return };
        if let Some(callbacks) = app.try_state::<Callbacks<R>>() {
            if let Some(f) = &callbacks.on_notification_click {
                f(&app, click);
                return;
            }
        }
        crate::engine::show_main_window(&app, &shared);
    });
}

/// Windows 通知的散列与 XML(与平台无关的部分,单独测试)。
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) mod toast {
    use sha2::{Digest, Sha256};

    use super::{encode_arg, Payload, Request};

    /// tag、group 最长 64 个字符(Windows 10 1703 起,之前 16 个),id 和会话 ID 不受此限:一律散列成 32 个十六进制字符。
    pub fn hash_key(prefix: &str, text: &str) -> String {
        let digest = Sha256::digest(format!("{prefix}:{text}").as_bytes());
        hex::encode(&digest[..16])
    }

    /// 开发构建借用的 AUMID(Windows 自带的 PowerShell 已在开始菜单登记)。
    pub const POWERSHELL_AUMID: &str = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";

    /// 开发时直接运行的构建:可执行文件在 target 下的 debug 或 release 目录中(含交叉编译的 target\<三元组>\debug)。
    pub fn is_dev_build(exe_dir: &str) -> bool {
        let dir = exe_dir.trim_end_matches(['\\', '/']).to_ascii_lowercase().replace('/', "\\");
        dir.contains("\\target\\") && (dir.ends_with("\\debug") || dir.ends_with("\\release"))
    }

    /// 用哪个 AUMID:登记过的(注册表中有)或安装包装的用 identifier,没有登记的开发构建用 PowerShell 的。
    pub fn pick_aumid(identifier: &str, registered: bool, dev_build: bool) -> String {
        if registered || !dev_build {
            identifier.to_string()
        } else {
            POWERSHELL_AUMID.to_string()
        }
    }

    pub fn tag(req_id: &str) -> String {
        hash_key("id", req_id)
    }

    pub fn group(group_key: &str) -> String {
        hash_key("group", group_key)
    }

    pub fn escape(text: &str) -> String {
        let mut out = String::with_capacity(text.len());
        for c in text.chars() {
            match c {
                '&' => out.push_str("&amp;"),
                '<' => out.push_str("&lt;"),
                '>' => out.push_str("&gt;"),
                '"' => out.push_str("&quot;"),
                '\'' => out.push_str("&apos;"),
                // XML 不允许的控制字符
                c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}
                c => out.push(c),
            }
        }
        out
    }

    /// 通知的 XML:点击通知本身和每个按钮都带上编码后的内容(运行中经 Activated 交回,退出后作为启动参数)。
    pub fn xml(req: &Request, payload: &Payload) -> String {
        let call = req.kind == "call";
        let mut out = format!(
            "<toast launch=\"{}\" activationType=\"foreground\"{}><visual><binding template=\"ToastGeneric\"><text hint-maxLines=\"1\">{}</text><text>{}</text></binding></visual>",
            escape(&encode_arg(payload)),
            if call { " scenario=\"incomingCall\"" } else { "" },
            escape(&req.title),
            escape(&req.body),
        );
        let actions = req.effective_actions();
        if !actions.is_empty() {
            out.push_str("<actions>");
            for action in &actions {
                let args = encode_arg(&payload.with_action(Some(action.id.clone())));
                out.push_str(&format!("<action content=\"{}\" arguments=\"{}\" activationType=\"foreground\"/>", escape(&action.title), escape(&args)));
            }
            out.push_str("</actions>");
        }
        if !req.sound {
            out.push_str("<audio silent=\"true\"/>");
        } else if req.kind == "message" {
            out.push_str("<audio src=\"ms-winsoundevent:Notification.IM\"/>");
        } else {
            out.push_str("<audio src=\"ms-winsoundevent:Notification.Default\"/>");
        }
        out.push_str("</toast>");
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn click(kind: &str) -> NotificationClick {
        NotificationClick { id: "dr:c1".into(), kind: kind.into(), conversation_id: Some("c1".into()), seq: Some(5), action: None, data: None, launched: false }
    }

    fn request() -> Request {
        Request { id: "dr:conv:c1".into(), title: "张三".into(), body: "你好 <b>&</b>".into(), kind: "message".into(), conversation_id: Some("c1".into()), seq: Some(42), sound: true, ..Default::default() }
    }

    #[test]
    fn first_claimer_wins() {
        let mut clicks = Clicks::default();
        let id = clicks.register(click("message"), true);
        assert!(clicks.claim(&id));
        assert!(!clicks.claim(&id));
        assert!(clicks.is_claimed(&id));
        // 被认领了:等待结束后不兜底,登记删除
        assert!(clicks.expire(&id).is_none());
        assert!(!clicks.claim(&id));
    }

    #[test]
    fn unclaimed_click_falls_back() {
        let mut clicks = Clicks::default();
        let a = clicks.register(click("message"), true);
        let b = clicks.register(click("call"), false);
        assert_ne!(a, b);
        assert_eq!(clicks.expire(&a).map(|c| c.id), Some("dr:c1".to_string()));
        // 只兜底一次
        assert!(clicks.expire(&a).is_none());
        // 来电的接听已经处理过:不兜底
        assert!(clicks.expire(&b).is_none());
        assert!(!clicks.claim("c999"));
    }

    #[test]
    fn launch_arg_roundtrip() {
        let mut data = Map::new();
        data.insert("call_id".into(), json!("call-1"));
        let payload = Payload { id: "dr:call:1".into(), kind: "call".into(), conversation_id: None, seq: None, data: Some(data), action: Some("accept".into()) };
        let arg = encode_arg(&payload);
        assert!(arg.starts_with(LAUNCH_ARG));
        // 参数中只有命令行和 XML 都安全的字符
        assert!(arg[LAUNCH_ARG.len()..].chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
        assert_eq!(decode_arg(&arg), Some(payload.clone()));
        // 嵌在 App 的 URI 协议中
        let uri = format!("myapp://open?drim-notification={}&x=1", &arg[LAUNCH_ARG.len()..]);
        assert_eq!(decode_arg(&uri), Some(payload));
        assert_eq!(decode_arg("--other"), None);
        assert_eq!(decode_arg("--drim-notification=!!!"), None);
    }

    #[test]
    fn request_validation() {
        assert!(request().validate().is_ok());
        let mut bad = request();
        bad.kind = "other".into();
        assert_eq!(bad.validate().unwrap_err().reason.as_deref(), Some("invalid_kind"));
        let mut bad = request();
        bad.actions = Some(vec![Action { id: "a".into(), title: "A".into() }; 3]);
        assert_eq!(bad.validate().unwrap_err().reason.as_deref(), Some("too_many_actions"));
        let mut bad = request();
        let mut data = Map::new();
        data.insert("x".into(), json!("y".repeat(1100)));
        bad.data = Some(data);
        assert_eq!(bad.validate().unwrap_err().reason.as_deref(), Some("data_too_large"));
        let mut bad = request();
        bad.id.clear();
        assert!(bad.validate().is_err());
    }

    #[test]
    fn call_gets_default_buttons() {
        let mut req = request();
        assert!(req.effective_actions().is_empty());
        req.kind = "call".into();
        let ids: Vec<String> = req.effective_actions().into_iter().map(|a| a.id).collect();
        assert_eq!(ids, vec!["accept", "decline"]);
        req.actions = Some(vec![]);
        assert!(req.effective_actions().is_empty());
    }

    #[test]
    fn toast_tag_is_short_and_stable() {
        let long = "dr:conv:".to_string() + &"x".repeat(500);
        let tag = toast::tag(&long);
        assert_eq!(tag.len(), 32);
        assert!(tag.chars().all(|c| c.is_ascii_hexdigit()));
        assert_eq!(tag, toast::tag(&long));
        assert_ne!(tag, toast::tag("dr:conv:y"));
        // tag 与 group 的散列空间分开
        assert_ne!(toast::tag("c1"), toast::group("c1"));
        let mut req = request();
        assert_eq!(req.group_key(), "c1");
        req.group = Some("g".into());
        assert_eq!(req.group_key(), "g");
        req.group = None;
        req.conversation_id = None;
        assert_eq!(req.group_key(), "message");
    }

    #[test]
    fn aumid_choice() {
        assert!(toast::is_dev_build(r"C:\work\app\src-tauri\target\debug"));
        assert!(toast::is_dev_build(r"C:\work\app\target\x86_64-pc-windows-msvc\Release\"));
        assert!(!toast::is_dev_build(r"C:\Program Files\Example IM"));
        assert_eq!(toast::pick_aumid("com.example.im", false, false), "com.example.im");
        assert_eq!(toast::pick_aumid("com.example.im", true, true), "com.example.im");
        assert_eq!(toast::pick_aumid("com.example.im", false, true), toast::POWERSHELL_AUMID);
        assert!(toast::POWERSHELL_AUMID.ends_with(r"\WindowsPowerShell\v1.0\powershell.exe"));
    }

    #[test]
    fn toast_xml_escapes_and_encodes() {
        let req = request();
        let xml = toast::xml(&req, &req.payload());
        assert!(xml.contains("你好 &lt;b&gt;&amp;&lt;/b&gt;"));
        assert!(xml.contains("ms-winsoundevent:Notification.IM"));
        assert!(!xml.contains("<actions>"));
        let launch = xml.split("launch=\"").nth(1).unwrap().split('"').next().unwrap();
        assert_eq!(decode_arg(launch), Some(req.payload()));

        let mut call = request();
        call.kind = "call".into();
        call.sound = false;
        let xml = toast::xml(&call, &call.payload());
        assert!(xml.contains("scenario=\"incomingCall\""));
        assert!(xml.contains("<audio silent=\"true\"/>"));
        let decline = xml.split("content=\"拒绝\" arguments=\"").nth(1).unwrap().split('"').next().unwrap();
        assert_eq!(decode_arg(decline).and_then(|p| p.action), Some("decline".to_string()));
    }
}