Repository navigation
Expand file tree
/
Copy pathdrafts.rs
More file actions
2257 lines (2243 loc) · 86.8 KB
/
Copy pathdrafts.rs
File metadata and controls
2257 lines (2243 loc) · 86.8 KB
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Host-owned reply drafts and send attempts (ADR 0007).
//!
//! Agent methods can propose text and actions. Only Rust callers holding a
//! `Review` obtained by the trusted host review UI can consume authorization.
//! The shell MUST invalidate reviews on account changes and reject injected
//! input before calling `approve_and_send`. No JSON method mints authorization.
use super::*;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{
atomic::{AtomicU64, Ordering},
OnceLock,
};
const BODY_MAX: usize = 8192;
const RECORD_MAX: usize = 512 * 1024;
const PUBLIC_COMPOSERS_MAX: usize = 128;
// Each admitted record may reach RECORD_MAX, including its final receipt.
const PUBLIC_COMPOSERS_BYTES: usize = PUBLIC_COMPOSERS_MAX * RECORD_MAX;
const REVIEW_SECONDS: u64 = 600;
static SERIAL: Mutex<()> = Mutex::new(());
static GENERATION: AtomicU64 = AtomicU64::new(0);
type Changed = Arc<dyn Fn() + Send + Sync>;
fn changed_hook() -> &'static Mutex<Option<Changed>> {
static HOOK: OnceLock<Mutex<Option<Changed>>> = OnceLock::new();
HOOK.get_or_init(Default::default)
}
pub(crate) fn wake_ui() {
let callback = changed_hook()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
if let Some(callback) = callback {
callback();
}
}
pub fn generation() -> u64 {
GENERATION.load(Ordering::Acquire)
}
/// Install a nonblocking UI signal callback. It must not reenter draft APIs.
pub fn on_change(callback: Option<Changed>) {
*changed_hook().lock().unwrap_or_else(|e| e.into_inner()) = callback;
}
pub type ReviewRequested = Arc<dyn Fn(Review) -> Result<(), String> + Send + Sync>;
fn review_hook() -> &'static Mutex<Option<ReviewRequested>> {
static HOOK: OnceLock<Mutex<Option<ReviewRequested>>> = OnceLock::new();
HOOK.get_or_init(Default::default)
}
/// Route a foreground composer's review into the shell's trusted Mail region.
/// The callback may display/queue it; receiving it is not approval.
pub fn on_review_requested(callback: Option<ReviewRequested>) {
*review_hook().lock().unwrap_or_else(|e| e.into_inner()) = callback;
}
pub type ClaimGuard = Arc<dyn Fn(&Path, &str, &str) -> Result<(), String> + Send + Sync>;
fn claim_guard() -> &'static Mutex<Option<ClaimGuard>> {
static GUARD: OnceLock<Mutex<Option<ClaimGuard>>> = OnceLock::new();
GUARD.get_or_init(Default::default)
}
/// Checked under the claim lock. This callback may read lifecycle state but
/// must not reenter draft APIs, invoke UI callbacks, or perform networking.
pub fn on_claim(callback: Option<ClaimGuard>) {
*claim_guard().lock().unwrap_or_else(|e| e.into_inner()) = callback;
}
pub(crate) fn lock() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
}
type Backend = (Arc<dyn Transport>, Arc<dyn Vault>);
fn backend() -> &'static Mutex<Option<Backend>> {
static BACKEND: OnceLock<Mutex<Option<Backend>>> = OnceLock::new();
BACKEND.get_or_init(Default::default)
}
pub(crate) fn set_backend(transport: Arc<dyn Transport>, vault: Arc<dyn Vault>) {
*backend().lock().unwrap_or_else(|e| e.into_inner()) = Some((transport, vault));
}
fn configured() -> Result<Backend, String> {
backend()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.ok_or("Mail service is not registered".into())
}
fn now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn unique(kind: &str) -> String {
static NEXT: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
format!(
"{kind}-{}",
&network::hash(&format!(
"{}:{nanos}:{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
))[..32]
)
}
/// A short-lived, single-use edit capability, issued only by the native host
/// for a person's chat turn. It confers no review or send authority.
struct ChatEdit {
store: PathBuf,
app: String,
account: String,
draft: String,
revision: u64,
expires: u64,
}
fn chat_edits() -> &'static Mutex<BTreeMap<String, ChatEdit>> {
static EDITS: OnceLock<Mutex<BTreeMap<String, ChatEdit>>> = OnceLock::new();
EDITS.get_or_init(Default::default)
}
pub fn issue_chat_edit(host_dir: &Path, app: &str, account: &str, draft: &str, expected: u64) -> Result<String, String> {
let (_, vault) = configured()?;
issue_chat_edit_in(&Store::at(host_dir, vault), app, account, draft, expected)
}
fn issue_chat_edit_in(store: &Store, app: &str, account: &str, draft: &str, expected: u64) -> Result<String, String> {
let _guard = lock();
let d = load(store, app, account, draft)?;
revision(&d, expected)?;
if !matches!(text(&d, "status"), "draft" | "awaiting_approval") {
return Err("This reply is no longer editable".into());
}
let mut random = [0u8; 32];
rustls::crypto::ring::default_provider().secure_random.fill(&mut random)
.map_err(|_| "Cannot create chat edit capability")?;
let token: String = random.iter().map(|b| format!("{b:02x}")).collect();
let mut edits = chat_edits().lock().unwrap_or_else(|e| e.into_inner());
edits.retain(|_, e| e.expires > now());
if edits.len() >= 128 { return Err("Too many active reply edits".into()); }
edits.insert(token.clone(), ChatEdit {store: store.dir.clone(), app: app.into(), account: account.into(), draft: draft.into(), revision: expected, expires: now() + 300});
Ok(token)
}
pub fn revoke_chat_edit(token: &str) {
let _guard = lock();
chat_edits().lock().unwrap_or_else(|e| e.into_inner()).remove(token);
}
fn apply_chat_edit(store: &Store, app: &str, account: &str, draft: &str, expected: u64, body: &str, token: &str) -> Result<Value, String> {
let _guard = lock();
let mut edits = chat_edits().lock().unwrap_or_else(|e| e.into_inner());
let grant = edits.get(token).ok_or("Chat edit expired or was already used; ask again")?;
if grant.expires <= now() || grant.store != store.dir || grant.app != app || grant.account != account || grant.draft != draft || grant.revision != expected {
return Err("Chat edit does not authorize this draft revision".into());
}
let guard = claim_guard().lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(guard) = guard { guard(store.dir.parent().ok_or("Invalid host root")?, app, account)?; }
let d = update_locked(store, app, account, draft, expected, &json!({"body":body}), None, true)?;
edits.remove(token);
Ok(d)
}
fn valid_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 96 && id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')
}
fn path(store: &Store, account: &str, id: &str) -> Result<PathBuf, String> {
if !valid_id(id) {
return Err("Invalid draft identity".into());
}
let directory = store.dir.join(format!("drafts-{}", network::hash(account)));
let file = directory.join(format!("{id}.json"));
// The host root is supplied by Rust, never the app's writable workspace.
// Refuse link substitution rather than following it outside that root.
for dir in [
store.dir.parent().ok_or("Invalid host root")?,
store.dir.as_path(),
directory.as_path(),
] {
match std::fs::symlink_metadata(dir) {
Ok(meta) if !meta.is_dir() || meta.file_type().is_symlink() => {
return Err("Unsafe draft storage directory".into())
}
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.to_string()),
_ => {}
}
}
for target in [&file, &file.with_extension("tmp")] {
match std::fs::symlink_metadata(target) {
Ok(meta) => {
if !meta.is_file() || meta.file_type().is_symlink() {
return Err("Unsafe draft storage file".into());
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if meta.nlink() != 1 {
return Err("Linked draft storage file is refused".into());
}
}
}
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.to_string()),
_ => {}
}
}
Ok(file)
}
fn check_account(store: &Store, app: &str, account: &str) -> Result<Value, String> {
if app != "os.mail" {
return Err("Only Mail owns reply drafts".into());
}
store.granted(app, account)
}
fn save(store: &Store, draft: &Value) -> Result<(), String> {
let path = path(store, text(draft, "account"), text(draft, "draft_id"))?;
let bytes = serde_json::to_vec(draft).map_err(|e| e.to_string())?;
if bytes.len() > RECORD_MAX {
return Err("Draft history is full; keep this receipt and create a new reply".into());
}
if draft["kind"] == "public_compose" {
public_storage_budget(
store,
draft,
bytes.len(),
PUBLIC_COMPOSERS_MAX,
PUBLIC_COMPOSERS_BYTES,
)?;
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))
.map_err(|e| e.to_string())?;
}
}
write_atomic(&path, &bytes)?;
GENERATION.fetch_add(1, Ordering::Release);
let signal = changed_hook()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
if let Some(signal) = signal {
signal();
}
Ok(())
}
fn active() -> &'static Mutex<BTreeSet<PathBuf>> {
static ACTIVE: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceLock::new();
ACTIVE.get_or_init(Default::default)
}
fn load(store: &Store, app: &str, account: &str, id: &str) -> Result<Value, String> {
// Public composers have a separate host-minted namespace. Legacy reply
// drafts remain Mail-only, including when another app shares the account.
if id.starts_with("composer-") {
store.granted(app, account)?;
} else {
check_account(store, app, account)?;
}
let file = path(store, account, id)?;
let bytes = std::fs::read(&file).map_err(|e| format!("Cannot read reply draft: {e}"))?;
if bytes.len() > RECORD_MAX {
return Err("Invalid draft record size".into());
}
let mut d: Value = serde_json::from_slice(&bytes).map_err(|_| "Invalid reply draft record")?;
if (id.starts_with("composer-") && d["kind"] != "public_compose")
|| d["schema"] != 1
|| d["publisher"] != app
|| d["account"] != account
|| d["draft_id"] != id
|| !d["attempts"].is_array()
|| !d["suggestions"].is_array()
{
return Err("Reply draft binding mismatch".into());
}
let rev = d["revision"]
.as_u64()
.filter(|r| *r > 0)
.ok_or("Invalid draft revision")?;
let states = [
"draft",
"awaiting_approval",
"sending",
"accepted",
"failed_before_delivery",
"outcome_unknown",
"cancelled",
];
if !states.contains(&text(&d, "status"))
|| !d["source_message"].is_object()
|| !d["email"].is_object()
|| [
"from",
"to",
"subject",
"body",
"in_reply_to",
"references",
"chat_thread",
"body_origin",
]
.iter()
.any(|k| !d[*k].is_string())
{
return Err("Invalid reply draft fields".into());
}
fields(text(&d, "to"), text(&d, "subject"), text(&d, "body"))?;
let mut operations = BTreeSet::new();
let attempts = d["attempts"].as_array().unwrap();
if attempts.len() > 32
|| attempts.iter().any(|a| {
!a.is_object()
|| !a["payload"].is_object()
|| !valid_id(text(a, "operation_id"))
|| !operations.insert(text(a, "operation_id"))
|| !states.contains(&text(a, "status"))
|| a["revision"].as_u64().is_none_or(|r| r == 0 || r > rev)
|| [
"from",
"to",
"subject",
"body",
"in_reply_to",
"references",
"message_id",
]
.iter()
.any(|k| !a["payload"][*k].is_string())
})
{
return Err("Invalid reply attempt ledger".into());
}
if d["suggestions"].as_array().unwrap().len() > 8
|| d["suggestions"].as_array().unwrap().iter().any(|s| {
!valid_id(text(s, "suggestion_id"))
|| !s["body"].is_string()
|| s["revision"].as_u64().is_none_or(|r| r == 0 || r > rev)
})
{
return Err("Invalid reply suggestions".into());
}
// A process that no longer owns an in-flight operation cannot infer failure.
if text(&d, "status") == "sending"
&& !active()
.lock()
.unwrap_or_else(|e| e.into_inner())
.contains(&file)
{
d["status"] = json!("outcome_unknown");
if let Some(a) = d["attempts"].as_array_mut().and_then(|v| v.last_mut()) {
a["status"] = json!("outcome_unknown");
a["notice"] = json!(
"The previous process stopped during submission. Delivery may have happened."
);
}
save(store, &d)?;
}
Ok(d)
}
fn snapshot(d: &Value) -> Value {
let mut v = d.clone();
v.as_object_mut().unwrap().remove("schema");
// Full snapshots are Rust-host-only; tools receive a bounded projection.
v
}
fn revision(d: &Value, expected: u64) -> Result<(), String> {
if d["revision"].as_u64() != Some(expected) {
return Err("revision_conflict: the draft changed; keep unsaved text and reload".into());
}
Ok(())
}
fn fields(to: &str, subject: &str, body: &str) -> Result<(), String> {
if to.is_empty()
|| to.len() > 254
|| !to.is_ascii()
|| to.split('@').count() != 2
|| to.starts_with('@')
|| to.ends_with('@')
|| to.chars().any(|c| c.is_whitespace() || c.is_control())
|| to.contains(['\r', '\n', '<', '>', ' ', ',', ';'])
{
return Err("Reply supports one To email address; no Cc/Bcc or recipient list".into());
}
if subject.len() > 512 || subject.contains(['\r', '\n', '\0']) {
return Err("Subject must be at most 512 bytes without line breaks".into());
}
if body.len() > BODY_MAX || body.contains('\0') {
return Err("Reply body must be at most 8192 UTF-8 bytes without NUL".into());
}
Ok(())
}
fn single_address(raw: &str) -> Result<String, String> {
let parsed = mailparse::addrparse(raw).map_err(|_| "Cannot parse source reply recipient")?;
if parsed.len() != 1 {
return Err("The source requires multiple reply recipients, which are unsupported".into());
}
match &parsed[0] {
mailparse::MailAddr::Single(address) => {
fields(&address.addr, "", "")?;
Ok(address.addr.clone())
}
_ => Err("Reply address groups are unsupported".into()),
}
}
fn headers(raw: &str) -> Result<String, String> {
if raw.len() > 4096 || raw.contains(['\r', '\n', '\0']) {
return Err("Unsupported source reply headers".into());
}
Ok(raw.trim().to_string())
}
fn create(
store: &Store,
app: &str,
account: &str,
folder: &str,
message: &str,
body: &str,
reply_key: &str,
) -> Result<Value, String> {
let _guard = lock();
let account_data = check_account(store, app, account)?;
if folder.len() > 256 || message.len() > 128 {
return Err("Invalid source identity".into());
}
if reply_key.len() > 64
|| !reply_key
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
{
return Err("reply_key must be at most 64 safe ASCII characters".into());
}
let mailbox = store.mailbox(account, folder);
let source = mailbox["messages"]
.as_array()
.and_then(|rows| rows.iter().find(|m| text(m, "id") == message))
.ok_or("There is no such source message")?;
let generation = mailbox["state"]["uidvalidity"].clone();
let mut identity = json!([account, folder, message, generation, source["message_id"]]);
if !reply_key.is_empty() {
identity.as_array_mut().unwrap().push(json!(reply_key));
}
let id = format!("draft-{}", &network::hash(&identity.to_string())[..32]);
if path(store, account, &id)?
.try_exists()
.map_err(|e| e.to_string())?
{
return load(store, app, account, &id).map(|d| snapshot(&d));
}
let recipient = single_address(if text(source, "reply_to").trim().is_empty() {
text(source, "address")
} else {
text(source, "reply_to")
})?;
let old_subject = text(source, "subject");
let subject = if old_subject.to_ascii_lowercase().starts_with("re:") {
old_subject.to_string()
} else {
format!("Re: {old_subject}")
};
fields(&recipient, &subject, body)?;
let in_reply_to = headers(text(source, "message_id"))?;
let old_refs = headers(text(source, "references"))?;
let references = if in_reply_to.is_empty() {
old_refs
} else {
format!("{old_refs} {in_reply_to}").trim().to_string()
};
let d = json!({"schema":1,"publisher":app,"account":account,"from":account_data["address"],"draft_id":id,"revision":1,
"chat_thread":format!("reply-{}", &network::hash(&id)[..24]),
"source_message":{"folder":folder,"message":message,"generation":generation,"internet_message_id":in_reply_to},
"email":{"sender":clip(text(source,"sender"),160),"address":clip(text(source,"address"),254),"subject":clip(old_subject,512),"body":clip(text(source,"body"),4000)},
"to":recipient,"subject":subject,"body":body,"body_origin":"model","in_reply_to":in_reply_to,"references":references,
"status":"draft","suggestions":[],"attempts":[]});
save(store, &d)?;
Ok(snapshot(&d))
}
/// Read the full bound draft, including email context and durable attempt receipts.
pub fn read(host_dir: &Path, app: &str, account: &str, draft_id: &str) -> Result<Value, String> {
let (_, vault) = configured()?;
let _guard = lock();
load(&Store::at(host_dir, vault), app, account, draft_id).map(|d| snapshot(&d))
}
/// Trusted editor update. This method is not exposed to scripts or agents.
/// Only `to`, `subject` and `body` may appear in `changes`.
pub fn update(
host_dir: &Path,
app: &str,
account: &str,
draft_id: &str,
expected_revision: u64,
changes: &Value,
) -> Result<Value, String> {
let (_, vault) = configured()?;
update_in(
&Store::at(host_dir, vault),
app,
account,
draft_id,
expected_revision,
changes,
None,
)
}
#[allow(clippy::too_many_arguments)]
fn update_in(
store: &Store,
app: &str,
account: &str,
id: &str,
expected: u64,
changes: &Value,
suggestion: Option<&str>,
) -> Result<Value, String> {
let _guard = lock();
update_locked(store, app, account, id, expected, changes, suggestion, false)
}
#[allow(clippy::too_many_arguments)]
fn update_locked(store: &Store, app: &str, account: &str, id: &str, expected: u64, changes: &Value, suggestion: Option<&str>, from_chat: bool) -> Result<Value, String> {
let mut d = load(store, app, account, id)?;
revision(&d, expected)?;
if d["attempts"].as_array().unwrap().iter().any(|a| {
matches!(
text(a, "status"),
"sending" | "accepted" | "outcome_unknown" | "failed_before_delivery"
)
}) {
return Err("This draft has a submission attempt; its payload is frozen".into());
}
let object = changes
.as_object()
.ok_or("Draft changes must be an object")?;
if object.is_empty()
|| object
.keys()
.any(|k| !matches!(k.as_str(), "to" | "subject" | "body"))
{
return Err("Only recipient, subject and body can be edited".into());
}
if let Some(sid) = suggestion {
let s = d["suggestions"]
.as_array()
.unwrap()
.iter()
.find(|s| s["suggestion_id"] == sid)
.ok_or("No such suggestion")?;
if s["revision"].as_u64() != Some(expected) || s["body"] != changes["body"] {
return Err("Suggestion is stale".into());
}
}
for (k, v) in object {
if !v.is_string() {
return Err("Draft fields must be text".into());
}
d[k] = v.clone();
}
fields(text(&d, "to"), text(&d, "subject"), text(&d, "body"))?;
d["revision"] = json!(expected.checked_add(1).ok_or("Revision limit reached")?);
d["body_origin"] = json!(if from_chat {
"model_chat"
} else if suggestion.is_some() {
"model_accepted"
} else if object.contains_key("body") {
"user"
} else {
text(&d, "body_origin")
});
d["status"] = json!("draft");
for a in d["attempts"].as_array_mut().unwrap() {
if a["status"] == "awaiting_approval" {
a["status"] = json!("cancelled");
}
}
d["suggestions"] = json!([]);
save(store, &d)?;
Ok(snapshot(&d))
}
/// Accept a model suggestion only if the person is still viewing its base revision.
pub fn accept_suggestion(
host_dir: &Path,
app: &str,
account: &str,
draft_id: &str,
suggestion_id: &str,
expected_revision: u64,
) -> Result<Value, String> {
let (_, vault) = configured()?;
let store = Store::at(host_dir, vault);
let body = {
let _guard = lock();
let d = load(&store, app, account, draft_id)?;
d["suggestions"]
.as_array()
.unwrap()
.iter()
.find(|s| s["suggestion_id"] == suggestion_id)
.ok_or("No such suggestion")?["body"]
.clone()
};
update_in(
&store,
app,
account,
draft_id,
expected_revision,
&json!({"body":body}),
Some(suggestion_id),
)
}
fn suggest(
store: &Store,
app: &str,
account: &str,
id: &str,
expected: u64,
body: &str,
) -> Result<Value, String> {
let _guard = lock();
let mut d = load(store, app, account, id)?;
revision(&d, expected)?;
fields(text(&d, "to"), text(&d, "subject"), body)?;
if !matches!(text(&d, "status"), "draft" | "awaiting_approval") {
return Err("This reply is no longer editable".into());
}
let suggestions = d["suggestions"].as_array_mut().unwrap();
if suggestions.len() >= 8 {
suggestions.remove(0);
}
suggestions.push(json!({"suggestion_id":unique("suggestion"),"revision":expected,"body":body,"origin":"model"}));
save(store, &d)?;
Ok(snapshot(&d))
}
fn propose(
store: &Store,
app: &str,
account: &str,
id: &str,
expected: u64,
) -> Result<Value, String> {
let _guard = lock();
let mut d = load(store, app, account, id)?;
revision(&d, expected)?;
if let Some(a) = d["attempts"].as_array().unwrap().last() {
if a["revision"].as_u64() == Some(expected) && a["status"] != "cancelled" {
return Ok(snapshot(&d));
}
}
add_attempt(&mut d, None)?;
save(store, &d)?;
Ok(snapshot(&d))
}
fn add_attempt(d: &mut Value, prior: Option<&str>) -> Result<(), String> {
if d["attempts"].as_array().unwrap().len() >= 32 {
return Err("Reply attempt limit reached".into());
}
fields(text(d, "to"), text(d, "subject"), text(d, "body"))?;
let operation = unique("send");
let domain = text(d, "from")
.split('@')
.nth(1)
.unwrap_or("octosense.local");
let payload = json!({"from":d["from"],"to":d["to"],"subject":d["subject"],"body":d["body"],"in_reply_to":d["in_reply_to"],"references":d["references"],"message_id":format!("<{operation}@{domain}>")});
let attempt = json!({"operation_id":operation,"revision":d["revision"],"status":"awaiting_approval","payload":payload,"prior_attempt":prior});
d["attempts"].as_array_mut().unwrap().push(attempt);
d["status"] = json!("awaiting_approval");
Ok(())
}
/// Opaque, process-local, single-use review capability. It is never serialized
/// into card data. Its snapshot is exactly what the trusted UI must display.
pub struct Review {
token: String,
snapshot: Value,
}
impl Review {
pub fn snapshot(&self) -> &Value {
&self.snapshot
}
}
struct ReviewState {
host_dir: PathBuf,
app: String,
account: String,
draft: String,
operation: String,
revision: u64,
expires: u64,
snapshot: Value,
}
fn reviews() -> &'static Mutex<BTreeMap<String, ReviewState>> {
static REVIEWS: OnceLock<Mutex<BTreeMap<String, ReviewState>>> = OnceLock::new();
REVIEWS.get_or_init(Default::default)
}
fn review_from(host_dir: &Path, app: &str, account: &str, d: &Value) -> Result<Review, String> {
let a = d["attempts"]
.as_array()
.and_then(|a| a.last())
.ok_or("No send proposal")?;
if a["status"] != "awaiting_approval" {
return Err("This attempt is not awaiting approval; inspect its receipt".into());
}
let prior_status = d["attempts"].as_array().unwrap().iter()
.find(|prior| !a["prior_attempt"].is_null() && prior["operation_id"] == a["prior_attempt"])
.map(|prior| prior["status"].clone()).unwrap_or(Value::Null);
let snapshot = json!({"publisher":app,"account":account,"draft_id":d["draft_id"],"revision":d["revision"],"source_message":d["source_message"],"operation_id":a["operation_id"],"payload":a["payload"],"prior_attempt":a["prior_attempt"],"prior_status":prior_status});
let token = unique("review");
let mut all = reviews().lock().unwrap_or_else(|e| e.into_inner());
all.retain(|_, r| r.expires > now());
if all.len() >= 128 {
return Err("Too many open reviews".into());
}
all.insert(
token.clone(),
ReviewState {
host_dir: host_dir.to_path_buf(),
app: app.into(),
account: account.into(),
draft: text(d, "draft_id").into(),
operation: text(a, "operation_id").into(),
revision: d["revision"].as_u64().ok_or("Invalid revision")?,
expires: now() + REVIEW_SECONDS,
snapshot: snapshot.clone(),
},
);
Ok(Review { token, snapshot })
}
pub fn prepare_review(
host_dir: &Path,
app: &str,
account: &str,
draft_id: &str,
expected_revision: u64,
) -> Result<Review, String> {
let (_, vault) = configured()?;
let store = Store::at(host_dir, vault);
propose(&store, app, account, draft_id, expected_revision)?;
let _guard = lock();
let d = load(&store, app, account, draft_id)?;
revision(&d, expected_revision)?;
review_from(host_dir, app, account, &d)
}
/// Explicit user Retry only. A model repeating propose_send cannot reach this.
pub fn retry_review(
host_dir: &Path,
app: &str,
account: &str,
draft_id: &str,
prior_attempt: &str,
acknowledge_duplicate: bool,
) -> Result<Review, String> {
let (_, vault) = configured()?;
let store = Store::at(host_dir, vault);
retry_in(
&store,
app,
account,
draft_id,
prior_attempt,
acknowledge_duplicate,
)
}
fn retry_in(
store: &Store,
app: &str,
account: &str,
draft_id: &str,
prior_attempt: &str,
acknowledge_duplicate: bool,
) -> Result<Review, String> {
let _guard = lock();
let mut d = load(store, app, account, draft_id)?;
let a = d["attempts"]
.as_array()
.and_then(|a| a.last())
.ok_or("No previous attempt")?;
if a["operation_id"] != prior_attempt
|| !matches!(
text(a, "status"),
"failed_before_delivery" | "outcome_unknown"
)
{
return Err("Only the last failed or uncertain attempt can be retried".into());
}
if a["status"] == "outcome_unknown" && !acknowledge_duplicate {
return Err("Acknowledge the possible duplicate before retrying uncertain delivery".into());
}
add_attempt(&mut d, Some(prior_attempt))?;
save(store, &d)?;
review_from(
store.dir.parent().ok_or("Invalid host root")?,
app,
account,
&d,
)
}
/// Invalidate all capabilities for an account when the shell changes selection.
pub fn invalidate_reviews(host_dir: &Path, account: &str) {
let _guard = lock();
invalidate_locked(host_dir, Some(account));
}
/// Rebinding Mail to a newly signed-in account invalidates every old review.
pub fn invalidate_all_reviews(host_dir: &Path) {
let _guard = lock();
invalidate_locked(host_dir, None);
}
pub(crate) fn invalidate_locked(host_dir: &Path, account: Option<&str>) {
reviews()
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|_, r| r.host_dir != host_dir || account.is_some_and(|a| r.account != a));
}
pub fn cancel_review(review: Review) -> Result<(), String> {
let (_, vault) = configured()?;
cancel_in(review, vault)
}
/// Retire one view's capability without cancelling the shared attempt another
/// view may currently be reviewing. Explicit Cancel uses `cancel_review`.
pub fn revoke_review(review: Review) {
let _guard = lock();
reviews()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&review.token);
}
/// Retire a native public view without draft I/O or the SERIAL lock. Claiming
/// and retirement both atomically remove this map entry; an already claimed
/// send is allowed to finish. Other views' review capabilities are unchanged.
pub(crate) fn retire_public_review(review: Review) {
reviews()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&review.token);
}
fn cancel_in(review: Review, vault: Arc<dyn Vault>) -> Result<(), String> {
let _guard = lock();
let Some(r) = reviews()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&review.token)
else {
return Ok(());
};
let store = Store::at(&r.host_dir, vault);
let mut d = load(&store, &r.app, &r.account, &r.draft)?;
if let Some(a) = d["attempts"]
.as_array_mut()
.unwrap()
.iter_mut()
.find(|a| a["operation_id"] == r.operation)
{
if a["status"] == "awaiting_approval" {
a["status"] = json!("cancelled");
d["status"] = json!("draft");
save(&store, &d)?;
}
}
Ok(())
}
/// Transport outcome classification. Unknown is deliberately the default for
/// third-party/test transports returning an ordinary error.
#[derive(Debug, Clone)]
pub enum SendFailure {
BeforeDelivery(String),
Unknown(String),
}
/// Blocking; invoke off the UI thread, ONLY after a trusted real activation of
/// the host review control. Neither developer mode nor script callers use it.
pub fn approve_and_send(review: Review) -> Result<Value, String> {
let (transport, vault) = configured()?;
execute(review, transport.as_ref(), vault)
}
pub(crate) fn approve_and_send_pending(review: Review, reply: &Replier) -> Result<Value, String> {
let (transport, vault) = configured()?;
execute_pending(review, transport.as_ref(), vault, || reply.is_pending())
}
fn execute(
review: Review,
transport: &dyn Transport,
vault: Arc<dyn Vault>,
) -> Result<Value, String> {
execute_pending(review, transport, vault, || true)
}
fn execute_pending(
review: Review,
transport: &dyn Transport,
vault: Arc<dyn Vault>,
originating_request_is_live: impl FnOnce() -> bool,
) -> Result<Value, String> {
let (r, store, account, payload, file) = {
let _guard = lock();
let r = reviews()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&review.token)
.ok_or("Review was cancelled, expired or already consumed")?;
if !originating_request_is_live() {
return Err("The originating app closed before the send claim".into());
}
if r.expires <= now() || r.snapshot != review.snapshot {
return Err("Review expired or snapshot changed".into());
}
let store = Store::at(&r.host_dir, vault);
let guard = claim_guard()
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
if let Some(guard) = guard {
guard(&r.host_dir, &r.app, &r.account)?;
}
let mut d = load(&store, &r.app, &r.account, &r.draft)?;
revision(&d, r.revision)?;
let a = d["attempts"]
.as_array_mut()
.unwrap()
.iter_mut()
.find(|a| a["operation_id"] == r.operation)
.ok_or("Unknown send operation")?;
if a["status"] != "awaiting_approval" {
return Ok(snapshot(&d));
}
if a["payload"] != r.snapshot["payload"] {
return Err("Outbound snapshot changed".into());
}
let account = store.account_for(&r.app, &r.account)?;
if account["address"] != a["payload"]["from"] {
return Err("Sending account changed; review again".into());
}
let payload = a["payload"].clone();
a["status"] = json!("sending");
d["status"] = json!("sending");
save(&store, &d)?; // Failure here never enters the transport.
let file = path(&store, &r.account, &r.draft)?;
active()
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(file.clone());
(r, store, account, payload, file)
};
// No draft/account lock is held across networking; sign-out remains usable.
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
transport.send_checked(&account, &payload)
}))
.unwrap_or_else(|_| {
Err(SendFailure::Unknown(
"Transport stopped without a result".into(),
))
});
let _guard = lock();
// Read before releasing ACTIVE so this live result is not called a crash.
let loaded = load(&store, &r.app, &r.account, &r.draft);
active()
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&file);
let mut d=loaded.map_err(|_|"Submission finished after account removal; no deleted draft was recreated. Check provider Sent before any retry.".to_string())?;
let a = d["attempts"]
.as_array_mut()
.unwrap()
.iter_mut()
.find(|a| a["operation_id"] == r.operation)
.ok_or("Missing submission receipt")?;
let status = match outcome {
Ok(receipt) if receipt["accepted"] == true => {
a["receipt"] = receipt;
"accepted"
}
Ok(_) => {
a["notice"] = json!("Transport returned no authoritative acceptance");
"outcome_unknown"
}
Err(SendFailure::BeforeDelivery(_)) => {
a["notice"]=json!("Submission failed before message delivery. Explicit Retry requires a new approval.");
"failed_before_delivery"
}
Err(SendFailure::Unknown(_)) => {
a["notice"] =
json!("Delivery may have happened. Check Sent; do not automatically resend.");
"outcome_unknown"
}
};
a["status"] = json!(status);
d["status"] = json!(status);
save(&store, &d)?;
if status == "accepted" {
contacts::record_sent(&store.dir, &r.account, text(&payload, "to"));
}
Ok(snapshot(&d))
}
/// Projection under the kernel's 4 KiB result ceiling. Full editor/review data
/// remains available to the Rust host; long model-visible text is explicit.
fn for_agent(d: &Value) -> Value {
let body = text(d, "body");
let subject = text(d, "subject");
let mut v = json!({"draft_id":d["draft_id"],"revision":d["revision"],"account":d["account"],
"source_message":{"folder":d["source_message"]["folder"],"message":d["source_message"]["message"],"generation":d["source_message"]["generation"]},
"chat_thread":d["chat_thread"],"to":d["to"],"subject":clip(subject,512),"subject_truncated":subject.len()>clip(subject,512).len(),
"body":clip(body,1800),"body_truncated":body.len()>clip(body,1800).len(),"body_origin":d["body_origin"],"status":d["status"]});
if let Some(a) = d["attempts"].as_array().and_then(|a| a.last()) {
v["attempt"] = json!({"operation_id":a["operation_id"],"status":a["status"],"message_id":a["payload"]["message_id"]});
}
if let Some(s) = d["suggestions"].as_array().and_then(|a| a.last()) {
v["suggestion"] = json!({"suggestion_id":s["suggestion_id"],"revision":s["revision"],"pending_user_acceptance":true});
}
v
}
pub(crate) fn agent_call(
store: &Store,