Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(email): create Outlook replies whose parent refuses createReply (#8789)

teo6a5da8d46b2e
diff --git a/crates/email_api_client/AGENTS.md b/crates/email_api_client/AGENTS.md
index ed7ebdc0cd..0cb6059f99 100644
--- a/crates/email_api_client/AGENTS.md
+++ b/crates/email_api_client/AGENTS.md
@@ -78,7 +78,12 @@ Outlook (Microsoft Graph) outbound adapters.
through it.
- Graph answers a bodyless POST or PATCH without `Content-Length: 0` with 411
Length Required. `transport.rs` adds the header, so new Graph calls must go
- through `request`/`conditional_request` rather than the raw client.
+ through `request`/`conditional_request` rather than the raw client. Use
+ `graph_request` only when a caller must branch on the Graph status, error
+ code, or request id; the others drop them.
+- Same-mailbox Outlook replies use `createReply`. When Graph refuses it with
+ 400 `ErrorInvalidOperation`, `create_draft` creates a standalone draft that
+ carries the same correlation and RFC reply headers.
## Related
diff --git a/crates/email_api_client/src/outbound/outlook/drafts.rs b/crates/email_api_client/src/outbound/outlook/drafts.rs
index e7f5ba9904..e7a9bb9b31 100644
--- a/crates/email_api_client/src/outbound/outlook/drafts.rs
+++ b/crates/email_api_client/src/outbound/outlook/drafts.rs
@@ -237,15 +237,38 @@ impl MailboxDraftClient for OutlookApiClientRepository {
token: &AccessToken,
request: &DraftRequest,
) -> Result<ProviderDraft, EmailApiError> {
- let (url, body) = if let Some(parent) = &request.reply_to {
- (
- self.endpoint(&["me", "messages", parent.as_str(), "createReply"])?,
- json!({"message":draft_body(request)?}),
- )
- } else {
- (self.endpoint(&["me", "messages"])?, draft_body(request)?)
+ let body = draft_body(request)?;
+ let standalone = self.endpoint(&["me", "messages"])?;
+ let response = match &request.reply_to {
+ Some(parent) => {
+ let url = self.endpoint(&["me", "messages", parent.as_str(), "createReply"])?;
+ let reply = json!({"message": &body});
+ match self
+ .graph_request(token, Method::POST, url, Some(&reply), None)
+ .await
+ {
+ Ok(response) => response,
+ // Graph refuses native replies to some parent items. The standalone
+ // draft still carries the RFC reply headers that thread it.
+ Err(failure)
+ if failure.status == Some(StatusCode::BAD_REQUEST)
+ && failure.code.as_deref() == Some("ErrorInvalidOperation") =>
+ {
+ tracing::warn!(
+ graph_request_id = failure.request_id.as_deref(),
+ "Microsoft Graph refused a native reply, creating a standalone draft"
+ );
+ self.request(token, Method::POST, standalone, Some(&body))
+ .await?
+ }
+ Err(failure) => return Err(failure.error),
+ }
+ }
+ None => {
+ self.request(token, Method::POST, standalone, Some(&body))
+ .await?
+ }
};
- let response = self.request(token, Method::POST, url, Some(&body)).await?;
written_json::<Draft>(response)
.await?
.try_into()
diff --git a/crates/email_api_client/src/outbound/outlook/drafts/test.rs b/crates/email_api_client/src/outbound/outlook/drafts/test.rs
index dbd4a5c609..1fa6011889 100644
--- a/crates/email_api_client/src/outbound/outlook/drafts/test.rs
+++ b/crates/email_api_client/src/outbound/outlook/drafts/test.rs
@@ -36,6 +36,12 @@ async fn same_mailbox_replies_use_native_reply_creation_and_keep_the_correlation
Mock::given(method("POST")).and(path("/v1.0/me/messages/parent/createReply"))
.and(body_partial_json(json!({"message":{"subject":"Reply","body":{"contentType":"HTML","content":"<b>Hello</b>"}}})))
.respond_with(ResponseTemplate::new(201).set_body_json(draft())).expect(1).mount(&server).await;
+ Mock::given(method("POST"))
+ .and(path("/v1.0/me/messages"))
+ .respond_with(ResponseTemplate::new(201).set_body_json(draft()))
+ .expect(0)
+ .mount(&server)
+ .await;
api.create_draft(&token, &request).await.unwrap();
let sent: Value =
serde_json::from_slice(&server.received_requests().await.unwrap()[0].body).unwrap();
@@ -49,6 +55,122 @@ async fn same_mailbox_replies_use_native_reply_creation_and_keep_the_correlation
);
}
+#[tokio::test]
+async fn a_parent_that_refuses_native_replies_gets_a_standalone_draft_with_its_content() {
+ let (server, api, token) = setup().await;
+ let mut request = request();
+ request.reply_to = Some(ProviderId::new("parent").unwrap());
+ Mock::given(method("POST"))
+ .and(path("/v1.0/me/messages/parent/createReply"))
+ .respond_with(
+ ResponseTemplate::new(400)
+ .insert_header("request-id", "refused-reply")
+ .set_body_json(json!({"error":{"code":"ErrorInvalidOperation","message":"Item type is invalid for creating a Reply."}})),
+ )
+ .expect(1)
+ .mount(&server)
+ .await;
+ let mut standalone = draft();
+ standalone["id"] = json!("standalone");
+ Mock::given(method("POST"))
+ .and(path("/v1.0/me/messages"))
+ .and(body_partial_json(json!({
+ "subject":"Reply",
+ "body":{"contentType":"HTML","content":"<b>Hello</b>"},
+ "from":{"emailAddress":{"address":"[email protected]"}},
+ "toRecipients":[{"emailAddress":{"address":"[email protected]"}}],
+ "singleValueExtendedProperties":[
+ {"id":CORRELATION_PROPERTY,"value":request.correlation.to_string()},
+ {"id":REVISION_PROPERTY,"value":"1"},
+ {"id":"String 0x1042","value":"<[email protected]>"},
+ {"id":"String 0x1039","value":"<[email protected]>"}
+ ]
+ })))
+ .respond_with(ResponseTemplate::new(201).set_body_json(standalone))
+ .expect(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/v1.0/me/messages/standalone/attachments"))
+ .and(body_partial_json(json!({"name":"notes.txt","contentId":"[email protected]","contentBytes":"bm90ZXM="})))
+ .respond_with(ResponseTemplate::new(201).set_body_json(json!({"id":"attachment","name":"notes.txt","size":5,"contentId":"[email protected]","isInline":false})))
+ .expect(1)
+ .mount(&server)
+ .await;
+ let created = api.create_draft(&token, &request).await.unwrap();
+ assert_eq!(created.id.as_str(), "standalone");
+ api.add_attachment(
+ &token,
+ &created.id,
+ AttachmentContent {
+ name: "notes.txt",
+ content_type: "text/plain",
+ content_id: "[email protected]",
+ inline: false,
+ data: b"notes",
+ },
+ )
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn other_native_reply_failures_surface_without_a_standalone_draft() {
+ for (status, code, expected) in [
+ (
+ 429,
+ None,
+ EmailApiError::RateLimited {
+ retry_after: None,
+ origin: RateLimitOrigin::Provider { concurrency: false },
+ },
+ ),
+ (
+ 503,
+ None,
+ EmailApiError::Transient {
+ message: "Microsoft Graph returned HTTP 503".into(),
+ },
+ ),
+ (
+ 400,
+ Some("ErrorInvalidRecipients"),
+ EmailApiError::Permanent {
+ message: "Microsoft Graph returned HTTP 400".into(),
+ },
+ ),
+ (403, Some("ErrorInvalidOperation"), EmailApiError::Forbidden),
+ (
+ 401,
+ Some("InvalidAuthenticationToken"),
+ EmailApiError::AuthRequired,
+ ),
+ ] {
+ let (server, api, token) = setup().await;
+ let mut request = request();
+ request.reply_to = Some(ProviderId::new("parent").unwrap());
+ Mock::given(method("POST"))
+ .and(path("/v1.0/me/messages/parent/createReply"))
+ .respond_with(
+ ResponseTemplate::new(status).set_body_json(json!({"error":{"code":code}})),
+ )
+ .expect(1)
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/v1.0/me/messages"))
+ .respond_with(ResponseTemplate::new(201).set_body_json(draft()))
+ .expect(0)
+ .mount(&server)
+ .await;
+ assert_eq!(
+ api.create_draft(&token, &request).await.unwrap_err(),
+ expected,
+ "HTTP {status}"
+ );
+ }
+}
+
#[test]
fn reply_headers_are_bracketed_and_cannot_inject_additional_headers() {
assert_eq!(
diff --git a/crates/email_api_client/src/outbound/outlook/transport.rs b/crates/email_api_client/src/outbound/outlook/transport.rs
index 664c01083d..d65dff9b2f 100644
--- a/crates/email_api_client/src/outbound/outlook/transport.rs
+++ b/crates/email_api_client/src/outbound/outlook/transport.rs
@@ -8,6 +8,25 @@ use url::Url;
use super::{IMMUTABLE_ID_PREFERENCE, OutlookApiClientRepository};
use crate::domain::models::{AccessToken, EmailApiError, RateLimitOrigin, StreamToken};
+/// A failed Graph request with the response details a caller may branch on.
+pub(super) struct GraphFailure {
+ pub(super) error: EmailApiError,
+ pub(super) status: Option<StatusCode>,
+ pub(super) code: Option<String>,
+ pub(super) request_id: Option<String>,
+}
+
+impl From<EmailApiError> for GraphFailure {
+ fn from(error: EmailApiError) -> Self {
+ Self {
+ error,
+ status: None,
+ code: None,
+ request_id: None,
+ }
+ }
+}
+
impl OutlookApiClientRepository {
pub(super) fn endpoint(&self, segments: &[&str]) -> Result<Url, EmailApiError> {
let mut url = self.root.clone();
@@ -54,6 +73,20 @@ impl OutlookApiClientRepository {
body: Option<&Value>,
expected_version: Option<&str>,
) -> Result<Response, EmailApiError> {
+ self.graph_request(token, method, url, body, expected_version)
+ .await
+ .map_err(|failure| failure.error)
+ }
+
+ /// Like `conditional_request`, for callers that branch on the Graph error code.
+ pub(super) async fn graph_request(
+ &self,
+ token: &AccessToken,
+ method: Method,
+ url: Url,
+ body: Option<&Value>,
+ expected_version: Option<&str>,
+ ) -> Result<Response, GraphFailure> {
let refreshed = self
.refreshed_token
.lock()
@@ -81,8 +114,11 @@ impl OutlookApiClientRepository {
.rejected_token_refresh
.as_ref()
.and_then(|_| request.try_clone());
- match self.gated_request(request).await {
- Err(EmailApiError::AuthRequired) => {
+ match self.gated_graph_request(request).await {
+ Err(GraphFailure {
+ error: EmailApiError::AuthRequired,
+ ..
+ }) => {
if let (Some(refresh), Some(retry), Some(mailbox)) =
(&self.rejected_token_refresh, retry, self.mailbox)
{
@@ -101,9 +137,9 @@ impl OutlookApiClientRepository {
.map_err(|_| invalid_response())?;
authorization.set_sensitive(true);
headers.insert(reqwest::header::AUTHORIZATION, authorization);
- self.gated_request(retry.headers(headers)).await
+ self.gated_graph_request(retry.headers(headers)).await
} else {
- Err(EmailApiError::AuthRequired)
+ Err(EmailApiError::AuthRequired.into())
}
}
result => result,
@@ -115,6 +151,12 @@ impl OutlookApiClientRepository {
&self,
request: RequestBuilder,
) -> Result<Response, EmailApiError> {
+ self.gated_graph_request(request)
+ .await
+ .map_err(|failure| failure.error)
+ }
+
+ async fn gated_graph_request(&self, request: RequestBuilder) -> Result<Response, GraphFailure> {
let permit = if let Some(gate) = &self.gate {
let mailbox = self.mailbox.ok_or_else(invalid_response)?;
Some((mailbox, gate.acquire(mailbox).await?))
@@ -124,9 +166,10 @@ impl OutlookApiClientRepository {
let result = Self::send_request(request).await;
if let (Some(gate), Some((mailbox, permit))) = (&self.gate, permit) {
let retry_after = match &result {
- Err(EmailApiError::RateLimited { retry_after, .. }) => {
- Some(retry_after.unwrap_or(Duration::from_secs(30)))
- }
+ Err(GraphFailure {
+ error: EmailApiError::RateLimited { retry_after, .. },
+ ..
+ }) => Some(retry_after.unwrap_or(Duration::from_secs(30))),
_ => None,
};
gate.finish(mailbox, permit, retry_after).await;
@@ -134,7 +177,7 @@ impl OutlookApiClientRepository {
result
}
- async fn send_request(request: RequestBuilder) -> Result<Response, EmailApiError> {
+ async fn send_request(request: RequestBuilder) -> Result<Response, GraphFailure> {
let transport_failed = |_| EmailApiError::Transient {
message: "Microsoft Graph transport failed".into(),
};
@@ -181,7 +224,7 @@ impl OutlookApiClientRepository {
);
}
// Do not propagate provider messages, bodies, request URLs, or cursor tokens.
- Err(match status {
+ let error = match status {
StatusCode::UNAUTHORIZED => EmailApiError::AuthRequired,
StatusCode::FORBIDDEN => EmailApiError::Forbidden,
StatusCode::GONE => EmailApiError::OutdatedCursor,
@@ -207,6 +250,12 @@ impl OutlookApiClientRepository {
status => EmailApiError::Permanent {
message: format!("Microsoft Graph returned HTTP {}", status.as_u16()),
},
+ };
+ Err(GraphFailure {
+ error,
+ status: Some(status),
+ code: code.map(str::to_owned),
+ request_id,
})
}