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 pill, phase 2: reply from the notch
Claude41d5cee482e0
diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstringsindex 8e399247..63e371f4 100644--- a/NotchBuddy/Resources/Localizable.xcstrings+++ b/NotchBuddy/Resources/Localizable.xcstrings@@ -1,6 +1,331 @@{"sourceLanguage" : "en","strings" : {+ "whatsapp.mark-read-on-open" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "تعليم كمقروء عند فتح محادثة"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "কথোপকথন খুললে পড়া হিসেবে চিহ্নিত করো"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mark as read when I open a conversation"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Marcar como leído al abrir una conversación"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Marquer comme lu quand j’ouvre une conversation"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "बातचीत खोलने पर पढ़ा हुआ मार्क करें"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tandai dibaca saat saya membuka percakapan"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Marcar como lida ao abrir uma conversa"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Отмечать прочитанным при открытии беседы"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开对话时标记为已读"+ }+ }+ }+ },+ "whatsapp.mark-read.hint" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "عند الإيقاف: تُعلَّم كمقروءة فقط عند الرد. لا تُعلَّم أبدًا لمجرد الوصول."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "বন্ধ: শুধু উত্তর দিলে পড়া হিসেবে চিহ্নিত। বার্তা এলেই কখনও নয়।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Off: marked read only when you reply. Never when a message just arrives."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Desactivado: se marca como leído solo al responder. Nunca solo por recibirlo."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Désactivé : marqué comme lu seulement quand tu réponds. Jamais à la simple réception."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "बंद: सिर्फ़ जवाब देने पर पढ़ा हुआ। संदेश आने भर से कभी नहीं।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mati: ditandai dibaca hanya saat kamu membalas. Tidak pernah hanya karena pesan masuk."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Desativado: marcada como lida só quando você responde. Nunca só por chegar."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Выключено: прочитанным отмечается только при ответе. Никогда при простом получении."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "关闭时:仅在你回复时标记为已读。收到消息时从不标记。"+ }+ }+ }+ },+ "whatsapp.reply.placeholder" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "رد… (⇧↩ سطر جديد)"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "উত্তর দিন… (⇧↩ নতুন লাইন)"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reply… (⇧↩ new line)"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Responder… (⇧↩ nueva línea)"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Répondre… (⇧↩ nouvelle ligne)"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "जवाब दें… (⇧↩ नई लाइन)"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Balas… (⇧↩ baris baru)"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Responder… (⇧↩ nova linha)"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ответить… (⇧↩ новая строка)"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "回复…(⇧↩ 换行)"+ }+ }+ }+ },+ "whatsapp.reply.too-fast" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "بضعة ردود في الدقيقة كحد أقصى: انتظر قليلًا."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "মিনিটে সর্বোচ্চ কয়েকটি উত্তর: একটু অপেক্ষা করুন।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "A few replies a minute at most: wait a moment."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Unas pocas respuestas por minuto como máximo: espera un momento."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Quelques réponses par minute au maximum : attends un instant."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "एक मिनट में कुछ ही जवाब: थोड़ा रुकें।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Paling banyak beberapa balasan per menit: tunggu sebentar."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "No máximo algumas respostas por minuto: espere um pouco."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Не больше нескольких ответов в минуту: подождите немного."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每分钟最多回复几条:请稍等。"+ }+ }+ }+ },+ "whatsapp.reply.too-long" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "طويل جدًا لرسالة واحدة (4096 حرفًا كحد أقصى)."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "একটি বার্তার জন্য খুব লম্বা (সর্বোচ্চ ৪০৯৬ অক্ষর)।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Too long for one message (4,096 characters at most)."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Demasiado largo para un mensaje (4096 caracteres como máximo)."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Trop long pour un seul message (4 096 caractères au maximum)."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "एक संदेश के लिए बहुत लंबा (अधिकतम 4,096 अक्षर)।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Terlalu panjang untuk satu pesan (maksimal 4.096 karakter)."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Longo demais para uma mensagem (no máximo 4.096 caracteres)."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Слишком длинно для одного сообщения (не больше 4096 символов)."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "单条消息过长(最多 4096 个字符)。"+ }+ }+ }+ },"whatsapp.add" : {"extractionState" : "manual","localizations" : {@@ -1573,7 +1898,7 @@"bn" : {"stringUnit" : {"state" : "translated",- "value" : "সরাও"+ "value" : "সরান"}},"en" : {@@ -1615,7 +1940,7 @@"ru" : {"stringUnit" : {"state" : "translated",- "value" : "Убрать"+ "value" : "Удалить"}},"zh-Hans" : {diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swiftindex 88eb474a..a152f4d9 100644--- a/NotchBuddy/Sources/App/IslandWindowController.swift+++ b/NotchBuddy/Sources/App/IslandWindowController.swift@@ -325,7 +325,13 @@ final class IslandWindowController: NSWindowController {}// An approval, or an email prepared by voice, stays open until I click.+ #if !APPSTORE+ // A WhatsApp reply being typed holds the island open, like a voice mail draft.+ fsm.isHeldOpen = { AppState.shared.pendingApproval != nil || AppState.shared.voiceMailDraft != nil+ || WhatsAppController.shared.composing }+ #elsefsm.isHeldOpen = { AppState.shared.pendingApproval != nil || AppState.shared.voiceMailDraft != nil }+ #endif// Voice: wake phrase detected → open listening island#if !APPSTOREdiff --git a/NotchBuddy/Sources/App/WhatsAppController.swift b/NotchBuddy/Sources/App/WhatsAppController.swiftindex e873286c..7006511b 100644--- a/NotchBuddy/Sources/App/WhatsAppController.swift+++ b/NotchBuddy/Sources/App/WhatsAppController.swift@@ -28,6 +28,12 @@ enum WhatsAppSettings {get { let p = ud.integer(forKey: "whatsappPort"); return (1024...65535).contains(p) ? p : defaultPort }set { ud.set(newValue, forKey: "whatsappPort") }}+ /// Read receipts: sent when a conversation is opened (on), or only when replying (off).+ /// Never on mere reception.+ static var markReadOnOpen: Bool {+ get { ud.object(forKey: "whatsappMarkReadOnOpen") as? Bool ?? true }+ set { ud.set(newValue, forKey: "whatsappMarkReadOnOpen") }+ }static var respectFocus: Bool {get { ud.object(forKey: "whatsappRespectFocus") as? Bool ?? true }set { ud.set(newValue, forKey: "whatsappRespectFocus") }@@ -111,6 +117,12 @@ final class WhatsAppController: ObservableObject {@Published private(set) var me: String?/// Whether macOS lets Coucou read the Focus state (nil: not asked yet).@Published private(set) var focusReadable: Bool?+ /// A reply on its way.+ @Published private(set) var sending = false+ /// A reply is being typed: the island stays open until it is sent or cleared.+ var composing = false+ /// Why the last reply didn't go (shown under the field until the next try).+ @Published private(set) var sendError: String?@Published var filters = WhatsAppSettings.filters {didSet { WhatsAppSettings.filters = filters }}@@ -129,6 +141,9 @@ final class WhatsAppController: ObservableObject {private var lastPoll = Date()private var lastAnnounce: Date = .distantPastprivate var namingGroups: Set<String> = []+ private var rateLimit = WARateLimit(limit: 6, window: 60)+ /// Failed checks in a row (the gateway down, refusing, unreachable).+ private var failures = 0private var cancellables = Set<AnyCancellable>()private var shouldRun: Bool {@@ -210,6 +225,7 @@ final class WhatsAppController: ObservableObject {backfilled = falselastWebhook = nilnamingGroups = []+ failures = 0if forget {inbox.clear()resetTask()@@ -227,7 +243,10 @@ final class WhatsAppController: ObservableObject {private func onTick() {tick += 1if link != .connected {- refresh() // every 5 s while linking (QR, gateway coming up)+ // Every 5 s while linking (QR, gateway coming up); every 30 s once the gateway+ // has been down for a minute.+ if failures > 12 && tick % 6 != 0 { return }+ refresh()} else {if tick % 12 == 0 { refresh() } // every minute: still linked?if tick % 4 == 0 { poll() } // every 20 s, unless the webhook delivers@@ -244,6 +263,7 @@ final class WhatsAppController: ObservableObject {do {let status = try await provider.status()guard self.provider != nil else { return }+ if failures > 0 { failures = 0; showDown(false) }me = status.meswitch status.link {case .connected:@@ -265,7 +285,7 @@ final class WhatsAppController: ObservableObject {} catch let error as WAError {apply(error)} catch {- link = .unreachable+ apply(.unreachable)}}}@@ -277,6 +297,18 @@ final class WhatsAppController: ObservableObject {case .notLoggedIn: link = .needsQRcase .refused(let why): link = .failed(why)}+ guard error != .notLoggedIn else { return }+ failures += 1+ // Twice in a row (not a gateway still starting): a small red dot on the pill, nothing more.+ if failures == 2 { showDown(true) }+ }++ /// The discreet error pill: the pill's red badge while the gateway is down.+ private func showDown(_ down: Bool) {+ let state = AppState.shared+ guard let i = state.tasks.firstIndex(where: { $0.id == Self.pillId }) else { return }+ if down { state.tasks[i].pillBadge = .error }+ else if state.tasks[i].pillBadge == .error { state.tasks[i].pillBadge = nil }}/// One check from Settings' "Test connection": what the gateway says, in a sentence.@@ -399,6 +431,81 @@ final class WhatsAppController: ObservableObject {}}+ // MARK: - Conversation (phase 2)++ /// A conversation opened in the card: its latest messages from the gateway, and the read+ /// receipt when Settings says so.+ func open(_ chat: String) {+ sendError = nil+ guard let provider else { return }+ if WhatsAppSettings.markReadOnOpen { markRead(chat) }+ Task {+ guard let history = try? await provider.messages(chat: chat, limit: 10, me: me), self.provider != nil else { return }+ for message in history { inbox.add(message, filters: filters, history: true) }+ }+ }++ /// 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() }+ // Nothing new: no receipt to send.+ guard hadUnread else { return }+ let last = conv.messages.last { !$0.fromMe }?.id+ Task { try? await provider.markRead(chat: key, lastIncoming: last) }+ }++ /// Sends a reply. Only to a conversation already in the inbox, one at a time, a few a minute.+ /// True once the gateway took it.+ func send(_ text: String, to chat: String) async -> Bool {+ let key = WAJID.normalized(chat)+ guard let provider, !sending else { return false }+ if let refusal = WAReply.check(text, to: key, in: inbox) {+ if refusal == .tooLong { sendError = String(localized: "whatsapp.reply.too-long") }+ return false+ }+ guard rateLimit.allow() else {+ sendError = String(localized: "whatsapp.reply.too-fast")+ return false+ }+ let body = text.trimmingCharacters(in: .whitespacesAndNewlines)+ sending = true+ sendError = nil+ defer { sending = false }+ do {+ let id = try await provider.send(text: body, to: key)+ 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() }+ Task { try? await provider.markRead(chat: key, lastIncoming: last) }+ return true+ } catch let error as WAError {+ switch error {+ case .unreachable: sendError = String(localized: "whatsapp.status.unreachable")+ case .unauthorized: sendError = String(localized: "whatsapp.status.unauthorized")+ case .notLoggedIn: sendError = String(localized: "whatsapp.status.needs-qr")+ case .refused(let why): sendError = why+ }+ return false+ } catch {+ sendError = String(localized: "whatsapp.status.unreachable")+ return false+ }+ }++ private func clearBadge() {+ let state = AppState.shared+ guard let i = state.tasks.firstIndex(where: { $0.id == Self.pillId }) else { return }+ state.tasks[i].pillBadge = nil+ }+// MARK: - Mochi/// A new message reaches you: Mochi's little "happy" emote, the global sound setting, anddiff --git a/NotchBuddy/Sources/App/WhatsAppModels.swift b/NotchBuddy/Sources/App/WhatsAppModels.swiftindex 30bd1bda..627ff77f 100644--- a/NotchBuddy/Sources/App/WhatsAppModels.swift+++ b/NotchBuddy/Sources/App/WhatsAppModels.swift@@ -123,7 +123,9 @@ struct WAInbox: Equatable, Sendable {/// 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 {+ /// `history`: an older message loaded on demand (a conversation opened): kept, never counted+ /// as unread, never announced.+ mutating func add(_ message: WAMessage, filters: WAFilters, name: String? = nil, history: Bool = false) -> Outcome {guard !seenIds.contains(message.id) else { return .duplicate }let chat = WAJID.normalized(message.chat)guard !filters.ignored.contains(chat) else { return .ignored }@@ -147,7 +149,9 @@ struct WAInbox: Equatable, Sendable {conversation.lastActivity = max(conversation.lastActivity, message.date)let outcome: Outcome- if message.fromMe {+ if history {+ outcome = .quiet+ } else if message.fromMe {// You answered from the phone: it is read there.conversation.unread = 0outcome = .quiet@@ -187,6 +191,22 @@ struct WAInbox: Equatable, Sendable {private func nonEmpty(_ s: String) -> String? { s.isEmpty ? nil : s }}+/// What may be sent from the notch: a reply, in a conversation already there, one at a time.+enum WAReply {+ enum Refusal: Equatable, Sendable { case empty, tooLong, notAConversation }+ /// The gateways' own cap (OpenWA's send-text takes 4,096 characters at most).+ static let maxLength = 4096++ static func check(_ text: String, to chat: String, in inbox: WAInbox) -> Refusal? {+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ if trimmed.isEmpty { return .empty }+ if trimmed.count > maxLength { return .tooLong }+ // Never a new chat, never a list of recipients: only a conversation that wrote to you.+ guard inbox.conversations[WAJID.normalized(chat)] != nil else { return .notAConversation }+ return nil+ }+}+/// A few sends a minute at most, whatever is clicked: Coucou is no bulk sender.struct WARateLimit: Sendable {var limit = 6diff --git a/NotchBuddy/Sources/App/WhatsAppViews.swift b/NotchBuddy/Sources/App/WhatsAppViews.swiftindex 52ef6b1e..77e174ec 100644--- a/NotchBuddy/Sources/App/WhatsAppViews.swift+++ b/NotchBuddy/Sources/App/WhatsAppViews.swift@@ -12,18 +12,30 @@ let whatsAppAccent = "#25D366"/// When the gateway isn't linked, the card says why and leads to Settings.struct WhatsAppCardView: View {@ObservedObject private var wa = WhatsAppController.shared+ /// The conversation opened in the card (phase 2: read and reply).+ @State private var openChat: String? = nilvar body: some View {- VStack(alignment: .leading, spacing: 0) {- header- if wa.link == .connected {- list+ Group {+ if wa.link == .connected, let chat = openChat, let conversation = wa.inbox.conversations[chat] {+ WhatsAppConversationView(conversation: conversation) {+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) { openChat = nil }+ }+ .transition(.opacity)} else {- status+ VStack(alignment: .leading, spacing: 0) {+ header+ if wa.link == .connected {+ list+ } else {+ status+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .padding(.top, 4)+ .transition(.opacity)}}- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)- .padding(.top, 4)}private var header: some View {@@ -63,7 +75,12 @@ struct WhatsAppCardView: View {ScrollView(.vertical, showsIndicators: false) {VStack(alignment: .leading, spacing: 3) {ForEach(conversations) { conversation in- WhatsAppRow(conversation: conversation)+ WhatsAppRow(conversation: conversation) {+ wa.open(conversation.id)+ withAnimation(.spring(response: 0.28, dampingFraction: 0.82)) {+ openChat = conversation.id+ }+ }}}}@@ -174,6 +191,183 @@ struct WhatsAppRow: View {}}+// MARK: - Conversation++/// One conversation opened in the card: its last ten messages and a reply field.+/// Return sends, Shift-Return starts a new line, Escape goes back to the list.+/// Nothing is sent without the user's own Return or click.+struct WhatsAppConversationView: View {+ let conversation: WAConversation+ let onClose: () -> Void+ @ObservedObject private var wa = WhatsAppController.shared+ @State private var draft = ""+ @FocusState private var focused: Bool++ private var shown: [WAMessage] { Array(conversation.messages.suffix(10)) }++ var body: some View {+ VStack(alignment: .leading, spacing: 4) {+ // Header: back, initials, name+ HStack(spacing: 6) {+ Button(action: onClose) {+ Image(systemName: "chevron.left")+ .font(.system(size: 10, weight: .semibold))+ .foregroundColor(Color(hex: "#6B7079"))+ .frame(width: 20, height: 20)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ WhatsAppAvatar(name: conversation.name, isGroup: conversation.isGroup, size: 16)+ Text(conversation.name)+ .font(.system(size: 11, weight: .semibold))+ .foregroundColor(Color(hex: "#F5F6F8"))+ .lineLimit(1).truncationMode(.tail)+ .help(WAJID.displayNumber(conversation.id))+ Spacer(minLength: 2)+ }+ // The card's ↗ button sits in the top-right corner (36 pt, like every card header).+ .padding(.trailing, 24)++ // The last messages, newest at the bottom.+ ScrollViewReader { proxy in+ ScrollView(.vertical, showsIndicators: false) {+ VStack(alignment: .leading, spacing: 3) {+ ForEach(shown) { message in+ WhatsAppBubble(message: message, isGroup: conversation.isGroup)+ .id(message.id)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .onAppear {+ if let last = shown.last?.id { proxy.scrollTo(last, anchor: .bottom) }+ }+ .onChange(of: shown.last?.id) { _, last in+ guard let last else { return }+ withAnimation(.easeOut(duration: 0.2)) { proxy.scrollTo(last, anchor: .bottom) }+ }+ }+ .frame(maxHeight: .infinity)++ // Reply+ HStack(spacing: 6) {+ TextField(String(localized: "whatsapp.reply.placeholder"), text: $draft, axis: .vertical)+ .textFieldStyle(.plain)+ .font(.system(size: 11))+ .lineLimit(1...3)+ .focused($focused)+ .onSubmit(submit)+ .onExitCommand(perform: onClose)+ .disabled(wa.sending)+ if wa.sending {+ ProgressView().controlSize(.mini)+ } else {+ Button(action: send) {+ Image(systemName: "arrow.up.circle.fill")+ .font(.system(size: 14))+ .foregroundColor(Color(hex: whatsAppAccent)+ .opacity(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? 0.3 : 1))+ }+ .buttonStyle(.plain)+ .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ .padding(.horizontal, 8).padding(.vertical, 4)+ .background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(0.06)))++ if let error = wa.sendError {+ Text(verbatim: error)+ .font(.system(size: 9.5))+ .foregroundColor(Color(hex: "#F4505E"))+ .lineLimit(1).truncationMode(.tail)+ }+ }+ .padding(.top, 4)+ .padding(.leading, 108)+ .padding(.trailing, 12)+ .padding(.bottom, 4)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .contentShape(Rectangle())+ .onAppear { focused = true }+ .onChange(of: draft) { _, text in+ wa.composing = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }+ .onDisappear { wa.composing = false }+ }++ /// Return: sends. Shift-Return: a new line instead.+ private func submit() {+ if NSEvent.modifierFlags.contains(.shift) {+ draft += "\n"+ focused = true+ return+ }+ send()+ }++ private func send() {+ let text = draft+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+ Task {+ if await wa.send(text, to: conversation.id) { draft = "" }+ focused = true+ }+ }+}++/// One message in the conversation: theirs on the left, yours tinted green on the right.+struct WhatsAppBubble: View {+ let message: WAMessage+ let isGroup: Bool++ var body: some View {+ let (key, value) = message.previewKey+ let label = key.isEmpty ? nil : NSLocalizedString(key, comment: "")+ HStack(spacing: 0) {+ if message.fromMe { Spacer(minLength: 40) }+ VStack(alignment: .leading, spacing: 1) {+ if isGroup && !message.fromMe && !message.senderName.isEmpty {+ Text(message.senderName)+ .font(.system(size: 9, weight: .semibold))+ .foregroundColor(Color(hex: whatsAppAccent).opacity(0.8))+ .lineLimit(1)+ }+ if let label {+ Label(label, systemImage: Self.icon(message.media))+ .font(.system(size: 10, weight: .medium))+ .foregroundColor(Color(hex: "#9398A1"))+ }+ if !value.isEmpty {+ Text(value)+ .font(.system(size: 10.5))+ .foregroundColor(Color(hex: message.fromMe ? "#E8E9EC" : "#C5C8CD"))+ .textSelection(.enabled)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ .padding(.horizontal, 7).padding(.vertical, 3)+ .background(+ RoundedRectangle(cornerRadius: 6)+ .fill(message.fromMe ? Color(hex: whatsAppAccent).opacity(0.16) : Color.white.opacity(0.06))+ )+ if !message.fromMe { Spacer(minLength: 40) }+ }+ }++ private static func icon(_ media: WAMedia) -> String {+ switch media {+ case .image: return "photo"+ case .video: return "video"+ case .audio, .voice: return "waveform"+ case .document: return "doc"+ case .sticker: return "face.smiling"+ case .location: return "mappin.and.ellipse"+ case .contact: return "person.crop.circle"+ case .none, .other: return "ellipsis.bubble"+ }+ }+}+/// Initials on WhatsApp green: no photo is ever fetched (they live on WhatsApp's servers).struct WhatsAppAvatar: View {let name: String@@ -234,6 +428,7 @@ struct WhatsAppSettingsSection: View {@State private var credential = KeychainStore.shared.get(WhatsAppSettings.credentialKey) ?? ""@State private var port = String(WhatsAppSettings.port)@State private var respectFocus = WhatsAppSettings.respectFocus+ @State private var markReadOnOpen = WhatsAppSettings.markReadOnOpen@State private var testResult: String?@State private var testing = false@State private var ignoreEntry = ""@@ -320,6 +515,13 @@ struct WhatsAppSettingsSection: View {.fixedSize(horizontal: false, vertical: true)}+ Toggle("whatsapp.mark-read-on-open", isOn: $markReadOnOpen)+ .onChange(of: markReadOnOpen) { _, on in WhatsAppSettings.markReadOnOpen = on }+ Text("whatsapp.mark-read.hint")+ .font(.system(size: 10))+ .foregroundColor(Color(hex: "#8E939C"))+ .fixedSize(horizontal: false, vertical: true)+ignoredChatsText("whatsapp.privacy")diff --git a/tests/WhatsAppGatewayTests.swift b/tests/WhatsAppGatewayTests.swiftindex 72b240f9..b12ee085 100644--- a/tests/WhatsAppGatewayTests.swift+++ b/tests/WhatsAppGatewayTests.swift@@ -273,6 +273,12 @@ extension WhatsAppTests {inbox.add(WAMessage(id: "o2", chat: "[email protected]", sender: "x", senderName: "Marie", text: "yo",date: Date()), filters: WAFilters())check("…their reply does", inbox.conversations["[email protected]"]?.name == "Marie")+ let before = inbox.conversations["[email protected]"]?.unread+ check("history loaded on opening is quiet and unread untouched",+ inbox.add(WAMessage(id: "h1", chat: "[email protected]", sender: "x", senderName: "Marie", text: "old",+ date: Date(timeIntervalSinceNow: -3600)), filters: WAFilters(), history: true) == .quiet+ && inbox.conversations["[email protected]"]?.unread == before+ && inbox.conversations["[email protected]"]?.messages.first?.id == "h1")}}}diff --git a/tests/WhatsAppTests.swift b/tests/WhatsAppTests.swiftindex 58e86077..96e118fc 100644--- a/tests/WhatsAppTests.swift+++ b/tests/WhatsAppTests.swift@@ -80,6 +80,17 @@ enum WhatsAppTests {check("again a minute later", limit.allow(now: now.addingTimeInterval(61)))}+ print("\nReplies")+ do {+ var inbox = WAInbox()+ inbox.add(msg("r1", chat: "[email protected]"), filters: WAFilters())+ check("a reply in an open conversation", WAReply.check("ok !", to: "[email protected]", in: inbox) == nil)+ check("…under its other form too", WAReply.check("ok", to: "[email protected]", in: inbox) == nil)+ check("never to a new chat", WAReply.check("hi", to: "[email protected]", in: inbox) == .notAConversation)+ check("nothing empty", WAReply.check(" \n ", to: "[email protected]", in: inbox) == .empty)+ check("not too long", WAReply.check(String(repeating: "a", count: 4097), to: "[email protected]", in: inbox) == .tooLong)+ }+print("\nThe webhook's HTTP request")do {let body = #"{"event":"message"}"#diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.jsonindex 22982fd8..c9ac1938 100644--- a/windows/src/i18n/extra.json+++ b/windows/src/i18n/extra.json@@ -1717,17 +1717,6 @@"ru": "Ретранслятор","id": "Relay"},- "Remove": {- "zh-Hans": "移除",- "hi": "हटाएँ",- "es": "Quitar",- "ar": "إزالة",- "fr": "Retirer",- "bn": "সরান",- "pt-BR": "Remover",- "ru": "Удалить",- "id": "Hapus"- },"Repositories": {"zh-Hans": "仓库","hi": "रिपॉज़िटरी",diff --git a/windows/src/i18n/strings.json b/windows/src/i18n/strings.jsonindex 3245e925..deca21d4 100644--- a/windows/src/i18n/strings.json+++ b/windows/src/i18n/strings.json@@ -79,6 +79,17 @@"ru": "7 дней","id": "7 hari"},+ "A few replies a minute at most: wait a moment.": {+ "zh-Hans": "每分钟最多回复几条:请稍等。",+ "hi": "एक मिनट में कुछ ही जवाब: थोड़ा रुकें।",+ "es": "Unas pocas respuestas por minuto como máximo: espera un momento.",+ "ar": "بضعة ردود في الدقيقة كحد أقصى: انتظر قليلًا.",+ "fr": "Quelques réponses par minute au maximum : attends un instant.",+ "bn": "মিনিটে সর্বোচ্চ কয়েকটি উত্তর: একটু অপেক্ষা করুন।",+ "pt-BR": "No máximo algumas respostas por minuto: espere um pouco.",+ "ru": "Не больше нескольких ответов в минуту: подождите немного.",+ "id": "Paling banyak beberapa balasan per menit: tunggu sebentar."+ },"A wrong word, or the wrong person? Fix it from the line's ⋯ menu. Words you correct are remembered for your next calls.": {"zh-Hans": "词听错了,或说话人不对?在该行的 ⋯ 菜单里修改。你改正的词会被记住,用于之后的通话。","hi": "कोई शब्द गलत है, या व्यक्ति गलत? पंक्ति के ⋯ मेनू से ठीक करें। आप जो शब्द सुधारते हैं, वे अगली कॉल के लिए याद रखे जाते हैं।",@@ -3016,6 +3027,17 @@"ru": "Отметить как прочитанное","id": "Tandai sudah dibaca"},+ "Mark as read when I open a conversation": {+ "zh-Hans": "打开对话时标记为已读",+ "hi": "बातचीत खोलने पर पढ़ा हुआ मार्क करें",+ "es": "Marcar como leído al abrir una conversación",+ "ar": "تعليم كمقروء عند فتح محادثة",+ "fr": "Marquer comme lu quand j’ouvre une conversation",+ "bn": "কথোপকথন খুললে পড়া হিসেবে চিহ্নিত করো",+ "pt-BR": "Marcar como lida ao abrir uma conversa",+ "ru": "Отмечать прочитанным при открытии беседы",+ "id": "Tandai dibaca saat saya membuka percakapan"+ },"Me": {"zh-Hans": "我","hi": "मैं",@@ -3764,6 +3786,17 @@"ru": "Хорошо, оставляю как есть","id": "Baik, biarkan seperti itu"},+ "Off: marked read only when you reply. Never when a message just arrives.": {+ "zh-Hans": "关闭时:仅在你回复时标记为已读。收到消息时从不标记。",+ "hi": "बंद: सिर्फ़ जवाब देने पर पढ़ा हुआ। संदेश आने भर से कभी नहीं।",+ "es": "Desactivado: se marca como leído solo al responder. Nunca solo por recibirlo.",+ "ar": "عند الإيقاف: تُعلَّم كمقروءة فقط عند الرد. لا تُعلَّم أبدًا لمجرد الوصول.",+ "fr": "Désactivé : marqué comme lu seulement quand tu réponds. Jamais à la simple réception.",+ "bn": "বন্ধ: শুধু উত্তর দিলে পড়া হিসেবে চিহ্নিত। বার্তা এলেই কখনও নয়।",+ "pt-BR": "Desativado: marcada como lida só quando você responde. Nunca só por chegar.",+ "ru": "Выключено: прочитанным отмечается только при ответе. Никогда при простом получении.",+ "id": "Mati: ditandai dibaca hanya saat kamu membalas. Tidak pernah hanya karena pesan masuk."+ },"Ollama disconnected.": {"zh-Hans": "Ollama 已断开连接。","hi": "Ollama डिस्कनेक्ट हो गया।",@@ -4716,9 +4749,9 @@"es": "Quitar","ar": "إزالة","fr": "Retirer",- "bn": "সরাও",+ "bn": "সরান","pt-BR": "Remover",- "ru": "Убрать",+ "ru": "Удалить","id": "Hapus"},"Remove from favorites": {@@ -4831,6 +4864,17 @@"ru": "Ответить в терминале","id": "Balas di terminal"},+ "Reply… (⇧↩ new line)": {+ "zh-Hans": "回复…(⇧↩ 换行)",+ "hi": "जवाब दें… (⇧↩ नई लाइन)",+ "es": "Responder… (⇧↩ nueva línea)",+ "ar": "رد… (⇧↩ سطر جديد)",+ "fr": "Répondre… (⇧↩ nouvelle ligne)",+ "bn": "উত্তর দিন… (⇧↩ নতুন লাইন)",+ "pt-BR": "Responder… (⇧↩ nova linha)",+ "ru": "Ответить… (⇧↩ новая строка)",+ "id": "Balas… (⇧↩ baris baru)"+ },"Request permissions": {"zh-Hans": "请求权限","hi": "अनुमतियाँ अनुरोध करें",@@ -6030,6 +6074,17 @@"ru": "Сегодня","id": "Hari ini"},+ "Too long for one message (4,096 characters at most).": {+ "zh-Hans": "单条消息过长(最多 4096 个字符)。",+ "hi": "एक संदेश के लिए बहुत लंबा (अधिकतम 4,096 अक्षर)।",+ "es": "Demasiado largo para un mensaje (4096 caracteres como máximo).",+ "ar": "طويل جدًا لرسالة واحدة (4096 حرفًا كحد أقصى).",+ "fr": "Trop long pour un seul message (4 096 caractères au maximum).",+ "bn": "একটি বার্তার জন্য খুব লম্বা (সর্বোচ্চ ৪০৯৬ অক্ষর)।",+ "pt-BR": "Longo demais para uma mensagem (no máximo 4.096 caracteres).",+ "ru": "Слишком длинно для одного сообщения (не больше 4096 символов).",+ "id": "Terlalu panjang untuk satu pesan (maksimal 4.096 karakter)."+ },"Too many hits at once.": {"zh-Hans": "一次点击太多次了。","hi": "एक बार में बहुत ज़्यादा टैप।",