Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Mail: stop freezing Apple Mail on a big inbox

Claude301ad1ab7a5c
diff --git a/NotchBuddy/Sources/App/MailController.swift b/NotchBuddy/Sources/App/MailController.swift
index b4548b0f..7cd57224 100644
--- a/NotchBuddy/Sources/App/MailController.swift
+++ b/NotchBuddy/Sources/App/MailController.swift
@@ -90,7 +90,10 @@ final class MailController: ObservableObject {
/// What the search or the filter found; nil when neither is used (the card shows `messages`).
@Published private(set) var results: [MailMessage]? = nil
@Published private(set) var searching = false
- private var searchToken = UUID()
+ /// The newest messages of each inbox, for the search and the filters (kept a minute).
+ private var searchPool: [MailMessage]? = nil
+ private var searchPoolDate: Date = .distantPast
+ private var poolFetching = false
/// The list the card shows.
var displayed: [MailMessage] { results ?? messages }
@@ -177,6 +180,7 @@ final class MailController: ObservableObject {
previews = [:]
loaded = false
results = nil
+ searchPool = nil
query = ""
filter = .all
shownCount = Self.keep
@@ -227,32 +231,50 @@ final class MailController: ObservableObject {
runSearch()
}
- /// Searches every inbox for the query and the filter (nothing to search: back to the list).
+ /// How deep the search and the filters look: the newest messages of each inbox, read in
+ /// one go (a `whose` search in Mail scans the whole mailbox and freezes Mail on a big one).
+ nonisolated static let searchDepth = 400
+
+ /// Filters the newest messages (read once, kept a minute) with the query and the filter;
+ /// nothing to search: back to the list.
func runSearch() {
let q = MailQuery.parse(query)
- guard let whose = MailScript.whoseClause(q, filter) else {
+ guard !q.isEmpty || filter != .all else {
results = nil
searching = false
return
}
- guard Self.mailRunning() else { return }
- let token = UUID()
- searchToken = token
+ if let pool = searchPool, Date().timeIntervalSince(searchPoolDate) < 60 {
+ results = Self.filtered(pool, q, filter)
+ searching = false
+ return
+ }
searching = true
+ // One read at a time: a chip clicked during it is applied when it lands.
+ guard !poolFetching, Self.mailRunning() else { return }
+ poolFetching = true
Task {
- let result = await runAppleScript(MailScript.searchScript(whose: whose, today: filter == .today))
- guard searchToken == token else { return }
- searching = false
+ let result = await runAppleScript(Self.listScript(perInbox: Self.searchDepth))
+ poolFetching = false
if case .success(let values) = result, let text = values.first {
- results = Array(Self.parseList(text).messages.sorted { $0.date > $1.date }.prefix(Self.maxShown))
- } else {
- results = []
+ searchPool = Self.parseList(text).messages
+ searchPoolDate = Date()
}
+ let q = MailQuery.parse(query)
+ guard searching, !q.isEmpty || filter != .all else { return }
+ searching = false
+ results = searchPool.map { Self.filtered($0, q, filter) } ?? []
}
}
+ nonisolated static func filtered(_ pool: [MailMessage], _ q: MailQuery, _ f: MailFilter) -> [MailMessage] {
+ Array(pool.filter {
+ MailSearch.matches(sender: $0.sender, subject: $0.subject, date: $0.date,
+ isRead: $0.isRead, isFlagged: $0.isFlagged, query: q, filter: f)
+ }.sorted { $0.date > $1.date }.prefix(maxShown))
+ }
+
func clearSearch() {
- searchToken = UUID()
query = ""
filter = .all
results = nil
@@ -312,6 +334,7 @@ final class MailController: ObservableObject {
}
messages = apply(messages)
if let r = results { results = apply(r) }
+ if let p = searchPool { searchPool = apply(p) }
}
/// Puts back a message the journal shows as sorted.
@@ -458,11 +481,13 @@ final class MailController: ObservableObject {
set RS to character id 30
set US to character id 31
tell application id "com.apple.mail"
+ -- Mail busy for 30 s: give up rather than queue more (it is never the user's wait).
+ with timeout of 30 seconds
set uc to 0
try
set uc to unread count of inbox
end try
- set out to (uc as string)
+ set L to {(uc as string)}
set accs to {}
try
set accs to (every account whose enabled is true)
@@ -481,6 +506,8 @@ final class MailController: ObservableObject {
end try
end try
if mb is not missing value then
+ set accName to name of acc
+ set mbName to name of mb
set n to 0
try
set n to count of messages of mb
@@ -522,15 +549,20 @@ final class MailController: ObservableObject {
try
set fl to ((item i of fls) as string)
end try
- set out to out & RS & ((item i of ids) as string) & US & (name of acc) & US & (name of mb) & US & f & US & s & US & d & US & ((item i of rds) as string) & US & fl
+ set end of L to ((item i of ids) as string) & US & accName & US & mbName & US & f & US & s & US & d & US & ((item i of rds) as string) & US & fl
end try
end repeat
end try
end if
end if
end repeat
- return out
+ end timeout
end tell
+ -- One join at the end (adding to a growing text each time is slow on long lists).
+ set AppleScript's text item delimiters to RS
+ set out to L as text
+ set AppleScript's text item delimiters to ""
+ return out
"""
}
@@ -539,7 +571,7 @@ final class MailController: ObservableObject {
"""
tell application id "com.apple.mail"
set mb to mailbox "\(escape(message.mailbox))" of account "\(escape(message.account))"
- set m to first message of mb whose id is \(message.messageId)
+ set m to message id \(message.messageId) of mb
\(body)
end tell
"""
diff --git a/NotchBuddy/Sources/App/MailPlan.swift b/NotchBuddy/Sources/App/MailPlan.swift
index d5dbd3a7..a51ffb53 100644
--- a/NotchBuddy/Sources/App/MailPlan.swift
+++ b/NotchBuddy/Sources/App/MailPlan.swift
@@ -336,7 +336,7 @@ extension MailScript {
let test = onlyName.map { "(name of a) is \(quote($0))" } ?? "true"
return """
tell application id "com.apple.mail"
- set m to first message of mailbox \(quote(mailbox)) of account \(quote(account)) whose id is \(messageId)
+ set m to message id \(messageId) of mailbox \(quote(mailbox)) of account \(quote(account))
set out to ""
repeat with a in mail attachments of m
if \(test) then
@@ -354,7 +354,7 @@ extension MailScript {
static func replyDraftScript(account: String, mailbox: String, messageId: Int, body: String) -> String {
"""
tell application id "com.apple.mail"
- set m to first message of mailbox \(quote(mailbox)) of account \(quote(account)) whose id is \(messageId)
+ set m to message id \(messageId) of mailbox \(quote(mailbox)) of account \(quote(account))
set r to reply m with opening window
try
set content of r to \(quote(body)) & return & return & (content of r)
@@ -370,7 +370,7 @@ extension MailScript {
static func detailsScript(account: String, mailbox: String, messageId: Int, textLimit: Int) -> String {
"""
tell application id "com.apple.mail"
- set m to first message of mailbox \(quote(mailbox)) of account \(quote(account)) whose id is \(messageId)
+ set m to message id \(messageId) of mailbox \(quote(mailbox)) of account \(quote(account))
set out to ""
try
repeat with a in mail attachments of m
diff --git a/NotchBuddy/Sources/App/MailTriage.swift b/NotchBuddy/Sources/App/MailTriage.swift
index a6de7f83..9b496115 100644
--- a/NotchBuddy/Sources/App/MailTriage.swift
+++ b/NotchBuddy/Sources/App/MailTriage.swift
@@ -213,100 +213,31 @@ enum MailFilter: String, CaseIterable, Sendable {
// MARK: - AppleScript pieces
-enum MailScript {
- /// A string inside AppleScript double quotes.
- static func quote(_ s: String) -> String {
- "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
- }
-
- /// The `whose` test for a search and a filter, nil when there is nothing to test.
- /// A "today" filter needs `set d0 to …` before it (see `todayPrelude`).
- static func whoseClause(_ q: MailQuery, _ filter: MailFilter) -> String? {
- var parts: [String] = []
- for w in q.words { parts.append("(subject contains \(quote(w)) or sender contains \(quote(w)))") }
- for f in q.from { parts.append("sender contains \(quote(f))") }
- for s in q.subject { parts.append("subject contains \(quote(s))") }
+/// The notch's search and quick filters, run here on the newest messages Mail gave in one
+/// read (MailController.searchDepth per inbox). Asking Mail to search (`whose`) scans whole
+/// mailboxes and freezes it on a big inbox.
+enum MailSearch {
+ static func matches(sender: String, subject: String, date: Date, isRead: Bool, isFlagged: Bool,
+ query: MailQuery, filter: MailFilter,
+ now: Date = Date(), calendar: Calendar = .current) -> Bool {
switch filter {
case .all: break
- case .unread: parts.append("read status is false")
- case .flagged: parts.append("flagged status is true")
- case .today: parts.append("date received > d0")
+ case .unread: if isRead { return false }
+ case .flagged: if !isFlagged { return false }
+ case .today: if !calendar.isDate(date, inSameDayAs: now) { return false }
}
- return parts.isEmpty ? nil : parts.joined(separator: " and ")
+ let s = MailTriage.normalize(sender), sub = MailTriage.normalize(subject)
+ for w in query.words.map(MailTriage.normalize) where !s.contains(w) && !sub.contains(w) { return false }
+ for f in query.from.map(MailTriage.normalize) where !s.contains(f) { return false }
+ for x in query.subject.map(MailTriage.normalize) where !sub.contains(x) { return false }
+ return true
}
+}
- static let todayPrelude = "set d0 to (current date) - (time of (current date))"
-
- /// Messages of every account's inbox matching `whose`, in the list format of
- /// MailController.parseList (unread count first, then one record per message).
- /// At most `limit` messages per inbox, the newest: an inbox with a thousand unread
- /// messages answers in a second, and the other scripts (a message opened) don't wait.
- static func searchScript(whose: String, today: Bool, limit: Int = 60) -> String {
- """
- set RS to character id 30
- set US to character id 31
- tell application id "com.apple.mail"
- \(today ? todayPrelude : "")
- set out to ""
- set accs to {}
- try
- set accs to (every account whose enabled is true)
- on error
- try
- set accs to every account
- end try
- end try
- repeat with acc in accs
- set mb to missing value
- try
- set mb to mailbox "INBOX" of acc
- on error
- try
- set mb to mailbox "Inbox" of acc
- end try
- end try
- if mb is not missing value then
- try
- set ids to id of (every message of mb whose \(whose))
- set subs to subject of (every message of mb whose \(whose))
- set snds to sender of (every message of mb whose \(whose))
- set dts to date received of (every message of mb whose \(whose))
- set rds to read status of (every message of mb whose \(whose))
- set fls to flagged status of (every message of mb whose \(whose))
- set c to count of ids
- set a to 1
- set b to c
- if c > \(limit) then
- -- The newest: the start of the list when message 1 is the most recent.
- try
- if (item 1 of dts) < (item c of dts) then
- set a to c - \(limit) + 1
- else
- set b to \(limit)
- end if
- on error
- set b to \(limit)
- end try
- end if
- repeat with i from a to b
- try
- set s to item i of subs
- if s is missing value then set s to ""
- set f to item i of snds
- if f is missing value then set f to ""
- set d to ""
- try
- set d to ((item i of dts) as «class isot» as string)
- end try
- set out to out & RS & ((item i of ids) as string) & US & (name of acc) & US & (name of mb) & US & f & US & s & US & d & US & ((item i of rds) as string) & US & ((item i of fls) as string)
- end try
- end repeat
- end try
- end if
- end repeat
- return out
- end tell
- """
+enum MailScript {
+ /// A string inside AppleScript double quotes.
+ static func quote(_ s: String) -> String {
+ "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
/// The names a Junk mailbox has, depending on the provider and the language.
@@ -380,7 +311,7 @@ enum MailScript {
"""
tell application id "com.apple.mail"
set acc to account \(quote(account))
- set m to first message of mailbox \(quote(mailbox)) of acc whose id is \(messageId)
+ set m to message id \(messageId) of mailbox \(quote(mailbox)) of acc
set rid to ""
try
set rid to message id of m
diff --git a/tests/MailTriageTests.swift b/tests/MailTriageTests.swift
index 6d099511..8d2b18e2 100644
--- a/tests/MailTriageTests.swift
+++ b/tests/MailTriageTests.swift
@@ -73,21 +73,28 @@ enum MailTriageTests {
precondition(MailQuery.parse("from: anne").from == ["anne"])
precondition(MailQuery.parse("Subject:Hello").subject == ["Hello"])
precondition(MailQuery.parse(" ").isEmpty)
- precondition(MailScript.whoseClause(MailQuery(), .all) == nil)
- let w = MailScript.whoseClause(q, .unread)!
- precondition(w.contains("sender contains \"dupont\""))
- precondition(w.contains("subject contains \"devis mai\""))
- precondition(w.contains("(subject contains \"facture\" or sender contains \"facture\")"))
- precondition(w.hasSuffix("read status is false"))
- precondition(MailScript.whoseClause(MailQuery(), .today) == "date received > d0")
- precondition(MailScript.whoseClause(MailQuery(), .flagged) == "flagged status is true")
+ // The notch's search and filters, on the messages Mail gave.
+ func m(_ sender: String, _ subject: String, read: Bool = false, flagged: Bool = false,
+ date: Date = Date(), _ q: String = "", _ f: MailFilter = .all) -> Bool {
+ MailSearch.matches(sender: sender, subject: subject, date: date, isRead: read, isFlagged: flagged,
+ query: MailQuery.parse(q), filter: f)
+ }
+ precondition(m("Jean Dupont <[email protected]>", "Devis mai", "de:dupont objet:\"devis mai\""))
+ precondition(m("Jean Dupont <[email protected]>", "Facture urgente", "facture urgente"))
+ precondition(m("Jean Dupont <[email protected]>", "Réunion été", "reunion"), "accents don't matter")
+ precondition(!m("Anne <[email protected]>", "Devis mai", "de:dupont"))
+ precondition(!m("Jean Dupont", "Hello", "facture"))
+ precondition(m("A", "B", read: false, "", .unread) && !m("A", "B", read: true, "", .unread))
+ precondition(m("A", "B", flagged: true, "", .flagged) && !m("A", "B", "", .flagged))
+ precondition(m("A", "B", "", .today) && !m("A", "B", date: Date(timeIntervalSinceNow: -3 * 86_400), "", .today))
// Quotes and backslashes can't break out of the script.
precondition(MailScript.quote("a\"b\\c") == "\"a\\\"b\\\\c\"")
}
static func scripts() {
let a = MailScript.applyScript(account: "Pro", mailbox: "INBOX", messageId: 42, action: .junk)
- precondition(a.contains("account \"Pro\"") && a.contains("whose id is 42"))
+ precondition(a.contains("account \"Pro\"") && a.contains("message id 42 of mailbox"))
+ precondition(!a.contains("whose id is"), "a direct reference, not a scan of the mailbox")
precondition(a.contains("set junk mail status of m to true") && a.contains("move m to junk mailbox"))
precondition(a.contains("message id of m"))
let mv = MailScript.applyScript(account: "Pro", mailbox: "INBOX", messageId: 1, action: .move("Clients"))
@@ -99,12 +106,5 @@ enum MailTriageTests {
let uf = MailScript.undoScript(account: "Pro", fromMailbox: "INBOX", rfcId: "<x@y>", action: .important)
precondition(uf.contains("set flagged status of m to false"))
precondition(!a.contains("delete"), "Coucou never deletes a message")
- let sc = MailScript.searchScript(whose: "read status is false", today: false)
- precondition(sc.contains("id of (every message of mb whose read status is false)"))
- precondition(sc.contains("flagged status of (every message of mb whose read status is false)"))
- precondition(!sc.contains("set d0"))
- precondition(sc.contains("if c > 60 then") && sc.contains("repeat with i from a to b"), "the newest 60 at most")
- precondition(MailScript.searchScript(whose: "read status is false", today: false, limit: 5).contains("set a to c - 5 + 1"))
- precondition(MailScript.searchScript(whose: "date received > d0", today: true).contains(MailScript.todayPrelude))
}
}