@@ -97,6 +97,18 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
9797 /// `reconcileChargers` (which runs both from the charger settle task and
9898 /// directly from tests).
9999 private let currentChargerSources : ( ) -> [ PowerSource ]
100+ /// Live IDs of the downstream Thunderbolt fabric switches (depth > 0;
101+ /// the Mac's own host-root switches are depth 0 and always present, so
102+ /// they're excluded before this closure is even called). Read fresh at
103+ /// settle time, same discipline as `currentDevices` /
104+ /// `currentChargerSources`. A bare `Set<Int64>`, not
105+ /// `WhatCableCore.IOThunderboltSwitch`, on purpose: the sequencer only
106+ /// ever needs identity (did the downstream set change), never any other
107+ /// field on the switch, so the seam carries the smallest type that says
108+ /// that, rather than a Core model this type has no other use for. The
109+ /// shim maps it from `WatcherHub.shared.tbWatcher.switches.filter {
110+ /// $0.depth > 0 }.map(\.id)`.
111+ private let currentDownstreamTBSwitchIDs : ( ) -> Set < Int64 >
100112 /// Gate read AFTER baseline bookkeeping in `diffDevices` /
101113 /// `reconcileChargers`, exactly where `AppSettings.shared.notifyOnChanges`
102114 /// was read in the original, so state stays primed even when
@@ -120,6 +132,13 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
120132 // baseline.
121133 var knownDevices : [ UInt64 : USBDeviceChangeGrouper . Snapshot ] = [ : ]
122134 var knownChargerLabels : [ String : String ] = [ : ]
135+ /// Baseline for `NotificationDecision.thunderboltInvolved(previous:current:)`.
136+ /// Updated in exactly the same two places `knownDevices` is (primed in
137+ /// `primeBaseline`, refreshed in `diffDevices` unconditionally, BEFORE
138+ /// the `notifyOnChanges` gate), so a user who has notifications off and
139+ /// later turns them on doesn't see a stale baseline manufacture a false
140+ /// "Thunderbolt involved" on the next diff.
141+ var knownTBSwitchIDs : Set < Int64 > = [ ]
123142 var didPrimeBaseline = false
124143
125144 private var chargerSettleTask : Task < Void , Never > ?
@@ -142,6 +161,19 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
142161 /// already waiting means a fresh device episode is starting, so the
143162 /// waiting one is superseded, same as `deviceSettleTask` itself.
144163 private var deferredDeviceDiffDevices : [ USBDevice ] ?
164+ /// The downstream TB switch-ID set captured ALONGSIDE `deferredDeviceDiffDevices`,
165+ /// at the same settle-time moment, not re-read when the diff eventually
166+ /// lands. Landing can be delayed up to `deferredDeviceDiffDeadlineWindow`
167+ /// (3.5s in production) after settle time; sampling
168+ /// `currentDownstreamTBSwitchIDs()` at landing instead of settle would
169+ /// let an UNRELATED TB switch change during that window mislabel a
170+ /// batch of plain USB devices as Thunderbolt (or the reverse: a real
171+ /// TB event settling with the batch, then reverting before landing,
172+ /// would wrongly read as "no Thunderbolt involved"). Set together with
173+ /// `deferredDeviceDiffDevices` at every park site (`deferDeviceDiff`,
174+ /// `parkAndDelayDevicePost`), cleared together at every consuming site
175+ /// (`landDeferredDeviceDiffNow`, `supersedeAnyParkedDiff`).
176+ private var deferredDeviceDiffTBSwitchIDs : Set < Int64 > ?
145177 /// The ABSOLUTE, NON-RESETTING backstop for a parked diff. Started ONCE,
146178 /// at park time (`scheduleAbsoluteDeadline`, called from `deferDeviceDiff`
147179 /// and `parkAndDelayDevicePost`), and never touched again except by an
@@ -384,6 +416,7 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
384416 clock : ClockType ,
385417 currentDevices : @escaping ( ) -> [ USBDevice ] ,
386418 currentChargerSources : @escaping ( ) -> [ PowerSource ] ,
419+ currentDownstreamTBSwitchIDs : @escaping ( ) -> Set < Int64 > = { [ ] } ,
387420 notifyOnChanges : @escaping ( ) -> Bool ,
388421 post : @escaping ( NotificationCategory , NotificationContent ) -> Void ,
389422 log : @escaping ( String ) -> Void = { _ in } ,
@@ -394,6 +427,7 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
394427 self . clock = clock
395428 self . currentDevices = currentDevices
396429 self . currentChargerSources = currentChargerSources
430+ self . currentDownstreamTBSwitchIDs = currentDownstreamTBSwitchIDs
397431 self . notifyOnChanges = notifyOnChanges
398432 self . post = post
399433 self . log = log
@@ -425,6 +459,7 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
425459 // baseline and the diff use the same key space (else every connected
426460 // charger would fire a spurious "connected" on the first poll).
427461 knownChargerLabels = chargerLabels ( for : chargerSources )
462+ knownTBSwitchIDs = currentDownstreamTBSwitchIDs ( )
428463 didPrimeBaseline = true
429464 }
430465
@@ -491,6 +526,11 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
491526 deferredDeviceDiffToken += 1
492527 let token = deferredDeviceDiffToken
493528 deferredDeviceDiffDevices = devices
529+ // Sampled here, at park time (this function runs synchronously
530+ // right after `scheduleDeviceDiff` reads `currentDevices()`), not
531+ // when the diff eventually lands. See `deferredDeviceDiffTBSwitchIDs`'s
532+ // doc comment for why landing-time sampling is wrong.
533+ deferredDeviceDiffTBSwitchIDs = currentDownstreamTBSwitchIDs ( )
494534
495535 deferredDeviceDiffPresentationGapTask ? . cancel ( )
496536 deferredDeviceDiffPresentationGapGeneration += 1
@@ -691,15 +731,24 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
691731 /// leaving the old parked one to land later against an already-mutated
692732 /// `knownDevices` baseline, producing a wrong diff for it.
693733 func runNowOrDelayForRecentChargerPost ( _ devices : [ USBDevice ] ) {
734+ // Sampled once, here, regardless of which branch below runs: this
735+ // call site IS settle time (see `deferredDeviceDiffTBSwitchIDs`'s
736+ // doc comment). The `delay == 0` branch's landing coincides with
737+ // settle time anyway, so sampling here changes nothing for it; the
738+ // `delay > 0` branch is the one this actually fixes, by carrying
739+ // the same settle-time snapshot through the park instead of
740+ // re-reading the closure when `parkAndDelayDevicePost`'s gap task
741+ // eventually lands it.
742+ let tbSwitchIDs = currentDownstreamTBSwitchIDs ( )
694743 let delay = NotificationDecision . devicePostDelay (
695744 elapsedSinceLastChargerPost : elapsedSinceLastChargerPost ( ) ,
696745 presentationGap : deferredDeviceDiffPresentationGapWindow
697746 )
698747 if delay > . zero {
699- parkAndDelayDevicePost ( devices , delay : delay )
748+ parkAndDelayDevicePost ( devices , tbSwitchIDs : tbSwitchIDs , delay : delay )
700749 } else {
701750 supersedeAnyParkedDiff ( )
702- diffDevices ( devices )
751+ diffDevices ( devices , tbSwitchIDs : tbSwitchIDs )
703752 }
704753 }
705754
@@ -710,10 +759,11 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
710759 /// `landDeferredDeviceDiff` doesn't care HOW a diff got parked before
711760 /// re-scheduling its gap), then schedules the gap-guarded landing after
712761 /// `delay`.
713- private func parkAndDelayDevicePost ( _ devices : [ USBDevice ] , delay : Duration ) {
762+ private func parkAndDelayDevicePost ( _ devices : [ USBDevice ] , tbSwitchIDs : Set < Int64 > , delay : Duration ) {
714763 deferredDeviceDiffToken += 1
715764 let token = deferredDeviceDiffToken
716765 deferredDeviceDiffDevices = devices
766+ deferredDeviceDiffTBSwitchIDs = tbSwitchIDs
717767 scheduleAbsoluteDeadline ( token : token )
718768 scheduleGapLanding ( token : token , delay : delay )
719769 }
@@ -732,6 +782,7 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
732782 private func supersedeAnyParkedDiff ( ) {
733783 deferredDeviceDiffToken += 1
734784 deferredDeviceDiffDevices = nil
785+ deferredDeviceDiffTBSwitchIDs = nil
735786 deferredDeviceDiffDeadlineTask ? . cancel ( )
736787 deferredDeviceDiffPresentationGapTask ? . cancel ( )
737788 deferredDeviceDiffPresentationGapGeneration += 1
@@ -746,22 +797,34 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
746797 /// is the guard that keeps only the first of those to actually arrive
747798 /// from doing anything; see the interleaving walk-through above.
748799 private func landDeferredDeviceDiffNow ( token : Int ) {
800+ // `deferredDeviceDiffTBSwitchIDs` is always set alongside
801+ // `deferredDeviceDiffDevices` at every park site (`deferDeviceDiff`,
802+ // `parkAndDelayDevicePost`), so it is bound in the same guard as the
803+ // devices rather than falling back to a landing-time
804+ // `currentDownstreamTBSwitchIDs()` read: that fallback would silently
805+ // reopen the exact settle-time-vs-landing-time bug this snapshot
806+ // exists to close if the invariant ever regressed. An absent
807+ // snapshot here means there was never a valid parked diff to land,
808+ // same as an absent `deferredDeviceDiffDevices`, so it backs out the
809+ // same way.
749810 guard let devices = deferredDeviceDiffDevices ,
811+ let tbSwitchIDs = deferredDeviceDiffTBSwitchIDs ,
750812 NotificationDecision . shouldLandDeferredDiff ( token : token , liveToken : deferredDeviceDiffToken )
751813 else { return }
752814 deferredDeviceDiffToken += 1
753815 deferredDeviceDiffDevices = nil
816+ deferredDeviceDiffTBSwitchIDs = nil
754817 deferredDeviceDiffDeadlineTask ? . cancel ( )
755818 deferredDeviceDiffPresentationGapTask ? . cancel ( )
756819 deferredDeviceDiffPresentationGapGeneration += 1
757820 // Defensive, not load-bearing on the deadline/immediate paths (which
758821 // never set this true): once ANY path actually lands the diff, no
759822 // gap should be treated as still pending for it.
760823 isPresentationGapPending = false
761- diffDevices ( devices )
824+ diffDevices ( devices , tbSwitchIDs : tbSwitchIDs )
762825 }
763826
764- private func diffDevices ( _ current : [ USBDevice ] ) {
827+ private func diffDevices ( _ current : [ USBDevice ] , tbSwitchIDs : Set < Int64 > ) {
765828 guard didPrimeBaseline else { return }
766829
767830 let previousSnapshots = Array ( knownDevices . values )
@@ -771,6 +834,22 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
771834 uniquingKeysWith : { first , _ in first }
772835 )
773836
837+ // Baseline discipline: refreshed unconditionally, in lockstep with
838+ // knownDevices above, BEFORE the notifyOnChanges gate below, so a
839+ // user who has notifications off during a TB plug/unplug doesn't
840+ // see a stale baseline manufacture a false "Thunderbolt involved" on
841+ // the first diff after turning notifications back on. `tbSwitchIDs`
842+ // is the caller's SETTLE-TIME snapshot (see
843+ // `deferredDeviceDiffTBSwitchIDs`'s doc comment), not re-read here:
844+ // re-reading `currentDownstreamTBSwitchIDs()` at landing time would
845+ // reopen the exact bug that snapshot exists to close.
846+ let previousTBSwitchIDs = knownTBSwitchIDs
847+ knownTBSwitchIDs = tbSwitchIDs
848+ let thunderboltInvolved = NotificationDecision . thunderboltInvolved (
849+ previous : previousTBSwitchIDs ,
850+ current : tbSwitchIDs
851+ )
852+
774853 guard notifyOnChanges ( ) else { return }
775854
776855 let ( addedGroups , removedGroups ) = USBDeviceChangeGrouper . diff (
@@ -790,7 +869,7 @@ public final class DeviceDiffSequencer<ClockType: Clock> where ClockType.Duratio
790869 // the same model report the same product name, so name matching
791870 // could pick the wrong one.
792871 let currentByID = Dictionary ( current . map { ( $0 . id , $0 ) } , uniquingKeysWith : { first , _ in first } )
793- let contents = NotificationDecision . deviceNotificationContents ( removedGroups : removedGroups , addedGroups : addedGroups ) { rootID in
872+ let contents = NotificationDecision . deviceNotificationContents ( removedGroups : removedGroups , addedGroups : addedGroups , thunderboltInvolved : thunderboltInvolved ) { rootID in
794873 currentByID [ rootID ] . map { " \( $0 . speedLabel ) \( $0 . vendorName . map { " · \( $0 ) " } ?? " " ) " }
795874 }
796875 for content in contents {
0 commit comments