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
fix(n8n): seed poller on launch and preserve real execution dates (#861)
unknown75473d1b1a5a
diff --git a/NotchBuddy/Sources/App/N8nPoller.swift b/NotchBuddy/Sources/App/N8nPoller.swiftindex c96643c2..6b9ba4da 100644--- a/NotchBuddy/Sources/App/N8nPoller.swift+++ b/NotchBuddy/Sources/App/N8nPoller.swift@@ -9,6 +9,29 @@ final class N8nPoller: @unchecked Sendable {static let shared = N8nPoller()private var timer: DispatchSourceTimer?private var lastExecutionId: String = ""+ private var isFirstLoad: Bool = true++ private static let isoFormatterFractional: ISO8601DateFormatter = {+ let f = ISO8601DateFormatter()+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ return f+ }()++ private static let isoFormatterStandard: ISO8601DateFormatter = {+ let f = ISO8601DateFormatter()+ f.formatOptions = [.withInternetDateTime]+ return f+ }()++ static func parseExecutionDate(from json: [String: Any]) -> Date {+ let dateString = (json["stoppedAt"] as? String) ?? (json["startedAt"] as? String)+ if let dateString {+ if let date = isoFormatterFractional.date(from: dateString) ?? isoFormatterStandard.date(from: dateString) {+ return date+ }+ }+ return Date()+ }private init() {}@@ -31,8 +54,8 @@ final class N8nPoller: @unchecked Sendable {}let base = rawBase.trimmingCharacters(in: CharacterSet(charactersIn: "/"))let endpoints = [- "\(base)/api/v1/executions?limit=1&includeData=false",- "\(base)/rest/executions?limit=1&includeData=false",+ "\(base)/api/v1/executions?limit=10&includeData=false",+ "\(base)/rest/executions?limit=10&includeData=false",]tryList(endpoints, apiKey: apiKey, base: base, idx: 0)}@@ -77,44 +100,86 @@ final class N8nPoller: @unchecked Sendable {return}- guard let first = items.first else { self.n8nLog("No executions found"); return }+ let terminal = ["success", "error", "crashed", "canceled", "failed"]+ let terminalItems = items.filter { item in+ let status = item["status"] as? String ?? ""+ return terminal.contains(status)+ }- let id: String- if let s = first["id"] as? String { id = s }- else if let n = first["id"] as? Int { id = "\(n)" }- else { self.n8nLog("No id in execution"); return }+ guard let newest = terminalItems.first else {+ if self.isFirstLoad && items.isEmpty {+ self.isFirstLoad = false+ }+ return+ }- guard id != self.lastExecutionId else { return }+ let newestId: String+ if let s = newest["id"] as? String { newestId = s }+ else if let n = newest["id"] as? Int { newestId = "\(n)" }+ else { self.n8nLog("No id in execution"); return }- // Terminal check: use status field — more reliable than the `finished` bool- // (published workflows often have finished=false on error)- let status = first["status"] as? String ?? ""- let isTerminal = ["success", "error", "crashed", "canceled", "failed"].contains(status)- guard isTerminal else {- self.n8nLog("id=\(id) status=\(status.isEmpty ? "?" : status) — not terminal")+ // First load — populate silently, anchor lastExecutionId to avoid duplicate on next poll+ if self.isFirstLoad {+ self.isFirstLoad = false+ self.lastExecutionId = newestId+ self.n8nLog("First load seeded lastExecutionId=\(newestId)")return}- self.lastExecutionId = id+ guard newestId != self.lastExecutionId else { return }++ // Identify all new terminal executions since lastExecutionId+ let newItems: [[String: Any]]+ if let idx = terminalItems.firstIndex(where: { item in+ let id = (item["id"] as? String) ?? (item["id"] as? Int).map(String.init) ?? ""+ return id == self.lastExecutionId+ }) {+ newItems = Array(terminalItems.prefix(upTo: idx))+ } else {+ newItems = terminalItems+ }++ guard let newestExec = newItems.first else { return }++ self.lastExecutionId = newestId+ let status = newestExec["status"] as? String ?? ""let success = status == "success"- self.n8nLog("New execution id=\(id) status=\(status)")+ let newestDate = Self.parseExecutionDate(from: newestExec)+ self.n8nLog("New execution id=\(newestId) status=\(status)")++ // Process intermediate completed executions into history (oldest to newest)+ if newItems.count > 1 {+ let intermediate = Array(newItems.dropFirst().reversed())+ DispatchQueue.main.async {+ let state = AppState.shared+ for item in intermediate {+ let name = self.extractWorkflowName(from: item)+ let ok = (item["status"] as? String ?? "") == "success"+ let date = Self.parseExecutionDate(from: item)+ if state.n8nWorkflowFilter.isEmpty || state.n8nWorkflowFilter.contains(name) {+ state.n8nRuns = Array(([N8nRun(workflow: name, detail: nil, success: ok, date: date)]+ + state.n8nRuns).prefix(10))+ }+ }+ }+ }- // Fetch full detail (includeData=true required in some n8n versions)+ // Fetch full detail for the newest executionlet detailUrls = [- "\(base)/api/v1/executions/\(id)?includeData=true",- "\(base)/api/v1/executions/\(id)",- "\(base)/rest/executions/\(id)?includeData=true",- "\(base)/rest/executions/\(id)",+ "\(base)/api/v1/executions/\(newestId)?includeData=true",+ "\(base)/api/v1/executions/\(newestId)",+ "\(base)/rest/executions/\(newestId)?includeData=true",+ "\(base)/rest/executions/\(newestId)",]- self.fetchDetail(detailUrls, apiKey: apiKey, success: success, idx: 0)+ self.fetchDetail(detailUrls, apiKey: apiKey, success: success, fallbackDate: newestDate, idx: 0)}.resume()}// MARK: - Fetch full execution detail- private func fetchDetail(_ urls: [String], apiKey: String, success: Bool, idx: Int) {+ private func fetchDetail(_ urls: [String], apiKey: String, success: Bool, fallbackDate: Date, idx: Int) {guard idx < urls.count, let url = URL(string: urls[idx]) else {- dispatch(success: success, name: "Workflow", detail: nil)+ dispatch(success: success, name: "Workflow", detail: nil, date: fallbackDate)return}var req = URLRequest(url: url, timeoutInterval: 10)@@ -126,17 +191,19 @@ final class N8nPoller: @unchecked Sendable {let code = (response as? HTTPURLResponse)?.statusCode ?? 0guard let data, code == 200 else {self.n8nLog("Detail HTTP \(code) \(url.host ?? "?")\(url.path)")- self.fetchDetail(urls, apiKey: apiKey, success: success, idx: idx + 1)+ self.fetchDetail(urls, apiKey: apiKey, success: success, fallbackDate: fallbackDate, idx: idx + 1)return}guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {- self.fetchDetail(urls, apiKey: apiKey, success: success, idx: idx + 1)+ self.fetchDetail(urls, apiKey: apiKey, success: success, fallbackDate: fallbackDate, idx: idx + 1)return}let name = self.extractWorkflowName(from: json)let detail = self.parseDetail(from: json, success: success)+ let date = Self.parseExecutionDate(from: json)+ let executionDate = (json["stoppedAt"] != nil || json["startedAt"] != nil) ? date : fallbackDateself.n8nLog("Parsed: \(name)")- self.dispatch(success: success, name: name, detail: detail)+ self.dispatch(success: success, name: name, detail: detail, date: executionDate)}.resume()}@@ -213,18 +280,18 @@ final class N8nPoller: @unchecked Sendable {// MARK: - Dispatch to main- private func dispatch(success: Bool, name: String, detail: String?) {- DispatchQueue.main.async { self.handleExecution(success: success, name: name, detail: detail) }+ private func dispatch(success: Bool, name: String, detail: String?, date: Date) {+ DispatchQueue.main.async { self.handleExecution(success: success, name: name, detail: detail, date: date) }}@MainActor- private func handleExecution(success: Bool, name: String, detail: String?) {+ private func handleExecution(success: Bool, name: String, detail: String?, date: Date) {let state = AppState.shared// Apply workflow filter (empty = all workflows)if !state.n8nWorkflowFilter.isEmpty && !state.n8nWorkflowFilter.contains(name) { return }- state.n8nRuns = Array(([N8nRun(workflow: name, detail: detail, success: success, date: Date())]+ state.n8nRuns = Array(([N8nRun(workflow: name, detail: detail, success: success, date: date)]+ state.n8nRuns).prefix(10))guard let idx = state.tasks.firstIndex(where: { $0.id == "integration_n8n" }) else { return }diff --git a/NotchBuddy/Tests/N8nPollerTests.swift b/NotchBuddy/Tests/N8nPollerTests.swiftnew file mode 100644index 00000000..ab5d022f--- /dev/null+++ b/NotchBuddy/Tests/N8nPollerTests.swift@@ -0,0 +1,73 @@+#!/usr/bin/swift+// N8nPollerTests.swift — standalone test script for n8n execution date parsing and status checks.+// Run from repo root:+// swift NotchBuddy/Tests/N8nPollerTests.swift++import Foundation++var passed = 0+var failed = 0++func assertEqual<T: Equatable>(_ actual: T, _ expected: T, _ desc: String) {+ if actual == expected {+ passed += 1+ print(" ✓ \(desc)")+ } else {+ failed += 1+ print(" ✗ \(desc) — expected: \(expected), got: \(actual)")+ }+}++let isoFormatterFractional: ISO8601DateFormatter = {+ let f = ISO8601DateFormatter()+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ return f+}()++let isoFormatterStandard: ISO8601DateFormatter = {+ let f = ISO8601DateFormatter()+ f.formatOptions = [.withInternetDateTime]+ return f+}()++func parseExecutionDate(from json: [String: Any]) -> Date? {+ let dateString = (json["stoppedAt"] as? String) ?? (json["startedAt"] as? String)+ guard let dateString else { return nil }+ return isoFormatterFractional.date(from: dateString) ?? isoFormatterStandard.date(from: dateString)+}++print("Running N8nPollerTests...")++// 1. Parse stoppedAt with fractional seconds+let date1Str = "2026-10-21T14:30:00.123Z"+let expectedDate1 = isoFormatterFractional.date(from: date1Str)!+let json1: [String: Any] = ["stoppedAt": date1Str, "startedAt": "2026-10-21T14:29:50.000Z"]+assertEqual(parseExecutionDate(from: json1), expectedDate1, "Parses stoppedAt with fractional seconds")++// 2. Parse stoppedAt with standard ISO8601 (no fractions)+let date2Str = "2026-10-21T14:30:00Z"+let expectedDate2 = isoFormatterStandard.date(from: date2Str)!+let json2: [String: Any] = ["stoppedAt": date2Str]+assertEqual(parseExecutionDate(from: json2), expectedDate2, "Parses stoppedAt with standard ISO8601")++// 3. Fallback to startedAt when stoppedAt is missing+let date3Str = "2026-10-21T12:00:00.500Z"+let expectedDate3 = isoFormatterFractional.date(from: date3Str)!+let json3: [String: Any] = ["startedAt": date3Str]+assertEqual(parseExecutionDate(from: json3), expectedDate3, "Falls back to startedAt when stoppedAt is nil")++// 4. Missing date returns nil+let json4: [String: Any] = ["id": "123", "status": "success"]+assertEqual(parseExecutionDate(from: json4), nil, "Returns nil when stoppedAt and startedAt are missing")++// 5. Terminal statuses verification+let terminal = ["success", "error", "crashed", "canceled", "failed"]+assertEqual(terminal.contains("success"), true, "success is terminal")+assertEqual(terminal.contains("error"), true, "error is terminal")+assertEqual(terminal.contains("crashed"), true, "crashed is terminal")+assertEqual(terminal.contains("running"), false, "running is not terminal")+assertEqual(terminal.contains("waiting"), false, "waiting is not terminal")++print("")+print("Results: \(passed) passed, \(failed) failed")+exit(failed > 0 ? 1 : 0)diff --git a/windows/src-tauri/src/integrations.rs b/windows/src-tauri/src/integrations.rsindex e41e2265..2db7b318 100644--- a/windows/src-tauri/src/integrations.rs+++ b/windows/src-tauri/src/integrations.rs@@ -1104,8 +1104,8 @@ async fn poll_n8n(app: AppHandle) {// Same two shapes as the Swift poller: the public API first, then /rest.let list_urls = [- format!("{base}/api/v1/executions?limit=1&includeData=false"),- format!("{base}/rest/executions?limit=1&includeData=false"),+ format!("{base}/api/v1/executions?limit=10&includeData=false"),+ format!("{base}/rest/executions?limit=10&includeData=false"),];let mut items: Option<Vec<Value>> = None;@@ -1130,17 +1130,10 @@ async fn poll_n8n(app: AppHandle) {}}- let Some(first) = items.and_then(|list| list.into_iter().next()) else { return };- let id = match first.get("id") {- Some(Value::String(s)) => s.clone(),- Some(Value::Number(n)) => n.to_string(),- _ => return,- };+ let Some(first) = items.as_deref().and_then(find_terminal_execution) else { return };+ let Some(id) = parse_execution_id(first) else { return };let status = first.get("status").and_then(Value::as_str).unwrap_or("");- if !["success", "error", "crashed", "canceled", "failed"].contains(&status) {- return;- }if !is_new("n8n", &id) {return;}@@ -1252,6 +1245,24 @@ fn fmt_value(v: &Value) -> String {}}+pub(crate) fn find_terminal_execution(list: &[Value]) -> Option<&Value> {+ const TERMINAL: [&str; 5] = ["success", "error", "crashed", "canceled", "failed"];+ list.iter().find(|item| {+ item.get("status")+ .and_then(Value::as_str)+ .map(|s| TERMINAL.contains(&s))+ .unwrap_or(false)+ })+}++pub(crate) fn parse_execution_id(item: &Value) -> Option<String> {+ match item.get("id") {+ Some(Value::String(s)) => Some(s.clone()),+ Some(Value::Number(n)) => Some(n.to_string()),+ _ => None,+ }+}+#[cfg(test)]mod tests {use super::*;@@ -1312,4 +1323,23 @@ mod tests {assert_eq!(data["activity"], json!({ "total": 5, "weeks": [], "fetchedAt": 9 }));assert!(data.get("pulse").is_none());}++ #[test]+ fn find_terminal_execution_skips_running_and_finds_terminal() {+ let list = vec![+ json!({ "id": "1", "status": "running" }),+ json!({ "id": "2", "status": "waiting" }),+ json!({ "id": "3", "status": "error" }),+ json!({ "id": "4", "status": "success" }),+ ];+ let term = find_terminal_execution(&list).unwrap();+ assert_eq!(term["id"], "3");+ }++ #[test]+ fn parse_execution_id_handles_string_and_number() {+ assert_eq!(parse_execution_id(&json!({ "id": "abc-123" })), Some("abc-123".to_string()));+ assert_eq!(parse_execution_id(&json!({ "id": 42 })), Some("42".to_string()));+ assert_eq!(parse_execution_id(&json!({ "foo": "bar" })), None);+ }}