Skip to content

Commit 9de8039

Browse files
committed
Merge remote-tracking branch 'origin/main' into cursor/compat-paste-mode
2 parents 2b8ce3f + f5f07bb commit 9de8039

9 files changed

Lines changed: 262 additions & 16 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
@@ -90,6 +90,9 @@ final class NativeOutputBackend {
9090
}
9191
}
9292
log.info(result.logSummary)
93+
if result.disposition == .uncertain, let shape = destination.unconfirmedSummary {
94+
log.info("Delivery unconfirmed shape: \(shape)")
95+
}
9396
return result
9497
}
9598
}

‎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
Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,82 @@
11
# Verification: Confirm a paste into an empty-looking web editor whose placeholder disappears
22

3-
**Status:** draft
4-
**Approved-by:** —
5-
**Approved-date:** —
3+
**Status:** approved
4+
**Approved-by:** Owner, chat answer "批准" (2026-11-04 11:17 UTC+8), accepting the residual risk of the waived hardware run; merge of #144 and the v0.0.63 tag authorized
5+
**Approved-date:** 2026-11-04
66
**Upstream:** [plan.md](plan.md)
77

8-
Not started. Batch 0 (read-only measurement) is recorded in the spec and in `evidence/batch0-shapes.txt`; nothing has
9-
been implemented, so nothing here shows the fix works yet.
8+
The automated half is done. **The hardware matrix was not run**: the owner chose not to test and delegated the
9+
judgement (see "Hardware verification"). This file proves the rule against the measured shapes, not a live ChatGPT
10+
dictation. That is a stated, owner-accepted residual risk.
11+
12+
## What was implemented (plan items A–E)
13+
14+
| Item | Result |
15+
|---|---|
16+
| A. `DeliveryExpectation.acceptedDocuments` | Done. The primary expected document is kept; for an empty-looking web content editor at range `(0, 0)` with a non-empty replacement, the replacement alone is a second accepted value. The original document is filtered out of the set, so an unchanged field is never accepted. The lone-`"\n"` rule is unchanged. |
17+
| B. `DeliveryTextObservation` | Done. `observe(accepting:)` takes the set, polls as before (25 ms, 3 s) and returns the last readable value; `confirm` is a thin wrapper with the old signature. |
18+
| C. `NativeDeliveryTarget` | Done. `confirm` and `insertionAnchor` use the accepted set; no new write path. |
19+
| D. Counts-only diagnostic (D5) | Done. On a timeout `DeliveryShapeDiagnostic.summary` produces numbers and flags only, logged once as `Delivery unconfirmed shape: …` when the receipt is `uncertain`. |
20+
| E. Mutation checks | Done, see below. |
21+
22+
## Automated evidence
23+
24+
- `swift test` on this branch: 631 tests, 26 skipped, 0 failures (second full run).
25+
- First full run had 1 failure in `VoiceEditingNativeE2EPresentationTests.testRealSession…NativePointerRestores…`, a
26+
real-window test that clicks with a real pointer and asserts the frontmost application is unchanged at the end. At
27+
the end of that run another app (Feishu) was frontmost instead of the one that started it. The same test passed on
28+
the base commit without these changes, then passed twice on this branch, and the full suite then passed. This is
29+
recorded as environmental interference with a real-pointer test, not proven as such; the cause was not isolated.
30+
- `bash scripts/ci-basic-checks.sh`: passed. `bash scripts/sdlc-checks.sh`: passed.
31+
- Mutation checks, each run with `swift test --filter UtterMacServicesTests.DeliveryExpectationTests` and restored
32+
afterwards (the restored suite passes):
33+
34+
| Mutation | Suite result | Failing tests point at |
35+
|---|---|---|
36+
| Never add the replacement-only candidate | failed | the measured empty-composer shape and the draft-with-line-feed case |
37+
| Drop the `(0, 0)` guard | failed | the "no extra candidate away from the start" cases |
38+
| Drop the "never accept the original" filter | failed | the unchanged-field case and the delete case (an empty replacement would otherwise accept the original) |
39+
| Drop the web-content-editor guard | failed | the native-editor case |
40+
41+
## Not covered by unit tests
42+
43+
- The AX-bound wiring in `NativeDeliveryTarget` (reading the live field, anchoring a restore) has no unit test: it
44+
needs a real focused element. The pure rule, the observation loop and the diagnostic are covered; the wiring is
45+
covered only by the hardware matrix below.
46+
- Multi-paragraph text in ChatGPT, ChatGPT in a browser tab, and the second cause of `uncertain` (T3 with text before
47+
the caret). The diagnostic is there to measure the latter; no fix is claimed.
48+
49+
## Hardware verification (spec Batch 3) — NOT RUN, owner waived
50+
51+
The spec asked for a verifier who is not the implementer, on a release-style build of this branch, with the installed
52+
Utter 0.0.62 replaced for the run.
53+
54+
| Case | Runs | Result |
55+
|---|---|---|
56+
| ChatGPT, empty composer | 10 | not run |
57+
| ChatGPT, caret at end of existing text | 10 | not run |
58+
| ChatGPT, caret in the middle | 5 | not run |
59+
| Cursor, T3, Dia, TextEdit unchanged | 1 each | not run |
60+
| Forced non-landing case still reports `uncertain` | 1 | not run |
61+
62+
Verifier: the implementing assistant. **Waivers:** the owner waived an independent verifier and allowed the installed
63+
Utter 0.0.62 to be replaced for the run, with the owner re-granting permissions afterwards (chat answer "批准",
64+
2026-11-03 23:28 UTC+8). Later the owner answered "你凭根据感觉来搞吧,不要我实测了" (2026-11-04 02:44 UTC+8): no
65+
owner testing, judgement delegated. The verification stage itself still needs the owner's approval.
66+
67+
### Judgement in place of the run (assistant's, not evidence)
68+
69+
- The accepted value for the empty composer is the exact shape recorded from the owner's ChatGPT in
70+
`evidence/batch0-shapes.txt` (12 units before, the replacement alone after); the rule is pinned to those numbers by
71+
tests and four mutation kills, and it never accepts the original value, so an unchanged field still ends `uncertain`.
72+
- Anything the rule does not recognise falls back to the old behaviour (`uncertain`), so a wrong guess costs a
73+
notice, not a wrongly reported insertion.
74+
- Combined with the compatibility change (no merge conflicts), every test bundle except `OpenTypeTests` passes locally
75+
and an ad-hoc `0.0.63` app builds; this branch's CI passed on its own head.
76+
- After release, the first ChatGPT dictation into an empty composer settles it: `inserted` instead of `uncertain`. If
77+
`uncertain` still appears, the new `Delivery unconfirmed shape:` log line records the numbers to fix it with.
78+
79+
## Rollback
80+
81+
Revert the change commits. The previous behavior is the unconfirmed notice on empty ChatGPT composers. The hidden
82+
switch `deliveryWebEditorPasteDisabled` also disables the new rule.

0 commit comments

Comments
 (0)