From fd2acea1d8c70ed5b3d55875ce9e0937ff4746ee Mon Sep 17 00:00:00 2001 From: Oddur Sigurdsson Date: Fri, 16 Oct 2026 19:14:04 -0400 Subject: [PATCH 1/2] feat(usage): learn from the start of past queries Learning only helped the exact query typed before, so choosing Safari for "safari" did nothing for "sa", which is the point of learning: typing less. A past choice now lends a share of its boost to queries that share its start, and the boosts for a query are worked out once instead of once per candidate. --- CHANGELOG.md | 1 + README.md | 2 +- Sources/CommandKit/Ranker.swift | 4 +- Sources/CommandKit/Usage.swift | 49 ++++++++++++++++++++----- Tests/CommandKitTests/SearchTests.swift | 28 ++++++++++++++ 5 files changed, 72 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a46252..2d3c764 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to this project are documented here. The format follows [Kee - Settings: shortcut, theme, size, translucency, visible results, sources, search engine, menu bar item, and open at login. - Liquid Glass on macOS 26 and the popover material on earlier versions, or a solid background. - System Settings topics and keywords from System Settings' own search terms, so "dark mode", "low power", or "firewall" find the right pane, shown with the pane's icon. +- A result chosen for a query also leans shorter and longer starts of that query its way, so you can type less next time. ### Fixed diff --git a/README.md b/README.md index fa0754c..8eba078 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Common Command is built to feel like part of macOS: - **It matches your Mac.** The panel follows light and dark mode, uses Liquid Glass on macOS 26 (the popover material before that), and highlights with your accent colour. Choose a fixed theme, a solid background, or a size in Settings. - **It stays out of the way.** The panel never activates the app, so the app you were in stays frontmost and keeps its menu bar. Escape, or a click anywhere else, returns you to it with nothing to restore. -- **It learns.** Whatever you choose for a query comes first the next time you type it, and things you open often rise for every query. Usage decays with a one-week half-life, so last year's habits fade. +- **It learns.** Whatever you choose for a query comes first the next time you type it, and leans the same way for a shorter start: choose Safari for "safari" once, and "sa" prefers it too. Things you open often rise for every query. Usage decays with a one-week half-life, so last year's habits fade. - **Typing is forgiving.** "vsc" finds Visual Studio Code, "sys set" finds System Settings, "cafe" finds Café. Matched letters are drawn in bold. Free and open source under the MIT licence. No network access except the web searches and links you open, no analytics, no helper tools, and no Accessibility or Full Disk Access permissions. diff --git a/Sources/CommandKit/Ranker.swift b/Sources/CommandKit/Ranker.swift index 89a0071..983ea44 100644 --- a/Sources/CommandKit/Ranker.swift +++ b/Sources/CommandKit/Ranker.swift @@ -22,7 +22,7 @@ public enum Ranker { ) -> [Ranked] { let q = Fuzzy.prepare(query) guard !q.isEmpty, limit > 0 else { return [] } - let key = Usage.key(query) + let booster = usage.booster(for: query, at: now) // Only the best few are ever shown, so keep those in order instead of sorting every match. var top: [(ranked: Ranked, length: Int)] = [] top.reserveCapacity(limit + 1) @@ -43,7 +43,7 @@ public enum Ranker { highlightsTitle = false } guard let matchScore else { continue } - let score = matchScore + candidate.weight + usage.boost(for: candidate.item.id, key: key, at: now) + let score = matchScore + candidate.weight + booster.boost(for: candidate.item.id) let length = candidate.names[0].keys.count if top.count == limit, let last = top.last, !isOrderedBefore(score, length, candidate.item, last) { continue diff --git a/Sources/CommandKit/Usage.swift b/Sources/CommandKit/Usage.swift index a6d5bc4..67b22e9 100644 --- a/Sources/CommandKit/Usage.swift +++ b/Sources/CommandKit/Usage.swift @@ -1,7 +1,8 @@ import Foundation /// What has been opened, how often, and how recently, and which result was chosen for which query. It -/// moves things you use up the list, and makes the query you typed last time pick the same thing again. +/// moves things you use up the list, makes the query you typed last time pick the same thing again, and +/// lets a shorter or longer start of that query lean the same way. public struct Usage: Codable, Sendable, Equatable { struct Entry: Codable, Sendable, Equatable { /// Uses, each decayed by its age, as of `last`. @@ -32,17 +33,47 @@ public struct Usage: Codable, Sendable, Equatable { } public func boost(for id: String, query: String, at now: Date) -> Int { - boost(for: id, key: Self.key(query), at: now) + booster(for: query, at: now).boost(for: id) } - /// For ranking many items against one query: `key` is `Usage.key(query)`, folded once. - func boost(for id: String, key: String, at now: Date) -> Int { - var boost = 0 - if choices[key] == id { boost += Self.choiceBoost } - if let entry = entries[id] { - boost += min(Self.maximumFrecencyBoost, Int(12 * log2(1 + decayed(entry, at: now)))) + /// Boosts for one query, worked out once so ranking many items costs a lookup each. + public struct Booster: Sendable { + let choices: [String: Int] + let usage: Usage + let now: Date + + public func boost(for id: String) -> Int { + var boost = choices[id] ?? 0 + if let entry = usage.entries[id] { + boost += min(Usage.maximumFrecencyBoost, Int(12 * log2(1 + usage.decayed(entry, at: now)))) + } + return boost + } + } + + public func booster(for query: String, at now: Date) -> Booster { + Booster(choices: choiceBoosts(Self.key(query)), usage: self, now: now) + } + + /// The exact query earns the full boost. A query that starts a past one ("sa" after choosing Safari for + /// "safari"), or that a past one starts ("safar" after "saf"), earns a share of half of it, in proportion + /// to how much of the longer one they have in common. + func choiceBoosts(_ key: String) -> [String: Int] { + guard !key.isEmpty else { return [:] } + var boosts: [String: Int] = [:] + for (stored, id) in choices { + let boost: Int + if stored == key { + boost = Self.choiceBoost + } else if stored.hasPrefix(key) || key.hasPrefix(stored) { + let shared = min(stored.count, key.count) + boost = Self.choiceBoost / 2 * shared / max(stored.count, key.count) + } else { + continue + } + boosts[id] = max(boosts[id] ?? 0, boost) } - return boost + return boosts } func decayed(_ entry: Entry, at now: Date) -> Double { diff --git a/Tests/CommandKitTests/SearchTests.swift b/Tests/CommandKitTests/SearchTests.swift index 3aba588..b8abc91 100644 --- a/Tests/CommandKitTests/SearchTests.swift +++ b/Tests/CommandKitTests/SearchTests.swift @@ -93,6 +93,14 @@ func titles(_ ranked: [Ranked]) -> [String] { ranked.map(\.item.title) } #expect(Ranker.rank(apps, query: "saf", usage: usage, now: now, limit: 1).first?.item.title == "Safari") } + @Test func aChoiceForALongerQueryLeansAShorterOneTheSameWay() { + var usage = Usage() + // Equally frequent, so only the remembered query can separate them. + usage.record("app:Safari", query: "", at: now) + usage.record("app:Sublime Text", query: "sublime", at: now) + #expect(Ranker.rank(apps, query: "s", usage: usage, now: now, limit: 1).first?.item.title == "Sublime Text") + } + @Test func alternativeNamesMatchWithoutHighlighting() { let localised = [app("Systemeinstellungen", alternatives: ["System Settings"])] let ranked = Ranker.rank(localised, query: "system set", usage: Usage(), now: now, limit: 1) @@ -195,6 +203,26 @@ func titles(_ ranked: [Ranked]) -> [String] { ranked.map(\.item.title) } #expect(usage.boost(for: "a", query: "cafe", at: now) >= Usage.choiceBoost) } + @Test func sharedStartsEarnAShareOfTheBoost() { + var usage = Usage() + usage.record("safari", query: "safari", at: now) + usage.record("saf-tool", query: "saf", at: now) + usage.record("slack", query: "sl", at: now) + #expect(usage.choiceBoosts("safari") == ["safari": 120, "saf-tool": 30]) + #expect(usage.choiceBoosts("sa") == ["safari": 20, "saf-tool": 40]) + #expect(usage.choiceBoosts("safar") == ["safari": 50, "saf-tool": 36]) + #expect(usage.choiceBoosts("s") == ["safari": 10, "saf-tool": 20, "slack": 30]) + #expect(usage.choiceBoosts("x").isEmpty) + #expect(usage.choiceBoosts("").isEmpty) + } + + @Test func anItemChosenForSeveralQueriesTakesTheBestBoost() { + var usage = Usage() + usage.record("safari", query: "sa", at: now) + usage.record("safari", query: "safari", at: now) + #expect(usage.choiceBoosts("saf") == ["safari": 40]) + } + @Test func storageStaysBounded() { var usage = Usage() for i in 0..<(Usage.maximumEntries + 50) { usage.record("id\(i)", query: "q\(i)", at: now) } From d5676ccafa2e3ecbfa0aee1cc61f08f5ac3105e7 Mon Sep 17 00:00:00 2001 From: Oddur Sigurdsson Date: Fri, 16 Oct 2026 19:17:12 -0400 Subject: [PATCH 2/2] perf(rank): break ties on folded names, not localized compare MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A one-letter query ties hundreds of names, and localizedStandardCompare on each tie cost more than matching. The folded keys are already in memory and order the same way for ties. Minimum of five interleaved release runs on the 2,000-name benchmark: 989 µs before, 704 µs after. --- Sources/CommandKit/Ranker.swift | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Sources/CommandKit/Ranker.swift b/Sources/CommandKit/Ranker.swift index 983ea44..77f2be3 100644 --- a/Sources/CommandKit/Ranker.swift +++ b/Sources/CommandKit/Ranker.swift @@ -24,7 +24,7 @@ public enum Ranker { guard !q.isEmpty, limit > 0 else { return [] } let booster = usage.booster(for: query, at: now) // Only the best few are ever shown, so keep those in order instead of sorting every match. - var top: [(ranked: Ranked, length: Int)] = [] + var top: [(ranked: Ranked, name: [UInt32])] = [] top.reserveCapacity(limit + 1) for candidate in candidates { var best: Match? @@ -44,28 +44,27 @@ public enum Ranker { } guard let matchScore else { continue } let score = matchScore + candidate.weight + booster.boost(for: candidate.item.id) - let length = candidate.names[0].keys.count - if top.count == limit, let last = top.last, !isOrderedBefore(score, length, candidate.item, last) { + let name = candidate.names[0].keys + if top.count == limit, let last = top.last, !isOrderedBefore(score, name, last) { continue } let entry = ( Ranked(item: candidate.item, score: score, highlights: highlightsTitle ? best?.positions ?? [] : []), - length + name ) - let index = - top.firstIndex { !isOrderedBefore($0.ranked.score, $0.length, $0.ranked.item, entry) } ?? top.count + let index = top.firstIndex { !isOrderedBefore($0.ranked.score, $0.name, entry) } ?? top.count top.insert(entry, at: index) if top.count > limit { top.removeLast() } } return top.map(\.ranked) } - /// Higher score first; on a tie the shorter name, then alphabetical. - static func isOrderedBefore(_ score: Int, _ length: Int, _ item: Item, _ other: (ranked: Ranked, length: Int)) - -> Bool - { + /// Higher score first; on a tie the shorter name, then alphabetical by folded name. A one-letter query + /// ties hundreds of names, so this compares the keys already folded for matching rather than calling + /// `localizedStandardCompare`, which costs more than the match itself. + static func isOrderedBefore(_ score: Int, _ name: [UInt32], _ other: (ranked: Ranked, name: [UInt32])) -> Bool { if score != other.ranked.score { return score > other.ranked.score } - if length != other.length { return length < other.length } - return item.title.localizedStandardCompare(other.ranked.item.title) == .orderedAscending + if name.count != other.name.count { return name.count < other.name.count } + return name.lexicographicallyPrecedes(other.name) } }