Skip to content

Commit ea7841c

Browse files
author
Mirror Bot
committed
Mirror from private (98a1b82c)
1 parent f6b2cf1 commit ea7841c

25 files changed

Lines changed: 627 additions & 19 deletions

‎Sources/WhatCable/Services/NotificationManager.swift‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ final class NotificationManager {
5151
clock: ContinuousClock(),
5252
currentDevices: { WatcherHub.shared.deviceWatcher.devices },
5353
currentChargerSources: { WatcherHub.shared.powerWatcher.sources },
54+
currentDownstreamTBSwitchIDs: {
55+
Set(WatcherHub.shared.tbWatcher.switches.filter { $0.depth > 0 }.map(\.id))
56+
},
5457
notifyOnChanges: { AppSettings.shared.notifyOnChanges },
5558
// Not a `[weak self]` capture: `self` isn't fully initialized
5659
// yet at this point in `init` (this closure is itself part of

‎Sources/WhatCableNotifications/DeviceDiffSequencer.swift‎

Lines changed: 85 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -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 {

‎Sources/WhatCableNotifications/NotificationDecision.swift‎

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,20 @@ public enum NotificationDecision {
4545
chargerSettlePending ? .deferUntilChargerReconcile : .runNow
4646
}
4747

48+
/// Whether a Thunderbolt device was involved in this settled batch: a
49+
/// downstream Thunderbolt fabric switch (depth > 0, so not one of the
50+
/// Mac's own host-root switches, which are always present) appeared or
51+
/// disappeared alongside the USB diff. A non-empty symmetric difference
52+
/// between the baseline and current sets of switch IDs covers both
53+
/// directions (appear, disappear) and also the case where one appeared
54+
/// AND a different one disappeared within the same settle window: any
55+
/// change to the downstream set counts, not just a net change in count.
56+
/// Pure and separate from `DeviceDiffSequencer` so the rule is
57+
/// unit-testable without `WatcherHub` or a real Thunderbolt device.
58+
public static func thunderboltInvolved(previous: Set<Int64>, current: Set<Int64>) -> Bool {
59+
previous != current
60+
}
61+
4862
/// Whether landing a parked device diff, on the reconcile-completion
4963
/// path specifically, should wait out a deliberate presentation gap
5064
/// first or run immediately. Pure rule extracted so the decision is
@@ -122,15 +136,16 @@ public enum NotificationDecision {
122136
public static func deviceNotificationContents(
123137
removedGroups: [USBDeviceChangeGrouper.ChangeGroup],
124138
addedGroups: [USBDeviceChangeGrouper.ChangeGroup],
139+
thunderboltInvolved: Bool = false,
125140
singleDeviceBody: (UInt64) -> String?
126141
) -> [NotificationContent] {
127142
if let removed = removedGroups.first, removedGroups.count == 1,
128143
let added = addedGroups.first, addedGroups.count == 1,
129144
isReconnectPair(removed: removed, added: added) {
130145
return [reconnectedNotificationContent(for: added, singleDeviceBody: singleDeviceBody)]
131146
}
132-
return removedNotificationContents(groups: removedGroups)
133-
+ addedNotificationContents(groups: addedGroups, singleDeviceBody: singleDeviceBody)
147+
return removedNotificationContents(groups: removedGroups, thunderboltInvolved: thunderboltInvolved)
148+
+ addedNotificationContents(groups: addedGroups, thunderboltInvolved: thunderboltInvolved, singleDeviceBody: singleDeviceBody)
134149
}
135150

136151
/// True when a removed group and an added group are almost certainly the
@@ -172,8 +187,19 @@ public enum NotificationDecision {
172187
/// showed up as "connected" even though they were posted. Mirrors
173188
/// `removedNotificationContents`'s merge so >1 group becomes ONE
174189
/// notification, same as a disconnect. See issue #556.
190+
///
191+
/// - Parameter thunderboltInvolved: when true and there's more than one
192+
/// group (so this is the MERGED title, never the single-group
193+
/// "Connected: <name>" title), the title reads "Thunderbolt devices
194+
/// connected" instead of "USB devices connected". Set by the caller
195+
/// from `NotificationDecision.thunderboltInvolved(previous:current:)`
196+
/// when a downstream Thunderbolt fabric switch appeared or disappeared
197+
/// in the same settle window. Defaults to false so existing call sites
198+
/// keep compiling and today's wording is byte-identical when it isn't
199+
/// passed.
175200
public static func addedNotificationContents(
176201
groups: [USBDeviceChangeGrouper.ChangeGroup],
202+
thunderboltInvolved: Bool = false,
177203
singleDeviceBody: (UInt64) -> String?
178204
) -> [NotificationContent] {
179205
if groups.count == 1, let group = groups.first {
@@ -184,10 +210,10 @@ public enum NotificationDecision {
184210
return [NotificationContent(title: title, body: body)]
185211
} else if groups.count > 1 {
186212
let allNames = groups.flatMap { [$0.rootName] + $0.memberNames }
187-
return [NotificationContent(
188-
title: String(localized: "USB devices connected", bundle: _notificationsLocalizedBundle),
189-
body: allNames.joined(separator: "\n")
190-
)]
213+
let title = thunderboltInvolved
214+
? String(localized: "Thunderbolt devices connected", bundle: _notificationsLocalizedBundle)
215+
: String(localized: "USB devices connected", bundle: _notificationsLocalizedBundle)
216+
return [NotificationContent(title: title, body: allNames.joined(separator: "\n"))]
191217
}
192218
return []
193219
}
@@ -197,18 +223,24 @@ public enum NotificationDecision {
197223
/// devices disconnected" notification), extracted so
198224
/// `deviceNotificationContents` can compose it with the reconnect gate.
199225
/// See issue #556.
226+
///
227+
/// - Parameter thunderboltInvolved: same swap as
228+
/// `addedNotificationContents`'s own parameter, "Thunderbolt devices
229+
/// disconnected" in place of "USB devices disconnected", only for the
230+
/// merged (>1 group) title.
200231
public static func removedNotificationContents(
201-
groups: [USBDeviceChangeGrouper.ChangeGroup]
232+
groups: [USBDeviceChangeGrouper.ChangeGroup],
233+
thunderboltInvolved: Bool = false
202234
) -> [NotificationContent] {
203235
if groups.count == 1, let group = groups.first {
204236
let title = String(localized: "Disconnected: \(group.rootName)", bundle: _notificationsLocalizedBundle)
205237
return [NotificationContent(title: title, body: group.memberNames.joined(separator: "\n"))]
206238
} else if groups.count > 1 {
207239
let allNames = groups.flatMap { [$0.rootName] + $0.memberNames }
208-
return [NotificationContent(
209-
title: String(localized: "USB devices disconnected", bundle: _notificationsLocalizedBundle),
210-
body: allNames.joined(separator: "\n")
211-
)]
240+
let title = thunderboltInvolved
241+
? String(localized: "Thunderbolt devices disconnected", bundle: _notificationsLocalizedBundle)
242+
: String(localized: "USB devices disconnected", bundle: _notificationsLocalizedBundle)
243+
return [NotificationContent(title: title, body: allNames.joined(separator: "\n"))]
212244
}
213245
return []
214246
}

‎Sources/WhatCableNotifications/Resources/de.lproj/Localizable.strings‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@
88
"USB device" = "USB-Gerät";
99
"USB devices connected" = "USB-Geräte verbunden";
1010
"USB devices disconnected" = "USB-Geräte getrennt";
11+
"Thunderbolt devices connected" = "Thunderbolt-Geräte verbunden";
12+
"Thunderbolt devices disconnected" = "Thunderbolt-Geräte getrennt";

‎Sources/WhatCableNotifications/Resources/en.lproj/Localizable.strings‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@
88
"USB device" = "USB device";
99
"USB devices connected" = "USB devices connected";
1010
"USB devices disconnected" = "USB devices disconnected";
11+
"Thunderbolt devices connected" = "Thunderbolt devices connected";
12+
"Thunderbolt devices disconnected" = "Thunderbolt devices disconnected";

‎Sources/WhatCableNotifications/Resources/es.lproj/Localizable.strings‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,5 @@
88
"USB device" = "Dispositivo USB";
99
"USB devices connected" = "Dispositivos USB conectados";
1010
"USB devices disconnected" = "Dispositivos USB desconectados";
11+
"Thunderbolt devices connected" = "Dispositivos Thunderbolt conectados";
12+
"Thunderbolt devices disconnected" = "Dispositivos Thunderbolt desconectados";

0 commit comments

Comments
 (0)