Geo notes latency: EOSE scoped to reached relays + connecting state with auto-retry (#1411)

* Empty-mesh liveliness: nearby conversations, echoes, wave action, dead drops, radar

The empty mesh timeline was a dead end: a grey zero and "nobody in range
yet". This turns it into a live surface and gives the app pull when the
mesh wakes up:

- Nearest conversation: background geohash sampling now tracks actual
  chat messages (not just presence) per regional channel; the empty state
  surfaces the busiest nearby conversation with a preview, one tap to
  join (GeohashChatActivityTracker, fed from GeoPresenceTracker).
- Echoes: the carried 6h store-and-forward window renders as dimmed
  "heard here earlier" rows at launch (new Transport
  collectArchivedPublicMessages -> GossipSyncManager snapshot, decoded
  with signature-derived nicknames; content-identity dedup guards
  against re-synced duplicates).
- Wave: the "bitchatters nearby" notification gains a "wave" quick
  action that broadcasts a mesh 👋 straight from the notification, even
  backgrounded (first UNNotificationCategory in the app).
- Dead drops: /drop pins a note to the current building geohash as a
  kind-1 location note with a 24h NIP-40 expiry; expired notes are now
  dropped client-side at ingest; the notices sheet shows "fades in Xh";
  a "location notes" toggle plus location-permission controls live in
  app info (also fixes the duplicated Voice section).
- Radar: an ambient sonar animation shows the radio scanning, with a
  privacy-safe daily tally ("N devices passed within range today" via
  salted per-day hashes) and a "notes left here" hint that opens the
  notices geo tab.

All new user-facing strings ship in all 29 locales. 1403 tests green,
including new suites for the activity tracker, sightings tally, and
note expiry/drop publishing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Review round: app-info polish, urgent/expiry parity, centered radar, pin fill, Codex P2s

- App info: LOCATION header uppercased like sibling sections; location
  notes and live voice descriptions shortened (29 locales); redundant
  "location access granted" line removed.
- Notices parity: urgent + expiry controls now show on the geo tab too;
  the bridged Nostr note carries ["t","urgent"] and NIP-40 so relay-side
  readers see both; urgent parsed back from incoming notes.
- Radar moved from the top of the empty state to the center of the chat
  area, below the help text (empty state fills the visible height).
- Header pin fills whenever the scope has notices (was: only unseen),
  and Nostr-only nearby notes now light it too.
- Codex P2 fixes: notification completion deferred until the wave action
  is handled (background suspension dropped the send); NIP-40 notes now
  prune on a timer when they expire while displayed; the location-notes
  kill switch retargets the nearby-notes counter immediately.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Hide macOS segmented picker's built-in label in notices composer (duplicate 'expires in')

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Geo notes: permanent (∞) expiry default, urgent stays mesh-only

- Geo expiry picker gains ∞ as the default: a permanent note posts as a
  pure relay note (no NIP-40 tag, no mesh-board copy — a board copy must
  fade within days, contradicting the ∞ the user picked). 1/3/7d keep
  the board + bridged-note path with NIP-40.
- The notes manager is now owned by the notices sheet (not the list) so
  the composer local-echoes ∞ notes into the list; it revives via
  refresh() after a tab-switch cancel, and its expiry-prune timer
  survives cancel (weak self, dies with the instance).
- Urgent toggle returns to mesh-only per review — notes are ambient;
  the read-side urgent-tag parse stays so tagged notes still render.
- macOS: hide the segmented picker's built-in label (duplicate
  "expires in").

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Geo notes latency: EOSE scoped to reached relays, connecting state with auto-retry

Field finding: opening notices on a cold launch showed "no notices yet"
after ~10s, with notes popping in later — the empty state was a lie told
by two mechanisms:

- EOSE tracking waited on ALL target relays, including ones still
  mid-Tor-circuit; one dead relay of five pinned "loading" until the
  10s fallback. Trackers now count a relay only once the REQ actually
  reached it (marked from the send completion, or proven by its EOSE),
  so the first responding relay resolves the initial load and dropped
  targets can't stall it. The 10s fallback stays as backstop.
- When that fallback fired with ZERO connected target relays (Tor still
  bootstrapping), LocationNotesManager reported .ready with no notes.
  It now enters a .connecting state — rendered as "connecting to
  relays…" instead of the empty state — and polls every 3s, re-
  subscribing for a fresh initial fetch the moment a target relay
  comes up.

New NostrRelayManager.isAnyRelayConnected(among:) feeds the check via
an injectable dependency (tests default to legacy behavior). String
localized in all 29 locales. 1412 tests green, iOS+macOS builds clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Clearing the mesh timeline dismisses echoes for good; tighter divider copy

Triple-tap /clear emptied the timeline but the next launch re-seeded
"heard here earlier" from the persisted archive. A MeshEchoSettings
watermark now records the clear; only messages heard after it come back
(the archive itself still carries everything for peers' sync). The
echo dedup keys reset with it, and panic wipe drops the watermark.

Divider copy tightened to "heard here earlier · last 6h" (29 locales).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Mark EOSE relays at send initiation, closing the in-flight-send race

Codex P2 on #1411: with several sockets already connected, a fast
relay's EOSE could complete the tracker while a slower relay's async
send completion hadn't yet moved it out of awaitingSend — the initial
load reported done with that relay's stored events still pending.
Relays are now marked awaiting-EOSE synchronously when the REQ send is
initiated (and when a flush skips an already-subscribed relay), so
every relay that was actually asked is counted before any EOSE can
race. Failed sends resolve via the disconnect settle or the fallback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Echoes visual polish: tinted history block, radar-captioned tally, ambient footer

Device-test feedback on the echoes screen:
- Archived echoes now sit on a subtle tinted background (secondary at
  8%) in addition to the dim, so "heard here earlier" reads as one
  distinct block; the divider carries the echo ID prefix to join it.
- "N devices passed within range today" moves out of the narration
  lines to sit centered under the radar as its caption.
- When the timeline holds only echoes/system lines, a compact ambient
  footer (small radar + tally + live hints) renders below the history
  instead of the whole ambient layer vanishing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Notes strip persists above the mesh chat; leaner empty-state narration

- The 📍 "notes left here" line was empty-state-only, so starting a
  conversation hid it. It is now a tappable strip pinned above the mesh
  timeline whenever unexpired notes exist at this place (opens the
  notices geo tab); the nearby-notes counter runs for the whole mesh
  timeline, not just the empty state.
- Empty state narration drops "nobody in range yet..." (the radar and
  the sightings caption already say it) and the nearby-conversation
  hint moves below the help line instead of splitting the narration.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Radar means searching: hide the sweep once mesh peers are connected or reachable

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Resolve leftover merge conflict markers from the main restack

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Drop two Nostr helper constants resurrected by the restack merge (dead on main)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
jack
2026-07-08 14:16:46 +02:00
committed by GitHub
co-authored by jack Claude Fable 5
parent 74b8a47d02
commit 4baeaab717
6 changed files with 382 additions and 12 deletions
+180
View File
@@ -46427,6 +46427,186 @@
}
}
},
"location_notes.connecting_relays" : {
"comment" : "Status line while geo notes wait for a relay connection (e.g. Tor still bootstrapping)",
"extractionState" : "manual",
"localizations" : {
"ar" : {
"stringUnit" : {
"state" : "translated",
"value" : "جارٍ الاتصال بالمرحّلات…"
}
},
"bn" : {
"stringUnit" : {
"state" : "translated",
"value" : "রিলেতে সংযোগ হচ্ছে…"
}
},
"de" : {
"stringUnit" : {
"state" : "translated",
"value" : "verbinde mit relays…"
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
"value" : "conectando a los relays…"
}
},
"fil" : {
"stringUnit" : {
"state" : "translated",
"value" : "kumokonekta sa mga relay…"
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
"value" : "connexion aux relais…"
}
},
"he" : {
"stringUnit" : {
"state" : "translated",
"value" : "מתחבר לממסרים…"
}
},
"hi" : {
"stringUnit" : {
"state" : "translated",
"value" : "रिले से कनेक्ट हो रहा है…"
}
},
"id" : {
"stringUnit" : {
"state" : "translated",
"value" : "menghubungkan ke relay…"
}
},
"it" : {
"stringUnit" : {
"state" : "translated",
"value" : "connessione ai relay…"
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
"value" : "リレーに接続中…"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
"value" : "릴레이에 연결 중…"
}
},
"ms" : {
"stringUnit" : {
"state" : "translated",
"value" : "menyambung ke relay…"
}
},
"ne" : {
"stringUnit" : {
"state" : "translated",
"value" : "रिलेमा जडान हुँदैछ…"
}
},
"nl" : {
"stringUnit" : {
"state" : "translated",
"value" : "verbinden met relays…"
}
},
"pl" : {
"stringUnit" : {
"state" : "translated",
"value" : "łączenie z relay…"
}
},
"pt" : {
"stringUnit" : {
"state" : "translated",
"value" : "a ligar aos relés…"
}
},
"pt-BR" : {
"stringUnit" : {
"state" : "translated",
"value" : "conectando aos relés…"
}
},
"ru" : {
"stringUnit" : {
"state" : "translated",
"value" : "подключение к релеям…"
}
},
"sv" : {
"stringUnit" : {
"state" : "translated",
"value" : "ansluter till reläer…"
}
},
"ta" : {
"stringUnit" : {
"state" : "translated",
"value" : "ரிலேயுடன் இணைக்கிறது…"
}
},
"th" : {
"stringUnit" : {
"state" : "translated",
"value" : "กำลังเชื่อมต่อรีเลย์…"
}
},
"tr" : {
"stringUnit" : {
"state" : "translated",
"value" : "relay'lere bağlanılıyor…"
}
},
"uk" : {
"stringUnit" : {
"state" : "translated",
"value" : "підключення до релеїв…"
}
},
"ur" : {
"stringUnit" : {
"state" : "translated",
"value" : "ریلے سے منسلک ہو رہا ہے…"
}
},
"vi" : {
"stringUnit" : {
"state" : "translated",
"value" : "đang kết nối đến relay…"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "正在连接中继…"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "正在連接中繼…"
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "connecting to relays…"
}
}
}
},
"location_notes.description" : {
"extractionState" : "manual",
"localizations" : {
+59 -9
View File
@@ -183,11 +183,26 @@ final class NostrRelayManager: ObservableObject {
}
private var subscriptionRequestState: [String: SubscriptionRequestState] = [:]
// Track EOSE per subscription to signal when initial stored events are done
// Track EOSE per subscription to signal when initial stored events are
// done. Completion is scoped to relays the REQ actually reached: targets
// still mid-connect must not hold the callback hostage until the fallback
// timer (a dead relay of five used to pin "loading" for the full 10s).
private struct EOSETracker {
var pendingRelays: Set<String>
/// Targets the REQ has not been delivered to yet (still connecting).
var awaitingSend: Set<String>
/// Relays that received the REQ and have not sent EOSE yet.
var awaitingEOSE: Set<String>
/// True once any relay received the REQ (or answered with EOSE)
/// completion with zero sends would mean "done" without ever asking.
var didSend = false
var callback: () -> Void
let epoch: Int
/// Done when every relay that got the REQ has resolved, provided at
/// least one did or when every target dropped out entirely.
var isComplete: Bool {
(didSend && awaitingEOSE.isEmpty) || (awaitingSend.isEmpty && awaitingEOSE.isEmpty)
}
}
private var eoseTrackers: [String: EOSETracker] = [:]
private var eoseTrackerEpoch = 0
@@ -793,7 +808,7 @@ final class NostrRelayManager: ObservableObject {
private func startEOSETracking(id: String, relayURLs: Set<String>, callback: @escaping () -> Void) {
eoseTrackerEpoch += 1
let epoch = eoseTrackerEpoch
eoseTrackers[id] = EOSETracker(pendingRelays: relayURLs, callback: callback, epoch: epoch)
eoseTrackers[id] = EOSETracker(awaitingSend: relayURLs, awaitingEOSE: [], callback: callback, epoch: epoch)
// Fallback timeout to avoid hanging if a relay never sends EOSE.
dependencies.scheduleAfter(TransportConfig.nostrSubscriptionEOSEFallbackSeconds) { [weak self] in
Task { @MainActor [weak self] in
@@ -933,8 +948,19 @@ final class NostrRelayManager: ObservableObject {
toSend[id] = state.messageString
}
for (id, messageString) in toSend {
if self.subscriptions[relayUrl]?.contains(id) == true { continue }
if self.subscriptions[relayUrl]?.contains(id) == true {
// Already subscribed on this relay (e.g. a tracker promoted
// after an earlier flush): its EOSE is coming, count it.
markEOSESubscribed(id: id, relayUrl: relayUrl)
continue
}
startPendingEOSETrackingIfNeeded(id: id)
// Mark at send *initiation*, not in the async completion: a fast
// relay's EOSE could otherwise complete the tracker while this
// relay REQ already on the wire still sat in awaitingSend.
// If the send fails the socket is going down with it, and the
// disconnect settle (or the fallback timer) releases the wait.
markEOSESubscribed(id: id, relayUrl: relayUrl)
connection.send(.string(messageString)) { [weak self, weak connection] error in
Task { @MainActor [weak self] in
guard let self else { return }
@@ -1016,8 +1042,12 @@ final class NostrRelayManager: ObservableObject {
}
case .eose(let subId):
if var tracker = eoseTrackers[subId] {
tracker.pendingRelays.remove(relayUrl)
if tracker.pendingRelays.isEmpty {
// An EOSE proves the relay received the REQ even if the local
// send completion hasn't run yet.
tracker.awaitingSend.remove(relayUrl)
tracker.awaitingEOSE.remove(relayUrl)
tracker.didSend = true
if tracker.isComplete {
eoseTrackers.removeValue(forKey: subId)
tracker.callback()
} else {
@@ -1097,9 +1127,11 @@ final class NostrRelayManager: ObservableObject {
/// callbacks; treat it as done and let the remaining relays (or the
/// fallback timeout) drive completion.
private func settleEOSETrackers(droppingRelay relayUrl: String) {
for (id, var tracker) in eoseTrackers where tracker.pendingRelays.contains(relayUrl) {
tracker.pendingRelays.remove(relayUrl)
if tracker.pendingRelays.isEmpty {
for (id, var tracker) in eoseTrackers
where tracker.awaitingSend.contains(relayUrl) || tracker.awaitingEOSE.contains(relayUrl) {
tracker.awaitingSend.remove(relayUrl)
tracker.awaitingEOSE.remove(relayUrl)
if tracker.isComplete {
eoseTrackers.removeValue(forKey: id)
tracker.callback()
} else {
@@ -1108,6 +1140,24 @@ final class NostrRelayManager: ObservableObject {
}
}
/// Whether any of `relayUrls` currently holds a live connection. Lets
/// subscribers distinguish "loaded, empty" from "never reached a relay"
/// when an EOSE fallback fires.
func isAnyRelayConnected(among relayUrls: [String]) -> Bool {
let targets = Set(relayUrls)
return relays.contains { targets.contains($0.url) && $0.isConnected }
}
/// Marks the REQ as delivered to `relayUrl`: EOSE completion now waits on
/// this relay instead of the never-connected remainder.
private func markEOSESubscribed(id: String, relayUrl: String) {
guard var tracker = eoseTrackers[id],
tracker.awaitingSend.remove(relayUrl) != nil else { return }
tracker.awaitingEOSE.insert(relayUrl)
tracker.didSend = true
eoseTrackers[id] = tracker
}
private func handleDisconnection(relayUrl: String, error: Error) {
connections.removeValue(forKey: relayUrl)
subscriptions.removeValue(forKey: relayUrl)
+54 -2
View File
@@ -17,6 +17,10 @@ struct LocationNotesDependencies {
var now: () -> Date
// Fires when the geo relay directory refreshes; used to retry after "no relays".
var relayDirectoryUpdates: AnyPublisher<Void, Never> = Empty(completeImmediately: false).eraseToAnyPublisher()
/// Whether any of the target relays has a live connection distinguishes
/// "loaded, empty" from "still connecting (Tor warming up)" when EOSE
/// fires without data. Defaults to true so tests keep legacy behavior.
var anyRelayConnected: @MainActor (_ relayUrls: [String]) -> Bool = { _ in true }
private static let idBridge = NostrIdentityBridge()
@@ -46,7 +50,10 @@ struct LocationNotesDependencies {
relayDirectoryUpdates: NotificationCenter.default
.publisher(for: .geoRelayDirectoryDidRefresh)
.map { _ in () }
.eraseToAnyPublisher()
.eraseToAnyPublisher(),
anyRelayConnected: { relayUrls in
NostrRelayManager.shared.isAnyRelayConnected(among: relayUrls)
}
)
}
@@ -57,6 +64,10 @@ final class LocationNotesManager: ObservableObject {
enum State: Equatable {
case idle
case loading
/// The initial fetch timed out with zero target relays connected
/// (usually Tor still bootstrapping): not "empty", just not there
/// yet. Retries automatically once a relay comes up.
case connecting
case ready
case noRelays
}
@@ -115,6 +126,7 @@ final class LocationNotesManager: ObservableObject {
private var noteIDs = Set<String>() // O(1) duplicate detection
private var directoryUpdateCancellable: AnyCancellable?
private var expiryPruneTimer: Timer?
private var connectivityRetryTimer: Timer?
private let dependencies: LocationNotesDependencies
private let maxNotesInMemory = 500 // Defensive cap (relay limit is 200)
@@ -160,6 +172,7 @@ final class LocationNotesManager: ObservableObject {
deinit {
expiryPruneTimer?.invalidate()
connectivityRetryTimer?.invalidate()
}
/// Drops notes whose NIP-40 expiry has passed. Their ids stay in
@@ -220,6 +233,8 @@ final class LocationNotesManager: ObservableObject {
private func subscribe() {
state = .loading
errorMessage = nil
connectivityRetryTimer?.invalidate()
connectivityRetryTimer = nil
if let sub = subscriptionID {
dependencies.unsubscribe(sub)
subscriptionID = nil
@@ -270,12 +285,47 @@ final class LocationNotesManager: ObservableObject {
}, { [weak self] in
guard let self = self else { return }
self.initialLoadComplete = true
if self.state != .noRelays {
guard self.state != .noRelays else { return }
// EOSE with no data and zero connected target relays means the
// 10s fallback fired while Tor was still warming up showing
// "no notes" would be a lie. Wait visibly and retry.
if self.notes.isEmpty, !self.dependencies.anyRelayConnected(relays) {
self.state = .connecting
self.scheduleConnectivityRetry(relays: relays)
} else {
self.state = .ready
}
})
}
/// While `.connecting`, poll for a live target relay and re-subscribe as
/// soon as one appears (fresh REQ, fresh EOSE tracking). The poll dies
/// with the state: any subscribe/cancel invalidates it.
private func scheduleConnectivityRetry(relays: [String]) {
connectivityRetryTimer?.invalidate()
connectivityRetryTimer = Timer.scheduledTimer(
withTimeInterval: TransportConfig.uiGeoNotesConnectivityRetrySeconds,
repeats: true
) { [weak self] _ in
Task { @MainActor [weak self] in
self?.retryIfRelaysAvailable(relays: relays)
}
}
}
func retryIfRelaysAvailable(relays: [String]) {
guard state == .connecting else {
connectivityRetryTimer?.invalidate()
connectivityRetryTimer = nil
return
}
guard dependencies.anyRelayConnected(relays) else { return }
connectivityRetryTimer?.invalidate()
connectivityRetryTimer = nil
SecureLogger.debug("LocationNotesManager: relay came up, retrying notes fetch for \(geohash)", category: .session)
refresh()
}
/// Send a location note for the current geohash using the per-geohash
/// identity, optionally expiring via NIP-40 (dead drops pass 24h; the
/// composer's option passes nil) and optionally tagged urgent.
@@ -410,6 +460,8 @@ final class LocationNotesManager: ObservableObject {
dependencies.unsubscribe(sub)
subscriptionID = nil
}
connectivityRetryTimer?.invalidate()
connectivityRetryTimer = nil
state = .idle
errorMessage = nil
}
+3
View File
@@ -180,6 +180,9 @@ enum TransportConfig {
static let uiArchivedEchoLoadDelaySeconds: TimeInterval = 1.5
// Dead drops: location notes left via /drop expire after this long.
static let locationDropExpirySeconds: TimeInterval = 24 * 60 * 60
// Poll cadence while geo notes wait for a relay connection (Tor warming
// up); re-subscribes as soon as one comes up.
static let uiGeoNotesConnectivityRetrySeconds: TimeInterval = 3.0
// Message deduplication
static let messageDedupMaxAgeSeconds: TimeInterval = 300
+13 -1
View File
@@ -126,6 +126,7 @@ struct NoticesView: View {
static let locationUnavailable = String(localized: "content.notes.location_unavailable", comment: "Shown when the device location is unavailable for geo notices")
static let enableLocation = String(localized: "content.location.enable", comment: "Button enabling location for geo notices")
static let loadingNotes: LocalizedStringKey = "location_notes.loading_notes"
static let connectingRelays: LocalizedStringKey = "location_notes.connecting_relays"
static let noRelaysNearby: LocalizedStringKey = "location_notes.no_relays_nearby"
static let relaysRetryHint: LocalizedStringKey = "location_notes.relays_retry_hint"
static let retry: LocalizedStringKey = "location_notes.action.retry"
@@ -476,7 +477,9 @@ private struct NoticesList: View {
/// once the sources settled.
private var showEmptyState: Bool {
guard let notesManager else { return true }
return notesManager.initialLoadComplete && notesManager.state != .loading
return notesManager.initialLoadComplete
&& notesManager.state != .loading
&& notesManager.state != .connecting
}
@ViewBuilder
@@ -491,6 +494,15 @@ private struct NoticesList: View {
Spacer()
}
.padding(.vertical, 8)
} else if notesManager.state == .connecting {
HStack(spacing: 10) {
ProgressView()
Text(Strings.connectingRelays)
.bitchatFont(size: 12)
.foregroundColor(palette.secondary)
Spacer()
}
.padding(.vertical, 8)
} else if notesManager.state == .noRelays {
VStack(alignment: .leading, spacing: 4) {
Text(Strings.noRelaysNearby)
@@ -336,6 +336,79 @@ struct LocationNotesManagerTests {
#expect(manager.notes.isEmpty)
}
@Test
func eoseWithoutConnectedRelays_showsConnectingInsteadOfEmpty() {
var storedEOSE: (() -> Void)?
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, eose in storedEOSE = eose },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in false }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
storedEOSE?()
#expect(manager.state == .connecting)
#expect(manager.initialLoadComplete)
}
@Test
func eoseWithConnectedRelayAndNoNotes_isReadyEmpty() {
var storedEOSE: (() -> Void)?
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, eose in storedEOSE = eose },
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in true }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
storedEOSE?()
#expect(manager.state == .ready)
}
@Test
func connectingState_retriesOnceARelayComesUp() {
var storedEOSE: (() -> Void)?
var subscribeCount = 0
var relayUp = false
var deps = LocationNotesDependencies(
relayLookup: { _, _ in ["wss://relay.one"] },
subscribe: { _, _, _, _, eose in
subscribeCount += 1
storedEOSE = eose
},
unsubscribe: { _ in },
sendEvent: { _, _ in },
deriveIdentity: { _ in throw TestError.shouldNotDerive },
now: { Date() }
)
deps.anyRelayConnected = { _ in relayUp }
let manager = LocationNotesManager(geohash: "u4pruydq", dependencies: deps)
#expect(subscribeCount == 1)
storedEOSE?()
#expect(manager.state == .connecting)
// Relay still down: no retry.
manager.retryIfRelaysAvailable(relays: ["wss://relay.one"])
#expect(subscribeCount == 1)
// Relay up: re-subscribes for a fresh initial fetch.
relayUp = true
manager.retryIfRelaysAvailable(relays: ["wss://relay.one"])
#expect(subscribeCount == 2)
#expect(manager.state == .loading)
}
private enum TestError: Error {
case shouldNotDerive
}