Skip to content

Commit f5f07bb

Browse files
authored
Merge pull request #144 from IchenDEV/cursor/confirm-empty-web-composer
fix: confirm dictation into an empty ChatGPT composer instead of showing the unconfirmed notice
2 parents 56093f5 + 09a5c9b commit f5f07bb

10 files changed

Lines changed: 266 additions & 18 deletions

File tree

‎Sources/UtterMacServices/DeliveryExpectation.swift‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,19 @@ enum DeliveryExpectation {
1313
!replacement.isEmpty else { return change.expectedDocument }
1414
return replacement
1515
}
16+
17+
/// Every value the field may hold once the text has landed. A caret at the very start of an empty-looking web
18+
/// editor is the one case with two: some editors (ChatGPT) keep a placeholder inside the value and drop it on
19+
/// insert, so the field ends up equal to the replacement alone. Seeing exactly the replacement can only mean the
20+
/// text arrived, so it is accepted in addition to the normal computation. Values equal to `document` are
21+
/// never returned: an unchanged field proves nothing.
22+
static func acceptedDocuments(document: String, range: NSRange, replacement: String,
23+
isWebContentEditor: Bool) -> [String]? {
24+
guard let primary = expectedDocument(document: document, range: range, replacement: replacement,
25+
isWebContentEditor: isWebContentEditor) else { return nil }
26+
var accepted = [primary]
27+
if isWebContentEditor, range == NSRange(location: 0, length: 0), !replacement.isEmpty,
28+
replacement != primary { accepted.append(replacement) }
29+
return accepted.filter { $0 != document }
30+
}
1631
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import Foundation
2+
3+
/// Describes why a delivery could not be confirmed using counts and flags only. No part of the observed, expected or
4+
/// original text can appear in the result.
5+
enum DeliveryShapeDiagnostic {
6+
static func summary(observed: String?, expected: String, original: String?) -> String {
7+
guard let observed else {
8+
return "readable=false expectedUnits=\(expected.utf16.count) originalUnits=\(original?.utf16.count ?? -1)"
9+
}
10+
let a = Array(observed.utf16), b = Array(expected.utf16)
11+
var prefix = 0
12+
while prefix < a.count, prefix < b.count, a[prefix] == b[prefix] { prefix += 1 }
13+
var suffix = 0
14+
while suffix < a.count - prefix, suffix < b.count - prefix, a[a.count - 1 - suffix] == b[b.count - 1 - suffix] { suffix += 1 }
15+
return [
16+
"readable=true",
17+
"observedUnits=\(a.count)", "expectedUnits=\(b.count)", "originalUnits=\(original?.utf16.count ?? -1)",
18+
"commonPrefix=\(prefix)", "commonSuffix=\(suffix)",
19+
"observedLineFeeds=\(a.filter { $0 == 0x0A }.count)", "expectedLineFeeds=\(b.filter { $0 == 0x0A }.count)",
20+
"observedNoBreakSpaces=\(a.filter { $0 == 0xA0 }.count)",
21+
"equalsOriginal=\(observed == original)",
22+
].joined(separator: " ")
23+
}
24+
}

‎Sources/UtterMacServices/DeliveryTextObservation.swift‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,28 @@ final class ContinuousDeliveryClock: DeliveryObservationClock {
1616

1717
@MainActor
1818
enum DeliveryTextObservation {
19+
struct Result {
20+
let confirmed: Bool
21+
/// Last value that could be read, kept only so a failure can be described by counts. Never logged as text.
22+
let lastRead: String?
23+
}
24+
1925
static func confirm(_ expected: String, read: () -> String?, clock: any DeliveryObservationClock,
2026
timeout: Duration = .seconds(3)) async -> Bool {
27+
await observe(accepting: [expected], read: read, clock: clock, timeout: timeout).confirmed
28+
}
29+
30+
static func observe(accepting accepted: [String], read: () -> String?, clock: any DeliveryObservationClock,
31+
timeout: Duration = .seconds(3)) async -> Result {
2132
let deadline = clock.now + timeout
33+
var lastRead: String?
2234
repeat {
23-
if read() == expected { return true }
24-
guard clock.now < deadline else { return false }
35+
let value = read()
36+
if let value { lastRead = value }
37+
if let value, accepted.contains(value) { return Result(confirmed: true, lastRead: lastRead) }
38+
guard clock.now < deadline else { return Result(confirmed: false, lastRead: lastRead) }
2539
do { try await clock.sleep(for: min(.milliseconds(25), deadline - clock.now)) }
26-
catch { return false }
40+
catch { return Result(confirmed: false, lastRead: lastRead) }
2741
} while true
2842
}
2943
}

‎Sources/UtterMacServices/Native/NativeDeliveryTarget.swift‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ final class NativeDeliveryTarget: DeliveryTextTarget {
1111
private let document: String?
1212
private let replacementRange: NSRange?
1313
private var prepared = false
14+
/// Counts only, set when the last confirmation timed out.
15+
private(set) var unconfirmedSummary: String?
1416
private let exposesChromiumNode: Bool
1517
private let clock: any DeliveryObservationClock
1618

@@ -72,8 +74,12 @@ final class NativeDeliveryTarget: DeliveryTextTarget {
7274

7375
func confirm(_ text: String) async -> Bool {
7476
// An unchanged value cannot prove that a pending paste consumed the clipboard.
75-
guard let expected = expectedDocument(text), expected != document else { return false }
76-
return await DeliveryTextObservation.confirm(expected, read: { AXTargetState.value(of: self.identity) }, clock: clock)
77+
guard let accepted = acceptedDocuments(text) else { return false }
78+
let outcome = await DeliveryTextObservation.observe(accepting: accepted,
79+
read: { AXTargetState.value(of: self.identity) }, clock: clock)
80+
unconfirmedSummary = outcome.confirmed ? nil
81+
: DeliveryShapeDiagnostic.summary(observed: outcome.lastRead, expected: accepted[0], original: document)
82+
return outcome.confirmed
7783
}
7884

7985
func restoreSelection() {
@@ -82,17 +88,20 @@ final class NativeDeliveryTarget: DeliveryTextTarget {
8288
}
8389

8490
func insertionAnchor(_ text: String, isCurrent: @escaping () -> Bool) -> (any OutputAnchor)? {
85-
guard !text.isEmpty, let range = replacementRange, let expected = expectedDocument(text),
86-
AXTargetState.value(of: identity) == expected, let state = AXTargetState.capture(),
91+
guard !text.isEmpty, let range = replacementRange, let accepted = acceptedDocuments(text),
92+
let current = AXTargetState.value(of: identity), accepted.contains(current), let state = AXTargetState.capture(),
8793
state.processIdentifier == lease.processIdentifier, CFEqual(identity, state.element) else { return nil }
8894
let insertedRange = NSRange(location: range.location, length: (text as NSString).length)
8995
let insertion = RecentInsertionAnchor(processIdentifier: lease.processIdentifier, element: identity, range: insertedRange, text: text)
9096
return NativeOutputAnchor(target: lease, anchor: insertion, state: state, isCurrent: isCurrent)
9197
}
9298

93-
private func expectedDocument(_ text: String) -> String? {
94-
guard let document, let range = replacementRange else { return nil }
95-
return DeliveryExpectation.expectedDocument(document: document, range: range, replacement: text,
96-
isWebContentEditor: isWebContentEditor)
99+
/// Nil when the change cannot be computed or when nothing the field could hold differs from what it holds now.
100+
private func acceptedDocuments(_ text: String) -> [String]? {
101+
guard let document, let range = replacementRange,
102+
let accepted = DeliveryExpectation.acceptedDocuments(document: document, range: range, replacement: text,
103+
isWebContentEditor: isWebContentEditor),
104+
!accepted.isEmpty else { return nil }
105+
return accepted
97106
}
98107
}

‎Sources/UtterMacServices/Native/NativeOutputBackend.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ final class NativeOutputBackend {
7676
}
7777
}
7878
log.info(result.logSummary)
79+
if result.disposition == .uncertain, let shape = destination.unconfirmedSummary {
80+
log.info("Delivery unconfirmed shape: \(shape)")
81+
}
7982
return result
8083
}
8184
}

‎Tests/OpenTypeTests/DesktopOverlayDwellTests.swift‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ final class DesktopOverlayDwellTests: XCTestCase {
1515

1616
func testUnconfirmedNoticeLeavesAfterTheDwell() async throws {
1717
let rig = try Rig(self)
18+
let shownAt = ContinuousClock.now
1819
rig.host.project(unconfirmed())
1920
XCTAssertTrue(rig.overlay.visible)
20-
try await Task.sleep(for: .milliseconds(40))
21-
XCTAssertTrue(rig.overlay.visible, "It must not leave before the dwell")
2221
try await rig.waitUntil { !$0.visible }
22+
XCTAssertGreaterThanOrEqual(ContinuousClock.now - shownAt, rig.dwell, "It must not leave before the dwell")
2323
XCTAssertEqual(rig.overlay.hides, 1)
2424
}
2525

@@ -95,8 +95,10 @@ private final class FakeOverlay: OverlayPresentationService {
9595
private final class Rig {
9696
let host: NativeDesktopHost
9797
let overlay = FakeOverlay()
98+
let dwell: Duration
9899

99100
init(_ test: XCTestCase, dwell: Duration = .milliseconds(120)) throws {
101+
self.dwell = dwell
100102
let suite = "DesktopOverlayDwell-" + UUID().uuidString
101103
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
102104
let settings = SettingsStore(defaults: defaults)

‎Tests/UtterMacServicesTests/DeliveryExpectationTests.swift‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,49 @@ final class DeliveryExpectationTests: XCTestCase {
5151
XCTAssertNil(expected("\n", at: -1, insert: "x", web: true))
5252
XCTAssertNil(expected("\n", at: 0, length: -1, insert: "x", web: true))
5353
}
54+
55+
// MARK: accepted documents (ChatGPT keeps its placeholder inside the value and drops it on insert)
56+
57+
private func accepted(_ document: String, at location: Int, length: Int = 0, insert replacement: String,
58+
web: Bool) -> [String]? {
59+
DeliveryExpectation.acceptedDocuments(document: document, range: NSRange(location: location, length: length),
60+
replacement: replacement, isWebContentEditor: web)
61+
}
62+
63+
/// 12 units: a word, a space, a word, then the trailing line feed, as measured in the ChatGPT composer.
64+
private let measuredPlaceholder = "Ask Xxxxxx\n"
65+
66+
func testAnEmptyLookingWebEditorAcceptsTheTextAloneAndTheNormalComputation() {
67+
XCTAssertEqual(accepted(measuredPlaceholder, at: 0, insert: "你好,世界", web: true),
68+
[("你好,世界" + measuredPlaceholder), "你好,世界"])
69+
}
70+
71+
func testTheLoneNewlinePlaceholderKeepsExactlyTheTextAsBefore() {
72+
XCTAssertEqual(accepted("\n", at: 0, insert: "hello", web: true), ["hello"])
73+
}
74+
75+
func testARealDraftAtTheStartOfAWebEditorAcceptsBothShapesButNeverTheOriginal() {
76+
let result = accepted("abc\n", at: 0, insert: "x", web: true)
77+
XCTAssertEqual(result, ["xabc\n", "x"])
78+
XCTAssertFalse(result?.contains("abc\n") ?? true)
79+
XCTAssertFalse(result?.contains("abc") ?? true)
80+
}
81+
82+
func testNothingExtraIsAcceptedAwayFromTheStartOrOnNativeTargetsOrForDeletes() {
83+
XCTAssertEqual(accepted(measuredPlaceholder, at: 3, insert: "x", web: true), ["Askx Xxxxxx\n"])
84+
XCTAssertEqual(accepted(measuredPlaceholder, at: 0, length: 2, insert: "x", web: true), ["x" + String(measuredPlaceholder.dropFirst(2))])
85+
XCTAssertEqual(accepted(measuredPlaceholder, at: 0, insert: "x", web: false), ["x" + measuredPlaceholder])
86+
XCTAssertEqual(accepted(measuredPlaceholder, at: 0, insert: "", web: true), [])
87+
}
88+
89+
func testAnUnchangedFieldIsNeverAcceptedEvenWhenTheTextEqualsTheDocument() {
90+
XCTAssertEqual(accepted("same", at: 0, insert: "same", web: true), ["samesame"])
91+
XCTAssertEqual(accepted("", at: 0, insert: "x", web: true), ["x"])
92+
}
93+
94+
func testInvalidChangesStayNil() {
95+
XCTAssertNil(accepted("😀", at: 1, insert: "x", web: true))
96+
XCTAssertNil(accepted("\n", at: 2, insert: "x", web: true))
97+
}
5498
}
99+
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import XCTest
2+
@testable import UtterMacServices
3+
4+
final class DeliveryShapeDiagnosticTests: XCTestCase {
5+
func testSummaryCountsUnitsPrefixSuffixAndLineFeeds() {
6+
let summary = DeliveryShapeDiagnostic.summary(observed: "ab\ncd", expected: "ab\nXcd", original: "ab\ncd")
7+
XCTAssertEqual(summary, "readable=true observedUnits=5 expectedUnits=6 originalUnits=5 commonPrefix=3 commonSuffix=2 "
8+
+ "observedLineFeeds=1 expectedLineFeeds=1 observedNoBreakSpaces=0 equalsOriginal=true")
9+
}
10+
11+
func testUnreadableValueIsStated() {
12+
XCTAssertEqual(DeliveryShapeDiagnostic.summary(observed: nil, expected: "abc", original: nil),
13+
"readable=false expectedUnits=3 originalUnits=-1")
14+
}
15+
16+
func testNoTextOfAnyInputAppearsInTheSummary() {
17+
let observed = "秘密观察文本ZQXJ\u{00A0}"
18+
let expected = "预期内容WVKP"
19+
let original = "原始草稿MNBV"
20+
let summary = DeliveryShapeDiagnostic.summary(observed: observed, expected: expected, original: original)
21+
for fragment in ["秘密", "ZQXJ", "预期", "WVKP", "原始", "MNBV"] {
22+
XCTAssertFalse(summary.contains(fragment), "summary leaked \(fragment)")
23+
}
24+
let allowed = Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789= -")
25+
XCTAssertTrue(summary.allSatisfy { allowed.contains($0) }, summary)
26+
XCTAssertTrue(summary.contains("observedNoBreakSpaces=1"))
27+
}
28+
29+
func testTheEmptyComposerShapeIsDescribedByItsCounts() {
30+
let summary = DeliveryShapeDiagnostic.summary(observed: "Ask Xxxxxx\n", expected: "你好", original: "Ask Xxxxxx\n")
31+
XCTAssertTrue(summary.contains("observedUnits=11"))
32+
XCTAssertTrue(summary.contains("equalsOriginal=true"))
33+
XCTAssertTrue(summary.contains("commonPrefix=0 commonSuffix=0"))
34+
}
35+
}

‎Tests/UtterMacServicesTests/DeliveryTextObservationTests.swift‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,34 @@ final class DeliveryTextObservationTests: XCTestCase {
2020
let confirmed = await DeliveryTextObservation.confirm("new", read: { nil }, clock: clock)
2121
XCTAssertFalse(confirmed)
2222
}
23+
24+
func testAnyAcceptedValueConfirmsAndOnlyAcceptedValuesDo() async {
25+
let clock = ObservationClock()
26+
let viaSecond = await DeliveryTextObservation.observe(accepting: ["text+placeholder", "text"],
27+
read: { clock.now >= .seconds(2) ? "text" : "placeholder" }, clock: clock)
28+
XCTAssertTrue(viaSecond.confirmed)
29+
XCTAssertEqual(clock.now, .seconds(2))
30+
31+
let unchanged = ObservationClock()
32+
let stays = await DeliveryTextObservation.observe(accepting: ["text+placeholder", "text"],
33+
read: { "placeholder" }, clock: unchanged)
34+
XCTAssertFalse(stays.confirmed)
35+
XCTAssertEqual(stays.lastRead, "placeholder")
36+
XCTAssertEqual(unchanged.now, .seconds(3))
37+
38+
let other = ObservationClock()
39+
let different = await DeliveryTextObservation.observe(accepting: ["text"], read: { "something else" }, clock: other)
40+
XCTAssertFalse(different.confirmed)
41+
XCTAssertEqual(different.lastRead, "something else")
42+
}
43+
44+
func testTheLastReadableValueSurvivesLaterUnreadableOnes() async {
45+
let clock = ObservationClock()
46+
let result = await DeliveryTextObservation.observe(accepting: ["text"],
47+
read: { clock.now < .seconds(1) ? "old" : nil }, clock: clock)
48+
XCTAssertFalse(result.confirmed)
49+
XCTAssertEqual(result.lastRead, "old")
50+
}
2351
}
2452

2553
@MainActor

0 commit comments

Comments
 (0)