From ab89b907c16ac814cdfa9610303f55a50d1e2da9 Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 1/9] fix(detect): keep code detection linear on long mails --- Sources/CodeCatchCore/CodeExtractor.swift | 21 ++++++++++++++----- .../CodeExtractorTests.swift | 16 ++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/Sources/CodeCatchCore/CodeExtractor.swift b/Sources/CodeCatchCore/CodeExtractor.swift index 3f88e61..ef983c9 100644 --- a/Sources/CodeCatchCore/CodeExtractor.swift +++ b/Sources/CodeCatchCore/CodeExtractor.swift @@ -35,6 +35,9 @@ public enum CodeExtractor { let keywords = keyword.matches(in: text, range: NSRange(location: 0, length: ns.length)).map(\.range) guard !keywords.isEmpty else { return nil } + // Asked of the whole text, so once: a long mail has thousands of candidates. + lazy var hasBooking = matches(bookingNumber, text) + lazy var hasTransaction = matches(transactionNumber, text) var best: (code: String, score: Double, range: NSRange, context: NSRange)? for (regex, isNumeric) in [(numeric, true), (alphanumeric, false)] { for match in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) { @@ -43,8 +46,9 @@ public enum CodeExtractor { if !isNumeric, !plausibleAlphanumeric(raw) { continue } let code = isNumeric ? raw.filter(\.isNumber) : raw - let before = ns.substring(to: range.location).suffix(40) - let after = ns.substring(from: range.location + range.length).prefix(40) + // Cut from a window, not from everything on that side: copying the rest of a long mail per candidate stalled it. + let before = ns.substring(with: NSRange(location: max(0, range.location - 640), length: min(640, range.location))).suffix(40) + let after = ns.substring(with: NSRange(location: range.upperBound, length: min(640, ns.length - range.upperBound))).prefix(40) let line = ns.lineRange(for: range) // A letters-only word set straight after the keyword is just the next word ("KODE RAHASIA utk", // "NEW API TOKEN CREATED"); "YOUR CODE IS SZBPM", "code: SZBPM" and "SZBPM is your code" name one. @@ -54,8 +58,8 @@ public enum CodeExtractor { // A PIN beside a booking's confirmation number ("Confirmation: 5984715426 / PIN: 0260") // manages that booking, and an auth code beside a transaction ID ("Transaction ID: 121875559327 / // Auth Code: 051115") is a receipt's card approval: neither is one-time. - if matches(pinLabel, String(before)), matches(bookingNumber, text) { continue } - if matches(approvalLabel, String(before)), matches(transactionNumber, text) { continue } + if matches(pinLabel, String(before)), hasBooking { continue } + if matches(approvalLabel, String(before)), hasTransaction { continue } let explicit = matches(explicitBefore, String(before)) || matches(explicitAfter, String(after)) // Introduced on the keyword's line ("… Moj A1: 30718264", "Enkratno geslo … je 318842"), // or on the line above a code standing alone ("… Steam Guard code you need …:" over "6VCC5"). @@ -84,7 +88,14 @@ public enum CodeExtractor { matches(codeNoun, ns.substring(with: NSRange(location: line.upperBound, length: below - line.upperBound))) ? below : line.upperBound let context = NSRange(location: leadStart, length: end - leadStart) - let near = keywords.filter { NSIntersectionRange($0, context).length > 0 }.map { k in + // Keywords are in text order: search for the first one reaching into the context, stop at the first past it. + var first = 0 + var past = keywords.count + while first < past { + let mid = (first + past) / 2 + if keywords[mid].upperBound <= context.location { first = mid + 1 } else { past = mid } + } + let near = keywords[first...].prefix { $0.location < context.upperBound }.map { k in k.upperBound <= range.location ? range.location - k.upperBound : k.location >= range.upperBound ? k.location - range.upperBound : 0 diff --git a/Tests/CodeCatchCoreTests/CodeExtractorTests.swift b/Tests/CodeCatchCoreTests/CodeExtractorTests.swift index ebab5be..b9e187d 100644 --- a/Tests/CodeCatchCoreTests/CodeExtractorTests.swift +++ b/Tests/CodeCatchCoreTests/CodeExtractorTests.swift @@ -16,6 +16,22 @@ import Testing } } +/// Detection runs on the main thread: work that grew with the square of a mail's candidates froze +/// the app for about ten seconds on one long mail. +@Test func longMailCannotStallDetection() { + // This thread's CPU time: other tests running beside this one can't stretch it. + func cost(_ count: Int) -> UInt64 { + let text = String(repeating: "Your code: 123456\n", count: count) + let start = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) + #expect(CodeExtractor.code(in: text) == "123456") + return clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - start + } + // Sixteen times the mail may cost about sixteen times as much, not fifty or more; seconds alone depend on the machine. + _ = cost(10) // the patterns compile on first use + let short = cost(300) + #expect(cost(4_800) < short * 32) +} + /// The card's title: a wrong or missing service makes codes indistinguishable. @Test( arguments: [ From 6ba850f147cd06ead822f381ce63153c80ce6ddc Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 2/9] fix(sources): show a resumed account live only after its provider answers --- Sources/CodeCatch/Mail/APIWatcher.swift | 15 +++++++++++-- Tests/CodeCatchTests/MailWatcherTests.swift | 25 ++++++++++++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/Sources/CodeCatch/Mail/APIWatcher.swift b/Sources/CodeCatch/Mail/APIWatcher.swift index a632e47..6f7d638 100644 --- a/Sources/CodeCatch/Mail/APIWatcher.swift +++ b/Sources/CodeCatch/Mail/APIWatcher.swift @@ -65,18 +65,29 @@ enum APIWatcher { try await MailWatcher.hand(messages, event: event, deliver: deliver) } + // Live once the provider has answered: a resumed account makes no call before its first check, + // and counting it as working there also reset the backoff on every failed try. + var live = false + func answered() async { + guard !live else { return } + live = true + await status(.live) + backoff = retryDelay + } + if cursor == nil { let start = try await mailbox.cursor() try await receive(try await mailbox.inbox(since: Date().addingTimeInterval(-lookback), limit: MailWatcher.backfill)) cursor = start await event(.read(.cursor(start))) resuming = false + try Task.checkCancellation() + await answered() } try Task.checkCancellation() - await status(.live) - backoff = retryDelay while !Task.isCancelled { let (added, next) = try await mailbox.added(since: cursor!) + await answered() // The same newest few on a retry, so a failed fetch can't widen the window to older mail. let pending = (resuming ? added.suffix(MailWatcher.backfill) : added[...]).filter { !seen.contains($0) } if pending.isEmpty { try await receive([]) } diff --git a/Tests/CodeCatchTests/MailWatcherTests.swift b/Tests/CodeCatchTests/MailWatcherTests.swift index 263b795..221fa7e 100644 --- a/Tests/CodeCatchTests/MailWatcherTests.swift +++ b/Tests/CodeCatchTests/MailWatcherTests.swift @@ -146,9 +146,11 @@ private actor FakeGmail: MailAPI { var historyChecks = 0 var backfills = 0 var fetched: [String] = [] - init(expireHistoryOnce: Bool = false, signInRevoked: Bool = false) { + let unreachable: Bool + init(expireHistoryOnce: Bool = false, signInRevoked: Bool = false, unreachable: Bool = false) { self.expireHistoryOnce = expireHistoryOnce self.signInRevoked = signInRevoked + self.unreachable = unreachable } func cursor() throws -> String { if signInRevoked { throw OAuth.Failure.token("invalid_grant") } @@ -160,6 +162,7 @@ private actor FakeGmail: MailAPI { } func added(since cursor: String) throws -> (ids: [String], cursor: String) { historyChecks += 1 + if unreachable { throw URLError(.notConnectedToInternet) } if expireHistoryOnce && historyChecks == 1 { throw MailAPIError.cursorExpired } // The backfilled mail also shows up in the first history check, as it can when it lands mid-backfill. return (fetched.contains("new") ? [] : ["backfilled", "new"], "101") @@ -215,6 +218,26 @@ private actor FakeGmail: MailAPI { #expect(reported == .failed(SourceStatus.signInExpired)) } +/// A resumed account makes no call before its first check: shown as working there, an unreachable +/// provider flickered between working and failed, and each failed try reset the retry backoff. +@Test @MainActor func resumedAccountIsNotLiveBeforeItsProviderAnswers() async { + let statuses = AsyncStream.makeStream() + let watcher = Task { + await APIWatcher.watch( + MailAccount(label: "Gmail", host: MailAccount.gmailHost, user: "test@gmail.com"), from: .cursor("100"), + status: { statuses.continuation.yield($0) }, deliver: { _ in }, + mailbox: FakeGmail(unreachable: true)) + } + var reported: SourceStatus? + for await status in statuses.stream where status != .connecting { + reported = status + break + } + watcher.cancel() + await watcher.value + #expect(reported != .live) +} + /// The status shows in the menu's banner: a system error's own text there reads as gibberish. @Test( arguments: [ From ed0e5e232830737d29b15d6ddfb420527fb9c556 Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 3/9] fix(sources): drop the cached access token when signing in again --- Sources/CodeCatch/Model/AppModel+Accounts.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/CodeCatch/Model/AppModel+Accounts.swift b/Sources/CodeCatch/Model/AppModel+Accounts.swift index 0c70fbd..c6fe5cb 100644 --- a/Sources/CodeCatch/Model/AppModel+Accounts.swift +++ b/Sources/CodeCatch/Model/AppModel+Accounts.swift @@ -23,6 +23,8 @@ extension AppModel { var account = account if let refreshToken { try keychain.write(refreshToken, account.refreshTokenKey) + // The cached access token belongs to the old sign-in and its permissions. + OAuth.forgetAccessToken(tokenKey: account.refreshTokenKey) account.signedIn = true } else if !account.usesSignIn { if !password.isEmpty { try keychain.write(password, account.secretKey) } From 2788113aa45bb82414d3a6767f448e401bd418c7 Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 4/9] fix(detect): read plain-text links when the HTML part has none --- Sources/CodeCatchCore/MIME.swift | 4 +++- Tests/CodeCatchCoreTests/MIMETests.swift | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Sources/CodeCatchCore/MIME.swift b/Sources/CodeCatchCore/MIME.swift index b0a236b..2d1a4b5 100644 --- a/Sources/CodeCatchCore/MIME.swift +++ b/Sources/CodeCatchCore/MIME.swift @@ -151,7 +151,9 @@ public enum MIME { var html: String? collect(headers: headers, body: body, plain: &plain, html: &html, depth: 0) let parsedHTML = html.map(readHTML) - let links = parsedHTML?.links ?? plain.map(bareLinks) ?? [] + // An HTML part without anchors can sit beside a plain part that spells the link out. + let htmlLinks = parsedHTML?.links ?? [] + let links = htmlLinks.isEmpty ? plain.map(bareLinks) ?? [] : htmlLinks if let plain, !plain.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return (plain, links) } return (parsedHTML?.text ?? "", links) } diff --git a/Tests/CodeCatchCoreTests/MIMETests.swift b/Tests/CodeCatchCoreTests/MIMETests.swift index 09167d8..0713679 100644 --- a/Tests/CodeCatchCoreTests/MIMETests.swift +++ b/Tests/CodeCatchCoreTests/MIMETests.swift @@ -54,6 +54,12 @@ import Testing "Content-Type: text/plain\r\nContent-Transfer-Encoding: base64\r\n\r\n" + Data("Your code: 482913. Thanks!".utf8).base64EncodedString().dropLast(3) #expect(MIME.parse(Data(cut.utf8)).text.hasPrefix("Your code: 482913")) + // An HTML part with no anchors must not hide the link the plain part spells out. + let alt = + "Content-Type: multipart/alternative; boundary=XX\r\n\r\n--XX\r\nContent-Type: text/plain\r\n\r\nSign in: https://a.com/login?t=abc\r\n" + + "--XX\r\nContent-Type: text/html\r\n\r\n

Sign in with the link

\r\n--XX--" + #expect(MIME.parse(Data(alt.utf8)).links == [MailLink(url: "https://a.com/login?t=abc", label: "Sign in")]) + let bare = "Subject: Vaša koda\r\nContent-Type: multipart/mixed; boundary=XX\r\n\r\n--XX\r\n\r\nYour code: 482913\r\n--XX--" #expect(MIME.parse(Data(bare.utf8)) == MailMessage(fromName: "", fromAddress: "", subject: "Vaša koda", text: "Your code: 482913\n")) } From 0c28982d6cd5ff326fbbe97b1dcea9c87b5c035d Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 5/9] fix(menu): keep the search field while a query is typed --- Sources/CodeCatch/UI/MenuBar/MenuContent.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CodeCatch/UI/MenuBar/MenuContent.swift b/Sources/CodeCatch/UI/MenuBar/MenuContent.swift index b14d235..1eca405 100644 --- a/Sources/CodeCatch/UI/MenuBar/MenuContent.swift +++ b/Sources/CodeCatch/UI/MenuBar/MenuContent.swift @@ -66,7 +66,7 @@ struct MenuContent: View { attention("All sources off", "Turn on a source in Settings.", fix: ("Open Settings", { openSettings(at: .sources) })) .padding(.horizontal, 10).padding(.bottom, 10) } - if model.items.count > Self.recent || hasLogins || searchRequested { searchField } + if model.items.count > Self.recent || hasLogins || searchRequested || !query.isEmpty { searchField } ScrollViewReader { scroll in ScrollView { VStack(spacing: 0) { From c22f958f3af969eb9c6ee82fea4048d8c44831b9 Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 6/9] fix(cli): reject a non-finite --timeout --- Sources/CodeCatchCLI/main.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CodeCatchCLI/main.swift b/Sources/CodeCatchCLI/main.swift index 8a880ff..89daca7 100644 --- a/Sources/CodeCatchCLI/main.swift +++ b/Sources/CodeCatchCLI/main.swift @@ -117,7 +117,7 @@ case "get": } var timeout: TimeInterval? if let text = option("--timeout") { - guard let seconds = Double(text), seconds > 0 else { usage("--timeout takes a number of seconds.") } + guard let seconds = Double(text), seconds > 0, seconds.isFinite else { usage("--timeout takes a number of seconds.") } timeout = seconds } guard args.count == 2, !args[1].hasPrefix("-") else { From 045957a0538f7814e8b2730853b87214736539f3 Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 7/9] fix(scripts): fail make-icon when iconutil fails --- scripts/make-icon.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/make-icon.swift b/scripts/make-icon.swift index d63a3fc..8da4afd 100644 --- a/scripts/make-icon.swift +++ b/scripts/make-icon.swift @@ -45,3 +45,4 @@ p.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil") p.arguments = ["-c", "icns", iconset, "-o", out] try! p.run() p.waitUntilExit() +exit(p.terminationStatus) From 825254965a09520572062dda5f9420b8ac8c0f73 Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 8/9] fix(site): stop the demo caret blinking under reduced motion --- site/styles.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/site/styles.css b/site/styles.css index ffc25ac..d0cad34 100644 --- a/site/styles.css +++ b/site/styles.css @@ -790,7 +790,7 @@ li.copied .tick, button.copied > svg { display: block; stroke-dasharray: 21; ani html { scroll-behavior: auto; } .reveal, .banner, .keys, .ring .arc, .row .ring, .button, .toc ol::before { transition: none; } .reveal { opacity: 1; transform: none; } - li.copied .tick, button.copied > svg { animation: none; } + li.copied .tick, button.copied > svg, .caret { animation: none; } } /* AgentCard.swift and AgentsTab.swift: an agent's request for a code, and Settings → Agents. */ From cfa1a25eb7ac0121128e823b78b99728e0bda32a Mon Sep 17 00:00:00 2001 From: Uros Gazvoda <25570106+ugzv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:24 +0100 Subject: [PATCH 9/9] docs: name hiding codes until hover, not blur --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 943b94f..65e5eed 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,8 @@ in any browser or app. - **Can type the code for you** (off by default). - **Works from the keyboard.** ⌃⌥⌘C copies the latest code. ⌃⌥⌘F opens search. - **Reads about 35 languages.** -- **Stays private.** Hidden from screen sharing, with optional blur and - clearing when the Mac locks. +- **Stays private.** Hidden from screen sharing, and can hide codes until + you point at them and clear them when the Mac locks. ## Install