Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): exclude spam and trash from all mail (#9077)
gbirman47265a039983
diff --git a/.github/workflows/android-play-release.yml b/.github/workflows/android-play-release.ymlindex a71bcf5eb8..c806cf8989 100644--- a/.github/workflows/android-play-release.yml+++ b/.github/workflows/android-play-release.yml@@ -42,12 +42,14 @@ jobs:# --- authenticated fetch ------------------------------------------------------# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base# commit, a moved PR head, GitHub's test merge commit) available. Checkouts- # here don't persist credentials, so authenticate the way actions/checkout- # does. Fails if the commit is unreachable (a force-pushed-away head).+ # may persist credentials, so clear inherited headers before supplying one+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.+ # Fails if the commit is unreachable (a force-pushed-away head).gh_fetch() {local authauth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')- git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \fetch -q --depth=1 origin "$1"}# ------------------------------------------------------------------------------@@ -339,12 +341,14 @@ jobs:# --- authenticated fetch ------------------------------------------------------# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base# commit, a moved PR head, GitHub's test merge commit) available. Checkouts- # here don't persist credentials, so authenticate the way actions/checkout- # does. Fails if the commit is unreachable (a force-pushed-away head).+ # may persist credentials, so clear inherited headers before supplying one+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.+ # Fails if the commit is unreachable (a force-pushed-away head).gh_fetch() {local authauth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')- git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \fetch -q --depth=1 origin "$1"}# ------------------------------------------------------------------------------diff --git a/.github/workflows/android-release-drift.yml b/.github/workflows/android-release-drift.ymlindex 39bec2a633..12c93834a8 100644--- a/.github/workflows/android-release-drift.yml+++ b/.github/workflows/android-release-drift.yml@@ -36,12 +36,14 @@ jobs:# --- authenticated fetch ------------------------------------------------------# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base# commit, a moved PR head, GitHub's test merge commit) available. Checkouts- # here don't persist credentials, so authenticate the way actions/checkout- # does. Fails if the commit is unreachable (a force-pushed-away head).+ # may persist credentials, so clear inherited headers before supplying one+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.+ # Fails if the commit is unreachable (a force-pushed-away head).gh_fetch() {local authauth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')- git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \fetch -q --depth=1 origin "$1"}# ------------------------------------------------------------------------------@@ -62,18 +64,14 @@ jobs:echo "No Android native changes in this push; the release stays valid."elseecho "changed=true" >> "$GITHUB_OUTPUT"- # The version code that may already be on Play is the old head's. After a- # force-push the old head is gone; the new head's code is the best guess (a- # push rarely changes it), and it keeps the Play check running — that- # check is what tells the author a stale bundle is already in production.+ # Only the verified old head identifies the version that may be on Play.+ # A force-push may also bump the version, so the new head cannot substitute.if [[ "$before" != unknown ]]; then- released=$BEFORE_SHA+ echo "version_code=$(bun scripts/android-native.mjs version-code "$BEFORE_SHA")" >> "$GITHUB_OUTPUT"else- released=$AFTER_SHA- echo "The previous head is unreachable (force-push); checking Play for the current head's version code instead."+ echo "The previous native tree could not be verified; the prior Play version and production status remain unknown."fi- echo "version_code=$(bun scripts/android-native.mjs version-code "$released")" >> "$GITHUB_OUTPUT"- echo "Android native code changed; the released bundle is stale."+ echo "Android native code changed or cannot be verified; treating the released bundle as stale."fishell: bashenv:@@ -141,8 +139,10 @@ jobs:bump='cd apps/web && just android-bump'if [[ "$PROMOTED" == "true" ]]; thenbody="🚨 Android native changes were pushed to this PR after version code ${VERSION_CODE} had already been promoted to Google Play production, so that bundle is (or is about to be) live with native code this PR no longer matches. A Play release cannot be withdrawn: bump (\`${bump}\`), commit, re-add the \`android-update\` label, and ship the follow-up as soon as possible. The label was removed."+ elif [[ "$PROMOTED" == "false" ]]; then+ body="🤖 Android native code changed after this PR's Play release started. Google Play reports that version code ${VERSION_CODE} has not been promoted to production. The \`android-update\` label was removed; any bundle on the internal track remains there for testers. Once in-progress release runs have stopped and the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."else- body="🤖 Android native code changed after this PR's Play release started, so the release was stopped: any in-progress build was cancelled and the \`android-update\` label removed. If a bundle already reached the internal track it stays there (internal testers only). When the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."+ body="⚠️ Android native code changed or could not be compared with this PR's prior release, and Google Play production status could not be verified. The prior bundle may already be in review or live. The \`android-update\` label was removed. Keep the reviewed-SHA authentication restriction and verify production status in Play Console or through a check from an approved revision. Treat the prior release as potentially live until verified."figh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body"shell: bashdiff --git a/.github/workflows/android-release-watch.yml b/.github/workflows/android-release-watch.ymlindex a3cf2f49ca..a7ca8afe05 100644--- a/.github/workflows/android-release-watch.yml+++ b/.github/workflows/android-release-watch.yml@@ -59,12 +59,14 @@ jobs:# --- authenticated fetch ------------------------------------------------------# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base# commit, a moved PR head, GitHub's test merge commit) available. Checkouts- # here don't persist credentials, so authenticate the way actions/checkout- # does. Fails if the commit is unreachable (a force-pushed-away head).+ # may persist credentials, so clear inherited headers before supplying one+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.+ # Fails if the commit is unreachable (a force-pushed-away head).gh_fetch() {local authauth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')- git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \fetch -q --depth=1 origin "$1"}# ------------------------------------------------------------------------------diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.ymlindex e0a10b4b93..4829b5101c 100644--- a/.github/workflows/web-app-check-main.yml+++ b/.github/workflows/web-app-check-main.yml@@ -136,12 +136,14 @@ jobs:# --- authenticated fetch ------------------------------------------------------# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base# commit, a moved PR head, GitHub's test merge commit) available. Checkouts- # here don't persist credentials, so authenticate the way actions/checkout- # does. Fails if the commit is unreachable (a force-pushed-away head).+ # may persist credentials, so clear inherited headers before supplying one+ # explicitly. Keep Nix build libraries out of the host Git HTTPS helper.+ # Fails if the commit is unreachable (a force-pushed-away head).gh_fetch() {local authauth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')- git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \fetch -q --depth=1 origin "$1"}# ------------------------------------------------------------------------------diff --git a/.sqlx/query-771d5c33b7cf11e4cf78990c047d9238e094c499479994e52651a746e7509689.json b/.sqlx/query-28cb329b5b45284d8b0444bdfb24fa3b21b3ea457c0a3e9997aa7e32398ffdde.jsonsimilarity index 53%rename from .sqlx/query-771d5c33b7cf11e4cf78990c047d9238e094c499479994e52651a746e7509689.jsonrename to .sqlx/query-28cb329b5b45284d8b0444bdfb24fa3b21b3ea457c0a3e9997aa7e32398ffdde.jsonindex 1f2bd64671..819adf7bbc 100644--- a/.sqlx/query-771d5c33b7cf11e4cf78990c047d9238e094c499479994e52651a746e7509689.json+++ b/.sqlx/query-28cb329b5b45284d8b0444bdfb24fa3b21b3ea457c0a3e9997aa7e32398ffdde.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH facts AS (\n SELECT m.*, f.in_inbox,f.in_trash,f.in_junk,f.in_sent,\n -- Outlook drafts composed in Macro gain a provider id once synced; their shadow row keeps them Macro drafts.\n m.is_draft AND (m.provider_id IS NULL OR EXISTS (\n SELECT 1 FROM email_mailbox_drafts d WHERE d.message_id = m.id AND NOT d.delete_requested\n )) AS macro_draft,\n EXISTS (SELECT 1 FROM email_message_recipients r WHERE r.message_id = m.id AND r.contact_id = m.from_contact_id) AS sender_is_recipient\n FROM email_messages m JOIN email_message_mailbox_facts f ON f.id = m.id\n WHERE m.thread_id = $1 AND m.link_id = $2 AND f.is_present\n ), aggregate AS (\n SELECT COALESCE(bool_or(in_inbox AND NOT in_sent),false) AS mailbox_visible,\n COALESCE(bool_or(macro_draft),false) AS has_macro_draft,\n COALESCE(bool_or(in_inbox AND NOT in_trash AND NOT in_junk),false) AS has_inbox,\n COALESCE(bool_and(is_read),true) AS is_read,\n max(internal_date_ts) FILTER (WHERE in_inbox AND NOT is_draft AND (NOT is_sent OR sender_is_recipient)) AS received_ts,\n max(updated_at) FILTER (WHERE macro_draft) AS draft_ts,\n max(internal_date_ts) FILTER (WHERE is_sent AND NOT in_trash) AS outbound_ts,\n greatest(max(internal_date_ts) FILTER (WHERE NOT in_trash AND NOT in_junk),max(updated_at) FILTER (WHERE macro_draft)) AS all_ts\n FROM facts\n ), effective AS (\n -- A Macro draft brings a thread back to the inbox only as a reply to received mail.\n SELECT a.*, a.mailbox_visible OR (t.has_received_mail AND a.has_macro_draft)\n OR (t.reminder_returned_at IS NOT NULL AND a.has_inbox) AS visible,\n greatest(a.received_ts, CASE WHEN t.has_received_mail THEN a.draft_ts END) AS inbound_ts\n FROM aggregate a JOIN email_threads t ON t.id = $1 AND t.link_id = $2\n )\n UPDATE email_threads t SET inbox_visible = a.visible,is_read = a.is_read,\n latest_inbound_message_ts = a.inbound_ts,latest_outbound_message_ts = a.outbound_ts,\n latest_non_spam_message_ts = a.all_ts,updated_at = now()\n FROM effective a WHERE t.id = $1 AND t.link_id = $2\n AND (t.inbox_visible,t.is_read,t.latest_inbound_message_ts,t.latest_outbound_message_ts,t.latest_non_spam_message_ts)\n IS DISTINCT FROM (a.visible,a.is_read,a.inbound_ts,a.outbound_ts,a.all_ts)\n ",+ "query": "\n WITH facts AS (\n SELECT m.*, f.in_inbox,f.in_trash,f.in_junk,f.in_sent,\n -- Outlook drafts composed in Macro gain a provider id once synced; their shadow row keeps them Macro drafts.\n m.is_draft AND (m.provider_id IS NULL OR EXISTS (\n SELECT 1 FROM email_mailbox_drafts d WHERE d.message_id = m.id AND NOT d.delete_requested\n )) AS macro_draft,\n EXISTS (SELECT 1 FROM email_message_recipients r WHERE r.message_id = m.id AND r.contact_id = m.from_contact_id) AS sender_is_recipient\n FROM email_messages m JOIN email_message_mailbox_facts f ON f.id = m.id\n WHERE m.thread_id = $1 AND m.link_id = $2 AND f.is_present\n ), aggregate AS (\n SELECT COALESCE(bool_or(in_inbox AND NOT in_sent),false) AS mailbox_visible,\n COALESCE(bool_or(macro_draft),false) AS has_macro_draft,\n COALESCE(bool_or(in_inbox AND NOT in_trash AND NOT in_junk),false) AS has_inbox,\n COALESCE(bool_and(is_read),true) AS is_read,\n max(internal_date_ts) FILTER (WHERE in_inbox AND NOT is_draft AND (NOT is_sent OR sender_is_recipient)) AS received_ts,\n max(updated_at) FILTER (WHERE macro_draft) AS draft_ts,\n max(internal_date_ts) FILTER (WHERE is_sent AND NOT in_trash) AS outbound_ts,\n greatest(max(COALESCE(internal_date_ts, CASE WHEN is_draft THEN created_at END)) FILTER (WHERE NOT in_trash AND NOT in_junk),max(updated_at) FILTER (WHERE macro_draft AND NOT in_trash AND NOT in_junk)) AS all_ts\n FROM facts\n ), effective AS (\n -- A Macro draft brings a thread back to the inbox only as a reply to received mail.\n SELECT a.*, a.mailbox_visible OR (t.has_received_mail AND a.has_macro_draft)\n OR (t.reminder_returned_at IS NOT NULL AND a.has_inbox) AS visible,\n greatest(a.received_ts, CASE WHEN t.has_received_mail THEN a.draft_ts END) AS inbound_ts\n FROM aggregate a JOIN email_threads t ON t.id = $1 AND t.link_id = $2\n )\n UPDATE email_threads t SET inbox_visible = a.visible,is_read = a.is_read,\n latest_inbound_message_ts = a.inbound_ts,latest_outbound_message_ts = a.outbound_ts,\n latest_non_spam_message_ts = a.all_ts,updated_at = now()\n FROM effective a WHERE t.id = $1 AND t.link_id = $2\n AND (t.inbox_visible,t.is_read,t.latest_inbound_message_ts,t.latest_outbound_message_ts,t.latest_non_spam_message_ts)\n IS DISTINCT FROM (a.visible,a.is_read,a.inbound_ts,a.outbound_ts,a.all_ts)\n ","describe": {"columns": [],"parameters": {@@ -11,5 +11,5 @@},"nullable": []},- "hash": "771d5c33b7cf11e4cf78990c047d9238e094c499479994e52651a746e7509689"+ "hash": "28cb329b5b45284d8b0444bdfb24fa3b21b3ea457c0a3e9997aa7e32398ffdde"}diff --git a/.sqlx/query-403198c6f81508920f70613d82636d5801f53a6071a14b6e0d190466ff2ba750.json b/.sqlx/query-403198c6f81508920f70613d82636d5801f53a6071a14b6e0d190466ff2ba750.jsondeleted file mode 100644index af653e28db..0000000000--- a/.sqlx/query-403198c6f81508920f70613d82636d5801f53a6071a14b6e0d190466ff2ba750.json+++ /dev/null@@ -1,134 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n t.id,\n t.provider_id,\n t.inbox_visible,\n t.is_read,\n t.is_signal,\n t.effective_ts AS \"sort_ts!\",\n t.created_at AS \"created_at!\",\n t.updated_at AS \"updated_at!\",\n t.project_id,\n t.viewed_at AS \"viewed_at?\",\n lmp.subject AS \"name?\",\n lmp.snippet AS \"snippet?\",\n lmp.is_draft,\n EXISTS (\n SELECT 1\n FROM email_messages m_imp\n JOIN email_message_mailbox_facts mf ON mf.id = m_imp.id\n WHERE m_imp.thread_id = t.id AND mf.is_present AND NOT mf.in_trash AND mf.provider_is_important\n ) AS \"is_important!\",\n c.email_address AS \"sender_email?\",\n COALESCE(lmp.from_name, c.name) AS \"sender_name?\",\n c.sfs_photo_url as \"sender_photo_url?\",\n el.macro_id AS \"owner_id!\",\n el.id AS \"link_id!\"\n FROM (\n -- Step 1: Efficiently find, sort, and limit the top N+1 threads.\n -- This subquery only touches `threads` and `user_history`, making it very fast.\n SELECT\n t.id,\n t.provider_id,\n t.link_id,\n t.inbox_visible,\n t.is_read,\n t.is_signal,\n t.project_id,\n t.latest_non_spam_message_ts AS created_at,\n t.latest_non_spam_message_ts AS updated_at,\n uh.updated_at AS viewed_at,\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END AS effective_ts\n FROM email_threads t\n LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id\n WHERE\n t.link_id = ANY($1)\n AND t.latest_non_spam_message_ts IS NOT NULL\n\n -- Cursor logic is moved inside for maximum efficiency\n AND (($3::timestamptz IS NULL) OR (\n -- This CASE must exactly match the one that defines `effective_ts`\n CASE $5 -- sort_method_str\n WHEN 'viewed_at' THEN COALESCE(uh.\"updated_at\", '1970-01-01 00:00:00+00')\n WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)\n ELSE t.latest_non_spam_message_ts\n END, t.id\n ) < ($3::timestamptz, $4::uuid))\n ORDER BY effective_ts DESC, t.updated_at DESC\n LIMIT $2\n ) AS t\n -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.\n CROSS JOIN LATERAL (\n SELECT\n m.subject,\n m.snippet,\n m.is_draft,\n m.from_contact_id,\n m.from_name\n FROM email_messages m\n WHERE m.thread_id = t.id\n AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_junk)\n AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash)\n ORDER BY m.internal_date_ts DESC\n LIMIT 1\n ) AS lmp\n -- Step 3: Join to get the sender's details for the final result set.\n LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id\n JOIN email_links el ON t.link_id = el.id\n ORDER BY t.effective_ts DESC, t.updated_at DESC\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "provider_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "inbox_visible",- "type_info": "Bool"- },- {- "ordinal": 3,- "name": "is_read",- "type_info": "Bool"- },- {- "ordinal": 4,- "name": "is_signal",- "type_info": "Bool"- },- {- "ordinal": 5,- "name": "sort_ts!",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "created_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "updated_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "project_id",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "viewed_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 10,- "name": "name?",- "type_info": "Text"- },- {- "ordinal": 11,- "name": "snippet?",- "type_info": "Text"- },- {- "ordinal": 12,- "name": "is_draft",- "type_info": "Bool"- },- {- "ordinal": 13,- "name": "is_important!",- "type_info": "Bool"- },- {- "ordinal": 14,- "name": "sender_email?",- "type_info": "Varchar"- },- {- "ordinal": 15,- "name": "sender_name?",- "type_info": "Varchar"- },- {- "ordinal": 16,- "name": "sender_photo_url?",- "type_info": "Text"- },- {- "ordinal": 17,- "name": "owner_id!",- "type_info": "Text"- },- {- "ordinal": 18,- "name": "link_id!",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "UuidArray",- "Int8",- "Timestamptz",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- false,- false,- null,- true,- true,- true,- false,- true,- true,- false,- null,- false,- null,- true,- false,- false- ]- },- "hash": "403198c6f81508920f70613d82636d5801f53a6071a14b6e0d190466ff2ba750"-}diff --git a/.sqlx/query-70cee10f9cf6e3f2b7aa171670924806e84d4c37e89259e2ed0fb60ec379bf9d.json b/.sqlx/query-70cee10f9cf6e3f2b7aa171670924806e84d4c37e89259e2ed0fb60ec379bf9d.jsonnew file mode 100644index 0000000000..3216134bda--- /dev/null+++ b/.sqlx/query-70cee10f9cf6e3f2b7aa171670924806e84d4c37e89259e2ed0fb60ec379bf9d.json@@ -0,0 +1,72 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH message_facts AS (\n SELECT m.id, m.thread_id, m.is_draft, m.is_read,\n draft.macro_draft,\n ((facts.in_inbox AND NOT facts.in_sent)\n OR (draft.macro_draft AND thread.has_received_mail)) AS inbox_visible,\n NOT facts.in_trash\n AND LOWER(SPLIT_PART(c.email_address, '@', 2)) IS DISTINCT FROM $3\n AND (\n rules.address_true OR (rules.domain_true AND NOT rules.address_false)\n OR (NOT (rules.address_false OR (rules.domain_false AND NOT rules.address_true))\n AND facts.provider_is_primary)\n ) AS is_signal,\n (EXISTS (SELECT 1 FROM email_attachments a WHERE a.message_id = m.id\n AND (a.filename ILIKE '%.ics' OR a.mime_type IN ('text/calendar','application/ics'))\n ) OR EXISTS (\n SELECT 1 FROM email_message_calendar_invites i WHERE i.message_id = m.id\n )) AS has_calendar_attachment,\n GREATEST(\n CASE WHEN facts.in_inbox AND NOT m.is_draft AND (\n NOT m.is_sent OR EXISTS (\n SELECT 1 FROM email_message_recipients r\n WHERE r.message_id = m.id AND r.contact_id = m.from_contact_id\n )) THEN m.internal_date_ts END,\n CASE WHEN draft.macro_draft AND thread.has_received_mail THEN m.updated_at END\n ) AS inbound_ts,\n GREATEST(\n CASE WHEN NOT (facts.in_junk OR facts.in_trash) THEN COALESCE(m.internal_date_ts, CASE WHEN m.is_draft THEN m.created_at END) END,\n CASE WHEN draft.macro_draft AND NOT (facts.in_junk OR facts.in_trash) THEN m.updated_at END\n ) AS all_ts,\n CASE WHEN m.is_sent AND NOT facts.in_trash THEN m.internal_date_ts END AS sent_ts,\n CASE WHEN NOT facts.in_trash AND (m.is_draft OR NOT facts.in_junk) THEN COALESCE(m.internal_date_ts, m.created_at) END AS preview_ts,\n CASE WHEN NOT facts.in_trash AND (m.is_draft OR NOT facts.in_junk) THEN jsonb_build_object(\n 'id', m.id, 'subject', m.subject, 'snippet', m.snippet, 'is_draft', m.is_draft,\n 'sender_email', c.email_address, 'sender_name', COALESCE(m.from_name, c.name), 'sender_photo_url', c.sfs_photo_url\n ) END AS preview\n FROM email_messages m\n JOIN email_threads thread ON thread.id = m.thread_id\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n JOIN email_message_mailbox_facts facts ON facts.id = m.id\n CROSS JOIN LATERAL (\n SELECT m.is_draft AND (m.provider_id IS NULL OR EXISTS (\n SELECT 1 FROM email_mailbox_drafts d WHERE d.message_id = m.id AND NOT d.delete_requested\n )) AS macro_draft\n ) draft\n CROSS JOIN LATERAL (\n SELECT COALESCE(bool_or(f.is_important) FILTER (WHERE LOWER(f.email_address) = LOWER(c.email_address)), false) AS address_true,\n COALESCE(bool_or(NOT f.is_important) FILTER (WHERE LOWER(f.email_address) = LOWER(c.email_address)), false) AS address_false,\n COALESCE(bool_or(f.is_important) FILTER (WHERE LOWER(f.email_domain) = LOWER(SPLIT_PART(c.email_address, '@', 2))), false) AS domain_true,\n COALESCE(bool_or(NOT f.is_important) FILTER (WHERE LOWER(f.email_domain) = LOWER(SPLIT_PART(c.email_address, '@', 2))), false) AS domain_false\n FROM email_filters f WHERE f.link_id = m.link_id\n ) rules\n WHERE m.thread_id = ANY($1) AND facts.is_present\n ), draft_states AS (\n SELECT thread_id, jsonb_build_object(\n 'baseline', jsonb_build_object(\n 'message_count', count(*) FILTER (WHERE NOT is_draft),\n 'inbox_visible', COALESCE(bool_or(inbox_visible) FILTER (WHERE NOT is_draft), false),\n 'is_read', COALESCE(bool_and(is_read) FILTER (WHERE NOT is_draft), true),\n 'is_signal', COALESCE(bool_or(is_signal) FILTER (WHERE NOT is_draft), false),\n 'has_calendar_attachment', COALESCE(bool_or(has_calendar_attachment) FILTER (WHERE NOT is_draft), false),\n 'latest_inbound_message_ts', max(inbound_ts) FILTER (WHERE NOT is_draft),\n 'latest_non_spam_message_ts', max(all_ts) FILTER (WHERE NOT is_draft),\n 'latest_outbound_message_ts', max(sent_ts) FILTER (WHERE NOT is_draft),\n 'preview', (array_agg(preview ORDER BY preview_ts DESC, id DESC) FILTER (WHERE NOT is_draft AND preview IS NOT NULL))[1],\n 'preview_ts', max(preview_ts) FILTER (WHERE NOT is_draft)\n ),\n 'drafts', COALESCE(jsonb_agg(jsonb_build_object(\n 'id', id, 'macro_draft', macro_draft, 'facts', jsonb_build_object(\n 'message_count', 1, 'inbox_visible', inbox_visible, 'is_read', is_read,\n 'is_signal', is_signal, 'has_calendar_attachment', has_calendar_attachment,\n 'latest_inbound_message_ts', inbound_ts, 'latest_non_spam_message_ts', all_ts,\n 'latest_outbound_message_ts', sent_ts, 'preview', preview, 'preview_ts', preview_ts\n )\n ) ORDER BY id) FILTER (WHERE is_draft), '[]'::jsonb)\n ) AS state FROM message_facts GROUP BY thread_id\n )\n SELECT t.id AS \"thread_id!\", ds.state AS \"draft_state?: Json<EmailThreadDraftState>\",\n t.latest_non_spam_message_ts, t.latest_outbound_message_ts,\n t.has_calendar_attachment,\n EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = t.id AND ea.entity_type = 'email_thread'\n AND (ea.source_id = $2\n OR ea.source_id IN (SELECT team_id::text FROM team_user WHERE user_id = $2)\n OR ea.source_id IN (SELECT cp.channel_id::text FROM comms_channel_participants cp\n WHERE cp.user_id = $2 AND cp.left_at IS NULL))\n ) AS \"has_thread_share!\",\n CASE WHEN am.id IS NOT NULL THEN jsonb_build_object(\n 'id', am.id, 'subject', am.subject, 'snippet', am.snippet, 'is_draft', am.is_draft,\n 'sender_email', ac.email_address, 'sender_name', COALESCE(am.from_name, ac.name), 'sender_photo_url', ac.sfs_photo_url\n ) END AS \"all_preview?: Json<EmailPreview>\",\n CASE WHEN dm.id IS NOT NULL THEN jsonb_build_object(\n 'id', dm.id, 'subject', dm.subject, 'snippet', dm.snippet, 'is_draft', dm.is_draft,\n 'sender_email', dc.email_address, 'sender_name', COALESCE(dm.from_name, dc.name), 'sender_photo_url', dc.sfs_photo_url\n ) END AS \"draft_preview?: Json<EmailPreview>\",\n CASE WHEN sm.id IS NOT NULL THEN jsonb_build_object(\n 'id', sm.id, 'subject', sm.subject, 'snippet', sm.snippet, 'is_draft', sm.is_draft,\n 'sender_email', sc.email_address, 'sender_name', COALESCE(sm.from_name, sc.name), 'sender_photo_url', sc.sfs_photo_url\n ) END AS \"sent_preview?: Json<EmailPreview>\"\n FROM email_threads t\n LEFT JOIN draft_states ds ON ds.thread_id = t.id\n LEFT JOIN LATERAL (\n SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name\n FROM email_messages m WHERE m.thread_id = t.id AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash AND NOT mf.in_junk) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1\n ) am ON TRUE\n LEFT JOIN email_contacts ac ON ac.id = am.from_contact_id\n LEFT JOIN LATERAL (\n SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name\n FROM email_messages m WHERE m.thread_id = t.id AND m.is_draft AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1\n ) dm ON TRUE\n LEFT JOIN email_contacts dc ON dc.id = dm.from_contact_id\n LEFT JOIN LATERAL (\n SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name\n FROM email_messages m WHERE m.thread_id = t.id AND m.is_sent AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1\n ) sm ON TRUE\n LEFT JOIN email_contacts sc ON sc.id = sm.from_contact_id\n WHERE t.id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "draft_state?: Json<EmailThreadDraftState>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 2,+ "name": "latest_non_spam_message_ts",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 3,+ "name": "latest_outbound_message_ts",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 4,+ "name": "has_calendar_attachment",+ "type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "has_thread_share!",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "all_preview?: Json<EmailPreview>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 7,+ "name": "draft_preview?: Json<EmailPreview>",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 8,+ "name": "sent_preview?: Json<EmailPreview>",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ null,+ true,+ true,+ false,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "70cee10f9cf6e3f2b7aa171670924806e84d4c37e89259e2ed0fb60ec379bf9d"+}diff --git a/.sqlx/query-eba1b3c051a9a314d874e42dd23b42abb5b2f9a4a49025139e7371496a3462d4.json b/.sqlx/query-eba1b3c051a9a314d874e42dd23b42abb5b2f9a4a49025139e7371496a3462d4.jsondeleted file mode 100644index 803654045b..0000000000--- a/.sqlx/query-eba1b3c051a9a314d874e42dd23b42abb5b2f9a4a49025139e7371496a3462d4.json+++ /dev/null@@ -1,72 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH message_facts AS (\n SELECT m.id, m.thread_id, m.is_draft, m.is_read,\n draft.macro_draft,\n ((facts.in_inbox AND NOT facts.in_sent)\n OR (draft.macro_draft AND thread.has_received_mail)) AS inbox_visible,\n NOT facts.in_trash\n AND LOWER(SPLIT_PART(c.email_address, '@', 2)) IS DISTINCT FROM $3\n AND (\n rules.address_true OR (rules.domain_true AND NOT rules.address_false)\n OR (NOT (rules.address_false OR (rules.domain_false AND NOT rules.address_true))\n AND facts.provider_is_primary)\n ) AS is_signal,\n (EXISTS (SELECT 1 FROM email_attachments a WHERE a.message_id = m.id\n AND (a.filename ILIKE '%.ics' OR a.mime_type IN ('text/calendar','application/ics'))\n ) OR EXISTS (\n SELECT 1 FROM email_message_calendar_invites i WHERE i.message_id = m.id\n )) AS has_calendar_attachment,\n GREATEST(\n CASE WHEN facts.in_inbox AND NOT m.is_draft AND (\n NOT m.is_sent OR EXISTS (\n SELECT 1 FROM email_message_recipients r\n WHERE r.message_id = m.id AND r.contact_id = m.from_contact_id\n )) THEN m.internal_date_ts END,\n CASE WHEN draft.macro_draft AND thread.has_received_mail THEN m.updated_at END\n ) AS inbound_ts,\n GREATEST(\n CASE WHEN NOT (facts.in_junk OR facts.in_trash) THEN m.internal_date_ts END,\n CASE WHEN draft.macro_draft THEN m.updated_at END\n ) AS all_ts,\n CASE WHEN m.is_sent AND NOT facts.in_trash THEN m.internal_date_ts END AS sent_ts,\n CASE WHEN NOT facts.in_trash THEN COALESCE(m.internal_date_ts, m.created_at) END AS preview_ts,\n CASE WHEN NOT facts.in_trash THEN jsonb_build_object(\n 'id', m.id, 'subject', m.subject, 'snippet', m.snippet, 'is_draft', m.is_draft,\n 'sender_email', c.email_address, 'sender_name', COALESCE(m.from_name, c.name), 'sender_photo_url', c.sfs_photo_url\n ) END AS preview\n FROM email_messages m\n JOIN email_threads thread ON thread.id = m.thread_id\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n JOIN email_message_mailbox_facts facts ON facts.id = m.id\n CROSS JOIN LATERAL (\n SELECT m.is_draft AND (m.provider_id IS NULL OR EXISTS (\n SELECT 1 FROM email_mailbox_drafts d WHERE d.message_id = m.id AND NOT d.delete_requested\n )) AS macro_draft\n ) draft\n CROSS JOIN LATERAL (\n SELECT COALESCE(bool_or(f.is_important) FILTER (WHERE LOWER(f.email_address) = LOWER(c.email_address)), false) AS address_true,\n COALESCE(bool_or(NOT f.is_important) FILTER (WHERE LOWER(f.email_address) = LOWER(c.email_address)), false) AS address_false,\n COALESCE(bool_or(f.is_important) FILTER (WHERE LOWER(f.email_domain) = LOWER(SPLIT_PART(c.email_address, '@', 2))), false) AS domain_true,\n COALESCE(bool_or(NOT f.is_important) FILTER (WHERE LOWER(f.email_domain) = LOWER(SPLIT_PART(c.email_address, '@', 2))), false) AS domain_false\n FROM email_filters f WHERE f.link_id = m.link_id\n ) rules\n WHERE m.thread_id = ANY($1) AND facts.is_present\n ), draft_states AS (\n SELECT thread_id, jsonb_build_object(\n 'baseline', jsonb_build_object(\n 'message_count', count(*) FILTER (WHERE NOT is_draft),\n 'inbox_visible', COALESCE(bool_or(inbox_visible) FILTER (WHERE NOT is_draft), false),\n 'is_read', COALESCE(bool_and(is_read) FILTER (WHERE NOT is_draft), true),\n 'is_signal', COALESCE(bool_or(is_signal) FILTER (WHERE NOT is_draft), false),\n 'has_calendar_attachment', COALESCE(bool_or(has_calendar_attachment) FILTER (WHERE NOT is_draft), false),\n 'latest_inbound_message_ts', max(inbound_ts) FILTER (WHERE NOT is_draft),\n 'latest_non_spam_message_ts', max(all_ts) FILTER (WHERE NOT is_draft),\n 'latest_outbound_message_ts', max(sent_ts) FILTER (WHERE NOT is_draft),\n 'preview', (array_agg(preview ORDER BY preview_ts DESC, id DESC) FILTER (WHERE NOT is_draft AND preview IS NOT NULL))[1],\n 'preview_ts', max(preview_ts) FILTER (WHERE NOT is_draft)\n ),\n 'drafts', COALESCE(jsonb_agg(jsonb_build_object(\n 'id', id, 'macro_draft', macro_draft, 'facts', jsonb_build_object(\n 'message_count', 1, 'inbox_visible', inbox_visible, 'is_read', is_read,\n 'is_signal', is_signal, 'has_calendar_attachment', has_calendar_attachment,\n 'latest_inbound_message_ts', inbound_ts, 'latest_non_spam_message_ts', all_ts,\n 'latest_outbound_message_ts', sent_ts, 'preview', preview, 'preview_ts', preview_ts\n )\n ) ORDER BY id) FILTER (WHERE is_draft), '[]'::jsonb)\n ) AS state FROM message_facts GROUP BY thread_id\n )\n SELECT t.id AS \"thread_id!\", ds.state AS \"draft_state?: Json<EmailThreadDraftState>\",\n t.latest_non_spam_message_ts, t.latest_outbound_message_ts,\n t.has_calendar_attachment,\n EXISTS (SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = t.id AND ea.entity_type = 'email_thread'\n AND (ea.source_id = $2\n OR ea.source_id IN (SELECT team_id::text FROM team_user WHERE user_id = $2)\n OR ea.source_id IN (SELECT cp.channel_id::text FROM comms_channel_participants cp\n WHERE cp.user_id = $2 AND cp.left_at IS NULL))\n ) AS \"has_thread_share!\",\n CASE WHEN am.id IS NOT NULL THEN jsonb_build_object(\n 'id', am.id, 'subject', am.subject, 'snippet', am.snippet, 'is_draft', am.is_draft,\n 'sender_email', ac.email_address, 'sender_name', COALESCE(am.from_name, ac.name), 'sender_photo_url', ac.sfs_photo_url\n ) END AS \"all_preview?: Json<EmailPreview>\",\n CASE WHEN dm.id IS NOT NULL THEN jsonb_build_object(\n 'id', dm.id, 'subject', dm.subject, 'snippet', dm.snippet, 'is_draft', dm.is_draft,\n 'sender_email', dc.email_address, 'sender_name', COALESCE(dm.from_name, dc.name), 'sender_photo_url', dc.sfs_photo_url\n ) END AS \"draft_preview?: Json<EmailPreview>\",\n CASE WHEN sm.id IS NOT NULL THEN jsonb_build_object(\n 'id', sm.id, 'subject', sm.subject, 'snippet', sm.snippet, 'is_draft', sm.is_draft,\n 'sender_email', sc.email_address, 'sender_name', COALESCE(sm.from_name, sc.name), 'sender_photo_url', sc.sfs_photo_url\n ) END AS \"sent_preview?: Json<EmailPreview>\"\n FROM email_threads t\n LEFT JOIN draft_states ds ON ds.thread_id = t.id\n LEFT JOIN LATERAL (\n SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name\n FROM email_messages m WHERE m.thread_id = t.id AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1\n ) am ON TRUE\n LEFT JOIN email_contacts ac ON ac.id = am.from_contact_id\n LEFT JOIN LATERAL (\n SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name\n FROM email_messages m WHERE m.thread_id = t.id AND m.is_draft AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1\n ) dm ON TRUE\n LEFT JOIN email_contacts dc ON dc.id = dm.from_contact_id\n LEFT JOIN LATERAL (\n SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name\n FROM email_messages m WHERE m.thread_id = t.id AND m.is_sent AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1\n ) sm ON TRUE\n LEFT JOIN email_contacts sc ON sc.id = sm.from_contact_id\n WHERE t.id = ANY($1)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "thread_id!",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "draft_state?: Json<EmailThreadDraftState>",- "type_info": "Jsonb"- },- {- "ordinal": 2,- "name": "latest_non_spam_message_ts",- "type_info": "Timestamptz"- },- {- "ordinal": 3,- "name": "latest_outbound_message_ts",- "type_info": "Timestamptz"- },- {- "ordinal": 4,- "name": "has_calendar_attachment",- "type_info": "Bool"- },- {- "ordinal": 5,- "name": "has_thread_share!",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "all_preview?: Json<EmailPreview>",- "type_info": "Jsonb"- },- {- "ordinal": 7,- "name": "draft_preview?: Json<EmailPreview>",- "type_info": "Jsonb"- },- {- "ordinal": 8,- "name": "sent_preview?: Json<EmailPreview>",- "type_info": "Jsonb"- }- ],- "parameters": {- "Left": [- "UuidArray",- "Text",- "Text"- ]- },- "nullable": [- false,- null,- true,- true,- false,- null,- null,- null,- null- ]- },- "hash": "eba1b3c051a9a314d874e42dd23b42abb5b2f9a4a49025139e7371496a3462d4"-}diff --git a/Cargo.lock b/Cargo.lockindex 48b96ae220..8e08f3646e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3716,7 +3716,7 @@ dependencies = [[[package]]name = "cache-wasm"-version = "0.6.52"+version = "0.6.53"dependencies = ["async-lock","cache-core",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex fdabc18f72..ef55138bd6 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -309,6 +309,10 @@ the user's newest account for that app from the last fifteen minutes.- Keep model picker triggers bounded with full-name title tooltips; wrap model names in catalog rows, including effort submenus and touch sheets.+- All Mail previews exclude spam/junk and trash. Keep draft edits from restoring+ an excluded preview or timestamp, including synced Macro drafts; Drafts and+ Sent retain their own canonical membership.+Agent split headers show live viewers through `BlockLiveIndicators` with theresolved session ID; keep the existing `AgentSessionProvider` subscription to`agent_session` rather than enabling legacy block tracking of placeholder IDs.@@ -853,3 +857,6 @@ The backend-free browser regression isUse `features/channel/channel-icon.tsx` for conversation identity in rows,favorites, and headers: channel pictures or hashtags, human/self-DM avatars,and bot personas share one renderer; keep surface sizing in the caller.++- Advertise Mail v5 capsules only for the current browser engine or a verified supported installed native build; OTA bundle version alone cannot establish native capability.+- Bound native Mail capability discovery to 1.5 seconds and cache the legacy profile on failure or timeout so stalled IPC cannot block GraphQL transport; record the selected profile and bounded outcome in HTTP and WebSocket setup spans without error text.diff --git a/apps/web/min-native-build.json b/apps/web/min-native-build.jsonindex 9922767e44..d6897d693d 100644--- a/apps/web/min-native-build.json+++ b/apps/web/min-native-build.json@@ -1,4 +1,4 @@{"android": 1,- "ios": 192+ "ios": 194}diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-capsules.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-capsules.tsindex 3cb9546f7e..f0fda06400 100644--- a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-capsules.ts+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-capsules.ts@@ -1,78 +1,78 @@// Generated from the canonical Rust Soup projection wire encoder.export const mailProjectionCapsules: readonly string[] = [- 'Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEFZW1haWwBgIDZ276wlQYAAAE',- 'Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDIFZW1haWwBgIDZ276wlQYAAAA',- 'Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDMFZW1haWwBgIDZ276wlQYAAAA',- 'Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDQFZW1haWwBgIDZ276wlQYAAAA',- 'Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwM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zb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwNzAFZW1haWwBgIDZ276wlQYAAQA',+ 'Awxzb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwNzEFZW1haWwBgIDZ276wlQYAAAE',+ 'Awxzb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwNzIFZW1haWwBgIDZ276wlQYBgIDjoLemlQYAAQ',+ 'Awxzb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwNzMFZW1haWwBgIDZ276wlQYAAAE',+ 'Awxzb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwNzQFZW1haWwBgIDZ276wlQYAAAE',+ 'Awxzb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwNzUFZW1haWwBgIDZ276wlQYAAQA',];diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-harness.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-harness.tsindex 595c57c61a..c4ee2f7a70 100644--- a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-harness.ts+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection-harness.ts@@ -544,7 +544,11 @@ await host.writeQuery({properties: [],isFavorited: false,mailAllPreview:- n === 7 ? null : preview(n + 10000, `Email ${n}`, false),+ n === 7 ||+ (new URLSearchParams(location.search).has('excluded-mail') &&+ (n === 68 || n === 69))+ ? null+ : preview(n + 10000, `Email ${n}`, false),mailDraftPreview:n % 3 === 0 && n !== 7? preview(n + 20000, `Draft ${n}`, true)diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection.browser.e2e.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection.browser.e2e.tsindex b8dc5778f9..d70eed5f40 100644--- a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection.browser.e2e.ts+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-projection.browser.e2e.ts@@ -297,13 +297,12 @@ test('a new offline draft reaches Drafts and reopens through another cache clien);await context.setOffline(true);try {- await page- .getByRole('combobox', { name: 'View', exact: true })- .selectOption('DRAFTS');+ const view = page.getByRole('combobox', { name: 'View', exact: true });+ await view.selectOption('DRAFTS');await page.getByRole('button', { name: 'Create offline draft' }).click();await expect(page.locator('#draft-status')).toHaveText('Draft queued');await expect(page.locator('#rows li').first()).toHaveText(- 'Offline standalone — Not Done'+ 'Offline standalone — Done');await page.getByRole('button', { name: 'Reopen cached draft' }).click();await expect(page.locator('#draft-status')).toContainText(@@ -314,7 +313,15 @@ test('a new offline draft reaches Drafts and reopens through another cache clien);await expect(page.locator('#draft-status')).toContainText('"pending":true');await expect(page.locator('#rows li').first()).toHaveText(- 'Offline standalone — Not Done'+ 'Offline standalone — Done'+ );+ await view.selectOption('INBOX');+ await expect(+ page.locator('#rows li').filter({ hasText: 'Offline standalone' })+ ).toHaveCount(0);+ await view.selectOption('ALL');+ await expect(page.locator('#rows li').first()).toHaveText(+ 'Offline standalone — Done');} finally {await context.setOffline(false);diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-tabs.browser.e2e.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-tabs.browser.e2e.tsindex e7aea5f344..d9c70c9024 100644--- a/apps/web/src/lib/graphql-cache/worker/browser-test/mail-tabs.browser.e2e.ts+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/mail-tabs.browser.e2e.ts@@ -65,3 +65,30 @@ test('Drafts, Sent, Calendar and Shared use canonical metadata offline', async (await context.setOffline(false);}});++test('All Mail excludes junk snapshots while Drafts and Sent keep their own membership', async ({+ page,+ context,+}) => {+ await page.goto('/mail-projection.html?excluded-mail');+ await expect(page.locator('#result')).toHaveAttribute(+ 'data-status',+ 'ready',+ { timeout: 60_000 }+ );+ await context.setOffline(true);+ try {+ const rows = page.locator('#rows li');+ const view = page.getByRole('combobox', { name: 'View', exact: true });+ await view.selectOption('ALL');+ await expect(rows).toHaveCount(10);+ await expect(rows.filter({ hasText: /Email (68|69) / })).toHaveCount(0);+ await expect(rows.first()).toContainText('Email 70');+ await view.selectOption('DRAFTS');+ await expect(rows.first()).toContainText('Draft 69');+ await view.selectOption('SENT');+ await expect(rows.first()).toContainText('Sent 68');+ } finally {+ await context.setOffline(false);+ }+});diff --git a/apps/web/src/lib/queries/email/graphql/draft.test.ts b/apps/web/src/lib/queries/email/graphql/draft.test.tsindex 9f8670ffc8..1b7e2cc1b4 100644--- a/apps/web/src/lib/queries/email/graphql/draft.test.ts+++ b/apps/web/src/lib/queries/email/graphql/draft.test.ts@@ -493,3 +493,67 @@ it('marks a conversation read when its only unread draft is edited or discarded'expect(updateDraftThread(thread, draft, true).isRead).toBe(true);expect(removeDraftFromThread(thread, draft.id)?.isRead).toBe(true);});++it('discarding a local draft does not bring a junk provider draft into All Mail', async () => {+ const { draft, thread } = await standalone();+ const state = thread.mailDraftState!;+ const junk = {+ ...state.drafts[0],+ id: 'junk-draft',+ macroDraft: false,+ facts: {+ ...state.drafts[0].facts,+ latestNonSpamMessageTs: null,+ preview: { ...state.drafts[0].facts.preview!, id: 'junk-draft' },+ },+ };+ state.drafts.push(junk);+ const result = removeDraftFromThread(thread, draft.id)!;+ expect(result.mailAllPreview).toBeNull();+ expect(result.mailDraftPreview?.id).toBe('junk-draft');+ expect(draftThreadIsEmpty(result)).toBe(false);+});++it.each([+ { folder: 'junk', mixed: false },+ { folder: 'trash', mixed: false },+ { folder: 'junk', mixed: true },+ { folder: 'trash', mixed: true },+])(+ 'editing a synced Macro draft in $folder preserves All Mail eligibility (mixed=$mixed)',+ async ({ folder, mixed }) => {+ const { draft, thread } = await standalone();+ const state = thread.mailDraftState!;+ const entry = state.drafts[0];+ const cleanTimestamp = '2026-01-01T00:00:00Z';+ if (mixed) {+ state.baseline = {+ ...state.baseline,+ messageCount: 1,+ latestNonSpamMessageTs: cleanTimestamp,+ previewTs: cleanTimestamp,+ preview: {+ ...entry.facts.preview!,+ id: 'clean-message',+ isDraft: false,+ },+ };+ }+ entry.facts.latestNonSpamMessageTs = null;+ if (folder === 'trash') entry.facts.preview = null;+ thread.mailAllPreview = state.baseline.preview;+ thread.latestNonSpamMessageTs = state.baseline.latestNonSpamMessageTs;+ const edited = updateDraftThread(+ thread,+ { ...draft, updatedAt: '2027-01-01T00:00:00Z' },+ true+ );+ expect(edited.latestNonSpamMessageTs).toBe(mixed ? cleanTimestamp : null);+ expect(edited.mailAllPreview?.id ?? null).toBe(+ mixed ? 'clean-message' : null+ );+ expect(edited.mailDraftPreview?.id ?? null).toBe(+ folder === 'junk' ? draft.id : null+ );+ }+);diff --git a/apps/web/src/lib/queries/email/graphql/optimistic-thread.ts b/apps/web/src/lib/queries/email/graphql/optimistic-thread.tsindex ff5b21514b..7eaebce1b1 100644--- a/apps/web/src/lib/queries/email/graphql/optimistic-thread.ts+++ b/apps/web/src/lib/queries/email/graphql/optimistic-thread.ts@@ -168,6 +168,15 @@ function applyDraftState(emptyAggregate());const all = mergeAggregate(state.baseline, drafts);+ // A provider draft in junk can remain in Drafts, but cannot supply All Mail's+ // preview. Each draft's non-spam timestamp records that eligibility.+ const allPreview = state.drafts.reduce(+ (sum, entry) =>+ entry.facts.latestNonSpamMessageTs === null+ ? sum+ : mergeAggregate(sum, entry.facts),+ state.baseline+ ).preview;// Read/unread mutations can update the canonical thread before the message// aggregate is refreshed. Preserve that newer intent across draft edits;// otherwise deleting the sole unread draft still recomputes the read state.@@ -190,13 +199,13 @@ function applyDraftState(isRead: hasNewerReadIntent ? existing.isRead : all.isRead,isSignal: all.isSignal,isImportant: all.isSignal,- displayName: all.preview?.subject ?? null,- emailName: all.preview?.subject ?? null,- snippet: all.preview?.snippet ?? null,- senderEmail: all.preview?.senderEmail ?? null,- senderName: all.preview?.senderName ?? null,- senderPhotoUrl: all.preview?.senderPhotoUrl ?? null,- mailAllPreview: all.preview,+ displayName: allPreview?.subject ?? null,+ emailName: allPreview?.subject ?? null,+ snippet: allPreview?.snippet ?? null,+ senderEmail: allPreview?.senderEmail ?? null,+ senderName: allPreview?.senderName ?? null,+ senderPhotoUrl: allPreview?.senderPhotoUrl ?? null,+ mailAllPreview: allPreview,mailDraftPreview: drafts.preview,};}@@ -237,9 +246,11 @@ export function updateDraftThread(latestInboundMessageTs: previous.macroDraft? fresh.facts.latestInboundMessageTs: previous.facts.latestInboundMessageTs,- latestNonSpamMessageTs: previous.macroDraft- ? draft.updatedAt- : previous.facts.latestNonSpamMessageTs,+ latestNonSpamMessageTs:+ previous.macroDraft &&+ previous.facts.latestNonSpamMessageTs !== null+ ? draft.updatedAt+ : previous.facts.latestNonSpamMessageTs,preview: previous.facts.preview ? fresh.facts.preview : null,},}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.tsindex 09b04978f9..21b6b3cfef 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts@@ -852,6 +852,9 @@ describe('GraphQL Soup browser cache session gate', () => {expect(payload.query).toContain('cacheProjection');expect(payload.query).toContain('@include');expect(payload.variables).toEqual({ includeId: true });+ expect(+ new Headers(transport.headers).get('x-macro-mail-cache-profile')+ ).toBe('soup-mail-v5');expect(new Headers(transport.headers).get('traceparent')).toBe(mocks.traceparent);diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.tsindex 8d6706b627..1b987c0db3 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts@@ -116,6 +116,7 @@ import {shouldRetryGraphqlSoupWebSocket,waitToRetryGraphqlSoupWebSocket,} from './graphql-soup-websocket';+import { mailCacheProfile } from './mail-cache-profile';export { emailThreadSortTs } from './email-thread-sort';@@ -331,11 +332,16 @@ export async function dssGraphqlFetch(const traceHeaders: Record<string, string> = {};span.injectTraceHeaders(traceHeaders);const requestInit = graphqlSoupTransportRequest(init);+ const mail = await mailCacheProfile();+ span.setAttr('mail.cache_profile', mail.profile);+ span.setAttr('mail.cache_profile_outcome', mail.outcome);// Links this request, and a queued mutation attempt above it, to the// server's request and `graphql.execute` spans.const transportInit: RequestInit = {...requestInit,- headers: mergeHeaders(requestInit?.headers, traceHeaders),+ headers: mergeHeaders(requestInit?.headers, traceHeaders, {+ 'x-macro-mail-cache-profile': mail.profile,+ }),};span.event('request_dispatch');const response = await authorizedDssGraphqlFetch(input, transportInit);@@ -417,6 +423,13 @@ function createGraphqlSoupWebSocketClient(});return createGraphqlWsClient({url: resolveWebSocketUrl,+ connectionParams: () =>+ Telemetry.span('graphql.websocket.connection_params', async (span) => {+ const mail = await mailCacheProfile();+ span.setAttr('mail.cache_profile', mail.profile);+ span.setAttr('mail.cache_profile_outcome', mail.outcome);+ return { mailCacheProfile: mail.profile };+ }),// Session cookies live in the native HTTP client's jar, which the WebView's// own WebSocket cannot send; the native socket forwards them.webSocketImpl:diff --git a/apps/web/src/lib/service-clients/service-storage/mail-cache-profile.test.ts b/apps/web/src/lib/service-clients/service-storage/mail-cache-profile.test.tsnew file mode 100644index 0000000000..77ef985380--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/mail-cache-profile.test.ts@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ native: false,+ platform: 'ios',+ invoke: vi.fn(),+}));+vi.mock('@tauri-apps/api/core', () => ({+ isTauri: () => mocks.native,+ invoke: mocks.invoke,+}));+vi.mock('@core/util/platform', () => ({+ getNativeMobilePlatform: () => mocks.platform,+}));++describe('Mail capsule capability', () => {+ beforeEach(() => {+ vi.resetModules();+ mocks.native = false;+ mocks.platform = 'ios';+ mocks.invoke.mockReset();+ });++ afterEach(() => vi.useRealTimers());++ it('uses the current browser engine without native IPC', async () => {+ const { mailCacheProfile } = await import('./mail-cache-profile');+ expect(await mailCacheProfile()).toEqual({+ profile: 'soup-mail-v5',+ outcome: 'browser',+ });+ expect(mocks.invoke).not.toHaveBeenCalled();+ });++ it.each([+ ['ios', 191, 'soup-mail-v2', 'native_unsupported'],+ ['ios', 192, 'soup-mail-v2', 'native_unsupported'],+ ['ios', 193, 'soup-mail-v5', 'native_supported'],+ ['android', 19, 'soup-mail-v2', 'native_unsupported'],+ ['android', 20, 'soup-mail-v5', 'native_supported'],+ ['desktop', 0, 'soup-mail-v2', 'native_unsupported'],+ ['ios', undefined, 'soup-mail-v2', 'native_unsupported'],+ ])(+ 'negotiates installed %s build %s as %s',+ async (platform, nativeBuild, profile, outcome) => {+ mocks.native = true;+ mocks.platform = platform;+ mocks.invoke.mockResolvedValue({ nativeBuild });+ const { mailCacheProfile } = await import('./mail-cache-profile');+ expect(await mailCacheProfile()).toEqual({ profile, outcome });+ expect(await mailCacheProfile()).toEqual({ profile, outcome });+ expect(mocks.invoke).toHaveBeenCalledOnce();+ }+ );++ it('keeps old engines compatible when build discovery fails', async () => {+ mocks.native = true;+ mocks.invoke.mockRejectedValue(new Error('unknown command'));+ const { mailCacheProfile } = await import('./mail-cache-profile');+ expect(await mailCacheProfile()).toEqual({+ profile: 'soup-mail-v2',+ outcome: 'native_lookup_failed',+ });+ });++ it('unblocks concurrent callers and keeps the legacy profile after a timeout', async () => {+ vi.useFakeTimers();+ mocks.native = true;+ const pending = Promise.withResolvers<{ nativeBuild: number }>();+ mocks.invoke.mockReturnValue(pending.promise);+ const { mailCacheProfile } = await import('./mail-cache-profile');+ const first = mailCacheProfile();+ const second = mailCacheProfile();++ await vi.advanceTimersByTimeAsync(1500);+ expect(await first).toEqual({+ profile: 'soup-mail-v2',+ outcome: 'native_lookup_timeout',+ });+ expect(await second).toEqual({+ profile: 'soup-mail-v2',+ outcome: 'native_lookup_timeout',+ });++ pending.resolve({ nativeBuild: 193 });+ await pending.promise;+ expect(await mailCacheProfile()).toEqual({+ profile: 'soup-mail-v2',+ outcome: 'native_lookup_timeout',+ });+ expect(mocks.invoke).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/lib/service-clients/service-storage/mail-cache-profile.ts b/apps/web/src/lib/service-clients/service-storage/mail-cache-profile.tsnew file mode 100644index 0000000000..2c604df43e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/mail-cache-profile.ts@@ -0,0 +1,57 @@+import { getNativeMobilePlatform } from '@core/util/platform';+import { invoke, isTauri } from '@tauri-apps/api/core';++const CURRENT_PROFILE = 'soup-mail-v5';+const LEGACY_PROFILE = 'soup-mail-v2';++type MailCacheProfile = {+ profile: typeof CURRENT_PROFILE | typeof LEGACY_PROFILE;+ outcome:+ | 'browser'+ | 'native_supported'+ | 'native_unsupported'+ | 'native_lookup_failed'+ | 'native_lookup_timeout';+};++let nativeProfile: Promise<MailCacheProfile> | undefined;++/** Negotiate against the installed engine, including when JS arrived by OTA. */+export function mailCacheProfile(): Promise<MailCacheProfile> {+ if (!isTauri()) {+ return Promise.resolve({ profile: CURRENT_PROFILE, outcome: 'browser' });+ }+ nativeProfile ??= installedNativeProfile();+ return nativeProfile;+}++async function installedNativeProfile(): Promise<MailCacheProfile> {+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ const info = await Promise.race([+ invoke<{ nativeBuild: number }>('get_bundle_debug_info'),+ new Promise<null>((resolve) => {+ timeout = setTimeout(() => resolve(null), 1500);+ }),+ ]);+ if (info === null) {+ return { profile: LEGACY_PROFILE, outcome: 'native_lookup_timeout' };+ }+ const platform = getNativeMobilePlatform();+ const minimum =+ platform === 'ios' ? 193 : platform === 'android' ? 20 : null;+ if (+ minimum !== null &&+ Number.isInteger(info.nativeBuild) &&+ info.nativeBuild >= minimum+ ) {+ return { profile: CURRENT_PROFILE, outcome: 'native_supported' };+ }+ return { profile: LEGACY_PROFILE, outcome: 'native_unsupported' };+ } catch {+ // Older engines may not expose build information. Never infer support from JS.+ return { profile: LEGACY_PROFILE, outcome: 'native_lookup_failed' };+ } finally {+ clearTimeout(timeout);+ }+}diff --git a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.ktsindex a8cc6f2686..6a95d4984f 100644--- a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts+++ b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts@@ -104,6 +104,10 @@ android {buildFeatures {buildConfig = true}+ packaging {+ // JSpecify and OpenTelemetry both ship this OSGi metadata; Android does not use it.+ resources.excludes.add("META-INF/versions/9/OSGI-INF/MANIFEST.MF")+ }}rust {diff --git a/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plist b/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plistindex b3f14a547d..d97d52d351 100644--- a/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/NotificationServiceExtension/Info.plist@@ -17,9 +17,9 @@<key>CFBundlePackageType</key><string>XPC!</string><key>CFBundleShortVersionString</key>- <string>2.0.13</string>+ <string>2.0.15</string><key>CFBundleVersion</key>- <string>192</string>+ <string>194</string><key>NSExtension</key><dict><key>NSExtensionPointIdentifier</key>diff --git a/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plist b/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plistindex db4a60b771..cb91796768 100644--- a/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/ShareExtension/Info.plist@@ -17,9 +17,9 @@<key>CFBundlePackageType</key><string>XPC!</string><key>CFBundleShortVersionString</key>- <string>2.0.13</string>+ <string>2.0.15</string><key>CFBundleVersion</key>- <string>192</string>+ <string>194</string><key>LSApplicationQueriesSchemes</key><array><string>macro</string>diff --git a/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist b/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plistindex 7366b6c966..b78dc39329 100644--- a/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist+++ b/apps/web/tauri/src-tauri/gen/apple/app_iOS/Info.plist@@ -15,7 +15,7 @@<key>CFBundlePackageType</key><string>APPL</string><key>CFBundleShortVersionString</key>- <string>2.0.13</string>+ <string>2.0.15</string><key>CFBundleURLTypes</key><array><dict>@@ -28,7 +28,7 @@</dict></array><key>CFBundleVersion</key>- <string>192</string>+ <string>194</string><key>ITSAppUsesNonExemptEncryption</key><false/><key>LSApplicationQueriesSchemes</key>diff --git a/apps/web/tauri/src-tauri/gen/apple/project.yml b/apps/web/tauri/src-tauri/gen/apple/project.ymlindex 318d3190b2..d2bce3f603 100644--- a/apps/web/tauri/src-tauri/gen/apple/project.yml+++ b/apps/web/tauri/src-tauri/gen/apple/project.yml@@ -58,8 +58,8 @@ targets:- UIInterfaceOrientationPortraitUpsideDown- UIInterfaceOrientationLandscapeLeft- UIInterfaceOrientationLandscapeRight- CFBundleShortVersionString: 2.0.13- CFBundleVersion: "192"+ CFBundleShortVersionString: 2.0.15+ CFBundleVersion: "194"# Exempt encryption only (HTTPS / OS crypto): answers App Store# Connect's export-compliance questionnaire for every build. Keep in# sync with src-tauri/Info.ios.plist.@@ -145,8 +145,8 @@ targets:path: ShareExtension/Info.plistproperties:CFBundleDisplayName: Share to Macro- CFBundleShortVersionString: 2.0.13- CFBundleVersion: "192"+ CFBundleShortVersionString: 2.0.15+ CFBundleVersion: "194"LSApplicationQueriesSchemes:- macroNSExtension:@@ -180,8 +180,8 @@ targets:path: NotificationServiceExtension/Info.plistproperties:CFBundleDisplayName: NotificationServiceExtension- CFBundleShortVersionString: 2.0.13- CFBundleVersion: "192"+ CFBundleShortVersionString: 2.0.15+ CFBundleVersion: "194"NSExtension:NSExtensionPointIdentifier: com.apple.usernotifications.serviceNSExtensionPrincipalClass: $(PRODUCT_MODULE_NAME).NotificationServicediff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.jsonindex c193de6350..77c89ee1a8 100644--- a/apps/web/tauri/src-tauri/tauri.android.conf.json+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json@@ -2,7 +2,7 @@"version": "2.5.0","bundle": {"android": {- "versionCode": 19+ "versionCode": 20}},"$schema": "https://schema.tauri.app/config/2",diff --git a/apps/web/tauri/src-tauri/tauri.ios.conf.json b/apps/web/tauri/src-tauri/tauri.ios.conf.jsonindex 7f6dac831d..7da9452478 100644--- a/apps/web/tauri/src-tauri/tauri.ios.conf.json+++ b/apps/web/tauri/src-tauri/tauri.ios.conf.json@@ -1,9 +1,9 @@{"productName": "macro",- "version": "2.0.13",+ "version": "2.0.15","bundle": {"iOS": {- "bundleVersion": "192"+ "bundleVersion": "194"}}}diff --git a/crates/client/cache-wasm/AGENTS.md b/crates/client/cache-wasm/AGENTS.mdindex fb7e8ad288..dd1eb99b99 100644--- a/crates/client/cache-wasm/AGENTS.md+++ b/crates/client/cache-wasm/AGENTS.md@@ -49,6 +49,10 @@ wasm-bindgen shell exposing `cache-core` + `cache-turso` + `turso-opfs` as a- Pass the existing entity-filter `baseline` to Mail pagination too; `retainedKeys`tells the frontend which server rows still lack canonical local metadata.+- Mail profiles v5/v6 require the corresponding native engine for offline behavior.+ The server emits v5 only after explicit HTTP/WS capability negotiation; unadvertised+ clients receive v2 so old engines retain durable offline draft admission.+- Email send persistence and cancellation belong to the frontend email journal, not the normalized cache or its mutation queue.- The engine is guarded by an async mutex so overlapping JS calls serializediff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.tomlindex 5731e2ce55..fad64ce060 100644--- a/crates/client/cache-wasm/Cargo.toml+++ b/crates/client/cache-wasm/Cargo.toml@@ -2,8 +2,8 @@edition = "2024"name = "cache-wasm"publish = false-# Rebuild with draft link patches and compressed normalized records.-version = "0.6.52"+# Rebuild with spam-free All Mail projections and per-tab cache membership.+version = "0.6.53"[features]default = []diff --git a/crates/complete_graph/AGENTS.md b/crates/complete_graph/AGENTS.mdindex 67f909cf62..abb09ab6d9 100644--- a/crates/complete_graph/AGENTS.md+++ b/crates/complete_graph/AGENTS.md@@ -123,3 +123,5 @@ deprecation (`Remove after YYYY-MM-DD`, at least 30 days out).it; see [step 8 of the field guide](../../docs/guides/add-graphql-field.md#8-compatibility-and-rollout).Saved-view definitions live under authenticated `GraphqlUser`; mutations use the authenticated request user and a domain service from request data. Run `cargo test -p complete_graph --lib saved_view_contract` after changing the saved-view contract.++- Mail capsule negotiation lives in `mail_cache_profile`: absent/unknown capabilities receive v2; explicit `soup-mail-v5` receives current capsules. Never infer client support from the server version.diff --git a/crates/complete_graph/src/edges.rs b/crates/complete_graph/src/edges.rsindex 303cc8bd31..97f1c63db2 100644--- a/crates/complete_graph/src/edges.rs+++ b/crates/complete_graph/src/edges.rs@@ -113,7 +113,17 @@ wherelet projection = load_email_thread_mail_projection::<ER>(ctx, thread_id).await?;let facts = &projection.cache_facts;let record_key = RecordKey::new(format!("GraphqlSoupEmailThread:{thread_id}"))?;- let supplement = SoupCacheProjectionSupplement::mail(+ let build_supplement = if ctx+ .data_opt::<crate::MailCacheProfile>()+ .copied()+ .unwrap_or_default()+ .is_current()+ {+ SoupCacheProjectionSupplement::mail+ } else {+ SoupCacheProjectionSupplement::mail_legacy_v2+ };+ let supplement = build_supplement(record_key,MailCacheProjectionFacts::new(facts.latest_non_spam_message_ts.map(utc_timestamp_micros),diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rsindex 63ea743364..90c523d3de 100644--- a/crates/complete_graph/src/lib.rs+++ b/crates/complete_graph/src/lib.rs@@ -8,6 +8,7 @@/// Cross-domain fields composed onto Soup entities.mod edges;+mod mail_cache_profile;mod realtime;mod saved_view;/// Complete schema types and construction helpers.@@ -77,6 +78,7 @@ pub use graphql_work_feed::{EntityAccessWorkFeedViewers, WorkFeedGraphqlContext, WorkFeedGraphqlService,WorkFeedViewerResolver,};+pub use mail_cache_profile::{MAIL_CACHE_PROFILE_HEADER, MailCacheProfile};pub use realtime::{AgentSessionLogSubscriptions, agent_session_log_subscriptions};pub use schema::{EmailThreadInput, SchemaOnlySoupSchema, SchemaOnlyState, SharedSoupSchema, SoupQueryRoot,diff --git a/crates/complete_graph/src/mail_cache_profile.rs b/crates/complete_graph/src/mail_cache_profile.rsnew file mode 100644index 0000000000..16c3ffdfc9--- /dev/null+++ b/crates/complete_graph/src/mail_cache_profile.rs@@ -0,0 +1,28 @@+//! Request-scoped negotiation for the Mail cache capsule.++/// HTTP clients advertise the same profile as WebSocket connection-init clients.+pub const MAIL_CACHE_PROFILE_HEADER: &str = "x-macro-mail-cache-profile";++/// Only an explicit capability opts into capsules older native engines reject.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct MailCacheProfile {+ /// Whether the caller understands the spam/trash-free Mail projection.+ current: bool,+}++impl MailCacheProfile {+ /// Unknown or absent capabilities retain the deployed v2 wire contract.+ pub fn from_advertised(version: Option<&str>) -> Self {+ Self {+ current: version == Some("soup-mail-v5"),+ }+ }++ /// Whether this request may receive v5 capsules.+ pub(crate) fn is_current(self) -> bool {+ self.current+ }+}++#[cfg(test)]+mod test;diff --git a/crates/complete_graph/src/mail_cache_profile/test.rs b/crates/complete_graph/src/mail_cache_profile/test.rsnew file mode 100644index 0000000000..b5c8c617e7--- /dev/null+++ b/crates/complete_graph/src/mail_cache_profile/test.rs@@ -0,0 +1,9 @@+use super::*;++#[test]+fn only_explicit_supported_capabilities_opt_in() {+ for version in [None, Some(""), Some("soup-mail-v2"), Some("soup-mail-v6")] {+ assert!(!MailCacheProfile::from_advertised(version).is_current());+ }+ assert!(MailCacheProfile::from_advertised(Some("soup-mail-v5")).is_current());+}diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 29f7ef0bd5..97ca42c761 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -2167,6 +2167,28 @@ async fn flat_soup_emits_server_fact_supplements_for_documents_and_mail() {.unwrap());assert!(mail_supplement.mail_facts().is_some());+ assert_eq!(+ mail_supplement.target_profile().token().as_str(),+ "soup-mail-v2"+ );+ let current = harness.schema.execute(+ harness.request("{ user { soup(input: {initial: {}}) { items { __typename cacheProjection } } } }", authenticated_parts())+ .data(crate::MailCacheProfile::from_advertised(Some("soup-mail-v5")))+ ).await;+ assert!(current.errors.is_empty(), "{:?}", current.errors);+ let current = current.data.into_json().unwrap();+ let current = current["user"]["soup"]["items"]+ .as_array()+ .unwrap()+ .iter()+ .find(|item| item["__typename"] == "GraphqlSoupEmailThread")+ .unwrap();+ let current = soup_filter_projection::decode_cache_projection_supplement(+ current["cacheProjection"].as_str().unwrap(),+ )+ .unwrap();+ assert_eq!(current.target_profile().token().as_str(), "soup-mail-v5");+ assert_eq!(current.mail_facts(), mail_supplement.mail_facts());for (typename, id) in [("GraphqlSoupProject", project_id),("GraphqlSoupChat", chat_id),diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex 6668d405b6..3ec94f4fe6 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -54,6 +54,13 @@ tools — hexagonal, heavily feature-gated.## Gotchas+- All Mail excludes present messages in spam/junk or trash before pagination;+ canonical cached previews and non-draft baselines use the same rule for Gmail+ labels and Outlook mailbox facts. Mixed threads show their latest eligible message.+ Synced Macro drafts in junk/trash must not advance All Mail timestamps.+ Filtered and unfiltered All Mail share the dynamic builder and its per-inbox+ ordered, limited scans; do not add a separate whole-mailbox sort.+- Reconcile deferred message deletion before claiming scheduled work; unresolved sends retain their message, attachments, and delivery job.- Durable send admission supports Gmail and Outlook; Outlook delivery stays with its provider coordinator.- Carry the captured `draft_generation` through every draft mutation; advance it on send acceptance/cancellation under the message lock and preserve attempt tombstones after message deletion.diff --git a/crates/email/fixtures/email_all_mail.sql b/crates/email/fixtures/email_all_mail.sqlnew file mode 100644index 0000000000..238b319188--- /dev/null+++ b/crates/email/fixtures/email_all_mail.sql@@ -0,0 +1,54 @@+-- Give the layered mailbox cases their own reserved-domain owner.+INSERT INTO macro_user (id, username, email, stripe_customer_id)+VALUES ('0e000000-0000-0000-0000-000000000001', '[email protected]', '[email protected]', 'stripe_all_mail');+INSERT INTO "User" (id, email, name, macro_user_id)+VALUES ('macro|[email protected]', '[email protected]', 'Mail Fixture', '0e000000-0000-0000-0000-000000000001');+UPDATE email_links SET macro_id = 'macro|[email protected]'+WHERE id IN ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '0a000000-0000-0000-0000-000000000001');++-- Layered on email_dynamic_query and email_outlook_threads. Deliberately retain+-- stale thread timestamps for excluded messages to exercise pre-LIMIT filtering.+INSERT INTO email_labels (id, link_id, provider_label_id, name, type)+VALUES ('10000012-0000-0000-0000-000000000012', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'SPAM', 'SPAM', 'System');++INSERT INTO email_threads (id, provider_id, link_id, inbox_visible, is_read, latest_non_spam_message_ts)+SELECT ('0b000000-0000-0000-0000-' || lpad((provider * 100 + n)::text, 12, '0'))::uuid,+ 'all-mail-' || provider || '-' || n, link_id, false, true,+ '2025-06-01T00:00:00Z'::timestamptz + (n - 1) * interval '1 day'+FROM (VALUES (1, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid),+ (2, '0a000000-0000-0000-0000-000000000001'::uuid)) links(provider, link_id)+CROSS JOIN generate_series(1, 4) n;++INSERT INTO email_messages (id, thread_id, link_id, provider_id, subject, internal_date_ts, mailbox_state)+SELECT ('0c000000-0000-0000-0000-' || lpad((provider * 100 + n)::text, 12, '0'))::uuid,+ ('0b000000-0000-0000-0000-' || lpad((provider * 100 + least(n, 4))::text, 12, '0'))::uuid,+ link_id, 'all-mail-message-' || provider || '-' || n,+ CASE n WHEN 1 THEN 'Archived mail' WHEN 2 THEN 'Mixed normal mail'+ WHEN 3 THEN 'Trash only' ELSE 'Spam only' END,+ '2025-06-01T00:00:00Z'::timestamptz + (n - 1) * interval '1 day',+ CASE WHEN provider = 2 THEN jsonb_build_object('in_trash', n = 3, 'in_junk', n = 4) END+FROM (VALUES (1, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid),+ (2, '0a000000-0000-0000-0000-000000000001'::uuid)) links(provider, link_id)+CROSS JOIN generate_series(1, 4) n;++INSERT INTO email_messages (id, thread_id, link_id, provider_id, subject, internal_date_ts, mailbox_state)+SELECT ('0c000000-0000-0000-0000-' || lpad((provider * 100 + n)::text, 12, '0'))::uuid,+ ('0b000000-0000-0000-0000-' || lpad((provider * 100 + 2)::text, 12, '0'))::uuid,+ link_id, 'all-mail-message-' || provider || '-' || n,+ CASE n WHEN 5 THEN 'Newer spam' ELSE 'Newest trash' END,+ '2025-06-01T00:00:00Z'::timestamptz + (n - 1) * interval '1 day',+ CASE WHEN provider = 2 THEN jsonb_build_object('in_trash', n = 6, 'in_junk', n = 5) END+FROM (VALUES (1, 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid),+ (2, '0a000000-0000-0000-0000-000000000001'::uuid)) links(provider, link_id)+CROSS JOIN generate_series(5, 6) n;++INSERT INTO email_message_labels (message_id, label_id) VALUES+ ('0c000000-0000-0000-0000-000000000103', '10000006-0000-0000-0000-000000000006'),+ ('0c000000-0000-0000-0000-000000000104', '10000012-0000-0000-0000-000000000012'),+ ('0c000000-0000-0000-0000-000000000105', '10000012-0000-0000-0000-000000000012'),+ ('0c000000-0000-0000-0000-000000000106', '10000006-0000-0000-0000-000000000006');++-- The base Outlook fixture predates denormalized timestamps. Keep its normal+-- messages ordered by their actual date, below the scenarios above.+UPDATE email_threads SET latest_non_spam_message_ts = '2025-01-01T11:00:00Z'+WHERE id IN ('0a000000-0000-0000-0000-0000000000a1', '0a000000-0000-0000-0000-0000000000a2');diff --git a/crates/email/src/domain/models/mail_projection.rs b/crates/email/src/domain/models/mail_projection.rsindex a684c0668f..76e79a4ccc 100644--- a/crates/email/src/domain/models/mail_projection.rs+++ b/crates/email/src/domain/models/mail_projection.rs@@ -29,7 +29,7 @@ pub struct EmailThreadMailCacheFacts {/// Canonical body-free preview choices for each Mail tab.#[derive(Debug, Clone, PartialEq, Eq)]pub struct EmailThreadMailPreviews {- /// Latest non-trashed message for ALL, INBOX, Calendar, and Shared.+ /// Latest present message outside spam and trash for ALL, INBOX, Calendar, and Shared.pub all: Option<EmailPreview>,/// Latest non-trashed draft, even if a newer non-draft exists.pub draft: Option<EmailPreview>,@@ -91,11 +91,12 @@ pub struct EmailDraftAggregate {pub has_calendar_attachment: bool,/// Maximum inbound or Macro-draft timestamp.pub latest_inbound_message_ts: Option<DateTime<Utc>>,- /// Maximum non-spam or Macro-draft timestamp.+ /// Maximum non-spam or Macro-draft timestamp; provider drafts without a date+ /// use creation time so each clean draft retains an All Mail contribution.pub latest_non_spam_message_ts: Option<DateTime<Utc>>,/// Maximum outbound timestamp.pub latest_outbound_message_ts: Option<DateTime<Utc>>,- /// Latest non-trashed preview.+ /// Latest non-trashed preview; the non-draft baseline also excludes spam.pub preview: Option<EmailPreview>,/// Preview ordering uses internal date or creation date, never edit time.pub preview_ts: Option<DateTime<Utc>>,diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rsindex 47caa9f498..b55855384e 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs@@ -934,8 +934,10 @@ pub(super) fn build_view_thread_filter(view: &PreviewView) -> SqlFragment {/// Builds message-level WHERE conditions based on the view typepub(super) fn build_view_message_filter(view: &PreviewView) -> SqlFragment {match view {- PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox)- | PreviewView::StandardLabel(PreviewViewStandardLabel::All) => SqlFragment::empty(),+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => SqlFragment::empty(),+ PreviewView::StandardLabel(PreviewViewStandardLabel::All) => SqlFragment::raw(+ " AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND NOT mf.in_junk)",+ ),PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {SqlFragment::raw(" AND m.is_sent = TRUE")}diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/query.rs b/crates/email/src/outbound/email_pg_repo/dynamic/query.rsindex aee182af0c..2299f2bb52 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic/query.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic/query.rs@@ -123,6 +123,12 @@ fn push_thread_candidate_select(source: ThreadCandidateSource,) {let defer_uh = !uses_view_history(email_filter, ¶ms.sort_method_str);+ // All Mail displays the latest eligible message date, even when a newer+ // junk/trash message or a read-state write updates the thread metadata.+ let updated_at_field = match view {+ PreviewView::StandardLabel(PreviewViewStandardLabel::All) => sort_ts_field,+ _ => "t.updated_at",+ };// Owned scans fan out one ordered, LIMITed subscan per link.// `link_id = ANY(...)` cannot return index order, even for a single id,@@ -166,7 +172,7 @@ fn push_thread_candidate_select(builder.push(format!(r#"{field} AS created_at,- t.updated_at AS updated_at,+ {updated_at_field} AS updated_at,{field} AS effective_ts"#,field = sort_ts_field));@@ -174,7 +180,7 @@ fn push_thread_candidate_select(builder.push(format!(r#"{} AS created_at,- t.updated_at AS updated_at,+ {updated_at_field} AS updated_at,uh.updated_at AS viewed_at,CASE "#,sort_ts_field@@ -343,7 +349,14 @@ fn push_thread_candidate_select(if wants_message_exists_pushdown(view) {build_thread_message_exists_filter(email_filter, view, ¶ms.resolved).push_into(builder, ¶ms.user_id);- } else if has_address_literals(email_filter) {+ }+ if has_address_literals(email_filter)+ && (!wants_message_exists_pushdown(view)+ || matches!(+ view,+ PreviewView::StandardLabel(PreviewViewStandardLabel::All)+ ))+ {build_thread_address_filter(email_filter).push_into(builder, ¶ms.user_id);}@@ -438,10 +451,14 @@ fn build_query(let defer_uh = !uses_view_history(email_filter, ¶ms.sort_method_str);let needs_shared_cte = !matches!(params.shared, SharedEmailFilter::Exclude);- // When the candidate stage pushes a full per-message EXISTS (view-level- // message filter), it already enforces "thread has a message the lateral- // will surface", so the address-only `matching_threads` CTE is redundant.- let matching_threads = if wants_message_exists_pushdown(view) {+ // All Mail keeps its index-driven address prefilter as well as the exact+ // message check, so large mailbox/CRM queries do not scan every thread.+ // Other message-filtered views retain their correlated EXISTS plan.+ let matching_threads = if wants_message_exists_pushdown(view)+ && !matches!(+ view,+ PreviewView::StandardLabel(PreviewViewStandardLabel::All)+ ) {None} else {// Owned-only queries can scope the CTE's contact/message scans todiff --git a/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs b/crates/email/src/outbound/email_pg_repo/dynamic/tests.rsindex dbfb13ba0f..c00c706632 100644--- a/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs+++ b/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs@@ -565,8 +565,8 @@ fn test_build_query_shared_include_uses_union_instead_of_or() {}#[test]-fn test_build_query_projects_real_updated_at_for_candidate_threads() {- let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);+fn test_build_query_preserves_thread_updated_at_outside_all_mail() {+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Sent);let expr = Expr::Literal(EmailLiteral::Shared(item_filters::SharedEmailFilter::Include,));diff --git a/crates/email/src/outbound/email_pg_repo/preview.rs b/crates/email/src/outbound/email_pg_repo/preview.rsindex c8fda6ed74..3f0d657108 100644--- a/crates/email/src/outbound/email_pg_repo/preview.rs+++ b/crates/email/src/outbound/email_pg_repo/preview.rs@@ -49,10 +49,12 @@ pub(super) async fn previews_for_view_cursor(.await?}(- view @ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent),+ view @ PreviewView::StandardLabel(+ PreviewViewStandardLabel::Sent | PreviewViewStandardLabel::All,+ ),Either::Left(query),) => {- // Sent always uses the dynamic builder, even with no filter;+ // Use the same per-inbox ordered scan for filtered and unfiltered mail;// CalendarOnly(false) is the documented no-op literal.let query =query.map_filter(|()| Arc::new(Expr::Literal(EmailLiteral::CalendarOnly(false))));@@ -75,10 +77,6 @@ pub(super) async fn previews_for_view_cursor(super::preview_views::starred::starred_preview_cursor(pool, &link_ids, limit, &query).await?}- (PreviewView::StandardLabel(PreviewViewStandardLabel::All), Either::Left(query)) => {- super::preview_views::all_mail::all_mail_preview_cursor(pool, &link_ids, limit, &query)- .await?- }(PreviewView::StandardLabel(PreviewViewStandardLabel::Important), Either::Left(query)) => {super::preview_views::important::important_preview_cursor(pool, &link_ids, limit, &query,diff --git a/crates/email/src/outbound/email_pg_repo/preview_views.rs b/crates/email/src/outbound/email_pg_repo/preview_views.rsindex 17cda409fb..3f76c46a32 100644--- a/crates/email/src/outbound/email_pg_repo/preview_views.rs+++ b/crates/email/src/outbound/email_pg_repo/preview_views.rs@@ -1,4 +1,3 @@-pub(super) mod all_mail;pub(super) mod draft;pub(super) mod important;pub(super) mod new_inbox;diff --git a/crates/email/src/outbound/email_pg_repo/preview_views/all_mail.rs b/crates/email/src/outbound/email_pg_repo/preview_views/all_mail.rsdeleted file mode 100644index d059bbd835..0000000000--- a/crates/email/src/outbound/email_pg_repo/preview_views/all_mail.rs+++ /dev/null@@ -1,115 +0,0 @@-use super::super::db_types::*;-use models_pagination::{Query, SimpleSortMethod};-use sqlx::PgPool;-use uuid::Uuid;--/// Fetches a paginated list of thread previews for the "All Mail" view using a-/// denormalized timestamp.-/// This view includes all threads that have at least one non-spam message, sorted by the-/// `latest_non_spam_message_ts` column on the `threads` table. The preview shows-/// details from the latest non-spam message-#[tracing::instrument(skip(pool), err)]-pub(crate) async fn all_mail_preview_cursor(- pool: &PgPool,- link_ids: &[Uuid],- limit: u32,- query: &Query<Uuid, SimpleSortMethod, ()>,-) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {- let query_limit = limit as i64;- let sort_method_str = query.sort_method().to_string();- let (cursor_id, cursor_timestamp) = query.vals();-- sqlx::query_as!(- ThreadPreviewCursorDbRow,- r#"- SELECT- t.id,- t.provider_id,- t.inbox_visible,- t.is_read,- t.is_signal,- t.effective_ts AS "sort_ts!",- t.created_at AS "created_at!",- t.updated_at AS "updated_at!",- t.project_id,- t.viewed_at AS "viewed_at?",- lmp.subject AS "name?",- lmp.snippet AS "snippet?",- lmp.is_draft,- EXISTS (- SELECT 1- FROM email_messages m_imp- JOIN email_message_mailbox_facts mf ON mf.id = m_imp.id- WHERE m_imp.thread_id = t.id AND mf.is_present AND NOT mf.in_trash AND mf.provider_is_important- ) AS "is_important!",- c.email_address AS "sender_email?",- COALESCE(lmp.from_name, c.name) AS "sender_name?",- c.sfs_photo_url as "sender_photo_url?",- el.macro_id AS "owner_id!",- el.id AS "link_id!"- FROM (- -- Step 1: Efficiently find, sort, and limit the top N+1 threads.- -- This subquery only touches `threads` and `user_history`, making it very fast.- SELECT- t.id,- t.provider_id,- t.link_id,- t.inbox_visible,- t.is_read,- t.is_signal,- t.project_id,- t.latest_non_spam_message_ts AS created_at,- t.latest_non_spam_message_ts AS updated_at,- uh.updated_at AS viewed_at,- CASE $5 -- sort_method_str- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)- ELSE t.latest_non_spam_message_ts- END AS effective_ts- FROM email_threads t- LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id- WHERE- t.link_id = ANY($1)- AND t.latest_non_spam_message_ts IS NOT NULL-- -- Cursor logic is moved inside for maximum efficiency- AND (($3::timestamptz IS NULL) OR (- -- This CASE must exactly match the one that defines `effective_ts`- CASE $5 -- sort_method_str- WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')- WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, t.latest_non_spam_message_ts)- ELSE t.latest_non_spam_message_ts- END, t.id- ) < ($3::timestamptz, $4::uuid))- ORDER BY effective_ts DESC, t.updated_at DESC- LIMIT $2- ) AS t- -- Step 2: For EACH of the limited threads from above, find its latest non-SPAM/TRASH message.- CROSS JOIN LATERAL (- SELECT- m.subject,- m.snippet,- m.is_draft,- m.from_contact_id,- m.from_name- FROM email_messages m- WHERE m.thread_id = t.id- AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_junk)- AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash)- ORDER BY m.internal_date_ts DESC- LIMIT 1- ) AS lmp- -- Step 3: Join to get the sender's details for the final result set.- LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id- JOIN email_links el ON t.link_id = el.id- ORDER BY t.effective_ts DESC, t.updated_at DESC- "#,- link_ids, // $1- query_limit, // $2- cursor_timestamp, // $3- cursor_id, // $4- sort_method_str, // $5- )- .fetch_all(pool)- .await-}diff --git a/crates/email/src/outbound/email_pg_repo/test.rs b/crates/email/src/outbound/email_pg_repo/test.rsindex 3085f51beb..f1107bed9a 100644--- a/crates/email/src/outbound/email_pg_repo/test.rs+++ b/crates/email/src/outbound/email_pg_repo/test.rs@@ -1,3 +1,4 @@+mod all_mail;mod crm_scope_dynamic_query;mod draft;mod dynamic_query;diff --git a/crates/email/src/outbound/email_pg_repo/test/all_mail.rs b/crates/email/src/outbound/email_pg_repo/test/all_mail.rsnew file mode 100644index 0000000000..c2f46045b3--- /dev/null+++ b/crates/email/src/outbound/email_pg_repo/test/all_mail.rs@@ -0,0 +1,295 @@+use super::*;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_outlook_threads", "email_all_mail")+ )+)]+async fn all_mail_excludes_spam_and_trash_before_pagination(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ for (link, mixed, archived) in [+ (+ uuid::uuid!("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000102"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000101"),+ ),+ (+ uuid::uuid!("0a000000-0000-0000-0000-000000000001"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000202"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000201"),+ ),+ ] {+ for filter in [+ None,+ Some(Arc::new(Expr::val(EmailLiteral::CalendarOnly(false)))),+ ] {+ let page = repo+ .previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::All),+ link_ids: vec![link],+ limit: 2,+ team_id: None,+ query: Query::new(None, SimpleSortMethod::UpdatedAt, filter.clone()),+ },+ viewer.clone(),+ )+ .await?;+ assert_eq!(+ page.iter().map(|row| row.id).collect::<Vec<_>>(),+ [mixed, archived]+ );+ assert_eq!(page[0].name.as_deref(), Some("Mixed normal mail"));+ assert_eq!(page[0].updated_at, page[0].sort_ts);+ let next = repo+ .previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::All),+ link_ids: vec![link],+ limit: 2,+ team_id: None,+ query: Query::new(+ Some(Cursor {+ id: mixed,+ limit: 2,+ val: CursorVal {+ sort_type: SimpleSortMethod::UpdatedAt,+ last_val: page[0].sort_ts,+ },+ filter: filter.clone(),+ }),+ SimpleSortMethod::UpdatedAt,+ filter,+ ),+ },+ viewer.clone(),+ )+ .await?;+ assert_eq!(next[0].id, archived);+ assert!(!next.iter().any(|row| row.id == mixed));+ }+ }+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_outlook_threads", "email_all_mail")+ )+)]+async fn all_mail_cache_and_draft_baselines_exclude_spam_and_trash(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let mixed = [+ uuid::uuid!("0b000000-0000-0000-0000-000000000102"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000202"),+ ];+ let excluded = [+ uuid::uuid!("0b000000-0000-0000-0000-000000000103"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000104"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000203"),+ uuid::uuid!("0b000000-0000-0000-0000-000000000204"),+ ];+ let rows = repo+ .thread_mail_projections_by_ids(viewer, &[mixed.as_slice(), excluded.as_slice()].concat())+ .await?;+ assert_eq!(rows.len(), 6);+ for row in rows {+ let baseline = &row.draft_state.as_ref().unwrap().baseline;+ if mixed.contains(&row.thread_id) {+ assert_eq!(+ row.previews.all.as_ref().unwrap().subject.as_deref(),+ Some("Mixed normal mail")+ );+ assert_eq!(baseline.preview, row.previews.all);+ } else {+ assert!(row.previews.all.is_none());+ assert!(baseline.preview.is_none());+ assert!(baseline.preview_ts.is_none());+ }+ }+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_outlook_threads", "email_all_mail")+ )+)]+async fn all_mail_keeps_provider_drafts_without_received_or_sent_dates(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let message = uuid::uuid!("0a000000-0000-0000-0000-0000000000b1");+ let thread = uuid::uuid!("0a000000-0000-0000-0000-0000000000a1");+ let link = uuid::uuid!("0a000000-0000-0000-0000-000000000001");+ sqlx::query!(+ "UPDATE email_messages SET is_draft = true, internal_date_ts = NULL WHERE id = $1",+ message+ )+ .execute(&pool)+ .await?;+ let mut conn = pool.acquire().await?;+ email_db_client::threads::update::recompute_thread_metadata(&mut conn, thread, link).await?;+ let timestamp = sqlx::query_scalar!(+ "SELECT latest_non_spam_message_ts FROM email_threads WHERE id = $1",+ thread+ )+ .fetch_one(&pool)+ .await?;+ let created_at = sqlx::query_scalar!(+ "SELECT created_at FROM email_messages WHERE id = $1",+ message+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(timestamp, Some(created_at));+ let repo = EmailPgRepo::new(pool.clone());+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ let projections = repo+ .thread_mail_projections_by_ids(viewer.clone(), &[thread])+ .await?;+ let projection = &projections[0];+ assert_eq!(projection.previews.all.as_ref().unwrap().id, message);+ let draft = &projection.draft_state.as_ref().unwrap().drafts[0];+ assert_eq!(draft.facts.preview.as_ref().unwrap().id, message);+ assert!(+ draft.facts.latest_non_spam_message_ts.is_some(),+ "clean drafts retain All Mail eligibility without provider timestamps"+ );+ for filter in [+ None,+ Some(Arc::new(Expr::val(EmailLiteral::CalendarOnly(false)))),+ ] {+ let page = repo+ .previews_for_view_cursor(+ PreviewCursorQuery {+ view: PreviewView::StandardLabel(PreviewViewStandardLabel::All),+ link_ids: vec![link],+ limit: 50,+ team_id: None,+ query: Query::new(None, SimpleSortMethod::UpdatedAt, filter),+ },+ viewer.clone(),+ )+ .await?;+ assert!(page.iter().any(|row| row.id == thread));+ }+ sqlx::query!(+ r#"UPDATE email_messages SET mailbox_state = '{"in_junk":true}'::jsonb WHERE id = $1"#,+ message+ )+ .execute(&pool)+ .await?;+ let projections = repo+ .thread_mail_projections_by_ids(viewer, &[thread])+ .await?;+ assert!(projections[0].previews.all.is_none());+ let junk = &projections[0].draft_state.as_ref().unwrap().drafts[0];+ assert!(junk.facts.latest_non_spam_message_ts.is_none());+ assert_eq!(+ junk.facts.preview.as_ref().unwrap().id,+ message,+ "junk drafts retain their own tab preview"+ );+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_outlook_threads", "email_all_mail")+ )+)]+async fn all_mail_excludes_synced_macro_drafts_in_junk_and_trash(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let message = uuid::uuid!("0a000000-0000-0000-0000-0000000000b1");+ let thread = uuid::uuid!("0a000000-0000-0000-0000-0000000000a1");+ let link = uuid::uuid!("0a000000-0000-0000-0000-000000000001");+ sqlx::query!(+ "UPDATE email_messages SET is_draft = true, internal_date_ts = NULL WHERE id = $1",+ message+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ r#"INSERT INTO email_mailbox_drafts+ (message_id, link_id, generation, actor_id, desired_content, state)+ VALUES ($1, $2, 1, 'macro|[email protected]', '{}'::jsonb, 'synced')"#,+ message,+ link+ )+ .execute(&pool)+ .await?;+ let repo = EmailPgRepo::new(pool.clone());+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")?;+ for mailbox_state in [+ serde_json::json!({"in_junk": true}),+ serde_json::json!({"in_trash": true}),+ ] {+ sqlx::query!(+ "UPDATE email_messages SET mailbox_state = $2 WHERE id = $1",+ message,+ mailbox_state+ )+ .execute(&pool)+ .await?;+ let mut conn = pool.acquire().await?;+ email_db_client::threads::update::recompute_thread_metadata(&mut conn, thread, link)+ .await?;+ let timestamp = sqlx::query_scalar!(+ "SELECT latest_non_spam_message_ts FROM email_threads WHERE id = $1",+ thread+ )+ .fetch_one(&pool)+ .await?;+ assert!(timestamp.is_none(), "isolated drafts cannot order All Mail");+ let projections = repo+ .thread_mail_projections_by_ids(viewer.clone(), &[thread])+ .await?;+ assert!(projections[0].previews.all.is_none());+ let draft = &projections[0].draft_state.as_ref().unwrap().drafts[0];+ assert!(draft.macro_draft, "synced drafts retain Macro ownership");+ assert!(draft.facts.latest_non_spam_message_ts.is_none());++ let clean = Uuid::now_v7();+ let clean_timestamp = chrono::DateTime::parse_from_rfc3339("2025-01-01T00:00:00Z")?+ .with_timezone(&chrono::Utc);+ sqlx::query!(+ r#"INSERT INTO email_messages (id, thread_id, link_id, provider_id, internal_date_ts)+ VALUES ($1, $2, $3, 'clean-message', $4)"#,+ clean,+ thread,+ link,+ clean_timestamp+ )+ .execute(&pool)+ .await?;+ email_db_client::threads::update::recompute_thread_metadata(&mut conn, thread, link)+ .await?;+ let mixed = repo+ .thread_mail_projections_by_ids(viewer.clone(), &[thread])+ .await?;+ assert_eq!(mixed[0].previews.all.as_ref().unwrap().id, clean);+ assert_eq!(+ mixed[0].cache_facts.latest_non_spam_message_ts,+ Some(clean_timestamp)+ );+ sqlx::query!("DELETE FROM email_messages WHERE id = $1", clean)+ .execute(&pool)+ .await?;+ }+ Ok(())+}diff --git a/crates/email/src/outbound/email_pg_repo/thread.rs b/crates/email/src/outbound/email_pg_repo/thread.rsindex 7713a8e82e..e45fdd4309 100644--- a/crates/email/src/outbound/email_pg_repo/thread.rs+++ b/crates/email/src/outbound/email_pg_repo/thread.rs@@ -114,12 +114,12 @@ pub(super) async fn thread_mail_projections_by_ids(CASE WHEN draft.macro_draft AND thread.has_received_mail THEN m.updated_at END) AS inbound_ts,GREATEST(- CASE WHEN NOT (facts.in_junk OR facts.in_trash) THEN m.internal_date_ts END,- CASE WHEN draft.macro_draft THEN m.updated_at END+ CASE WHEN NOT (facts.in_junk OR facts.in_trash) THEN COALESCE(m.internal_date_ts, CASE WHEN m.is_draft THEN m.created_at END) END,+ CASE WHEN draft.macro_draft AND NOT (facts.in_junk OR facts.in_trash) THEN m.updated_at END) AS all_ts,CASE WHEN m.is_sent AND NOT facts.in_trash THEN m.internal_date_ts END AS sent_ts,- CASE WHEN NOT facts.in_trash THEN COALESCE(m.internal_date_ts, m.created_at) END AS preview_ts,- CASE WHEN NOT facts.in_trash THEN jsonb_build_object(+ CASE WHEN NOT facts.in_trash AND (m.is_draft OR NOT facts.in_junk) THEN COALESCE(m.internal_date_ts, m.created_at) END AS preview_ts,+ CASE WHEN NOT facts.in_trash AND (m.is_draft OR NOT facts.in_junk) THEN jsonb_build_object('id', m.id, 'subject', m.subject, 'snippet', m.snippet, 'is_draft', m.is_draft,'sender_email', c.email_address, 'sender_name', COALESCE(m.from_name, c.name), 'sender_photo_url', c.sfs_photo_url) END AS preview@@ -190,7 +190,7 @@ pub(super) async fn thread_mail_projections_by_ids(LEFT JOIN draft_states ds ON ds.thread_id = t.idLEFT JOIN LATERAL (SELECT m.id, m.subject, m.snippet, m.is_draft, m.from_contact_id, m.from_name- FROM email_messages m WHERE m.thread_id = t.id AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1+ FROM email_messages m WHERE m.thread_id = t.id AND EXISTS (SELECT 1 FROM email_message_mailbox_facts mf WHERE mf.id = m.id AND mf.is_present AND NOT mf.in_trash AND NOT mf.in_junk) ORDER BY COALESCE(m.internal_date_ts, m.created_at) DESC, m.id DESC LIMIT 1) am ON TRUELEFT JOIN email_contacts ac ON ac.id = am.from_contact_idLEFT JOIN LATERAL (diff --git a/crates/email_api_client/AGENTS.md b/crates/email_api_client/AGENTS.mdindex ac9afed46a..67941df91a 100644--- a/crates/email_api_client/AGENTS.md+++ b/crates/email_api_client/AGENTS.md@@ -54,6 +54,9 @@ Outlook (Microsoft Graph) outbound adapters.## Gotchas+- Undated provider drafts use creation time for All Mail eligibility; spam/junk+ and trash remain excluded. Keep ingestion, recomputation, and cached projections aligned.+- `#![deny(missing_docs)]`.- The service is generic over `<R, T, L>` (repository, token source, requestgate) — add a new dependency as a port + generic bound, not a concretediff --git a/crates/email_api_client/src/outbound/gmail/convert/thread.rs b/crates/email_api_client/src/outbound/gmail/convert/thread.rsindex 3923a17fa7..9b1eae5a9d 100644--- a/crates/email_api_client/src/outbound/gmail/convert/thread.rs+++ b/crates/email_api_client/src/outbound/gmail/convert/thread.rs@@ -40,8 +40,13 @@ pub(crate) fn map_thread_resource_to_service(.and_then(|message| message.internal_date_ts);let latest_non_spam_message_ts = messages.iter()- .rfind(|message| !is_spam_or_trash(message))- .and_then(|message| message.internal_date_ts);+ .filter(|message| !is_spam_or_trash(message))+ .filter_map(|message| {+ message+ .internal_date_ts+ .or_else(|| message.is_draft.then_some(message.created_at))+ })+ .max();let thread_db_id = Uuid::now_v7();for message in &mut messages {diff --git a/crates/email_api_client/src/outbound/gmail/convert/thread/test.rs b/crates/email_api_client/src/outbound/gmail/convert/thread/test.rsindex 36acf09bbf..126a36923d 100644--- a/crates/email_api_client/src/outbound/gmail/convert/thread/test.rs+++ b/crates/email_api_client/src/outbound/gmail/convert/thread/test.rs@@ -79,3 +79,31 @@ fn sorts_messages_and_derives_thread_state() {.all(|message| message.thread_db_id == thread.db_id));}++#[test]+fn undated_provider_drafts_keep_all_mail_timestamp_but_spam_drafts_do_not() {+ let mut draft = message("draft", 0, vec!["DRAFT".into()]);+ draft.internal_date = String::new();+ let resource = ThreadResource {+ id: "thread".into(),+ messages: vec![draft.clone(), message("older", 1000, vec![])],+ };+ let thread = map_thread_resource_to_service(resource, Uuid::now_v7()).unwrap();+ let created_at = thread+ .messages+ .iter()+ .find(|m| m.is_draft)+ .unwrap()+ .created_at;+ assert_eq!(thread.latest_non_spam_message_ts, Some(created_at));+ draft.label_ids.push("SPAM".into());+ let thread = map_thread_resource_to_service(+ ThreadResource {+ id: "thread".into(),+ messages: vec![draft],+ },+ Uuid::now_v7(),+ )+ .unwrap();+ assert_eq!(thread.latest_non_spam_message_ts, None);+}diff --git a/crates/email_db_client/AGENTS.md b/crates/email_db_client/AGENTS.mdindex 891f030274..cb28edec39 100644--- a/crates/email_db_client/AGENTS.md+++ b/crates/email_db_client/AGENTS.md@@ -45,6 +45,10 @@ Parsed message responses expose the draft generation captured in the same SQL sn## Gotchas+- Undated provider drafts use creation time for All Mail eligibility; spam/junk+ and trash remain excluded, including the timestamp override for synced Macro+ drafts. Keep ingestion, recomputation, and cached projections aligned.+- Message deletion may return `Deferred` while an accepted send owns the row; reconcile retained deletions under the message lock and compare both provider identity and draft generation.- Resolve provider deletions with `get_simple_message_by_provider_and_link_for_update` inside the deletion transaction; retain the message lock through cleanup and deletion so Send completion or Undo cannot invalidate the snapshot.diff --git a/crates/email_db_client/src/threads/update.rs b/crates/email_db_client/src/threads/update.rsindex 9ffbbadb42..2d4e92d92c 100644--- a/crates/email_db_client/src/threads/update.rs+++ b/crates/email_db_client/src/threads/update.rs@@ -221,7 +221,7 @@ pub async fn recompute_thread_metadata(max(internal_date_ts) FILTER (WHERE in_inbox AND NOT is_draft AND (NOT is_sent OR sender_is_recipient)) AS received_ts,max(updated_at) FILTER (WHERE macro_draft) AS draft_ts,max(internal_date_ts) FILTER (WHERE is_sent AND NOT in_trash) AS outbound_ts,- greatest(max(internal_date_ts) FILTER (WHERE NOT in_trash AND NOT in_junk),max(updated_at) FILTER (WHERE macro_draft)) AS all_ts+ greatest(max(COALESCE(internal_date_ts, CASE WHEN is_draft THEN created_at END)) FILTER (WHERE NOT in_trash AND NOT in_junk),max(updated_at) FILTER (WHERE macro_draft AND NOT in_trash AND NOT in_junk)) AS all_tsFROM facts), effective AS (-- A Macro draft brings a thread back to the inbox only as a reply to received mail.diff --git a/crates/item_filter_index/AGENTS.md b/crates/item_filter_index/AGENTS.mdindex dfbb60c7d0..2bf0d27b3c 100644--- a/crates/item_filter_index/AGENTS.md+++ b/crates/item_filter_index/AGENTS.md@@ -45,6 +45,9 @@ engine) — keep it free of native-only dependencies.## Gotchas+- Mail All/Inbox require an All Mail preview; Drafts/Sent use their own preview+ membership because a message in junk cannot supply All Mail.+- `STATUS_PROPERTY_DEFINITION_ID` hardcodes `SystemPropertyKey::STATUS_UUID`to avoid a native dependency on `system_properties` for wasm; a native testlocks the two values together, so don't drift them independently.diff --git a/crates/item_filter_index/src/mail.rs b/crates/item_filter_index/src/mail.rsindex 1bf2c7e37b..eb9d304b61 100644--- a/crates/item_filter_index/src/mail.rs+++ b/crates/item_filter_index/src/mail.rs@@ -4,7 +4,7 @@ use item_filters::SharedEmailFilter;/// Stable, separately versioned Mail projection; existing Soup profiles remain usable.pub fn profile() -> Profile {- Profile::new(token("soup-mail-v2"))+ Profile::new(token("soup-mail-v5"))}/// Email thread partition.pub fn partition() -> Token {@@ -117,8 +117,12 @@ pub fn compile(),}};- for gate in [scope, boolean("mail-has-message", true)] {- predicate = PredicateExpr::And(Box::new(predicate), Box::new(gate));+ predicate = PredicateExpr::And(Box::new(predicate), Box::new(scope));+ if matches!(view, "ALL" | "INBOX") {+ predicate = PredicateExpr::And(+ Box::new(predicate),+ Box::new(boolean("mail-has-message", true)),+ );}if view == "INBOX" {predicate = PredicateExpr::And(diff --git a/crates/item_filter_index/src/properties.rs b/crates/item_filter_index/src/properties.rsindex 731c515eb6..45a53a7671 100644--- a/crates/item_filter_index/src/properties.rs+++ b/crates/item_filter_index/src/properties.rs@@ -27,7 +27,7 @@ pub fn is_property_attribute(attribute: &Token) -> bool {/// A cached-Mail profile containing the same canonical message facts plus properties.pub fn mail_profile() -> Profile {- Profile::new(mail::token("soup-mail-v4"))+ Profile::new(mail::token("soup-mail-v6"))}fn supported(ast: &EntityFilterAst) -> bool {diff --git a/crates/soup_filter_cache_adapter/AGENTS.md b/crates/soup_filter_cache_adapter/AGENTS.mdindex 005ad42771..e20ff56d28 100644--- a/crates/soup_filter_cache_adapter/AGENTS.md+++ b/crates/soup_filter_cache_adapter/AGENTS.md@@ -63,6 +63,9 @@ understand. Runs both natively (Tauri) and compiled to wasm (web).unless an optimistic shadow takes precedence; an older reader must not undoauthoritative first-page repair. Missing facts still retain server membership.+- A thread may have Drafts/Sent previews with no All Mail preview (junk);+ keep those projections complete and let each tab apply its own membership.+- This crate must stay wasm-compatible — no `sqlx`, no native-only crates indefault features; native-only test fixtures live under`[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]`.diff --git a/crates/soup_filter_cache_adapter/src/mail.rs b/crates/soup_filter_cache_adapter/src/mail.rsindex 90993f226e..93b5a8f7bf 100644--- a/crates/soup_filter_cache_adapter/src/mail.rs+++ b/crates/soup_filter_cache_adapter/src/mail.rs@@ -157,9 +157,6 @@ fn project_with_facts(let all = preview_ref(record, "mailAllPreview")?;let draft = preview_ref(record, "mailDraftPreview")?;let sent = preview_ref(record, "mailSentPreview")?;- if all.is_none() && (draft.is_some() || sent.is_some()) {- return None;- }facts.push(boolean_fact(all.is_some(), "mail-has-message")?);for (attribute, id) in [("mail-all-message", all),diff --git a/crates/soup_filter_cache_adapter/src/mail/test.rs b/crates/soup_filter_cache_adapter/src/mail/test.rsindex 014c58eadc..6d1f51c2c8 100644--- a/crates/soup_filter_cache_adapter/src/mail/test.rs+++ b/crates/soup_filter_cache_adapter/src/mail/test.rs@@ -725,3 +725,58 @@ fn missing_proof_is_not_a_false_fact() {));})}++#[test]+fn spam_only_threads_stay_out_of_all_without_hiding_other_tabs() {+ pollster::block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ let mut data = seed();+ // Canonical All Mail previews exclude junk, even if a sent message or a+ // provider draft still qualifies for its own tab.+ for n in [3, 8] {+ data["user"]["soup"]["items"][n - 1]["mailAllPreview"] = Value::Null;+ }+ write(&mut engine, QUERY, &data).await;+ let all = all_keys(&mut engine, filters(), "ALL").await;+ assert!(!all.contains(&format!("{TYPE}:{}", id(3))));+ assert!(!all.contains(&format!("{TYPE}:{}", id(8))));+ assert!(+ all_keys(&mut engine, filters(), "DRAFTS")+ .await+ .contains(&format!("{TYPE}:{}", id(3)))+ );+ assert!(+ all_keys(&mut engine, filters(), "SENT")+ .await+ .contains(&format!("{TYPE}:{}", id(8)))+ );+ });+}++#[test]+fn legacy_mail_capsule_cannot_restore_spam_membership() {+ pollster::block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ let mut data = seed();+ let mut legacy = row(1);+ legacy["cacheProjection"] = json!(+ "Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEFZW1haWwBgIDZ276wlQYAAAE"+ );+ data["user"]["soup"]["items"] = json!([legacy]);+ write(&mut engine, QUERY, &data).await;+ let key = RecordKey::new(format!("{TYPE}:{}", id(1))).unwrap();+ assert!(matches!(+ engine+ .storage()+ .load_projection_states(&[key])+ .await+ .unwrap()[0],+ Some(ProjectionState::Incomplete { .. })+ ));+ assert!(all_keys(&mut engine, filters(), "ALL").await.is_empty());+ data["user"]["soup"]["items"][0] = row(1);+ data["user"]["soup"]["items"][0]["mailAllPreview"] = Value::Null;+ write(&mut engine, QUERY, &data).await;+ assert!(all_keys(&mut engine, filters(), "ALL").await.is_empty());+ });+}diff --git a/crates/soup_filter_projection/AGENTS.md b/crates/soup_filter_projection/AGENTS.mdindex ad2f9d80f1..b6216ecce8 100644--- a/crates/soup_filter_projection/AGENTS.md+++ b/crates/soup_filter_projection/AGENTS.md@@ -46,6 +46,10 @@ Soup entity's filterable facts, shared by server and client-side cache code.## Gotchas+- Mail capsules target `soup-mail-v5` (spam/trash-free All Mail previews);+ legacy `soup-mail-v2` capsules still decode but cannot establish current Mail+ completeness. Property-backed Mail projections use `soup-mail-v6`.+- `default-features = false` (no `models`) is the wasm-safe build; don't add anon-optional dependency on `soup`/`models_soup` outside the `models` feature.- Decoding must stay backward-compatible with every `SOUP_CACHE_PROJECTION_WIRE_VERSION_V*`@@ -54,3 +58,5 @@ Soup entity's filterable facts, shared by server and client-side cache code.## Related- Rules: `.agents/rules/web/data.md`++- Use `mail_legacy_v2` at the server transport boundary for clients without an explicit `soup-mail-v5` capability, including unsupported advertised profiles; keep the frozen v2 golden wire payload compatible with deployed native engines.diff --git a/crates/soup_filter_projection/src/test.rs b/crates/soup_filter_projection/src/test.rsindex 3cd162246b..ad95300ad2 100644--- a/crates/soup_filter_projection/src/test.rs+++ b/crates/soup_filter_projection/src/test.rs@@ -331,7 +331,7 @@ fn mail_supplement_golden_round_trip_preserves_server_only_facts() {let encoded = encode_cache_projection_supplement(&supplement).unwrap();assert_eq!(encoded,- "Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEFZW1haWwBgIDZ276wlQYAAAE"+ "Awxzb3VwLW1haWwtdjU7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEFZW1haWwBgIDZ276wlQYAAAE");let decoded = decode_cache_projection_supplement(&encoded).unwrap();assert_eq!(decoded, supplement);@@ -459,3 +459,26 @@ fn supplement_decoder_rejects_invalid_profile_partition_and_record_binding() {Err(SoupCacheProjectionWireError::RecordKeyPartitionMismatch)));}++#[test]+fn legacy_mail_capsules_decode_without_claiming_current_preview_semantics() {+ let encoded = "Awxzb3VwLW1haWwtdjI7R3JhcGhxbFNvdXBFbWFpbFRocmVhZDowMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDEFZW1haWwBgIDZ276wlQYAAAE";+ let supplement = decode_cache_projection_supplement(encoded).unwrap();+ let legacy = SoupCacheProjectionSupplement::mail_legacy_v2(+ supplement.record_key().clone(),+ supplement.mail_facts().unwrap().clone(),+ );+ assert_eq!(+ encode_cache_projection_supplement(&legacy).unwrap(),+ encoded+ );+ assert_eq!(supplement.target_profile().token().as_str(), "soup-mail-v2");+ assert_ne!(+ supplement.target_profile(),+ &item_filter_index::mail::profile()+ );+ assert_eq!(+ encode_cache_projection_supplement(&supplement).unwrap(),+ encoded+ );+}diff --git a/crates/soup_filter_projection/src/wire.rs b/crates/soup_filter_projection/src/wire.rsindex 0662a1e418..675c4d2938 100644--- a/crates/soup_filter_projection/src/wire.rs+++ b/crates/soup_filter_projection/src/wire.rs@@ -135,6 +135,15 @@ impl SoupCacheProjectionSupplement {}}+ /// Preserve the deployed Mail contract for clients that have not opted into v5.+ /// These capsules never establish completeness in a current-profile client.+ pub fn mail_legacy_v2(record_key: RecordKey, facts: MailCacheProjectionFacts) -> Self {+ Self {+ target_profile: Profile::new(Token::new("soup-mail-v2").expect("static profile")),+ ..Self::mail(record_key, facts)+ }+ }+/// Read the normalized record binding.pub fn record_key(&self) -> &RecordKey {&self.record_key@@ -424,7 +433,9 @@ impl TryFrom<&SoupCacheProjectionSupplement> for SoupCacheProjectionCapsuleV3 {type Error = SoupCacheProjectionWireError;fn try_from(supplement: &SoupCacheProjectionSupplement) -> Result<Self, Self::Error> {- if supplement.target_profile != item_filter_index::mail::profile() {+ if supplement.target_profile != item_filter_index::mail::profile()+ && supplement.target_profile.token().as_str() != "soup-mail-v2"+ {return Err(SoupCacheProjectionWireError::UnsupportedTargetProfile(supplement.target_profile.token().as_str().to_owned(),));@@ -544,7 +555,9 @@ fn validate_supplement("GraphqlSoupDocument:"}SoupCacheProjectionFacts::Mail(_) => {- if supplement.target_profile != item_filter_index::mail::profile() {+ if supplement.target_profile != item_filter_index::mail::profile()+ && supplement.target_profile.token().as_str() != "soup-mail-v2"+ {return Err(SoupCacheProjectionWireError::UnsupportedTargetProfile(supplement.target_profile.token().as_str().to_owned(),));diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.mdindex 36ee925c90..263fdb5845 100644--- a/docs/agent-guide/email.md+++ b/docs/agent-guide/email.md@@ -391,7 +391,26 @@ headers use the selected Mail view's indexed timestamps, not a preview cached franother view. Drafts and Sent display their latest eligible message snapshot, evenwhen a newer normal message is the ALL preview; no message bodies are needed.Sent also requires a canonical outbound timestamp. Trashed messages cannot supply-any preview. Calendar uses the authoritative thread calendar-attachment flag.+any preview. All Mail also excludes spam/junk, including its cached preview and+non-draft baseline after draft edits. Mixed threads show the latest message outside+spam and trash; excluded messages must not consume a page slot. Drafts and Sent+keep their own canonical preview membership. Mail profiles v5/v6 require fresh+server metadata after upgrading, so older spam-inclusive cache entries cannot+reappear. HTTP and WebSocket clients explicitly negotiate the Mail capsule profile.+Absent/unknown capabilities receive legacy v2 capsules, preserving old native draft+queue admission. Browsers advertise v5; native clients do so only after verifying+installed iOS build 193 or Android build 20 (unknown/desktop builds retain v2).+Native discovery falls back to v2 after 1.5 seconds and retains that result for+the session, so unavailable IPC cannot indefinitely delay GraphQL requests.+The HTTP transport and WebSocket connection-parameter spans record the selected+profile and whether discovery used the browser, a supported/unsupported native+build, failed, or timed out; they do not include native error text.+Current engines treat v2 capsules as incomplete and use the network for Mail lists.+Deploy the backend (including its CORS capability header) before the new frontend.+The backend can deploy before store releases; native v5 offline behavior still+requires the corresponding native cache update.+Verify Gmail labels and Outlook+folder state. Calendar uses the authoritative thread calendar-attachment flag.A successful authoritative `Soup` first page also invalidates cached Mail factsthat match its supported view/filter but are missing inside its covered sortdiff --git a/docs/development/android.md b/docs/development/android.mdindex 66c32d9d66..abc00fdc18 100644--- a/docs/development/android.md+++ b/docs/development/android.md@@ -59,6 +59,11 @@ Build commands embed the production frontend. Outputs are underRelease builds automatically prepare the signing configuration below and producesigned artifacts. Debug builds do not fetch release signing credentials.+The app's Gradle packaging excludes the duplicate+`META-INF/versions/9/OSGI-INF/MANIFEST.MF` from JSpecify and OpenTelemetry. This+OSGi metadata is unused on Android. Keep the exclusion exact: broad `META-INF`+exclusions can remove service-provider registrations used by OpenTelemetry.+## Release signingThe existing upload keystore and signing credentials are stored in Doppler@@ -204,9 +209,13 @@ To release:the bundle stale: **`Android Release Drift`** cancels an in-progress build,removes the label and comments. A Play production release cannot bewithdrawn once submitted, so if the stale bundle was already promoted the- comment says so and the follow-up should ship as soon as possible (after- a force-push the old head is gone, so drift checks Play for the new- head's version code instead).+ comment says so and the follow-up should ship as soon as possible. If the+ previous native tree cannot be verified (for example, after a force-push),+ drift skips the Play lookup and reports production status as unknown; the+ new head's version code cannot identify the prior release. Authentication+ or Play lookup failures also report unknown status. Keep the reviewed-SHA+ restriction and verify through an approved check or Play Console before+ treating the prior release as stopped.Play is the source of truth for what is live; nothing ties Android bundlesto production release tags any more. `publish-android-play.yml` remains as@@ -229,6 +238,10 @@ there: its `fuser -km /nix` can kill the runner when `/nix` is on the rootfilesystem, preventing GitHub from receiving the build logs. Let the hostedVM be discarded.+The shared authenticated Git fetch helper clears `LD_LIBRARY_PATH` for Git only.+After Nix setup, the host Git HTTPS helper cannot safely load the build shell's+Nix libraries; keep this isolation in the helper used by the release head guard.+Testers install through Google Play's internal testing track once thebundle is uploaded; an AAB cannot be installed directly on a device.@@ -298,8 +311,10 @@ attribute.repository_id=assertion.repository_idUse issuer `https://token.actions.githubusercontent.com`. Restrict the provider'sattribute condition to the numeric repository and owner IDs (available from-`gh api repos/macro-inc/macro --jq '{repository: .id, owner: .owner.id}'`), the-publishing workflow on `main`, and its branch identity:+`gh api repos/macro-inc/macro --jq '{repository: .id, owner: .owner.id}'`).+The initial condition below permits only the manual publishing workflow on+`main`; automatic PR releases also need the explicit grants described in+"Authorize an approved PR release" below:```textassertion.repository_id == '1092407718' &&@@ -316,8 +331,8 @@ principalSet://iam.googleapis.com/projects/1024168288732/locations/global/workloIn GitHub → Settings → Secrets and variables → Actions → Variables, add these**repository variables**, which contain identifiers, not secrets. The workflow-checks its branch, and the Google provider independently enforces both the branch-and workflow identity:+checks its branch, and the Google provider independently enforces the approved+ref and workflow identity:| Variable | Value || --- | --- |@@ -358,6 +373,87 @@ gh variable set GOOGLE_PLAY_SERVICE_ACCOUNT --repo macro-inc/macro \--body [email protected]```+#### Authorize an approved PR release++The initial provider condition rejects the PR-based native check and release+workflows. Before releasing a reviewed same-repository PR, an identity+administrator must extend that condition with narrowly scoped alternatives:++- Keep the numeric repository and owner ID checks around every alternative,+ and retain the existing manual publisher on `main`.+- Permit `android-release-watch.yml@refs/heads/main` only with the main ref and+ main subject, for `schedule` or `workflow_dispatch` events.+- Permit the specific approved `refs/pull/<PR_NUMBER>/merge` only for+ `pull_request` events, the `repo:macro-inc/macro:pull_request` subject,+ `base_ref == 'main'`, the reviewed merge commit in `assertion.sha`, and these+ exact workflow paths at that same merge ref:+ `web-app-check-main.yml`, `android-play-release.yml`, and+ `android-release-drift.yml` under `macro-inc/macro/.github/workflows/`.++Check the PR's head repository and review its merge commit before granting access.+Do not replace the approved PR ref or SHA with a wildcard: PR workflows execute+the proposed code with the publishing identity. For `pull_request` workflows,+`assertion.sha` identifies the event's merge commit, not the PR head. A later push+or base-branch update creates a different merge commit; review the changes before+updating the grant. Reruns retain the original event SHA, and release jobs request+credentials after building. Retain each reviewed event SHA in an explicit+`assertion.sha in [...]` allowlist while its approved gate, release, or drift run+still needs credentials, then remove it. Remove the PR's alternative after it+merges or closes. Keep the main watcher permission so it can verify releases and+rerun native gates.++Back up the existing provider, then create the complete condition below. Replace+`<PR_NUMBER>` and `<REVIEWED_MERGE_SHA>` with the approved PR number and full+40-character merge commit SHA. This example preserves the initial publisher and+adds the watcher; preserve any other independently approved grants already in+`provider-before.json` instead of overwriting them.++```sh+gcloud iam workload-identity-pools providers describe macro \+ --project=macro-435922 --location=global \+ --workload-identity-pool=github-play --format=json > provider-before.json++cat > approved-play-condition.cel <<'CEL'+assertion.repository_id == '1092407718' &&+assertion.repository_owner_id == '65687018' &&+(+ (+ assertion.workflow_ref == 'macro-inc/macro/.github/workflows/publish-android-play.yml@refs/heads/main' &&+ assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main'+ ) ||+ (+ assertion.workflow_ref == 'macro-inc/macro/.github/workflows/android-release-watch.yml@refs/heads/main' &&+ assertion.ref == 'refs/heads/main' &&+ assertion.sub == 'repo:macro-inc/macro:ref:refs/heads/main' &&+ assertion.event_name in ['schedule', 'workflow_dispatch']+ ) ||+ (+ assertion.event_name == 'pull_request' &&+ assertion.sub == 'repo:macro-inc/macro:pull_request' &&+ assertion.ref == 'refs/pull/<PR_NUMBER>/merge' &&+ assertion.base_ref == 'main' &&+ assertion.sha == '<REVIEWED_MERGE_SHA>' &&+ assertion.workflow_ref in [+ 'macro-inc/macro/.github/workflows/web-app-check-main.yml@refs/pull/<PR_NUMBER>/merge',+ 'macro-inc/macro/.github/workflows/android-play-release.yml@refs/pull/<PR_NUMBER>/merge',+ 'macro-inc/macro/.github/workflows/android-release-drift.yml@refs/pull/<PR_NUMBER>/merge'+ ]+ )+)+CEL++gcloud iam workload-identity-pools providers update-oidc macro \+ --project=macro-435922 --location=global \+ --workload-identity-pool=github-play \+ --attribute-condition="$(cat approved-play-condition.cel)"+```++Keep the existing attribute mappings and service-account role binding. Verify the+updated condition, then rerun the failed Android native-check job: successful+authentication must reach the Play status check before triggering the release.+See [GitHub's OIDC claims](https://docs.github.com/en/actions/reference/security/oidc)+for the distinction between PR subjects and branch subjects.+#### Manual upload (fallback)The `Android Play Release` workflow uploads and promotes automatically. For a@@ -416,9 +512,9 @@ retrying. Failed or no-op attempts discard their pending edit when possible;commits are never automatically retried. The workflow summary reports submission,not confirmation that the release is already available to users.-Promotion remains a separate manual action; building a GitHub release or uploading-to internal testing never triggers production promotion. It uses the existing-workflow identity, so no Google identity-provider changes are required.+The fallback promotion command is a separate manual action and uses the existing+main publishing identity. The PR release workflow promotes automatically after+its internal upload and requires the approved PR identity grant described above.## Firebasediff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.mdindex ce96edae22..49fca96cd6 100644--- a/services/document_storage_service/AGENTS.md+++ b/services/document_storage_service/AGENTS.md@@ -99,3 +99,5 @@ threads, pins, recents, notifications, folders, activity.## Related- Rules: `.agents/rules/rust/db.md`, `.agents/rules/observability.md`++- Negotiate Mail cache profiles through `x-macro-mail-cache-profile` (CORS-enabled HTTP) and `mailCacheProfile` (WebSocket connection init); preserve authenticated connection data and default unknown capabilities to v2.diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rsindex 40bee25def..1940988cfb 100644--- a/services/document_storage_service/src/api.rs+++ b/services/document_storage_service/src/api.rs@@ -61,7 +61,12 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {},validate_api_version,))- .layer(macro_cors::cors_layer().expose_headers([axum::http::header::RETRY_AFTER]))+ .layer(+ macro_cors::cors_layer_with_headers(vec![axum::http::HeaderName::from_static(+ complete_graph::MAIL_CACHE_PROFILE_HEADER,+ )])+ .expose_headers([axum::http::header::RETRY_AFTER]),+ ).layer(CompressionLayer::new().gzip(true)),)// The health router is attached here so we don't attach the logging middleware to itdiff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rsindex 7cb82c90c4..6d1bdf3d8d 100644--- a/services/document_storage_service/src/api/graphql_soup.rs+++ b/services/document_storage_service/src/api/graphql_soup.rs@@ -15,7 +15,7 @@ use axum::{};use axum_extra::extract::Cached;use bots::outbound::pg_bots_repo::PgBotsRepo;-use complete_graph::GraphqlRequestParts;+use complete_graph::{GraphqlRequestParts, MAIL_CACHE_PROFILE_HEADER, MailCacheProfile};use entity_registry::OwnerGrantPolicy;use entity_registry_db_utils::OwnedEntityRegistrar;use graphql_soup::email_mutation_thread_loader;@@ -63,6 +63,12 @@ async fn graphql_handler(.authorization.as_ref().and_then(UserOrInternalServiceAuthorization::acting_user);+ let mail_profile = MailCacheProfile::from_advertised(+ request_parts+ .headers+ .get(MAIL_CACHE_PROFILE_HEADER)+ .and_then(|value| value.to_str().ok()),+ );let result = telemetry::observe(request.into_inner(), acting_user.is_some(), |request| {let request = graphql_query_context_data(request,@@ -71,9 +77,11 @@ async fn graphql_handler(acting_user.and_then(|user| user.user_context.organization_id.map(i64::from)),acting_user.and_then(opaque_viewer_id),);- state- .graphql_soup_schema- .execute(request.data(GraphqlRequestParts::new(request_parts)))+ state.graphql_soup_schema.execute(+ request+ .data(mail_profile)+ .data(GraphqlRequestParts::new(request_parts)),+ )}).await;graphql_response(result)diff --git a/services/document_storage_service/src/api/graphql_soup/websocket.rs b/services/document_storage_service/src/api/graphql_soup/websocket.rsindex 9f6c1618bc..49f8aa82b0 100644--- a/services/document_storage_service/src/api/graphql_soup/websocket.rs+++ b/services/document_storage_service/src/api/graphql_soup/websocket.rs@@ -128,7 +128,17 @@ async fn serve(_ => None,})});- let output = WebSocket::new(executor, input, protocol).connection_data(data);+ let output = WebSocket::new(executor, input, protocol)+ .connection_data(data)+ .on_connection_init(|payload: serde_json::Value| async move {+ let mut capabilities = Data::default();+ capabilities.insert(complete_graph::MailCacheProfile::from_advertised(+ payload+ .get("mailCacheProfile")+ .and_then(serde_json::Value::as_str),+ ));+ Ok(capabilities)+ });futures::pin_mut!(output);while let Some(message) = output.next().await {let message = match message {diff --git a/services/document_storage_service/src/api/graphql_soup/websocket/test.rs b/services/document_storage_service/src/api/graphql_soup/websocket/test.rsindex 06a20b6bf5..406fbec4bf 100644--- a/services/document_storage_service/src/api/graphql_soup/websocket/test.rs+++ b/services/document_storage_service/src/api/graphql_soup/websocket/test.rs@@ -28,6 +28,14 @@ struct Subscriptions;#[Subscription]impl Subscriptions {+ async fn current_mail_profile(&self, context: &Context<'_>) -> impl Stream<Item = bool> {+ assert_eq!(context.data_unchecked::<String>(), "authorized-viewer");+ futures::stream::iter([context.data_opt::<complete_graph::MailCacheProfile>()+ == Some(&complete_graph::MailCacheProfile::from_advertised(Some(+ "soup-mail-v5",+ )))])+ }+async fn viewer(&self, context: &Context<'_>) -> impl Stream<Item = String> {let viewer = context.data_unchecked::<String>().clone();futures::stream::iter([viewer.clone(), viewer])@@ -509,3 +517,30 @@ fn does_not_mistake_quoted_values_for_extension_offers() {);assert!(negotiate_compression(&headers).is_none());}++#[tokio::test]+async fn mail_profile_negotiation_preserves_authorized_connection_context() {+ let server = start_server().await;+ for (payload, expected) in [+ (json!({}), false),+ (json!({"mailCacheProfile":"soup-mail-v5"}), true),+ (json!({"mailCacheProfile":"unknown"}), false),+ ] {+ let (mut socket, _) = handshake(server.address, "graphql-transport-ws", None, true).await;+ send_json(+ &mut socket,+ json!({"type":"connection_init", "payload":payload}),+ false,+ )+ .await;+ assert_eq!(+ read_json(&mut socket, false).await["type"],+ "connection_ack"+ );+ send_json(&mut socket, json!({"id":"1", "type":"subscribe", "payload":{"query":"subscription { currentMailProfile }"}}), false).await;+ assert_eq!(+ read_json(&mut socket, false).await["payload"]["data"]["currentMailProfile"],+ expected+ );+ }+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rsindex d1da14fd14..6d8e0a8a30 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift.rs@@ -13,7 +13,9 @@//! Unlike App Store review, a Play production release cannot be withdrawn//! once submitted: if the stale bundle was already promoted, the comment//! says so loudly and the follow-up should ship as soon as possible. The-//! iOS counterpart is [`super::ios_release_drift`].+//! production status remains unknown when the prior native tree cannot be+//! verified, authentication fails, or the Play lookup fails.+//! The iOS counterpart is [`super::ios_release_drift`].use gh_workflow::{Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run, Step, Use,@@ -22,6 +24,9 @@ use gh_workflow::{use crate::workflows::{runners, steps};+#[cfg(test)]+mod test;+const CHANGED: &str = "steps.detect.outputs.changed == 'true'";/// Build the workflow.@@ -185,8 +190,10 @@ fn comment() -> Step<Run> {bump='cd apps/web && just android-bump'if [[ "$PROMOTED" == "true" ]]; thenbody="🚨 Android native changes were pushed to this PR after version code ${VERSION_CODE} had already been promoted to Google Play production, so that bundle is (or is about to be) live with native code this PR no longer matches. A Play release cannot be withdrawn: bump (\`${bump}\`), commit, re-add the \`android-update\` label, and ship the follow-up as soon as possible. The label was removed."+ elif [[ "$PROMOTED" == "false" ]]; then+ body="🤖 Android native code changed after this PR's Play release started. Google Play reports that version code ${VERSION_CODE} has not been promoted to production. The \`android-update\` label was removed; any bundle on the internal track remains there for testers. Once in-progress release runs have stopped and the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."else- body="🤖 Android native code changed after this PR's Play release started, so the release was stopped: any in-progress build was cancelled and the \`android-update\` label removed. If a bundle already reached the internal track it stays there (internal testers only). When the PR is ready again, bump (\`${bump}\`), commit, push, and re-add \`android-update\`."+ body="⚠️ Android native code changed or could not be compared with this PR's prior release, and Google Play production status could not be verified. The prior bundle may already be in review or live. The \`android-update\` label was removed. Keep the reviewed-SHA authentication restriction and verify production status in Play Console or through a check from an approved revision. Treat the prior release as potentially live until verified."figh pr comment "$PR_NUMBER" --repo "$GH_REPO" --body "$body""#})diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift/test.rsnew file mode 100644index 0000000000..a2fbc24ed0--- /dev/null+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/android_release_drift/test.rs@@ -0,0 +1,102 @@+use super::*;++#[test]+fn missing_play_status_cannot_report_a_verified_nonproduction_release() {+ let yaml = android_release_drift().to_string().expect("workflow YAML");+ let workflow: serde_yaml::Value = serde_yaml::from_str(&yaml).expect("parsed workflow");+ let steps = workflow["jobs"]["drift"]["steps"]+ .as_sequence()+ .expect("drift steps");+ let comment = steps+ .iter()+ .find(|step| step["name"].as_str() == Some("Comment on the PR"))+ .expect("comment step");+ let script = comment["run"].as_str().expect("comment script");+ let reports = ["", "false", "true", "unexpected"].map(|promoted| {+ let output = std::process::Command::new("bash")+ .arg("-c")+ .arg(format!(+ "{}\n{script}",+ r#"gh() {+ [[ "$#" == 7 && "$1" == pr && "$2" == comment && "$3" == "$PR_NUMBER" && "$4" == --repo && "$5" == "$GH_REPO" && "$6" == --body ]] || return 1+ printf '%s' "$7"+}"#+ ))+ .env_remove("BASH_ENV")+ .env("PROMOTED", promoted)+ .env("VERSION_CODE", "20")+ .env("PR_NUMBER", "1")+ .env("GH_REPO", "example/repo")+ .output()+ .expect("run drift report");+ assert!(output.status.success(), "{output:?}");+ String::from_utf8(output.stdout).expect("UTF-8 report")+ });+ assert_ne!(+ reports[0], reports[1],+ "failed or skipped authentication/lookup leaves no output; it must not claim the release is absent"+ );+ assert_ne!(reports[0], reports[2]);+ assert_ne!(reports[1], reports[2]);+ assert_eq!(+ reports[0], reports[3],+ "unrecognized status is also unknown"+ );+}++#[test]+fn drift_only_checks_play_for_a_verified_previous_version() {+ for (before_state, changed, version) in [+ ("available", "true", Some("20")),+ ("unreachable", "true", None),+ ("hash-failed", "true", None),+ ("unchanged", "false", None),+ ] {+ let outputs = tempfile::NamedTempFile::new().expect("step outputs");+ let script = include_str!("../scripts/android_release_drift.sh");+ let output = std::process::Command::new("bash")+ .arg("-c")+ .arg(format!(+ "{}\n{script}",+ r#"+gh_fetch() {+ [[ "$1" != before || "$BEFORE_STATE" != unreachable ]]+}+bun() {+ case "$2:$3" in+ hash:before)+ [[ "$BEFORE_STATE" != hash-failed ]] || return 1+ if [[ "$BEFORE_STATE" == unchanged ]]; then echo new; else echo old; fi+ ;;+ hash:after) echo new ;;+ version-code:before) echo 20 ;;+ version-code:after) echo 21 ;;+ *) return 1 ;;+ esac+}+"#+ ))+ .env_remove("BASH_ENV")+ .env("BEFORE_STATE", before_state)+ .env("BEFORE_SHA", "before")+ .env("AFTER_SHA", "after")+ .env("GITHUB_OUTPUT", outputs.path())+ .output()+ .expect("run drift detection");+ assert!(output.status.success(), "{before_state}: {output:?}");+ let outputs = std::fs::read_to_string(outputs.path()).expect("read step outputs");+ assert!(+ outputs+ .lines()+ .any(|line| line == format!("changed={changed}")),+ "{before_state}: {outputs}"+ );+ assert_eq!(+ outputs+ .lines()+ .find_map(|line| line.strip_prefix("version_code=")),+ version,+ "{before_state}: a new head's bumped code cannot identify the prior release"+ );+ }+}diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.shindex 34574b63c8..ab3a953ba7 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_git_fetch.sh@@ -1,12 +1,14 @@# --- authenticated fetch ------------------------------------------------------# gh_fetch <sha|ref>: make a commit that is not in this checkout (the base# commit, a moved PR head, GitHub's test merge commit) available. Checkouts-# here don't persist credentials, so authenticate the way actions/checkout-# does. Fails if the commit is unreachable (a force-pushed-away head).+# may persist credentials, so clear inherited headers before supplying one+# explicitly. Keep Nix build libraries out of the host Git HTTPS helper.+# Fails if the commit is unreachable (a force-pushed-away head).gh_fetch() {local authauth=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n')- git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \+ LD_LIBRARY_PATH= git -c "http.https://github.com/.extraheader=" \+ -c "http.https://github.com/.extraheader=AUTHORIZATION: basic ${auth}" \fetch -q --depth=1 origin "$1"}# ------------------------------------------------------------------------------diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.shindex b4969d3b4b..db69cca31f 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.sh+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/android_release_drift.sh@@ -15,16 +15,12 @@ if [[ "$before" == "$after" ]]; thenecho "No Android native changes in this push; the release stays valid."elseecho "changed=true" >> "$GITHUB_OUTPUT"- # The version code that may already be on Play is the old head's. After a- # force-push the old head is gone; the new head's code is the best guess (a- # push rarely changes it), and it keeps the Play check running — that- # check is what tells the author a stale bundle is already in production.+ # Only the verified old head identifies the version that may be on Play.+ # A force-push may also bump the version, so the new head cannot substitute.if [[ "$before" != unknown ]]; then- released=$BEFORE_SHA+ echo "version_code=$(bun scripts/android-native.mjs version-code "$BEFORE_SHA")" >> "$GITHUB_OUTPUT"else- released=$AFTER_SHA- echo "The previous head is unreachable (force-push); checking Play for the current head's version code instead."+ echo "The previous native tree could not be verified; the prior Play version and production status remain unknown."fi- echo "version_code=$(bun scripts/android-native.mjs version-code "$released")" >> "$GITHUB_OUTPUT"- echo "Android native code changed; the released bundle is stale."+ echo "Android native code changed or cannot be verified; treating the released bundle as stale."fidiff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rsindex b0a4fe022e..c1ad5bb36c 100644--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main/test.rs@@ -405,23 +405,60 @@ fn test_job_keeps_vitest_module_cache_on_the_cache_volume() {}/// Exercise Git's actual HTTP header handling with and without checkout's-/// persisted credentials. The local endpoint records the request, then rejects-/// it: fetching repository objects is irrelevant to this authentication test.+/// persisted credentials and Android's inherited Nix build environment. The+/// local endpoint records the request, then rejects it: repository objects are+/// irrelevant to this transport test.#[test]-fn native_tree_fetch_sends_one_authorization_header() {+fn native_fetches_send_one_authorization_header() {use std::io::{BufRead, BufReader, Write};use std::net::TcpListener;use std::process::Command;- for persisted in [false, true] {+ for (source, fetch, persisted, build_environment) in [+ (+ include_str!("../scripts/ios_native_tree.sh"),+ "native_tree_fetch",+ false,+ false,+ ),+ (+ include_str!("../scripts/ios_native_tree.sh"),+ "native_tree_fetch",+ true,+ false,+ ),+ (+ include_str!("../scripts/android_git_fetch.sh"),+ "gh_fetch",+ false,+ false,+ ),+ (+ include_str!("../scripts/android_git_fetch.sh"),+ "gh_fetch",+ true,+ false,+ ),+ (+ include_str!("../scripts/android_git_fetch.sh"),+ "gh_fetch",+ false,+ true,+ ),+ (+ include_str!("../scripts/android_git_fetch.sh"),+ "gh_fetch",+ true,+ true,+ ),+ ] {let repo = tempfile::tempdir().expect("temporary checkout");let listener = TcpListener::bind("127.0.0.1:0").expect("local HTTP endpoint");let url = format!("http://{}/",listener.local_addr().expect("endpoint address"));- let script =- include_str!("../scripts/ios_native_tree.sh").replace("https://github.com/", &url);+ let script = source.replace("https://github.com/", &url);let (sender, receiver) = std::sync::mpsc::channel();std::thread::spawn(move || {let (mut socket, _) = listener.accept().expect("Git HTTP request");@@ -449,20 +486,25 @@ fn native_tree_fetch_sends_one_authorization_header() {.arg("-c").arg(format!(r#"set -euo pipefail+build_library_path=${{LD_LIBRARY_PATH-}}+unset LD_LIBRARY_PATHgit init -qgit remote add origin "$TEST_URL"if [[ "$TEST_PERSISTED" == true ]]; thengit config "http.${{TEST_URL}}.extraheader" "AUTHORIZATION: basic checkout-token"fi{script}-native_tree_fetch HEAD+if [[ "$TEST_BUILD_ENVIRONMENT" == true ]]; then+ export LD_LIBRARY_PATH="$build_library_path"+fi+{fetch} HEAD"#)).current_dir(repo.path())- // CI's BASH_ENV reloads the Nix dev shell; its library path can- // make the runner's host git-remote-http fail before connecting.+ // Keep fixture setup outside the build environment; restore its+ // library path at the fetch boundary, as the release head guard sees it..env_remove("BASH_ENV")- .env_remove("LD_LIBRARY_PATH")+ .env("TEST_BUILD_ENVIRONMENT", build_environment.to_string()).env("TEST_URL", &url).env("TEST_PERSISTED", persisted.to_string()).env("GH_TOKEN", "test-token")@@ -480,7 +522,7 @@ native_tree_fetch HEADString::from_utf8_lossy(&output.stderr))),["AUTHORIZATION: basic eC1hY2Nlc3MtdG9rZW46dGVzdC10b2tlbg=="],- "persisted credentials: {persisted}"+ "fetch helper: {fetch}; persisted credentials: {persisted}; build environment: {build_environment}");}}