Skip to main content

agentmux_srv_core/backend/google/
gmail_thread.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! What the window that asks to send a draft says about the thread the draft replies into: which
5//! thread it is, who is in it, and a warning when none of the draft's recipients has taken part in
6//! it (a draft for one person that sits in another person's thread, #47852). It is shown text only:
7//! the digest of the draft, which decides what is sent, does not take it. The pure half, as
8//! [`super::gmail_write`] is: the flow that fetches the thread is [`super::gmail_flow`].
9
10use serde_json::Value;
11
12use super::gmail::{get, header, id_arg, line, url_of};
13use super::gmail_write::DraftView;
14use super::{clip, GoogleRequest};
15
16/// The warning, as the window shows it and as the refusal repeats it.
17pub const NO_PARTICIPANT: &str = "None of these recipients has taken part in that thread.";
18const UNCHECKED: &str = "This draft replies into a thread, but the thread could not be read, so its recipients were not checked against it.";
19/// How many of a thread's addresses the window lists, and how many it keeps to compare with.
20const SHOWN_PEOPLE: usize = 5;
21const KEPT_PEOPLE: usize = 500;
22
23/// The request for the headers that say who is in a thread and what it is called.
24pub fn context_plan(thread_id: &str) -> Result<GoogleRequest, String> {
25    let id = id_arg("thread_id", Some(thread_id))?;
26    let mut q = vec![("format", "metadata".to_string())];
27    for h in ["From", "To", "Cc", "Bcc", "Subject"] {
28        q.push(("metadataHeaders", h.to_string()));
29    }
30    Ok(get(url_of(&["threads", &id])?, q))
31}
32
33/// A thread as far as the window needs it.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ThreadContext {
36    pub subject: String,
37    pub messages: usize,
38    /// Every address that wrote or received a message in it (lower case, first seen first).
39    pub people: Vec<String>,
40}
41
42/// From Google's `threads.get` answer (format metadata).
43pub fn context_of(thread: &Value) -> ThreadContext {
44    // Drafts are left out: Google lists the draft being sent (and anyone's other unsent drafts) in
45    // its thread, and their recipients have taken part in nothing.
46    let sent = |m: &&Value| !m.get("labelIds").and_then(Value::as_array).is_some_and(|l| l.iter().any(|x| x.as_str() == Some("DRAFT")));
47    let all: Vec<&Value> = thread.get("messages").and_then(Value::as_array).map(|a| a.iter().filter(sent).collect()).unwrap_or_default();
48    let mut people: Vec<String> = Vec::new();
49    for m in &all {
50        let p = m.get("payload").unwrap_or(&Value::Null);
51        for name in ["From", "To", "Cc", "Bcc"] {
52            for a in addresses_in(header(p, name)) {
53                if people.len() < KEPT_PEOPLE && !people.contains(&a) {
54                    people.push(a);
55                }
56            }
57        }
58    }
59    let subject = all.first().map(|m| line(header(m.get("payload").unwrap_or(&Value::Null), "Subject"), 200)).unwrap_or_default();
60    ThreadContext { subject, messages: all.len(), people }
61}
62
63/// The addresses in a header's value (`To`, `Cc`, `From`), lower case. A name is never read as an
64/// address: with an `<address>` in the entry, only that counts, so a name that spells another
65/// person's address can't put them in the thread.
66pub fn addresses_in(value: &str) -> Vec<String> {
67    let (mut out, mut entry) = (Vec::new(), String::new());
68    let (mut quoted, mut escaped, mut angle) = (false, false, false);
69    for c in value.chars().chain(std::iter::once(',')) {
70        match c {
71            _ if escaped => escaped = false,
72            '\\' if quoted => escaped = true,
73            '"' => quoted = !quoted,
74            '<' if !quoted => angle = true,
75            '>' if !quoted => angle = false,
76            ',' | ';' if !quoted && !angle => {
77                out.extend(entry_address(&entry));
78                entry.clear();
79                continue;
80            }
81            _ => {}
82        }
83        entry.push(c);
84    }
85    out
86}
87
88fn entry_address(entry: &str) -> Option<String> {
89    let inner = match (entry.rfind('<'), entry.rfind('>')) {
90        (Some(open), Some(close)) if open < close => &entry[open + 1..close],
91        _ => entry,
92    };
93    let a = inner.trim().trim_matches('"').to_ascii_lowercase();
94    let (local, domain) = a.split_once('@')?;
95    (!local.is_empty() && !domain.is_empty() && !domain.contains('@') && !a.chars().any(|c| c.is_whitespace() || c.is_control())).then_some(a)
96}
97
98/// What the window adds for the thread a draft replies into.
99#[derive(Debug, Clone, Default, PartialEq, Eq)]
100pub struct ThreadNote {
101    /// Shown first: no recipient is in the thread, or the thread could not be read.
102    pub warning: Option<String>,
103    /// Which thread, and who is in it.
104    pub line: Option<String>,
105    /// Whether no recipient has taken part in the thread: the refusal says so too.
106    pub strangers: bool,
107}
108
109impl ThreadNote {
110    /// The draft's recipients against the thread `ctx`; `own` is the account's address, left out of
111    /// the list of who is in the thread (it is in nearly every thread) but not of the comparison.
112    pub fn of(view: &DraftView, ctx: &ThreadContext, own: &str) -> ThreadNote {
113        // Google gives a new mail's draft a thread of its own, holding only the draft: it replies
114        // into nothing, so there is nothing to say and nobody to warn about.
115        if ctx.messages == 0 {
116            return ThreadNote::default();
117        }
118        let recipients: Vec<String> = [&view.to, &view.cc, &view.bcc].iter().flat_map(|r| addresses_in(r)).collect();
119        let strangers = !recipients.iter().any(|r| ctx.people.contains(r));
120        let own = own.trim().to_ascii_lowercase();
121        let others: Vec<&String> = ctx.people.iter().filter(|p| **p != own).collect();
122        let who = if others.is_empty() {
123            String::new()
124        } else {
125            let shown: Vec<&str> = others.iter().take(SHOWN_PEOPLE).map(|p| p.as_str()).collect();
126            let more = if others.len() > SHOWN_PEOPLE { format!(" and {} more", others.len() - SHOWN_PEOPLE) } else { String::new() };
127            format!(", with {}{more}", shown.join(", "))
128        };
129        let subject = if ctx.subject.is_empty() { "(no subject)" } else { &ctx.subject };
130        let line = format!("Replies in the thread: {} ({} message{}{who})", clip(subject, 120), ctx.messages, if ctx.messages == 1 { "" } else { "s" });
131        ThreadNote { warning: strangers.then(|| NO_PARTICIPANT.to_string()), line: Some(line), strangers }
132    }
133
134    /// The thread could not be read: the person is told, and decides.
135    pub fn unchecked() -> ThreadNote {
136        ThreadNote { warning: Some(UNCHECKED.to_string()), line: None, strangers: false }
137    }
138}
139
140#[cfg(test)]
141#[path = "gmail_thread_tests.rs"]
142mod tests;