Skip to content

fix(desktop): defer native PTT evidence attach until its journal row exists - #13235

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix/ptt-native-evidence-attach-admission
Sep 9, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix/ptt-native-evidence-attach-admission

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Fixes #13205. Native PTT OCR could finish before the streaming journal inserted the user row; resolveNativeTurnEvidence then synthesized a stable turn ID and ran an UPDATE-only attach, which failed with a missing-row RPC, logged journal_evidence_append_failed, and marked the ledger persistenceFailed. Direct attach now runs only when journalUserTurnID is already bound; otherwise the resolved evidence stays on the ledger for the projection constructor / post-admission persist / producing-row bind. If streaming starts while the deferred attach is in flight, the write joins the ordered tail. Accepted spawn_agent receipts now bind the producing user row immediately, because that path creates the kernel row without the streaming constructor.

Product invariants affected

  • INV-CHAT-1

How it was verified

Swift unit tests only. Installed binaries were not rebuilt or live-tested (restored authenticated QA sessions took precedence). Pre-fix live evidence is in issue #13205.

cd desktop/macos && xcrun swift test --package-path Desktop --filter 'RealtimeTurnEvidenceTests|RealtimeHubBargeInContinuityTests'

93 tests, 0 failures (RealtimeTurnEvidenceTests 26/26 including 3 new admission tests; RealtimeHubBargeInContinuityTests 67/67).

cd desktop/macos && ./scripts/agent-logic-harness.sh --swift-only

Passed (focused Swift lifecycle/state tests, 33s).

python3 desktop/macos/scripts/check_desktop_test_quality.py

OK.

Tests

RealtimeTurnEvidenceTests now drives resolveNativeTurnEvidence through an injectable attach seam:

  1. OCR before any journal row / streaming ledger → no attach, ledger keeps evidence with persistenceFailed == false, later persistNativeEvidenceAfterJournalAdmission carries it.
  2. OCR after journalUserTurnID is bound and streaming has finalized → direct attach exactly once.
  3. OCR while the streaming ledger contains the key → attach is enqueued behind the record task.

Failure class (fixes)

Failure-Class: none

Scoped cleanups (optional)

Caller audit of voice:<uuid> user-row creation:

  • Streaming constructor includes ledger evidence and attachJournalUserTurn.
  • Non-streaming recordExchange includes evidence, binds the row, then persistNativeEvidenceAfterJournalAdmission.
  • Dictation / typed fallback call bindNativeTurnEvidenceToProducingRow.
  • Spawn-accepted receipts created the kernel row without any of those; this PR adds bindNativeTurnEvidenceToProducingRow there. persistNativeEvidenceAfterJournalAdmission also binds journalUserTurnID while OCR is still pending so a later resolve can attach.

Line-Count-Exception: desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+SessionDelegate.swift | 1588 -> 1592 | Bind native PTT evidence to the spawn-admitted user row.

Review in cubic

…exists

OCR can finish before the streaming journal inserts the user row. The
direct UPDATE then failed with a missing-row RPC and dropped native
evidence (#13205).

Co-authored-by: Cursor <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 issues found across 6 files

Confidence score: 2/5

  • RealtimeHubController+PushToTalk.swift can issue the deferred attach UPDATE before the streaming record because the direct UPDATE is not included in the streaming tail, creating an ordering race; serialize the attach through the streaming ledger so it runs after the record.
  • RealtimeHubController+PushToTalk.swift may treat a populated journalUserTurnID as evidence that a row exists even when streaming admission was rejected, allowing an UPDATE before fallback admission creates the record; only permit the update after confirmed record creation.
  • RealtimeTurnEvidenceTests.swift mutates process-global UserDefaults.standard and restores it with defer, so concurrent tests or production paths using .authUserId could observe the temporary owner; isolate the test setting from global defaults.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+PushToTalk.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+PushToTalk.swift:81">
P2: When streaming admission is rejected, `journalUserTurnID` may already be populated even though its record task never created a row. This guard then allows a direct evidence UPDATE before the fallback admission runs. Track record acceptance separately and bind the producing ID only after admission succeeds, or keep the evidence deferred until that result is known.</violation>

<violation number="2" location="desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+PushToTalk.swift:91">
P1: When streaming starts after the second `contains` check, this direct UPDATE is still in flight and is not part of the streaming tail. Serialize the deferred attach with the streaming ledger so it runs after the record task, rather than sampling the ledger only before the await.</violation>
</file>

<file name="desktop/macos/Desktop/Tests/RealtimeTurnEvidenceTests.swift">

<violation number="1" location="desktop/macos/Desktop/Tests/RealtimeTurnEvidenceTests.swift:653">
P3: This helper mutates the process-global `UserDefaults.standard` `.authUserId` key to install a test owner, restoring it only via `defer`. Because `currentOwnerId()` and many production paths (`AuthService`, `AuthOwnerTransition`) read that same shared key, the synthetic owner leaks to any concurrently running test in the same process during the async `body`, and stays persisted if the process dies mid-test. Use the dedicated test hook `RuntimeOwnerIdentity.applyAutomationOwnerOverride` instead, which the codebase already documents for injecting a synthetic owner without touching real auth state.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

self.enqueueNativeEvidenceUpdate(continuityKey: continuityKey, evidence: current)
return
}
let accepted = await self.attachResolvedNativeUserEvidence(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: When streaming starts after the second contains check, this direct UPDATE is still in flight and is not part of the streaming tail. Serialize the deferred attach with the streaming ledger so it runs after the record task, rather than sampling the ledger only before the await.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+PushToTalk.swift, line 91:

<comment>When streaming starts after the second `contains` check, this direct UPDATE is still in flight and is not part of the streaming tail. Serialize the deferred attach with the streaming ledger so it runs after the record task, rather than sampling the ledger only before the await.</comment>

<file context>
@@ -67,20 +74,21 @@ extension RealtimeHubController {
+        self.enqueueNativeEvidenceUpdate(continuityKey: continuityKey, evidence: current)
+        return
+      }
+      let accepted = await self.attachResolvedNativeUserEvidence(
         surface: surface,
         ownerID: ownerID,
</file context>

enqueueNativeEvidenceUpdate(continuityKey: continuityKey, evidence: evidence)
return
}
guard let surface = entry.surface, let userTurnID = entry.journalUserTurnID else { return }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: When streaming admission is rejected, journalUserTurnID may already be populated even though its record task never created a row. This guard then allows a direct evidence UPDATE before the fallback admission runs. Track record acceptance separately and bind the producing ID only after admission succeeds, or keep the evidence deferred until that result is known.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/FloatingControlBar/RealtimeHubController+PushToTalk.swift, line 81:

<comment>When streaming admission is rejected, `journalUserTurnID` may already be populated even though its record task never created a row. This guard then allows a direct evidence UPDATE before the fallback admission runs. Track record acceptance separately and bind the producing ID only after admission succeeds, or keep the evidence deferred until that result is known.</comment>

<file context>
@@ -67,20 +74,21 @@ extension RealtimeHubController {
       enqueueNativeEvidenceUpdate(continuityKey: continuityKey, evidence: evidence)
       return
     }
+    guard let surface = entry.surface, let userTurnID = entry.journalUserTurnID else { return }
     Task { @MainActor [weak self] in
       guard let self,
</file context>

let defaults = UserDefaults.standard
let previous = defaults.string(forKey: .authUserId)
let ownerID = "evidence-attach-\(UUID().uuidString.lowercased())"
defaults.set(ownerID, forKey: .authUserId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This helper mutates the process-global UserDefaults.standard .authUserId key to install a test owner, restoring it only via defer. Because currentOwnerId() and many production paths (AuthService, AuthOwnerTransition) read that same shared key, the synthetic owner leaks to any concurrently running test in the same process during the async body, and stays persisted if the process dies mid-test. Use the dedicated test hook RuntimeOwnerIdentity.applyAutomationOwnerOverride instead, which the codebase already documents for injecting a synthetic owner without touching real auth state.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Tests/RealtimeTurnEvidenceTests.swift, line 653:

<comment>This helper mutates the process-global `UserDefaults.standard` `.authUserId` key to install a test owner, restoring it only via `defer`. Because `currentOwnerId()` and many production paths (`AuthService`, `AuthOwnerTransition`) read that same shared key, the synthetic owner leaks to any concurrently running test in the same process during the async `body`, and stays persisted if the process dies mid-test. Use the dedicated test hook `RuntimeOwnerIdentity.applyAutomationOwnerOverride` instead, which the codebase already documents for injecting a synthetic owner without touching real auth state.</comment>

<file context>
@@ -511,6 +511,157 @@ final class RealtimeTurnEvidenceTests: XCTestCase {
+  let defaults = UserDefaults.standard
+  let previous = defaults.string(forKey: .authUserId)
+  let ownerID = "evidence-attach-\(UUID().uuidString.lowercased())"
+  defaults.set(ownerID, forKey: .authUserId)
+  defer {
+    if let previous {
</file context>

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Correction on the KernelTurnRecordedProjectionTests.testAnOwnerTransitionDissolvesAnOutstandingRevocation failure in Desktop Swift Static & Test Contracts: it is not a generic main flake. The test (from #12664) runs its owner transition against UserDefaults.standard, and the fence only cycles the revocation when the planned owner differs from the persisted one. The standard xctest domain is shared across parallel suite processes on the runner, so when a concurrent suite has auth_userId set there the transition is a same-owner no-op and the assertion fails. Reproduced locally by seeding that key; unrelated desktop PRs pass or fail depending on batch scheduling.

Test-only fix: #13260. Nothing in this PR touches owner or defaults state; once #13260 lands, a rebase or rerun of this job should be green.

@Git-on-my-level
Git-on-my-level merged commit 970b97f into main Sep 9, 2026
33 of 35 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/ptt-native-evidence-attach-admission branch September 9, 2026 07:06
Git-on-my-level added a commit that referenced this pull request Sep 10, 2026
…-mode test build compiles

CI's 'Test UserNotifications callback regression in release mode' step runs
swift test -c release, which compiles the whole test target. Three tests here
assign RealtimeTurnEvidenceLedger.testingAttachRealtimeUserEvidence, a seam
declared under #if DEBUG (since #13235), so the release build fails on any PR
that touches desktop tests. Main stayed green only because the step is skipped
on pushes that do not touch Desktop/Tests. Wrap the three tests in #if DEBUG to
match the seam. Tracked as #13458.

Verification: xcrun swift build --build-tests --package-path desktop/macos/Desktop
(Build complete); release-mode step run locally before push.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Sep 11, 2026
…-mode test build compiles (#13467)

CI's 'Test UserNotifications callback regression in release mode' step runs
swift test -c release, which compiles the whole test target. Three tests here
assign RealtimeTurnEvidenceLedger.testingAttachRealtimeUserEvidence, a seam
declared under #if DEBUG (since #13235), so the release build fails on any PR
that touches desktop tests. Main stayed green only because the step is skipped
on pushes that do not touch Desktop/Tests. Wrap the three tests in #if DEBUG to
match the seam. Tracked as #13458.

Audit of Desktop/Sources #if DEBUG seams vs Desktop/Tests: 75 DEBUG-only
regions in 32 source files. Distinctive DEBUG-only types and testing*/
*ForTesting APIs are already #if DEBUG-guarded in Tests (or are string-literal
source-inspection, which still compiles). No further unguarded member accesses.

Verification (cwd desktop/macos, Xcode 26.6 / Swift 6.3.3):
  xcrun swift build --build-tests --package-path Desktop
    Build complete! (268.91s)
  xcrun swift test --package-path Desktop --filter RealtimeTurnEvidenceTests/
    Executed 26 tests, with 0 failures (including the three DEBUG-guarded
    attach tests: testOCRBeforeJournalRowDoesNotAttachAndLaterAdmissionCarriesEvidence,
    testOCRAfterBoundUserRowAndFinalizedStreamingAttachesOnce,
    testOCRWhileStreamingLedgerContainsKeyWaitsForRecordTask)
  xcrun swift test -c release --package-path Desktop --filter UserNotificationCallbackBridgeTests/
    Build complete! (491.09s)
    Executed 11 tests, with 0 failures (0 unexpected)

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Successful hub voice turn can fail to retain native evidence in its journal

1 participant