Files
coucou/NotchBuddy/Sources/App/CalcomPoller.swift
Claude b4343d9dfa perf: idle CPU and smoothness pass (no visual change)
Hidden island
- The idle poll measured "near" from the 720x560 panel, so a hidden island polled at
  60 Hz most of the time: measured from the island now, 8 Hz elsewhere.
- Poll stops while the screen sleeps or is locked; small timer tolerance.
- Countdown bar's 10 Hz timer only runs while the island is open.
- Global key monitor: no Task per keystroke, only Escape goes further.

Drawing
- Island views behind the active one pause their animations (environment flag):
  ticker shimmer, mini Mochis, upload bar.
- Mini Mochis drawn at 30 fps with the same motion (engine still steps per display
  frame); notch Mochi not drawn while it lives on the desktop.
- Mochi's look target and seasonal outfit no longer recomputed with screen lookups
  and calendar math every frame.
- Desktop Mochi polls at 30 Hz (it draws at 30), feeds the eye tracking, and stops
  when the screen sleeps.

Voice
- VAD durations follow the real buffer length (macOS often gives 100 ms buffers: the
  silence tail was ~3.5 s instead of 0.8 s, keeping recognition running on noise).
- vDSP for the mic power, recognizer reused per pipeline, system voice cached,
  micLevel no longer @Published, repeated partials ignored, watchdog tolerance,
  no "deaf recognizer" rebuild while music plays.

Background
- Logging on a background queue with a cached formatter (was ~8 file ops on main).
- n8n poller silent when not configured; quiet polls write nothing.
- Poller timer leeway; Stripe/Notion/Cal.com publish only on change.
- Status line: plan usage published on change (or every 30 s), not several times/s.
- Codex plan fetch rate-limited on the attempt, not only on success.
- Apple Mail send runs off the main thread (the island froze for 1 s+).
- iPhone instructions: checked on CloudKit push, poll 90 s when pushes work.
- Window highlight during an attach drag only rescans when the pointer moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT
2026-10-10 20:17:27 +02:00

106 lines
4.7 KiB
Swift

import Foundation
final class CalcomPoller: @unchecked Sendable {
static let shared = CalcomPoller()
private var timer: DispatchSourceTimer?
private init() {}
func start() {
guard timer == nil else { return }
let t = DispatchSource.makeTimerSource(queue: .global(qos: .background))
t.schedule(deadline: .now() + 8, repeating: 300, leeway: .seconds(30))
t.setEventHandler { [weak self] in self?.poll() }
t.resume()
timer = t
}
func pollNow() { poll() }
private func poll() {
guard !DemoEngine.isPollerPaused else { return }
guard let key = KeychainStore.shared.get("calcom-api-key") else { return }
let cal = Calendar.current
let today = cal.startOfDay(for: Date())
let future = cal.date(byAdding: .day, value: 60, to: today)!
let iso = ISO8601DateFormatter(); iso.formatOptions = [.withInternetDateTime]
let startStr = iso.string(from: today)
let endStr = iso.string(from: future)
// API v2 (2024-08-13) filters on afterStart / beforeEnd; `start` and `end` aren't
// query parameters there, so they returned nothing.
var components = URLComponents(string: "https://api.cal.com/v2/bookings")!
components.queryItems = [URLQueryItem(name: "status", value: "upcoming"),
URLQueryItem(name: "afterStart", value: startStr),
URLQueryItem(name: "beforeEnd", value: endStr),
URLQueryItem(name: "take", value: "50")]
guard let url = components.url else { return }
var req = URLRequest(url: url, timeoutInterval: 10)
req.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
req.setValue("2024-08-13", forHTTPHeaderField: "cal-api-version")
URLSession.shared.dataTask(with: req) { [weak self] data, response, error in
guard let self else { return }
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
if code != 200 {
let msg: String
if code == 401 { msg = "Invalid API key (401)" }
else if code == 0 { msg = error?.localizedDescription ?? "No connection" }
else { msg = "API error \(code)" }
DispatchQueue.main.async { AppState.shared.setIfChanged(\.calcomError, msg) }
return
}
guard let data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let rawList = json["data"] as? [[String: Any]] else { return }
let parsed = rawList.compactMap { self.parseBooking($0) }
DispatchQueue.main.async {
AppState.shared.setIfChanged(\.calcomError, nil)
AppState.shared.setIfChanged(\.calcomBookings, parsed)
AppState.shared.setIfChanged(\.calcomLoaded, true)
}
}.resume()
}
private func parseBooking(_ b: [String: Any]) -> CalcomBooking? {
let id: Int
if let i = b["id"] as? Int { id = i }
else if let s = b["id"] as? String, let i = Int(s) { id = i }
else { return nil }
let title = (b["title"] as? String) ?? "Meeting"
let status = (b["status"] as? String) ?? "accepted"
guard let startStr = (b["start"] as? String) ?? (b["startTime"] as? String) else { return nil }
let iso = ISO8601DateFormatter()
iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
var startTime = iso.date(from: startStr)
if startTime == nil {
let iso2 = ISO8601DateFormatter(); iso2.formatOptions = [.withInternetDateTime]
startTime = iso2.date(from: startStr)
}
guard let startTime else { return nil }
let endStr = (b["end"] as? String) ?? (b["endTime"] as? String) ?? ""
let endTime: Date = iso.date(from: endStr) ?? startTime
let attendees = b["attendees"] as? [[String: Any]] ?? []
let first = attendees.first
let name = first?["name"] as? String
let email = first?["email"] as? String
var notes: String? = nil
if let responses = b["responses"] as? [String: Any],
let notesObj = responses["notes"] as? [String: Any] {
notes = notesObj["value"] as? String
}
if (notes == nil || notes!.isEmpty), let desc = b["description"] as? String, !desc.isEmpty {
notes = desc
}
return CalcomBooking(id: id, title: title, startTime: startTime, endTime: endTime,
status: status, attendeeName: name, attendeeEmail: email,
attendeeNotes: notes)
}
}