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.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
WhatsApp (WIP): in-memory inbox, filters, rate limit, local webhook listener
Claudefe43357ebfe5
diff --git a/NotchBuddy/Sources/App/WhatsAppModels.swift b/NotchBuddy/Sources/App/WhatsAppModels.swiftnew file mode 100644index 00000000..3ddd3b81--- /dev/null+++ b/NotchBuddy/Sources/App/WhatsAppModels.swift@@ -0,0 +1,253 @@+import Foundation++// WhatsApp in the notch (GitHub build only): what Coucou keeps of the conversations, in memory+// only, and the rules that decide what reaches the pill. Pure Foundation, so the parsing and+// the rules are tested without the app (tests/WhatsAppTests.swift). Nothing here is ever+// written to disk or to a log.++/// What a message holds besides text: only a label is shown, the media itself is never fetched.+enum WAMedia: Equatable, Sendable {+ case none+ case image+ case video+ case audio(seconds: Int?)+ case voice(seconds: Int?)+ case document(name: String?)+ case sticker+ case location+ case contact+ case other+}++struct WAMessage: Identifiable, Equatable, Sendable {+ var id: String+ /// The conversation: a person (…@s.whatsapp.net, …@lid, …@c.us) or a group (…@g.us).+ var chat: String+ /// Who wrote it (in a group, the member; in a private chat, the chat itself).+ var sender: String+ var senderName: String+ var text: String+ var media: WAMedia = .none+ var date: Date+ var fromMe: Bool = false+ /// The message mentions this account (only meaningful in groups).+ var mentionsMe: Bool = false+ /// Set by the gateway when the chat name came with the message.+ var chatName: String? = nil+}++extension WAMessage {+ /// One line for the pill: the text, else the media's label (English keys, localized by the view).+ var previewKey: (key: String, value: String) {+ switch media {+ case .none: return ("", text)+ case .image: return ("whatsapp.media.photo", text)+ case .video: return ("whatsapp.media.video", text)+ case .audio(let s), .voice(let s): return ("whatsapp.media.voice", s.map(WAJID.duration) ?? "")+ case .document(let name): return ("whatsapp.media.document", name ?? text)+ case .sticker: return ("whatsapp.media.sticker", "")+ case .location: return ("whatsapp.media.location", "")+ case .contact: return ("whatsapp.media.contact", "")+ case .other: return ("whatsapp.media.other", text)+ }+ }+}++struct WAConversation: Identifiable, Equatable, Sendable {+ var id: String // the chat JID+ var name: String+ var isGroup: Bool+ /// Newest last, the last `WAInbox.keep` only.+ var messages: [WAMessage] = []+ var unread: Int = 0+ var lastActivity: Date+}++/// What the user chose in Settings → WhatsApp.+struct WAFilters: Equatable, Sendable {+ /// Groups stay quiet unless the message mentions you.+ var muteGroups = true+ /// Chats never shown (JIDs).+ var ignored: Set<String> = []+}++enum WAJID {+ static func isGroup(_ jid: String) -> Bool { jid.hasSuffix("@g.us") }++ /// "[email protected]" → "+33 6 12 34 56 78"-ish: the digits with a plus.+ static func displayNumber(_ jid: String) -> String {+ let user = jid.split(separator: "@").first.map(String.init) ?? jid+ let digits = user.split(separator: ":").first.map(String.init) ?? user+ return digits.allSatisfy(\.isNumber) && !digits.isEmpty ? "+" + digits : digits+ }++ /// Two letters for the avatar: "Marie Dupont" → "MD", "+33 6…" → "#".+ static func initials(_ name: String) -> String {+ let words = name.split { $0 == " " || $0 == "-" }.filter { $0.first?.isLetter == true }+ let letters = words.prefix(2).compactMap { $0.first.map { String($0).uppercased() } }+ return letters.isEmpty ? "#" : letters.joined()+ }++ /// 12 → "0:12", 75 → "1:15".+ static func duration(_ seconds: Int) -> String {+ String(format: "%d:%02d", max(0, seconds) / 60, max(0, seconds) % 60)+ }++ /// The same person under its several forms: "33612345678:[email protected]" and+ /// "[email protected]" are one chat.+ static func normalized(_ jid: String) -> String {+ let parts = jid.split(separator: "@", maxSplits: 1).map(String.init)+ guard parts.count == 2 else { return jid }+ let user = parts[0].split(separator: ":").first.map(String.init) ?? parts[0]+ let server = parts[1] == "c.us" ? "s.whatsapp.net" : parts[1]+ return "\(user)@\(server)"+ }+}++/// The conversations, grouped by chat: one entry per conversation, never one per message.+struct WAInbox: Equatable, Sendable {+ static let keep = 20++ private(set) var conversations: [String: WAConversation] = [:]+ private var seenIds: Set<String> = []++ /// Newest activity first.+ var sorted: [WAConversation] {+ conversations.values.sorted { $0.lastActivity > $1.lastActivity }+ }++ var totalUnread: Int { conversations.values.reduce(0) { $0 + $1.unread } }++ enum Outcome: Equatable { case duplicate, ignored, quiet, notify }++ /// Adds a message to its conversation. `.notify` when it should reach you (Mochi reacts),+ /// `.quiet` when it is kept but stays silent (a muted group, your own message).+ @discardableResult+ mutating func add(_ message: WAMessage, filters: WAFilters, name: String? = nil) -> Outcome {+ guard !seenIds.contains(message.id) else { return .duplicate }+ 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)) }++ let isGroup = WAJID.isGroup(chat)+ var conversation = conversations[chat] ?? WAConversation(+ id: chat, name: name ?? message.chatName ?? (isGroup ? WAJID.displayNumber(chat) : nonEmpty(message.senderName) ?? WAJID.displayNumber(chat)),+ isGroup: isGroup, lastActivity: message.date)+ if let name = name ?? message.chatName, !name.isEmpty { conversation.name = name }+ var msg = message+ msg.chat = chat+ conversation.messages.append(msg)+ conversation.messages.sort { $0.date < $1.date }+ if conversation.messages.count > Self.keep { conversation.messages.removeFirst(conversation.messages.count - Self.keep) }+ conversation.lastActivity = max(conversation.lastActivity, message.date)++ let outcome: Outcome+ if message.fromMe {+ // You answered from the phone: it is read there.+ conversation.unread = 0+ outcome = .quiet+ } else {+ conversation.unread += 1+ outcome = isGroup && filters.muteGroups && !message.mentionsMe ? .quiet : .notify+ }+ conversations[chat] = conversation+ return outcome+ }++ /// The conversations the pill lists: muted groups without unread mentions stay out of it.+ func visible(filters: WAFilters) -> [WAConversation] {+ sorted.filter { !filters.ignored.contains($0.id) && (!$0.isGroup || !filters.muteGroups || $0.messages.contains { $0.mentionsMe && !$0.fromMe }) }+ }++ mutating func markRead(_ chat: String) {+ conversations[WAJID.normalized(chat)]?.unread = 0+ }++ mutating func rename(_ chat: String, to name: String) {+ guard !name.isEmpty else { return }+ conversations[WAJID.normalized(chat)]?.name = name+ }++ /// Everything goes (Coucou quits, WhatsApp turned off).+ mutating func clear() {+ conversations = [:]+ seenIds = []+ }++ private func nonEmpty(_ s: String) -> String? { s.isEmpty ? nil : s }+}++/// A few sends a minute at most, whatever is clicked: Coucou is no bulk sender.+struct WARateLimit: Sendable {+ var limit = 6+ var window: TimeInterval = 60+ private(set) var sent: [Date] = []++ init(limit: Int = 6, window: TimeInterval = 60) {+ self.limit = limit+ self.window = window+ }++ mutating func allow(now: Date = Date()) -> Bool {+ sent.removeAll { now.timeIntervalSince($0) > window }+ guard sent.count < limit else { return false }+ sent.append(now)+ return true+ }+}++// MARK: - The webhook's HTTP request++/// One HTTP request read from the local socket: enough of HTTP/1.1 for a gateway's webhook.+struct WAHTTPRequest: Equatable, Sendable {+ var method: String+ var path: String+ /// Lowercased names.+ var headers: [String: String]+ var body: Data++ enum Parse: Equatable { case incomplete, invalid, done(WAHTTPRequest) }++ /// Parses what arrived so far; `.incomplete` until the whole body is there.+ static func parse(_ data: Data, maxBody: Int = 1_000_000) -> Parse {+ guard let end = data.range(of: Data("\r\n\r\n".utf8)) else {+ return data.count > 16_384 ? .invalid : .incomplete+ }+ guard let head = String(data: data[data.startIndex..<end.lowerBound], encoding: .utf8) else { return .invalid }+ let lines = head.components(separatedBy: "\r\n")+ let first = lines[0].split(separator: " ")+ guard first.count >= 2 else { return .invalid }+ var headers: [String: String] = [:]+ for line in lines.dropFirst() {+ guard let colon = line.firstIndex(of: ":") else { continue }+ let name = line[..<colon].trimmingCharacters(in: .whitespaces).lowercased()+ headers[name] = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)+ }+ let length = Int(headers["content-length"] ?? "0") ?? -1+ guard length >= 0, length <= maxBody else { return .invalid }+ let bodyStart = end.upperBound+ guard data.count - (bodyStart - data.startIndex) >= length else { return .incomplete }+ let body = data[bodyStart..<(bodyStart + length)]+ return .done(WAHTTPRequest(method: String(first[0]), path: String(first[1]), headers: headers, body: Data(body)))+ }++ static func response(_ status: Int, _ reason: String) -> Data {+ Data("HTTP/1.1 \(status) \(reason)\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".utf8)+ }+}++// MARK: - Hex++extension Data {+ var hexString: String { map { String(format: "%02x", $0) }.joined() }+}++/// Compares two strings in constant time (signatures).+func waConstantTimeEqual(_ a: String, _ b: String) -> Bool {+ let x = Array(a.utf8), y = Array(b.utf8)+ guard x.count == y.count else { return false }+ var diff: UInt8 = 0+ for i in x.indices { diff |= x[i] ^ y[i] }+ return diff == 0+}diff --git a/NotchBuddy/Sources/App/WhatsAppWebhook.swift b/NotchBuddy/Sources/App/WhatsAppWebhook.swiftnew file mode 100644index 00000000..dfcc0712--- /dev/null+++ b/NotchBuddy/Sources/App/WhatsAppWebhook.swift@@ -0,0 +1,79 @@+#if !APPSTORE+import Foundation+import Network++/// The local door the WhatsApp gateway knocks on with each new message: an HTTP listener bound+/// to 127.0.0.1 only (never reachable from another machine), on the port set in Settings.+/// Each request is handed over whole; nothing of it is logged.+final class WhatsAppWebhook: @unchecked Sendable {+ private var listener: NWListener?+ private let queue = DispatchQueue(label: "fr.louisraille.NotchBuddy.whatsapp.webhook")+ private(set) var port: UInt16 = 0++ /// Called on `queue` with each complete request; returns the HTTP status to answer.+ var onRequest: (@Sendable (WAHTTPRequest) -> Int)?++ /// Starts listening; false when the port is taken or invalid.+ @discardableResult+ func start(port: UInt16) -> Bool {+ stop()+ guard port > 0, let nwPort = NWEndpoint.Port(rawValue: port) else { return false }+ let params = NWParameters.tcp+ params.allowLocalEndpointReuse = true+ params.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: nwPort)+ params.acceptLocalOnly = true+ guard let listener = try? NWListener(using: params) else { return false }+ listener.newConnectionHandler = { [weak self] connection in self?.serve(connection) }+ listener.stateUpdateHandler = { state in+ if case .failed(let error) = state {+ appendAppLog("nb.log", "[WhatsApp] webhook listener failed: \(error.localizedDescription)")+ }+ }+ listener.start(queue: queue)+ self.listener = listener+ self.port = port+ return true+ }++ func stop() {+ listener?.cancel()+ listener = nil+ port = 0+ }++ private func serve(_ connection: NWConnection) {+ // Only the loopback: the listener is bound to it, this is a second lock.+ if case .hostPort(let host, _) = connection.endpoint {+ switch host {+ case .ipv4(let a) where a == .loopback: break+ case .ipv6(let a) where a == .loopback: break+ default:+ connection.cancel()+ return+ }+ }+ connection.start(queue: queue)+ receive(connection, buffer: Data())+ // A request that never finishes is dropped.+ queue.asyncAfter(deadline: .now() + 10) { connection.cancel() }+ }++ private func receive(_ connection: NWConnection, buffer: Data) {+ connection.receive(minimumIncompleteLength: 1, maximumLength: 65_536) { [weak self] data, _, isComplete, error in+ guard let self else { return }+ var buffer = buffer+ if let data { buffer.append(data) }+ switch WAHTTPRequest.parse(buffer) {+ case .incomplete where !isComplete && error == nil:+ self.receive(connection, buffer: buffer)+ case .done(let request):+ let status = self.onRequest?(request) ?? 503+ let reason = status == 200 ? "OK" : (status == 401 ? "Unauthorized" : "Error")+ connection.send(content: WAHTTPRequest.response(status, reason), completion: .contentProcessed { _ in connection.cancel() })+ default:+ connection.send(content: WAHTTPRequest.response(400, "Bad Request"), completion: .contentProcessed { _ in connection.cancel() })+ }+ }+ }+}+#endifdiff --git a/tests/WhatsAppTests.swift b/tests/WhatsAppTests.swiftnew file mode 100644index 00000000..58e86077--- /dev/null+++ b/tests/WhatsAppTests.swift@@ -0,0 +1,106 @@+import Foundation++@main+enum WhatsAppTests {+ static var failures = 0++ static func check(_ label: String, _ got: Bool) {+ if got { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ static func msg(_ id: String, chat: String, from: String? = nil, text: String = "hi", at: Double = 0,+ fromMe: Bool = false, mention: Bool = false) -> WAMessage {+ WAMessage(id: id, chat: chat, sender: from ?? chat, senderName: "Marie", text: text,+ date: Date(timeIntervalSince1970: 1_800_000_000 + at), fromMe: fromMe, mentionsMe: mention)+ }++ static func main() {+ print("\nInbox: one conversation per chat")+ do {+ var inbox = WAInbox()+ let f = WAFilters()+ check("a new message notifies", inbox.add(msg("1", chat: "[email protected]"), filters: f) == .notify)+ inbox.add(msg("2", chat: "[email protected]", at: 5), filters: f)+ inbox.add(msg("3", chat: "[email protected]", at: 3), filters: f)+ check("grouped by chat", inbox.conversations.count == 2)+ check("unread counted", inbox.conversations["[email protected]"]?.unread == 2)+ check("newest first", inbox.sorted.first?.id == "[email protected]")+ check("a duplicate is ignored", inbox.add(msg("2", chat: "[email protected]"), filters: f) == .duplicate)+ check("the same person under another form", inbox.add(msg("4", chat: "33600000001:[email protected]", at: 9), filters: f) == .notify+ && inbox.conversations.count == 2)+ inbox.markRead("[email protected]")+ check("marked read", inbox.conversations["[email protected]"]?.unread == 0)+ check("total", inbox.totalUnread == 1)+ check("my own message is quiet and reads the chat",+ inbox.add(msg("5", chat: "[email protected]", at: 10, fromMe: true), filters: f) == .quiet+ && inbox.conversations["[email protected]"]?.unread == 0)+ }++ print("\nFilters")+ do {+ var inbox = WAInbox()+ var f = WAFilters()+ let group = "[email protected]"+ check("a group stays quiet", inbox.add(msg("g1", chat: group, from: "[email protected]"), filters: f) == .quiet)+ check("hidden from the pill", inbox.visible(filters: f).isEmpty)+ check("unless it mentions me", inbox.add(msg("g2", chat: group, from: "[email protected]", mention: true), filters: f) == .notify)+ check("then it shows", inbox.visible(filters: f).count == 1)+ f.ignored = ["[email protected]"]+ check("an ignored chat never comes in", inbox.add(msg("i1", chat: "[email protected]"), filters: f) == .ignored)+ f.muteGroups = false+ check("groups heard when not muted", inbox.add(msg("g3", chat: group, from: "[email protected]"), filters: f) == .notify)+ }++ print("\nOnly the last messages are kept")+ do {+ var inbox = WAInbox()+ 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")+ inbox.clear()+ check("cleared", inbox.conversations.isEmpty)+ }++ print("\nLabels")+ do {+ check("initials", WAJID.initials("Marie Dupont") == "MD" && WAJID.initials("+33 6") == "#")+ check("number", WAJID.displayNumber("[email protected]") == "+33612345678")+ check("group", WAJID.isGroup("[email protected]") && !WAJID.isGroup("[email protected]"))+ check("voice duration", WAMessage(id: "v", chat: "c", sender: "c", senderName: "", text: "", media: .voice(seconds: 12),+ date: Date()).previewKey == ("whatsapp.media.voice", "0:12"))+ }++ print("\nRate limit")+ do {+ var limit = WARateLimit(limit: 3, window: 60)+ let now = Date()+ check("three in a minute", limit.allow(now: now) && limit.allow(now: now) && limit.allow(now: now))+ check("not four", !limit.allow(now: now))+ check("again a minute later", limit.allow(now: now.addingTimeInterval(61)))+ }++ print("\nThe webhook's HTTP request")+ do {+ let body = #"{"event":"message"}"#+ let raw = "POST /whatsapp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\nX-Hub-Signature-256: sha256=ab\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)"+ if case .done(let r) = WAHTTPRequest.parse(Data(raw.utf8)) {+ check("method and path", r.method == "POST" && r.path == "/whatsapp")+ check("headers lowercased", r.headers["x-hub-signature-256"] == "sha256=ab")+ check("body", String(data: r.body, encoding: .utf8) == body)+ } else { check("parsed", false) }+ check("incomplete body waits", WAHTTPRequest.parse(Data(String(raw.dropLast(3)).utf8)) == .incomplete)+ check("headers not done yet", WAHTTPRequest.parse(Data("POST / HTTP/1.1\r\nHost: x".utf8)) == .incomplete)+ check("garbage refused", WAHTTPRequest.parse(Data("\r\n\r\n".utf8)) == .invalid)+ check("constant-time compare", waConstantTimeEqual("abc", "abc") && !waConstantTimeEqual("abc", "abd"))+ }++ runGatewayTests()++ if failures > 0 {+ print("\n\(failures) failure(s)")+ exit(1)+ }+ print("\nAll WhatsApp tests passed")+ }+}