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.

WhatsApp: fixes from an independent review

Claude57d132076bdd
diff --git a/NotchBuddy/Sources/App/WhatsAppController.swift b/NotchBuddy/Sources/App/WhatsAppController.swift
index 37904be6..5715ba38 100644
--- a/NotchBuddy/Sources/App/WhatsAppController.swift
+++ b/NotchBuddy/Sources/App/WhatsAppController.swift
@@ -141,6 +141,8 @@ final class WhatsAppController: ObservableObject {
private var lastPoll = Date()
private var lastAnnounce: Date = .distantPast
private var namingGroups: Set<String> = []
+ /// The conversation open in the card: what arrives there is seen, so it isn't unread.
+ private(set) var openChat: String?
private var rateLimit = WARateLimit(limit: 6, window: 60)
/// Failed checks in a row (the gateway down, refusing, unreachable).
private var failures = 0
@@ -207,7 +209,7 @@ final class WhatsAppController: ObservableObject {
startListener(kind: provider.kind)
if WhatsAppSettings.respectFocus { askFocus() }
// GOWA started by Coucou when asked to (Settings), before the first check.
- WhatsAppGOWAProcess.shared.startIfNeeded()
+ WhatsAppGOWAProcess.shared.sync()
let t = Timer(timeInterval: 5, repeats: true) { _ in
MainActor.assumeIsolated { WhatsAppController.shared.onTick() }
}
@@ -234,9 +236,11 @@ final class WhatsAppController: ObservableObject {
lastWebhook = nil
namingGroups = []
failures = 0
- // Started again on the next begin() with the new settings, or gone for good.
- WhatsAppGOWAProcess.shared.stop()
+ // Turned off: GOWA goes too. Otherwise begin() keeps it, or restarts it if its
+ // settings changed.
+ if !shouldRun { WhatsAppGOWAProcess.shared.stopNow() }
if forget {
+ openChat = nil
inbox.clear()
resetTask()
}
@@ -285,6 +289,9 @@ final class WhatsAppController: ObservableObject {
case .needsQR:
link = .needsQR
if qrPNG == nil || Date() > qrExpiry {
+ // Not asked again for 15 s even when nothing came: each GOWA login call
+ // restarts the pairing.
+ qrExpiry = Date().addingTimeInterval(15)
if let qr = try await provider.qrCode(), gen == generation {
qrPNG = qr.png
qrExpiry = Date().addingTimeInterval(TimeInterval(qr.seconds))
@@ -313,7 +320,7 @@ final class WhatsAppController: ObservableObject {
// Twice in a row (not a gateway still starting): a small red dot on the pill, nothing more.
if failures == 2 { showDown(true) }
// GOWA started by Coucou and gone (crash, killed): started again, once a minute at most.
- if error == .unreachable { WhatsAppGOWAProcess.shared.startIfNeeded() }
+ if error == .unreachable { WhatsAppGOWAProcess.shared.sync() }
}
/// The discreet error pill: the pill's red badge while the gateway is down.
@@ -326,9 +333,21 @@ final class WhatsAppController: ObservableObject {
/// One check from Settings' "Test connection": what the gateway says, in a sentence.
func testConnection() async -> String {
- guard let provider = WhatsAppSettings.makeProvider() else { return String(localized: "whatsapp.status.bad-url") }
+ // The running connection when there is one (a second one could race it for OpenWA's session).
+ guard let provider = provider ?? WhatsAppSettings.makeProvider() else { return String(localized: "whatsapp.status.bad-url") }
do {
- let status = try await provider.status()
+ var status: WAStatus
+ var attempt = 0
+ while true {
+ do {
+ status = try await provider.status()
+ break
+ } catch WAError.unreachable where WhatsAppGOWAProcess.shared.isRunning && attempt < 8 {
+ // GOWA just started by Coucou: give it a few seconds to come up.
+ attempt += 1
+ try? await Task.sleep(for: .seconds(1))
+ }
+ }
switch status.link {
case .connected:
let who = status.me.map(WAJID.displayNumber) ?? ""
@@ -407,8 +426,9 @@ final class WhatsAppController: ObservableObject {
backfilled = true
let since = Date().addingTimeInterval(-12 * 3600)
guard let messages = try? await provider.recentMessages(since: since, me: me), gen == generation else { return }
- ingest(messages, announce: false)
- inbox.markAllRead()
+ // History: kept, never counted as unread (whether it was read is unknown), never announced.
+ for message in messages { inbox.add(message, filters: filters, history: true) }
+ for message in messages { nameGroupIfNeeded(WAJID.normalized(message.chat)) }
lastPoll = Date()
}
@@ -429,9 +449,16 @@ final class WhatsAppController: ObservableObject {
private func ingest(_ messages: [WAMessage], announce: Bool) {
var fresh: WAMessage?
for message in messages {
+ let key = WAJID.normalized(message.chat)
let outcome = inbox.add(message, filters: filters)
+ nameGroupIfNeeded(key)
+ if key == openChat {
+ // Read on screen: no unread, no Mochi. The receipt waits for a reply (or the
+ // next opening), as Settings says.
+ inbox.markRead(key)
+ continue
+ }
if outcome == .notify, !message.fromMe { fresh = message }
- nameGroupIfNeeded(WAJID.normalized(message.chat))
}
if announce, let fresh { self.announce(fresh) }
}
@@ -453,6 +480,7 @@ final class WhatsAppController: ObservableObject {
/// receipt when Settings says so.
func open(_ chat: String) {
sendError = nil
+ openChat = WAJID.normalized(chat)
guard let provider else { return }
if WhatsAppSettings.markReadOnOpen { markRead(chat) }
let gen = generation
@@ -462,13 +490,18 @@ final class WhatsAppController: ObservableObject {
}
}
+ /// The conversation closed (back to the list, Escape, the island folded).
+ func close(_ chat: String) {
+ if openChat == WAJID.normalized(chat) { openChat = nil }
+ }
+
/// Marks the chat read here and on WhatsApp (up to its newest received message).
func markRead(_ chat: String) {
let key = WAJID.normalized(chat)
guard let provider, let conv = inbox.conversations[key] else { return }
let hadUnread = conv.unread > 0
inbox.markRead(key)
- if inbox.totalUnread == 0 { clearBadge() }
+ if inbox.visibleUnread(filters: filters) == 0 { clearBadge() }
// Nothing new: no receipt to send.
guard hadUnread else { return }
let last = conv.messages.last { !$0.fromMe }?.id
@@ -492,15 +525,18 @@ final class WhatsAppController: ObservableObject {
sending = true
sendError = nil
defer { sending = false }
+ let gen = generation
do {
let id = try await provider.send(text: body, to: key)
+ // Turned off or restarted meanwhile: the inbox it belonged to is gone.
+ guard gen == generation else { return true }
var mine = WAMessage(id: id ?? "coucou-\(UUID().uuidString)", chat: key, sender: me ?? "",
senderName: "", text: body, date: Date(), fromMe: true)
mine.chatName = inbox.conversations[key]?.name
inbox.add(mine, filters: filters)
// Replying reads the conversation, whatever the setting.
let last = inbox.conversations[key]?.messages.last { !$0.fromMe }?.id
- if inbox.totalUnread == 0 { clearBadge() }
+ if inbox.visibleUnread(filters: filters) == 0 { clearBadge() }
Task { try? await provider.markRead(chat: key, lastIncoming: last) }
return true
} catch let error as WAError {
@@ -577,7 +613,8 @@ final class WhatsAppController: ObservableObject {
case .authorized:
focusReadable = center.focusStatus.isFocused != nil
case .notDetermined:
- center.requestAuthorization { status in
+ // Intents may answer on any queue: the closure is @Sendable and hops to the main actor.
+ center.requestAuthorization { @Sendable status in
Task { @MainActor in
WhatsAppController.shared.focusReadable = status == .authorized
&& INFocusStatusCenter.default.focusStatus.isFocused != nil
@@ -591,7 +628,10 @@ final class WhatsAppController: ObservableObject {
// MARK: - Filters
func ignore(_ chat: String) {
- filters.ignored.insert(WAJID.normalized(chat))
+ let key = WAJID.normalized(chat)
+ filters.ignored.insert(key)
+ inbox.remove(key)
+ if openChat == key { openChat = nil }
}
func unignore(_ chat: String) {
diff --git a/NotchBuddy/Sources/App/WhatsAppGOWAProcess.swift b/NotchBuddy/Sources/App/WhatsAppGOWAProcess.swift
index 4068a450..e7fbe1a5 100644
--- a/NotchBuddy/Sources/App/WhatsAppGOWAProcess.swift
+++ b/NotchBuddy/Sources/App/WhatsAppGOWAProcess.swift
@@ -33,21 +33,33 @@ final class WhatsAppGOWAProcess {
return base.appendingPathComponent("Coucou/GOWA", isDirectory: true)
}
- /// Starts GOWA unless it already runs (or was started less than a minute ago).
- /// Returns false when the binary can't be run.
+ /// What the running GOWA was started with: changed, it is restarted; same, left alone.
+ private var launchedWith: String?
+
+ /// Brings GOWA in line with Settings: started when "Start GOWA automatically" is on (and
+ /// the gateway is GOWA on this Mac), restarted only when its binary, address or password
+ /// changed, stopped when the option is off. A GOWA that keeps dying is started again once
+ /// a minute at most. Returns false when it can't run.
@discardableResult
- func startIfNeeded() -> Bool {
- guard Self.autoStart, WhatsAppSettings.gateway == .gowa else { return false }
- if isRunning { return true }
- guard Date().timeIntervalSince(lastStart) > 60 else { return true }
+ func sync() -> Bool {
+ guard Self.autoStart, WhatsAppSettings.gateway == .gowa else { stopNow(); return false }
let path = (Self.binaryPath as NSString).expandingTildeInPath
guard !path.isEmpty, FileManager.default.isExecutableFile(atPath: path),
let url = URL(string: WhatsAppSettings.url) else {
appendAppLog("nb.log", "[WhatsApp] GOWA binary missing or not executable")
+ stopNow()
return false
}
// Only ever on this Mac: an address elsewhere is someone else's gateway.
- guard ["127.0.0.1", "localhost", "::1"].contains(url.host ?? "") else { return false }
+ guard ["127.0.0.1", "localhost", "::1"].contains(url.host ?? "") else { stopNow(); return false }
+ let credential = KeychainStore.shared.get(WhatsAppSettings.credentialKey) ?? ""
+ let signature = [path, url.absoluteString, credential].joined(separator: "\u{1F}")
+ if isRunning {
+ if launchedWith == signature { return true }
+ stopNow() // waits for it to let go of the port and its database
+ } else if launchedWith == signature, Date().timeIntervalSince(lastStart) < 60 {
+ return true
+ }
try? FileManager.default.createDirectory(at: Self.workingDirectory, withIntermediateDirectories: true)
let p = Process()
@@ -56,9 +68,7 @@ final class WhatsAppGOWAProcess {
p.currentDirectoryURL = Self.workingDirectory
var env = ProcessInfo.processInfo.environment
// The credential goes through the environment, not the command line (`ps` shows that).
- if let auth = KeychainStore.shared.get(WhatsAppSettings.credentialKey), auth.contains(":") {
- env["APP_BASIC_AUTH"] = auth
- }
+ if credential.contains(":") { env["APP_BASIC_AUTH"] = credential }
p.environment = env
// GOWA's own output may name contacts or quote messages: it goes nowhere.
p.standardOutput = FileHandle.nullDevice
@@ -73,6 +83,7 @@ final class WhatsAppGOWAProcess {
try p.run()
process = p
lastStart = Date()
+ launchedWith = signature
appendAppLog("nb.log", "[WhatsApp] GOWA started (pid \(p.processIdentifier))")
return true
} catch {
@@ -81,23 +92,12 @@ final class WhatsAppGOWAProcess {
}
}
- /// Stops GOWA if Coucou started it (Coucou quits, the option or WhatsApp is turned off).
- func stop() {
- lastStart = .distantPast
- guard let p = process else { return }
- process = nil
- guard p.isRunning else { return }
- p.terminate()
- // Still there after 2 s: killed.
- let pid = p.processIdentifier
- DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
- if kill(pid, 0) == 0 { kill(pid, SIGKILL) }
- }
- }
-
- /// At quit: the gateway can't outlive Coucou, and there is no time to wait.
+ /// Stops GOWA if Coucou started it, waiting a second at most for it to go (at quit, or
+ /// before starting it again so two never share its database).
func stopNow() {
- guard let p = process, p.isRunning else { return }
+ launchedWith = nil
+ guard let p = process else { return }
+ guard p.isRunning else { process = nil; return }
p.terminate()
let deadline = Date().addingTimeInterval(1)
while p.isRunning && Date() < deadline { usleep(50_000) }
diff --git a/NotchBuddy/Sources/App/WhatsAppModels.swift b/NotchBuddy/Sources/App/WhatsAppModels.swift
index 627ff77f..13a92120 100644
--- a/NotchBuddy/Sources/App/WhatsAppModels.swift
+++ b/NotchBuddy/Sources/App/WhatsAppModels.swift
@@ -110,6 +110,8 @@ struct WAInbox: Equatable, Sendable {
private(set) var conversations: [String: WAConversation] = [:]
private var seenIds: Set<String> = []
+ /// The same ids in arrival order, so the oldest are the ones forgotten.
+ private var seenOrder: [String] = []
/// Newest activity first.
var sorted: [WAConversation] {
@@ -130,7 +132,12 @@ struct WAInbox: Equatable, Sendable {
let chat = WAJID.normalized(message.chat)
guard !filters.ignored.contains(chat) else { return .ignored }
seenIds.insert(message.id)
- if seenIds.count > 2_000 { seenIds = Set(seenIds.suffix(1_000)) }
+ seenOrder.append(message.id)
+ if seenOrder.count > 2_000 {
+ let dropped = seenOrder.prefix(1_000)
+ seenOrder.removeFirst(1_000)
+ for id in dropped { seenIds.remove(id) }
+ }
let isGroup = WAJID.isGroup(chat)
let number = WAJID.displayNumber(chat)
@@ -168,6 +175,17 @@ struct WAInbox: Equatable, Sendable {
sorted.filter { !filters.ignored.contains($0.id) && (!$0.isGroup || !filters.muteGroups || $0.messages.contains { $0.mentionsMe && !$0.fromMe }) }
}
+ /// Unread messages in the conversations the pill shows (a muted group's quiet messages
+ /// and an ignored chat can't be opened, so they don't count).
+ func visibleUnread(filters: WAFilters) -> Int {
+ visible(filters: filters).reduce(0) { $0 + $1.unread }
+ }
+
+ /// A chat dropped from the inbox (the user ignores it).
+ mutating func remove(_ chat: String) {
+ conversations[WAJID.normalized(chat)] = nil
+ }
+
mutating func markRead(_ chat: String) {
conversations[WAJID.normalized(chat)]?.unread = 0
}
@@ -186,6 +204,7 @@ struct WAInbox: Equatable, Sendable {
mutating func clear() {
conversations = [:]
seenIds = []
+ seenOrder = []
}
private func nonEmpty(_ s: String) -> String? { s.isEmpty ? nil : s }
diff --git a/NotchBuddy/Sources/App/WhatsAppProvider.swift b/NotchBuddy/Sources/App/WhatsAppProvider.swift
index 7509d1f9..3778440e 100644
--- a/NotchBuddy/Sources/App/WhatsAppProvider.swift
+++ b/NotchBuddy/Sources/App/WhatsAppProvider.swift
@@ -38,7 +38,17 @@ protocol WhatsAppProvider: Sendable {
func groupName(_ chat: String) async -> String?
}
-/// HTTP to the local gateway: no cookies, no cache, nothing stored on disk.
+/// Never follows a redirect: a request (with its credentials and, for a send, the reply's
+/// text) goes to the configured gateway and nowhere else.
+final class WANoRedirect: NSObject, URLSessionTaskDelegate, Sendable {
+ func urlSession(_ session: URLSession, task: URLSessionTask,
+ willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest,
+ completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
+ completionHandler(nil)
+ }
+}
+
+/// HTTP to the local gateway: no cookies, no cache, no redirect, nothing stored on disk.
final class WAHTTP: Sendable {
let base: URL
let headers: [String: String]
@@ -53,7 +63,7 @@ final class WAHTTP: Sendable {
config.httpCookieStorage = nil
config.timeoutIntervalForRequest = 60 // each request sets its own (10 s, longer for a QR)
config.connectionProxyDictionary = [:] // straight to the local gateway
- session = URLSession(configuration: config)
+ session = URLSession(configuration: config, delegate: WANoRedirect(), delegateQueue: nil)
}
/// `path` is appended to the base URL as given (already percent-encoded where needed).
@@ -74,6 +84,8 @@ final class WAHTTP: Sendable {
}
do {
let (data, response) = try await session.data(for: req)
+ // Second lock: an answer from anywhere but the gateway is not one.
+ if let final = response.url, final.host != url.host || final.port != url.port { throw WAError.unreachable }
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
return (data, code)
} catch {
diff --git a/NotchBuddy/Sources/App/WhatsAppViews.swift b/NotchBuddy/Sources/App/WhatsAppViews.swift
index ddd86b68..c426a5d3 100644
--- a/NotchBuddy/Sources/App/WhatsAppViews.swift
+++ b/NotchBuddy/Sources/App/WhatsAppViews.swift
@@ -17,7 +17,8 @@ struct WhatsAppCardView: View {
var body: some View {
Group {
- if wa.link == .connected, let chat = openChat, let conversation = wa.inbox.conversations[chat] {
+ // Kept open through a missed check (the draft too): only gone when WhatsApp is off.
+ if wa.link != .off, let chat = openChat, let conversation = wa.inbox.conversations[chat] {
WhatsAppConversationView(conversation: conversation) {
withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { openChat = nil }
}
@@ -275,7 +276,12 @@ struct WhatsAppConversationView: View {
.padding(.horizontal, 8).padding(.vertical, 4)
.background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(0.06)))
- if let error = wa.sendError {
+ if wa.link != .connected {
+ Text(verbatim: WhatsAppStatus.label(wa.link))
+ .font(.system(size: 9.5))
+ .foregroundColor(Color(hex: "#F5B83D"))
+ .lineLimit(1).truncationMode(.tail)
+ } else if let error = wa.sendError {
Text(verbatim: error)
.font(.system(size: 9.5))
.foregroundColor(Color(hex: "#F4505E"))
@@ -292,7 +298,10 @@ struct WhatsAppConversationView: View {
.onChange(of: draft) { _, text in
wa.composing = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
- .onDisappear { wa.composing = false }
+ .onDisappear {
+ wa.composing = false
+ wa.close(conversation.id)
+ }
}
/// Return: sends. Shift-Return: a new line instead.
diff --git a/NotchBuddy/Sources/App/WhatsAppWebhook.swift b/NotchBuddy/Sources/App/WhatsAppWebhook.swift
index 2f7e321b..949d718d 100644
--- a/NotchBuddy/Sources/App/WhatsAppWebhook.swift
+++ b/NotchBuddy/Sources/App/WhatsAppWebhook.swift
@@ -10,10 +10,21 @@ final class WhatsAppWebhook: @unchecked Sendable {
private let queue = DispatchQueue(label: "fr.louisraille.NotchBuddy.whatsapp.webhook")
private(set) var port: UInt16 = 0
+ private let lock = NSLock()
+ private var _onRequest: (@Sendable (WAHTTPRequest) -> Int)?
+ private var _onListening: (@Sendable (Bool) -> Void)?
+
/// Called on `queue` with each complete request; returns the HTTP status to answer.
- var onRequest: (@Sendable (WAHTTPRequest) -> Int)?
+ /// Set on the main thread, read on `queue`: behind a lock.
+ var onRequest: (@Sendable (WAHTTPRequest) -> Int)? {
+ get { lock.withLock { _onRequest } }
+ set { lock.withLock { _onRequest = newValue } }
+ }
/// Called on `queue`: true once listening, false when the port can't be used.
- var onListening: (@Sendable (Bool) -> Void)?
+ var onListening: (@Sendable (Bool) -> Void)? {
+ get { lock.withLock { _onListening } }
+ set { lock.withLock { _onListening = newValue } }
+ }
/// Starts listening; false when the port is taken or invalid.
@discardableResult
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index acf4c4c2..58cd8bf4 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -333,7 +333,7 @@ Pas d'API WhatsApp pour un compte perso : Coucou parle à une **passerelle local
- **Répondre** : clic → 10 derniers messages + champ (Entrée envoie, Maj+Entrée saut de ligne, Échap ferme ; le brouillon garde l'île ouverte). Réponse seulement dans une conversation déjà là, 4 096 caractères max, 6 par minute. Lu à l'ouverture (option) ou à la réponse, jamais à la réception.
- **Filtres** : groupes muets sauf mention, chats ignorés (clic droit ou Réglages), Concentration via `INFocusStatusCenter` (demande la capability Communication Notifications ; sans elle, le réglage s'affiche indisponible).
- **Vie privée** : rien d'autre que la passerelle locale (pas de photo de profil, elles sont sur les serveurs de WhatsApp), historique en mémoire seulement (20 messages par conversation), vidé à la fermeture ou à la désactivation, aucun contenu dans les logs ni sur disque. URL, identifiants et secret dans le Keychain.
-- **Lancer GOWA automatiquement** : processus enfant `rest --host=127.0.0.1 --port=<port de l'URL> --auto-download-media=false`, identifiant passé par `APP_BASIC_AUTH` (pas sur la ligne de commande), sortie vers `/dev/null`, dossier `~/Library/Application Support/Coucou/GOWA`, arrêté à la fermeture de Coucou, relancé s'il tombe (une fois par minute au plus).
+- **Lancer GOWA automatiquement** : processus enfant `rest --host=127.0.0.1 --port=<port de l'URL> --auto-download-media=false`, identifiant passé par `APP_BASIC_AUTH` (pas sur la ligne de commande), sortie vers `/dev/null`, dossier `~/Library/Application Support/Coucou/GOWA`, arrêté à la fermeture de Coucou ou quand l'option est coupée, redémarré seulement si son binaire, son adresse ou son mot de passe change (en attendant que l'ancien soit parti), relancé s'il tombe (une fois par minute au plus). Aucune requête ne suit de redirection : rien ne part ailleurs que vers la passerelle.
---
diff --git a/tests/WhatsAppTests.swift b/tests/WhatsAppTests.swift
index 96e118fc..32d82716 100644
--- a/tests/WhatsAppTests.swift
+++ b/tests/WhatsAppTests.swift
@@ -58,6 +58,14 @@ enum WhatsAppTests {
for i in 0..<30 { inbox.add(msg("m\(i)", chat: "[email protected]", at: Double(i)), filters: WAFilters()) }
check("20 kept, newest last", inbox.conversations["[email protected]"]?.messages.count == 20
&& inbox.conversations["[email protected]"]?.messages.last?.id == "m29")
+ var big = WAInbox()
+ for i in 0..<2_500 { big.add(msg("b\(i)", chat: "[email protected]", at: Double(i)), filters: WAFilters()) }
+ check("the newest ids are still known after 2,000", big.add(msg("b2499", chat: "[email protected]"), filters: WAFilters()) == .duplicate)
+ var groups = WAInbox()
+ groups.add(msg("q1", chat: "[email protected]", from: "[email protected]"), filters: WAFilters())
+ check("a muted group's quiet messages don't count as unread to read", groups.visibleUnread(filters: WAFilters()) == 0)
+ groups.remove("[email protected]")
+ check("removed", groups.conversations.isEmpty)
inbox.clear()
check("cleared", inbox.conversations.isEmpty)
}