Repository navigation
fix(desktop): invalidate leaked run-loop timers and pump the live-scroll test drain to its deadline (#13460) - #13468
Conversation
…oll drain UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing fails order-dependently when it shares a SwiftPM process with certain other suites (reproduced on an unmodified origin/main desktop tree with CI's batch worker-0-2-h1 composition). The detector queues its terminal bounds read with DispatchQueue.main.async; the test drained with one RunLoop.main.run(mode:before:), which returns as soon as any source fires, so a repeating .common-mode timer left behind by an earlier suite ended the drain before the read ran. Pump the run loop until the deadline instead, as ChatTranscriptGestureHarnessTests and AuthRestoreWatchdogTests already do. The existing wall-clock-wait annotation is retained; no new wait is added. Verification: the 38-suite batch that failed on CI (exact composition) now passes 3/3 locally (242 tests, 0 failures); suite alone and the whole file pass; python3 desktop/macos/scripts/check_desktop_test_quality.py OK. Co-Authored-By: Claude Fable 5.1 <[email protected]>
ChatFollowGlide and ChatLiveEdgePinner add repeating .common-mode timers with RunLoop.main.add. The run loop retains those timers independently of the object, so SwiftUI or a test releasing an armed clock left a 60 Hz source that ended later RunLoop.main.run(mode:before:) drains before queued DispatchQueue.main.async work (the UserScrollDetector flake in #13460). Invalidate on deinit, matching ChatOmiMarkFrameView. Failure-Class: none Verification: xcrun swift test --package-path Desktop --filter UserScrollDetectorTests|ChatScrollLiveEdgeTests|ChatPressPromotionPolicyTests passed (UserScrollDetectorTests 6 tests, ChatScrollLiveEdgeTests 14 tests). Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-authored-by: Cursor <[email protected]>
WALService.startRecording schedules repeating chunk and flush timers via Timer.scheduledTimer. Tests in the same process (WALServiceUploadTests calls startRecording without stopRecording in tearDown) released the service while those timers stayed on the main run loop. Invalidate them on deinit so a leftover default-mode source cannot starve later RunLoop.main.run(mode:before:) drains. Failure-Class: none Verification: xcrun swift test --package-path Desktop --filter WALServiceUploadTests|WALServiceOrphanSdCardTests|WifiSyncServiceTests passed (WALServiceUploadTests 25 tests including testRecordingTimersInvalidateOnDeinit). Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-authored-by: Cursor <[email protected]>
UnhandledKeystrokeSilenceTests constructs a real FloatingControlBarWindow (NSHostingView + SwiftUI) and previously only called close(). Clear contentView on teardown so the hosted view tree cannot keep run-loop sources alive after the suite finishes in a batched SwiftPM process. Verification: xcrun swift test --package-path Desktop --filter UnhandledKeystrokeSilenceTests passed (4 tests). Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-authored-by: Cursor <[email protected]>
A repeating run-loop timer is retained by RunLoop.main, not by its owner; an owner released without invalidating leaves a source that breaks later single-shot run-loop drains in the same process (#13460). The guard tests in ChatScrollLiveEdgeTests and WALServiceUploadTests are the prevention artifact. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
2 issues found across 7 files
Confidence score: 3/5
- In
desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift, releasing an owner off the main thread can bypasscancel(), leaving itsRunLoop.maintimer alive and consuming background CPU after the view or session is gone; ensure the retained timer is invalidated regardless of the release thread. - In
desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json, the entry focuses on internal timer ownership rather than the user-visible cleanup outcome; describe that chat scrolling and recording cleanup no longer consume background CPU after closure.
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/MainWindow/Components/ChatScrollBehavior.swift">
<violation number="1" location="desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift:230">
P2: When one of these owners is released off the main thread, the `Thread.isMainThread` guard skips `cancel()`, leaving its `RunLoop.main` timer running after the owner is gone. Invalidate the retained timer through a thread-safe, nonisolated cleanup path or marshal the timer itself to the main actor instead of abandoning it.</violation>
</file>
<file name="desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json">
<violation number="1" location="desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json:2">
P3: The changelog entry describes internal timer ownership instead of the user-visible outcome. State that chat scrolling and recording cleanup no longer consume background CPU after their views or sessions close.
(Based on your team's feedback about user-facing desktop changelog outcomes.)</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| // invalidate here, SwiftUI dropping a transcript (or a test releasing the | ||
| // glide) leaves a 60 Hz `.common` source on `RunLoop.main` that ends later | ||
| // `run(mode:before:)` drains before queued main-async work can run. | ||
| if Thread.isMainThread { |
There was a problem hiding this comment.
P2: When one of these owners is released off the main thread, the Thread.isMainThread guard skips cancel(), leaving its RunLoop.main timer running after the owner is gone. Invalidate the retained timer through a thread-safe, nonisolated cleanup path or marshal the timer itself to the main actor instead of abandoning it.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift, line 230:
<comment>When one of these owners is released off the main thread, the `Thread.isMainThread` guard skips `cancel()`, leaving its `RunLoop.main` timer running after the owner is gone. Invalidate the retained timer through a thread-safe, nonisolated cleanup path or marshal the timer itself to the main actor instead of abandoning it.</comment>
<file context>
@@ -218,6 +222,16 @@ final class ChatFollowGlide {
+ // invalidate here, SwiftUI dropping a transcript (or a test releasing the
+ // glide) leaves a 60 Hz `.common` source on `RunLoop.main` that ends later
+ // `run(mode:before:)` drains before queued main-async work can run.
+ if Thread.isMainThread {
+ MainActor.assumeIsolated { cancel() }
+ }
</file context>
| @@ -0,0 +1,3 @@ | |||
| { | |||
| "change": "Fixed: chat follow/pin scroll timers and recording timers no longer keep running after their owner is gone, removing a small idle CPU wake." | |||
There was a problem hiding this comment.
P3: The changelog entry describes internal timer ownership instead of the user-visible outcome. State that chat scrolling and recording cleanup no longer consume background CPU after their views or sessions close.
(Based on your team's feedback about user-facing desktop changelog outcomes.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/changelog/unreleased/2026-09-10-chat-scroll-timer-invalidation.json, line 2:
<comment>The changelog entry describes internal timer ownership instead of the user-visible outcome. State that chat scrolling and recording cleanup no longer consume background CPU after their views or sessions close.
(Based on your team's feedback about user-facing desktop changelog outcomes.) </comment>
<file context>
@@ -0,0 +1,3 @@
+{
+ "change": "Fixed: chat follow/pin scroll timers and recording timers no longer keep running after their owner is gone, removing a small idle CPU wake."
+}
</file context>
| "change": "Fixed: chat follow/pin scroll timers and recording timers no longer keep running after their owner is gone, removing a small idle CPU wake." | |
| "change": "Fixed chat scrolling and recording cleanup so the app no longer uses background CPU after those views or sessions close." |
) * test(desktop): inherit defaults and timer isolation Reuse unique defaults-domain ownership and XCTest teardown in the auth fixtures repaired by #13260. Both chat repeating timer owners from #13468 now use a shared invalidating token; drive elapsed time and callbacks through a manual scheduler to exercise completion, retargeting, cancel and release. Ratchet existing direct shared-defaults mutations at 292, with narrow local integration reasons, in the existing quality guard and manifest lanes. Verification: make setup; 15 Python checker tests; both named local manifest checks; strict Swift 6 isolated type checks. A temporary SwiftPM fixture using the exact changed timer classes/test methods and defaults support passed six XCTest cases. Removing token deinit invalidation made two release tests fail. Integrated desktop compilation and historical suite sequencing are delegated to the parent task after combining worktrees; no live app was launched. Failure-Class: FC-run-loop-timer-outlives-owner * docs(desktop): keep test isolation guidance within component budget * feat(desktop): require explicit automation effects and read-only dispatch * test(desktop): cover lazy action effects and async defaults ownership * test(desktop): expect mandatory effect descriptions in discovery * test(desktop): make timer lifetime observable through the flow * docs(desktop): explain cold-path automation effects * test: raise stale shared-defaults baseline to main's current debt (this branch adds 0) * fix(desktop): add typed effects to main-side action registrations added after this branch forked * test: probe descriptor safety label tracks main's added remote_write delivery persistence
Summary
Closes #13460.
UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowingpasses alone and fails when batched with CI'sworker-0-2-h1suites on an unmodifiedorigin/maintree. The detector reads its terminal position viaDispatchQueue.main.async; the test drained with a singleRunLoop.main.run(mode:before:), which returns as soon as any leftover.common-mode timer from an earlier suite fires.ChatTranscriptGestureHarnessTestsandAuthRestoreWatchdogTestsalready use) and fixes the leak at its source: the chat follow glide, the live-edge pinner, and the WAL recording timers now invalidate ondeinit, with guard tests that release an armed owner and assert the timer is invalid.Product invariants affected
ChatScrollBehavior.swiftonly gainsdeinittimer invalidation on the follow glide and live-edge pinner. No transcript, session, or agent state is stored or mirrored; the kernel-owned transcript is untouched.ChatScrollLiveEdgeTests.swiftis this invariant's guard test; only the harness drain changes. Scroll ownership, placement, and virtualization behaviour and the guarded assertions are unchanged.Failure-Class
Failure-Class: new
FC-run-loop-timer-outlives-owner, defined in this PR: a repeating timer onRunLoop.mainis retained by the run loop, not its owner, so an owner released without invalidating keeps firing. Guard tests inChatScrollLiveEdgeTestsandWALServiceUploadTestsare the prevention artifact.What changed
Desktop/Tests/ChatScrollLiveEdgeTests.swift—drainMainQueue()pumpsRunLoop.mainuntil its 50 ms deadline (same commit as carried on feat(desktop): opt-in on-device embeddings with FTS hybrid retrieval; backend keyword fallback for screen search #13456); new DEBUG-guarded tests prove a releasedChatFollowGlide/ChatLiveEdgePinnerleaves no live timer.Desktop/Sources/MainWindow/Components/ChatScrollBehavior.swift—ChatFollowGlideandChatLiveEdgePinnerinvalidate their 60 Hz.commontimer indeinit(main-threadassumeIsolated, same shape asChatOmiMarkFrameView). Behaviour while alive is unchanged.Desktop/Sources/WAL/WALService.swift— chunk/flush timers invalidate indeinit;WALServiceUploadTestsgainstestRecordingTimersInvalidateOnDeinit.Desktop/Tests/UnhandledKeystrokeSilenceTests.swift— drops the panel's hosting view before closing so the hosted SwiftUI tree leaves no run-loop sources behind..github/failure-classes/FC-run-loop-timer-outlives-owner.json— the class definition.Root cause found in CI's
worker-0-2-h1batch: earlier suites left.common/default-mode repeating timers onRunLoop.main(armed glide/pinner released withoutcancel(),WALServiceinstances released while recording, a real floating-bar panel closed with its hosting view attached). The detector'sDispatchQueue.main.asyncread then lost the race with a singlerun(mode:before:)drain.Verification
From
desktop/macoson Xcode 26.6 / Swift 6.3.3, CI's exact batch (38 suitesSuggestionCommitmentGuardTests…WorkContextCheapPathTests, one SwiftPM process):022432d0f8: 280 tests, 1 failure (UserScrollDetectorTests.testCompletedLiveScrollAtBottomCanResumeFollowing,settledAtBottom0 ≠ 1) — reproduces the issue.UserScrollDetectorTests(6),ChatScrollLiveEdgeTests(14),UnhandledKeystrokeSilenceTests(4),WALServiceUploadTests(25),WALServiceOrphanSdCardTests,WifiSyncServiceTests— all green.python3 desktop/macos/scripts/check_desktop_test_quality.py— OK.Known limit: the
deinitinvalidation only runs when the owner is released on the main thread (same tradeoff asChatOmiMarkFrameView). Other repeating-timer owners (DesktopUsageDailyReporter,MeetingDetector,RecordingTimer,ResourceMonitor, …) have the same shape and are not touched here.🤖 Generated with Claude Code