Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cotabby.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
91D1F16B8C5DA281D4B7F699 /* CustomRulesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD752451330486FE270018B0 /* CustomRulesTests.swift */; };
924489CEE8171F7AD8579D71 /* FocusDebugOverlayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F5E263AB69029D5E13D5EE8 /* FocusDebugOverlayController.swift */; };
934885ACC2DEA20B27F10948 /* PromptContextSanitizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D80CC2CCAAFE3F23FB8C37A /* PromptContextSanitizerTests.swift */; };
9592370F425B5116E0DD6FD0 /* StaleCompletionReconcilerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE1F514806CEFDA700C77E84 /* StaleCompletionReconcilerTests.swift */; };
96498E097A5899AFC9F0C853 /* EmojiCatalogMatcherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 292DC9D4D9D5D26AE882E39B /* EmojiCatalogMatcherTests.swift */; };
96782E57CA26A16409368B69 /* TextDirectionDetector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 328847A0F494360033366791 /* TextDirectionDetector.swift */; };
9706D778FB549E9E7AE05F4F /* EmojiMatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1441B2D89DAE6878DAD11F17 /* EmojiMatcher.swift */; };
Expand Down Expand Up @@ -193,6 +194,7 @@
E912D4617AE1376061DF1F00 /* LanguageSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4793D4EA5D36D7E5CC216C27 /* LanguageSupportTests.swift */; };
E994FE418A961FB234D9057A /* DownloadFileRescuerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2F46767D9D1F0D44E239CA8 /* DownloadFileRescuerTests.swift */; };
E9E4CC657771DF9F4C56183C /* VisualContextCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A854CAFB1F557BC4CAED8819 /* VisualContextCoordinator.swift */; };
EA7A31903D43AE3C8B4DAEC0 /* StaleCompletionReconciler.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB9482082EC7A71418EC5BCE /* StaleCompletionReconciler.swift */; };
ED0843752B297D7E9DB2C468 /* EmojiTriggerStateMachineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 723E1EFA85D2E61B6C5F33E8 /* EmojiTriggerStateMachineTests.swift */; };
ED9C51B0D7056F0753AADF2D /* GhostSuggestionLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 043E8AA850F930222DD112C0 /* GhostSuggestionLayout.swift */; };
EDA8E8250FC2F70B206B4894 /* LlamaVisualContextSummarizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D2782B6C7BE3F56BCB22DE /* LlamaVisualContextSummarizer.swift */; };
Expand Down Expand Up @@ -402,6 +404,7 @@
DB0CE9AB1286367BA2E82392 /* SettingsContainerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsContainerView.swift; sourceTree = "<group>"; };
DDE858CB1E687E3CEB8FDD5B /* SuggestionRequestFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SuggestionRequestFactory.swift; sourceTree = "<group>"; };
DDF6A4E9CE93FD53C60E67E3 /* EmojiQueryRun.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmojiQueryRun.swift; sourceTree = "<group>"; };
DE1F514806CEFDA700C77E84 /* StaleCompletionReconcilerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaleCompletionReconcilerTests.swift; sourceTree = "<group>"; };
DEB16474A67CE1D210B944C9 /* SuggestionSubsystemContracts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SuggestionSubsystemContracts.swift; sourceTree = "<group>"; };
E1D2782B6C7BE3F56BCB22DE /* LlamaVisualContextSummarizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LlamaVisualContextSummarizer.swift; sourceTree = "<group>"; };
E217A66717D78E1E49350EC8 /* DownloadOutcomeClassifierTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadOutcomeClassifierTests.swift; sourceTree = "<group>"; };
Expand All @@ -412,6 +415,7 @@
E7F42112F14026E6253BB865 /* PermissionAndContextModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PermissionAndContextModelTests.swift; sourceTree = "<group>"; };
EAAE6B395FAB604DF059280A /* KeyCodeLabels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyCodeLabels.swift; sourceTree = "<group>"; };
EB630F9814388203DD1CA2EC /* ShortcutsPaneView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShortcutsPaneView.swift; sourceTree = "<group>"; };
EB9482082EC7A71418EC5BCE /* StaleCompletionReconciler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaleCompletionReconciler.swift; sourceTree = "<group>"; };
ED8672B87CEC72BE3978C6BB /* CotabbyTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CotabbyTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
EE8BB19D8EC9A75CD3458A6B /* EmojiVariantResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmojiVariantResolverTests.swift; sourceTree = "<group>"; };
EE94342B888A5A2CCF66BC93 /* SuggestionRequestFactoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SuggestionRequestFactoryTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -669,6 +673,7 @@
0D80CC2CCAAFE3F23FB8C37A /* PromptContextSanitizerTests.swift */,
4696A84D17890B154533A08F /* PromptPolicyTests.swift */,
2BC293F6125E2B14DCF05AD9 /* SettingsAttentionEvaluatorTests.swift */,
DE1F514806CEFDA700C77E84 /* StaleCompletionReconcilerTests.swift */,
C05B0439348261163B37C508 /* SuggestionAvailabilityEvaluatorTests.swift */,
C375227649689775275AA4B3 /* SuggestionCoordinatorAcceptanceTests.swift */,
CDB25ABC4FFB0E63477CDCB0 /* SuggestionOverlayStabilityGateTests.swift */,
Expand Down Expand Up @@ -805,6 +810,7 @@
FA4B45B91D4DEAC979C3113E /* PromptContextSanitizer.swift */,
6DC693E00430F46E41CB56E6 /* RequestID.swift */,
2A02336442BB735EE2E8D064 /* SettingsAttentionEvaluator.swift */,
EB9482082EC7A71418EC5BCE /* StaleCompletionReconciler.swift */,
3609CC88A5280B3AA40414DF /* SuggestionAvailabilityEvaluator.swift */,
B2F95847D76893C8A5B504B4 /* SuggestionOverlayStabilityGate.swift */,
DDE858CB1E687E3CEB8FDD5B /* SuggestionRequestFactory.swift */,
Expand Down Expand Up @@ -1048,6 +1054,7 @@
078FDE669437D756678E9AB7 /* SettingsRowLabel.swift in Sources */,
27D4F5CACADE171F142178B4 /* SettingsSidebarView.swift in Sources */,
12995E5DDB11E3395E6AF82F /* ShortcutsPaneView.swift in Sources */,
EA7A31903D43AE3C8B4DAEC0 /* StaleCompletionReconciler.swift in Sources */,
4F369F5284DDCEABF082E59B /* SuggestionAvailabilityEvaluator.swift in Sources */,
A0657CE0488F69F0BD559CBC /* SuggestionCoordinator+Acceptance.swift in Sources */,
D2F1DD215989BF32675308C2 /* SuggestionCoordinator+Input.swift in Sources */,
Expand Down Expand Up @@ -1129,6 +1136,7 @@
934885ACC2DEA20B27F10948 /* PromptContextSanitizerTests.swift in Sources */,
3CF1A4E39F24917DF0470A7D /* PromptPolicyTests.swift in Sources */,
C618C5595DA9C57C806A3E03 /* SettingsAttentionEvaluatorTests.swift in Sources */,
9592370F425B5116E0DD6FD0 /* StaleCompletionReconcilerTests.swift in Sources */,
88BCD795A14E1C9308F7BB31 /* SuggestionAvailabilityEvaluatorTests.swift in Sources */,
5B404450B412A6102F514250 /* SuggestionCoordinatorAcceptanceTests.swift in Sources */,
4C6D8ED0A7B45D2EADF06DA5 /* SuggestionOverlayStabilityGateTests.swift in Sources */,
Expand Down
80 changes: 76 additions & 4 deletions Cotabby/App/Coordinators/SuggestionCoordinator+Prediction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ extension SuggestionCoordinator {
return
}

await apply(result: result, workID: workID)
await apply(result: result, requestContext: request.context, workID: workID)
} catch SuggestionClientError.cancelled {
return
} catch {
Expand All @@ -134,7 +134,7 @@ extension SuggestionCoordinator {
}

/// Promotes a generated result to `ready` only when it is still fresh for the current field.
func apply(result: SuggestionResult, workID: UInt64) async {
func apply(result: SuggestionResult, requestContext: FocusedInputContext, workID: UInt64) async {

guard workController.isCurrent(workID) else {

Expand Down Expand Up @@ -170,10 +170,21 @@ extension SuggestionCoordinator {
lastAcceptedTail = nil

// Generation numbers are our stale-result guard. If the text changed while the model was
// thinking, we drop the answer instead of showing a suggestion for old content.
// thinking, the answer was generated against an older prefix. Before dropping it, try to
// salvage it by trimming the characters the user typed during the race (see
// `StaleCompletionReconciler`) and present the remaining tail instead of dropping it.
guard liveContext.generation == result.generation else {

latestRawModelOutput = SuggestionDebugLogger.debugPreview(result.rawText)

if let salvage = salvagedStaleCompletion(
result: result,
requestContext: requestContext,
liveContext: liveContext
) {
presentSalvagedCompletion(salvage, result: result, liveContext: liveContext, workID: workID)
return
}
Comment on lines 176 to +186
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Feature flag gate is missing — salvage is live for all users

The PR description explicitly states the salvage path is "gated behind a hidden, default-off setting" (cotabbyStaleCompletionSalvageEnabled), that with the flag off the only behavior change is an extra stale-salvageable log line, and that the setting is read into the settings snapshot at launch. Neither the flag nor the stale-salvageable log stage appear anywhere in the codebase: SuggestionSettingsModel, SuggestionSettingsSnapshot, and SuggestionSubsystemContracts.swift all have zero references to it.

As written, whenever salvagedStaleCompletion returns a non-nil value the salvaged completion is presented unconditionally, making the salvage path active for every user from the first install of this build. The staged roll-out and instrumentation period described in the risk notes never happen.

Fix in Codex Fix in Claude Code


logStage(
"stale-drop",
workID: workID,
Expand Down Expand Up @@ -268,6 +279,67 @@ extension SuggestionCoordinator {
)
}

/// Bridges live and request-time context to the pure salvage rules, applying the context-level
/// guardrails the string helper can't see: the result must belong to the same process, the field
/// must have no active selection, and the text after the caret must be unchanged. Any of those
/// failing means the user did more than type ahead, so the continuation no longer attaches.
private func salvagedStaleCompletion(
result: SuggestionResult,
requestContext: FocusedInputContext,
liveContext: FocusedInputContext
) -> StaleCompletionReconciler.Reconciled? {
guard liveContext.processIdentifier == requestContext.processIdentifier else {
return nil
}
guard liveContext.selection.length == 0 else {
return nil
}
guard liveContext.trailingText == requestContext.trailingText else {
return nil
}

return StaleCompletionReconciler.reconcile(
continuation: result.text,
prefixAtRequest: requestContext.precedingText,
currentPrefix: liveContext.precedingText
)
}

/// Promotes a salvaged stale completion to a ready session anchored at the *current* field state.
/// Mirrors the fresh-result ready path but stamps the live generation (not the stale one) so the
/// session reconciles correctly as the user keeps typing through the recovered tail.
private func presentSalvagedCompletion(
_ salvage: StaleCompletionReconciler.Reconciled,
result: SuggestionResult,
liveContext: FocusedInputContext,
workID: UInt64
) {
latestLatencyMilliseconds = Int(result.latency * 1000)
latestGenerationNumber = liveContext.generation
let session = interactionState.startSession(
fullText: salvage.text,
liveContext: liveContext,
latency: result.latency
)
applySessionDiagnostics(session, acceptanceAction: "Salvaged a stale suggestion after type-ahead.")
state = .ready(text: session.remainingText, latency: session.latency)
presentOverlay(
text: session.remainingText,
at: liveContext.caretRect,
context: liveContext,
isRightToLeft: TextDirectionDetector.isRightToLeft(liveContext.precedingText)
)
logStage(
"stale-salvage",
workID: workID,
generation: liveContext.generation,
message: "Salvaged a stale result by trimming \(salvage.typedSinceRequest.count) " +
"typed character(s) (\(salvage.confidence.rawValue)).",
rawOutput: result.rawText,
normalizedOutput: session.remainingText
)
}

/// Converts a runtime or engine failure into visible coordinator state and clears stale UI.
func applyFailure(_ message: String, workID: UInt64) async {
guard workController.isCurrent(workID) else {
Expand Down
5 changes: 2 additions & 3 deletions Cotabby/Models/SuggestionSettingsModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,6 @@ final class SuggestionSettingsModel: ObservableObject {
.string(forKey: Self.acceptanceGranularityDefaultsKey)
.flatMap(AcceptanceGranularity.init(rawValue:))
?? .word

isGloballyEnabled = resolvedGloballyEnabled
disabledAppRules = resolvedDisabledAppRules
showIndicator = resolvedShowIndicator
Expand Down Expand Up @@ -946,8 +945,8 @@ extension SuggestionSettingsModel: SuggestionSettingsProviding {
// `presentationToggles` carries the visual-pipeline knobs (clipboard, fast mode, mirror
// preference); they share the property of "affects how/when suggestions are shown".
//
// The outer CombineLatest4 is at the cap, so `$acceptanceGranularity` is layered above it
// via a second CombineLatest to avoid restructuring the existing groupings.
// The outer CombineLatest4 is at the cap, so `$acceptanceGranularity` is layered above it via
// a second combiner to avoid restructuring the existing groupings.
let primary = Publishers.CombineLatest4(
Publishers.CombineLatest4(
$isGloballyEnabled,
Expand Down
128 changes: 128 additions & 0 deletions Cotabby/Support/StaleCompletionReconciler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import Foundation

/// File overview:
/// Pure rules for salvaging a completion that finished generating *after* the user kept typing.
///
/// Inline autocomplete has an unavoidable race. A request is built from the prefix at time `t0`, the
/// model decodes for some milliseconds, and a fast typist can append characters before the result
/// lands at `t1`. The naive response is to throw the now-stale result away (the generation guard in
/// `SuggestionCoordinator.apply`). This helper instead tries to recover it: it trims the characters
/// typed during the race off the front of the continuation, so a request built from
/// "thanks for meet" whose model returned "ing with me today" still renders " with me today" after
/// the user has typed "ing".
///
/// This type is intentionally pure (identical inputs always yield identical output), so the salvage
/// decision is unit-testable in isolation from Accessibility timing and runtime state. The
/// context-level guardrails (focus shift, selected text, a changed suffix) stay with the coordinator,
/// which owns that live data; this helper only reasons about the three strings involved.
enum StaleCompletionReconciler {
/// How confident we are that the salvaged tail is correct.
///
/// `exact` means the continuation literally began with the typed-ahead text, so the trim is
/// unambiguous. `overlap` means we recovered the join by matching a suffix of the typed text
/// against a prefix of the continuation, which is plausible but weaker, so callers can log or
/// gate it separately.
enum Confidence: String, Equatable, Sendable {
case exact
case overlap
}

/// A salvaged continuation plus the evidence behind it.
struct Reconciled: Equatable, Sendable {
/// The continuation with the race-window typing trimmed off the front.
let text: String
/// The characters the user typed between the request going out and the result landing.
let typedSinceRequest: String
let confidence: Confidence
}

/// Minimum suffix/prefix overlap, in characters, before the fuzzy join is trusted. One- and
/// two-character overlaps fire constantly on spaces and single letters, so they would salvage
/// garbage; three keeps the fallback meaningful without being reckless.
static let defaultMinimumOverlap = 3

/// Attempts to salvage `continuation` given the prefix it was generated against and the prefix
/// now in the field. Returns `nil` when the result is unsalvageable: the user deleted past the
/// request baseline, did not actually type ahead, typed something disjoint from the continuation,
/// or the trimmed tail collapses to whitespace.
static func reconcile(
continuation: String,
prefixAtRequest: String,
currentPrefix: String,
minimumOverlap: Int = defaultMinimumOverlap
) -> Reconciled? {
// The user must only have *added* text since the request. If the current prefix no longer
// begins with the request prefix they deleted past the baseline or the field diverged, and
// any trim we computed would be guesswork.
guard currentPrefix.hasPrefix(prefixAtRequest) else {
return nil
}

let typed = String(currentPrefix.dropFirst(prefixAtRequest.count))

// Salvage exists to recover from type-ahead specifically. With nothing typed there is no
// overlap to remove, so this is a plain stale drop, not a rescue; let the caller handle it.
guard !typed.isEmpty else {
return nil
}

// Clean case: the user is typing straight along the predicted continuation, so it begins with
// exactly what they typed. Drop that prefix and show the remainder.
if continuation.hasPrefix(typed) {
return finalize(
String(continuation.dropFirst(typed.count)),
typedSinceRequest: typed,
confidence: .exact
)
}

// Fuzzy case: the continuation and the typed-ahead text converge partway in. If a suffix of
// what the user typed equals a prefix of the continuation (typed "see you ", model returned
// "you soon"), drop the overlapping head so "you soon" becomes "soon".
let overlap = longestSuffixPrefixOverlap(suffix: typed, prefix: continuation)
if overlap >= minimumOverlap {
return finalize(
String(continuation.dropFirst(overlap)),
typedSinceRequest: typed,
confidence: .overlap
)
}
Comment on lines +82 to +89
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 When the overlap path fires and finalize rejects the trimmed tail (e.g. the tail is whitespace-only because the user's typed suffix covers the entire non-whitespace portion of the continuation), reconcile returns nil without trying any shorter overlaps that passed elementsEqual. In practice this is rare — it requires the typed text's trailing segment to align exactly with all non-whitespace content in the continuation — but it means a valid shorter salvage is silently skipped. Consider returning the best valid (non-nil) finalize result rather than only trying the longest overlap.

Suggested change
let overlap = longestSuffixPrefixOverlap(suffix: typed, prefix: continuation)
if overlap >= minimumOverlap {
return finalize(
String(continuation.dropFirst(overlap)),
typedSinceRequest: typed,
confidence: .overlap
)
}
let overlap = longestSuffixPrefixOverlap(suffix: typed, prefix: continuation)
if overlap >= minimumOverlap {
if let reconciled = finalize(
String(continuation.dropFirst(overlap)),
typedSinceRequest: typed,
confidence: .overlap
) {
return reconciled
}
// Longest overlap produced an empty/whitespace tail; fall through to nil.
}

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Codex Fix in Claude Code


return nil
}

/// Returns the largest `k` such that the last `k` characters of `suffix` equal the first `k`
/// characters of `prefix`. Operates in `Character` units so multi-scalar graphemes (emoji,
/// composed characters) are never split mid-cluster.
static func longestSuffixPrefixOverlap(suffix: String, prefix: String) -> Int {
let suffixCharacters = Array(suffix)
let prefixCharacters = Array(prefix)
let maxOverlap = min(suffixCharacters.count, prefixCharacters.count)
guard maxOverlap > 0 else {
return 0
}

var best = 0
for candidate in 1...maxOverlap {
let tail = suffixCharacters[(suffixCharacters.count - candidate)...]
let head = prefixCharacters[..<candidate]
if tail.elementsEqual(head) {
best = candidate
}
}
return best
}

/// Rejects salvaged tails that are empty or whitespace-only. Showing "ghost spaces" reads as a
/// broken suggestion, matching `ActiveSuggestionSession.isExhausted`.
private static func finalize(
_ text: String,
typedSinceRequest: String,
confidence: Confidence
) -> Reconciled? {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return nil
}
return Reconciled(text: text, typedSinceRequest: typedSinceRequest, confidence: confidence)
}
}
Loading