Adds a dedicated NIP-88 poll results screen showing how many votes each
option got and who voted for what, and fixes the tally bugs and the
missing subscription it would otherwise have inherited.
Tally is now poll-aware. PollTallyPolicy carries the kind-1068 rules —
valid option codes, poll type, and the open window — into ResponseTally,
which previously had no access to the poll it was counting. That fixes
four things at once: single-choice polls now read only the first response
tag instead of every one of them, unknown option codes no longer create
phantom buckets that drag real percentages down, responses stamped
outside the poll's window are excluded rather than winning on timestamp,
and percentages divide by distinct voters instead of total selections.
Responses routinely arrive before their poll, so the tally starts
permissive and recomputes when updatePolicy lands; both caches set it
from either arrival order.
Percentages are now share-of-voters. Single choice is unchanged; on
multiple choice a bar reads "7 in 10 people" and the bars can sum past
100%.
Android now asks the poll's own relay tags for kind 1018. Votes are
published there per NIP-88 and EventBroadcaster obeys that on the way
out, but the engagement filter only queried the author's inbox relays and
where the note was seen, so tallies were systematically short. Desktop
had already patched this per-card.
The screen itself reads that same tally off the poll Note — no new
subscription, no second cache, so the feed card and the results page
cannot disagree. Voter rows are UserLine unmodified, with the vote passed
into the trailingContent slot it already exposes. Tapping an option
scopes the list without moving the summary above it. Muted voters still
count toward the totals but are not listed, and the footer accounts for
every response excluded and why.
Entry points: a vote count beside each percentage on the feed card, and a
"N votes" link that opens the screen — so the avatar stack's "+N" is no
longer a dead end.
Desktop column, audience filter, sort, search and zap polls are not in
this change.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQorYBSv9oMvKa8hF1uGBv
UserLine (ShowUserSuggestionList.kt:185) is already the row this needs: a
SlimListItem with ClickableUserPicture / UsernameDisplay /
WatchAndDisplayNip05Row, and it already exposes a nullable
trailingContent parameter. So the results screen writes no row and
modifies no existing composable — it passes the option label and
timestamp into the slot that is already there. Drops the previously
proposed trailingContent addition to UserCompose.
The second line is now the NIP-05 identifier rather than the about text,
drawn the way the app draws it: local part, verified mark, domain, no @,
with the local part ellipsizing and the domain left visible. A root
identifier shows the domain alone; the npub appears only as the
no-NIP-05 fallback.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQorYBSv9oMvKa8hF1uGBv
Three revisions to the poll results proposal and its mockup.
Voter rows are no longer a bespoke row. A voter is a user, and the app
already draws users one way: SlimListItem with UserPicture /
UsernameDisplay / AboutDisplay, which is what UserCompose is. The results
row wants the first three verbatim and differs only in the trailing slot,
where the vote goes instead of the follow buttons — so the proposal adds
a trailingContent parameter to UserCompose with a default that leaves
every existing call site unchanged, rather than forking the row. The
second line is the profile's about text, and the bespoke follows/you
chips are gone; ordering already carries that.
Drops the privacy call-out entirely.
Moves the audience filter, sort control and voter search out of the first
version into their own later phase; option chips remain the only filter.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQorYBSv9oMvKa8hF1uGBv
Self-contained HTML mockup accompanying the poll results proposal: the
Android screen with seven numbered callouts, the Desktop deck column, the
loading / closed / empty states, and a side-by-side of the two candidate
readings for a multiple-choice percentage.
Mockup interiors use the app's real theme values from ui/theme/Color.kt
and Theme.kt so the screens read as Amethyst rather than as generic UI;
the annotation layer around them uses a separate neutral set. Light and
dark both supported, following the viewer's preference.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQorYBSv9oMvKa8hF1uGBv
Design proposal for a dedicated NIP-88 poll results surface showing
per-option vote counts and the full list of who voted for what, shared
between Android and Desktop.
Also documents four correctness gaps in the current tally that the page
would otherwise inherit: multi-choice percentages divide by selections
instead of voters, single-choice polls count every response tag instead
of the first, votes outside the poll timeframe still count, and unknown
option codes inflate the denominator. All four collapse into making
ResponseTally poll-aware.
Plus the data-completeness gap: Android never queries a poll's own
`relay` tags for kind 1018, so its tallies are systematically short
compared to Desktop, which already works around this per-card.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQorYBSv9oMvKa8hF1uGBv
Audit follow-up on the timeout work.
- fetchAllPages matched each event with `for ((i, f) in activeFilters)`.
That destructuring form allocates an Iterator on every event, on the
relay's reader thread, for the whole download -- millions of short-lived
objects in a bulk walk. Switched to an indexed loop, which is why quartz
uses the fast* operators elsewhere in hot event paths (those only cover
Array, so a List needs the index form).
- count() and fetchFirst() drain their channels in an inner loop that only
suspends when the channel is empty, so a backlog was consumed with no
cancellation check: neither the idle window expiring nor the caller
giving up could interrupt it mid-drain. Added an explicit ensureActive(),
matching the check fetchAllPages already does per page.
- count() could also lose a result that arrived after the last window
closed but before unsubscribe, understating the returned map. Added the
post-loop tryReceive drain that fetchAllWithHooks and fetchFirst have.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZe1Pq2ejoHehdufhPDRgb
Every wait in the accessories package is an idle window measured from the
relay's most recent progress, so the parameter now says so. The name is
the contract: a caller reading timeoutMs reasonably expects a deadline,
which is exactly the misreading that made fetchAllPages' hard per-page
cap look correct for so long.
Renamed across the public surface -- fetchAll (7 overloads),
fetchAllWithHooks, fetchAllPages (2), fetchAllPagesFromPool,
fetchAllPagesFromPoolWithHooks, fetchFirst, count (2), countMerged -- plus
the quartz wrappers whose own parameter is a pure pass-through of that
window (KeyPackageFetcher, RecipientRelayFetcher, FollowerCrawler.Config)
and every call site across commons, cli, desktopApp and amethyst.
Deliberately NOT renamed, because these are genuine wall-clock bounds and
the differing name is the tell:
- publishAndConfirm's timeoutInSeconds -- one fixed window to collect
the OKs, a bounded confirmation round-trip rather than a stream.
- GrapeRankCrawler.Config.timeoutMs -- a hard per-drain gate
(withTimeoutOrNull(config.timeoutMs)) that also drives parking.
- Context.awaitReply's timeoutMs, Context.syncIncoming, and the
non-accessory app-layer helpers (RelayProber, FeedMetadataCoordinator,
RelayAuthPromptBus).
This is a source-breaking change for named-argument callers of quartz.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZe1Pq2ejoHehdufhPDRgb
Follow-up audit on the timeout normalization. Three findings.
1. The maxTotalMs I added to fetchFirst and multi-relay count was the
wrong shape twice over. A hard wall-clock bound already composes at the
call site -- withTimeoutOrNull(ms) { fetchFirst(...) } -- so putting it
in the signature duplicates what the caller has for free. And it was
papering over the real defect: repeat chatter from a relay already
accounted for (a CLOSED/reconnect loop, a duplicate COUNT) was treated
as activity and restarted the idle window, so a flapping relay could
hold the call open indefinitely. Both now reset the window only on
genuine progress -- an event, or the first terminal signal from a relay
still being waited on -- which is the rule the negentropy watchdog
already applies to NOTICE/CLOSED chatter, and which makes both calls
self-bounding at one window per relay. Ceiling params removed; the
overflow guard they needed goes with them.
2. fetchFirst could drop a match: an event landing after the last terminal
signal but before unsubscribe was left unread in the channel and the
fetch reported nothing found. Added the post-loop drain that
fetchAllWithHooks already does. Covered by a test.
3. fetchAllPages published its per-page counters across threads without a
barrier on the idle path. received/delivered/pageMinTs/idsAtPageMin are
written on the relay reader thread and read by the driver once the wait
ends; the EOSE path gets happens-before from the channel, the idle path
had none, so the driver could read a stale pageMinTs (ending the walk
early) or an unsafely published idsAtPageMin. The volatile IdleClock
bump now runs in a finally, so it covers every event including the
early-returning duplicate and orders after the counters.
Also folded the single-relay count channel close into its finally, so a
throw mid-wait cleans up like every sibling accessory.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZe1Pq2ejoHehdufhPDRgb
The per-page wall-clock ceiling added alongside the idle-window change did
not do what it claimed. fetchAllPages waits inside a while(true): when a
page's wait ends, the loop advances the until cursor and issues the next
REQ rather than returning, so a ceiling bounds one page, never the call.
Measured against a relay trickling events forever with an unbounded
filter, maxPageMs=400 produced 8 REQs and no return -- the walk ran until
the caller cancelled, exactly as it would with no ceiling at all.
It also made truncation unsafe. Cutting a page mid-stream advances until
to the oldest event received so far, which only preserves the set if the
relay streams strictly newest-first -- NIP-01 recommends that but does not
require it -- so a ceiling firing on an out-of-order relay can skip the
not-yet-sent events above that cursor. That is the same class of silent
gap the idle window was introduced to close.
What actually bounds a paged download is the filter's limit (already the
documented way) or cancelling the caller, which the ensureActive() at the
top of each page honors. Removed from fetchAllPages, fetchAllPagesFromPool
and fetchAllPagesFromPoolWithHooks; a regression test pins the real
contract so nobody re-adds a ceiling believing it caps the walk.
maxTotalMs stays on fetchAll/fetchAllWithHooks, fetchFirst and multi-relay
count: those wait in a single loop and return, so there the ceiling
genuinely ends the call (each is covered by a test asserting it does).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZe1Pq2ejoHehdufhPDRgb
Audit follow-ups on the idle-window normalization:
- maxTotalMs/maxPageMs defaults are timeoutMs * 10, which silently
overflows to a negative Long for an effectively-infinite idle window
(Long.MAX_VALUE * 10 wraps to -10). withTimeoutOrNull then expired
immediately, inverting 'wait forever' into 'never wait'. All three
ceilings (fetchAllPages, fetchFirst, fetchAllWithHooks) now treat a
non-positive ceiling as uncapped, matching the idle window's <= 0
convention. Regression-tested via fetchFirst.
- count(filters) leaked its RelayConnectionListener and left COUNT subs
open if the caller cancelled mid-wait or a listener threw: the cleanup
ran as straight-line code with no try/finally, unlike every sibling
accessory. Wrapped so unsubscribe + removeConnectionListener + channel
close always run.
- New FetchFirstIdleTimeoutTest pins fetchFirst's idle-window semantics
(signals restart the window, silence costs exactly one window, the
ceiling stops endless terminal chatter, overflow means uncapped).
- README: note publishAndConfirm's fixed window as the deliberate
exception, and correct the fetchAllPagesFromPool row, which claimed
cross-relay dedup the function explicitly does not do.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZe1Pq2ejoHehdufhPDRgb
fetchAllPages waited for each page's EOSE under a hard wall-clock
withTimeoutOrNull, unlike fetchAll / fetchAllWithHooks / the negentropy
sync, whose timeouts are idle windows reset by every arriving message.
A slow-but-streaming page could be silently truncated, and a relay
slower than timeoutMs to first byte was mistaken for a drained set.
- Extract IdleClock + receiveWithinIdle out of NostrClientNegentropySyncExt
into a shared internal IdleWatchdog.kt and document the package-wide
convention in the accessories README.
- fetchAllPages (+ pool/hooks variants): the per-page timeout is now an
idle window bumped by every event; a maxPageMs ceiling (10x, matching
fetchAllWithHooks' maxTotalMs) backstops a never-EOSE trickle. A
non-positive ceiling means uncapped, mirroring the idle <= 0 convention.
- fetchFirst: the wait restarts on every arriving signal instead of one
hard deadline across all relays; maxTotalMs ceiling added.
- count (multi-relay): each arriving COUNT result restarts the window;
maxTotalMs ceiling added. Single-relay count is trivially idle already.
- NegentropyStoreSync page fallback clamps a disabled watchdog (0) to
DEFAULT_DOWNLOAD_IDLE_MS like fetchByIds, instead of paging unbounded.
- New NostrClientFetchAllPagesIdleTimeoutTest pins the semantics
(verified to fail against the old hard-deadline wait).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KZe1Pq2ejoHehdufhPDRgb
A relay holding 12,289,614 profiles answers
["COUNT","c1",{"kinds":[0]}] -> {"count":500}
LimitsPolicy ran the same clampLimits over CountCmd as over ReqCmd, so
an unbounded COUNT was given RelayLimits.defaultLimit and the store then
counted at most that many.
defaultLimit answers "how many events should a REQ return when the client
names none". A COUNT returns no events, so the question has no meaning
for it, and applying the answer anyway turns every unbounded COUNT into
min(matches, defaultLimit).
The failure is quiet, which is what let it survive: 500 is a plausible
number, and the kinds under the default answered correctly. On the relay
that surfaced it, kinds 1 and 10040 were right while 0, 10002 and 30382
were all exactly 500.
maxLimit still applies — a client asking to count at most N is asking
something a relay may bound. Only the invented default is dropped.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
updateFilter only added the rank provider to the trusted-author set, so
when the follower-count provider differed (different pubkey and/or
relay), its kind:30382 cards were never requested from the relay.
followerCountStrFlow then filtered for a signer whose cards never
arrived and rendered "--" forever.
Add liveUserFollowerCount (with its relayUrl) into the same mapOfSet
block, symmetrically with liveUserRankProvider.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G7AA1AxqA6StnPVdjGDcwv
Declaring 'advanced' as the base Filter type keeps the copy() regression
guard as a genuine runtime assertion instead of a compile-time triviality,
which is what the compiler was warning about.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KG9YkeFp6zyth5J364DLF
The relay-group section header and joinRelayGroup KDoc were left
dangling at the end of AccountConcordActions when the clusters were
split into separate files; reattach them to the function they describe.
Found by the post-refactor audit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
The account-qualification regex in the AccountMarmotActions extraction
also rewrote 'marmotManager is NULL' to 'account.marmotManager is NULL'
inside two log string literals, changing log output text. Restore the
original wording. Found by the post-refactor equivalence audit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
Moves the ~270-line zap/payment orchestration (NIP-57 zap requests,
NWC wallet requests with spoof tracking, NIP-B1 BOLT12 zaps, NIP-BC
onchain zaps/sends/splits) into AccountZapActions, exposed as
account.zaps. The onchain backend-not-configured constant moves with
it. External callers (ZapPaymentHandler, V4VPaymentHandler, wallet
viewmodels, blossom payments, app functions) now call account.zaps.*
directly. Moved code is unchanged except for account. qualification.
Completes the Account decoupling series: Account.kt went from 6228 to
3618 lines across EventBroadcaster, AccountConcordActions,
AccountMarmotActions, AccountRelayGroupActions, and AccountZapActions.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
Moves the ~460-line NIP-29 relay-group + Buzz workspace orchestration
(join/leave/create/delete/archive, threads, invites, pins, member/role
management, metadata edits, Buzz DMs/jobs/workflows/typing,
community member add/remove) into AccountRelayGroupActions, exposed as
account.relayGroups. External callers now use account.relayGroups.*
directly. Moved code is unchanged except for account. qualification.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
Moves the ~540-line Marmot/MLS orchestration cluster (group create/
leave/reset, member add/remove via key-package fetch, admin grant/
revoke, metadata updates, group messaging, key-package publishing and
relay resolution) into AccountMarmotActions, exposed as account.marmot.
External callers (marmot group screens, AccountViewModel forwarders,
NotificationReplyReceiver, DecryptAndIndexProcessor) now call
account.marmot.* directly. Moved code is unchanged except for
account. qualification.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
Moves the ~1,000-line Concord orchestration cluster (join/create/invite
flows, channel messages/reactions/edits/typing, roles and moderation,
refound/rekey/stranded-recovery, metadata + channel management,
control-plane sync) into AccountConcordActions, exposed as
account.concord. The two Concord file-level constants move with it.
Rumor ingestion (consumeConcordRumorGated, refreshConcordChannelIndex)
stays on Account since ConcordSessionManager is constructed with it,
as do the cross-feature sendMinichatReply and the read-path
isConcordBanned policy. External callers (Concord screens,
AccountViewModel forwarders, note action menus) now call
account.concord.* directly - no delegating shims.
Moved code is unchanged except for account. qualification.
Account.kt: 6228 -> 4935 lines so far in this series.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
It was measured from onConnecting to onConnected, which includes the time
the call sat in the client's dispatcher queue. Under a 16,507-relay
fan-out that queue dominates everything else: published records showed a
median rtt-open of 33.5 SECONDS and a max of 90, against a true minimum
of 140ms.
That is the field aggregators rank relays by, so it was worse than
publishing nothing — a signed claim that healthy relays are slow, when
the slowness was ours.
pingMillis already carried the right number and was being handed to the
listener unused: BasicOkHttpWebSocket computes it as
receivedResponseAtMillis - sentRequestAtMillis, so it starts when the
upgrade request actually goes out and excludes everything before it.
Zero or negative means the transport could not time the handshake, and
then no timing is published rather than a fabricated one — the same rule
the rest of this class already followed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Audit finding on the StoreQueryContext seam: RelaySession kept
authenticatedUsers as a plain mutable LinkedHashSet and handed out a
live view through RequestContext. A store (or EventSource) reading the
set during a long REQ replay — exactly what StoreQueryContext invites —
could race a concurrent NIP-42 AUTH commit on another coroutine:
iteration vs. add on an unsynchronized set is a
ConcurrentModificationException or a torn read.
The engine now swaps an immutable Set behind a @Volatile field on each
AUTH (the only writer), so every read is a consistent snapshot and
holding one across a replay is safe. AUTH is rare; the copy is off the
hot path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hH4RY2AUwfMZ54RkMiT45
Moves the sign-and-publish choke point out of Account into an
EventBroadcaster class: relay-set computation (outbox model, hints,
channel home relays, broadcast lists, DM inboxes, the recursive
linked-event descent) plus every publish path (sendAutomatic,
sendMyPublicAndPrivateOutbox, sendLiterallyEverywhere, broadcast,
signAndSendPrivately*, signAndComputeBroadcast,
signAnonymouslyAndBroadcast, republishEventsTo).
Account keeps one-line delegates so its 85+ internal call sites and all
external callers are unchanged; upcoming Account*Actions extractions
will call the broadcaster directly. Moved code is unchanged except for
account. qualification.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
Two read/reclaim policy clusters leave the LocalCache god object into
sibling classes in the same package, each taking the cache as its only
constructor dependency so the policies are testable in isolation:
- CachePruner: cleanMemory/cleanObservers, the six prune passes
(hidden/old/expired/superseded/replies+reactions), and the shared
unlinkAndRemove removal primitive (with removeIfWrap and
editedTargetIdOf). LocalCache.deleteNote and
DecryptAndIndexProcessor now call pruner.unlinkAndRemove;
MemoryTrimmingService drives cache.pruner.*.
refreshDeletedNoteObservers becomes internal so the pruner can
notify observers.
- CacheSearch: findUsersStartingWith(username, account),
findNotesStartingWith, and the three channel prefix searches, plus
their private exclusion rules. Callers (SearchBarViewModel,
AgentAttestationScreen, UserSuggestionState, BuzzNewDmViewModel) use
cache.search.* directly - no delegating shims left behind.
Also moves the Dao interface out of ui/actions/NewMessageTagger.kt into
the model package where its implementor (LocalCache) and its types
live, removing a model-layer interface defined in a UI file.
All moved code is unchanged except for cache. qualification; behavior
is identical. LocalCache.kt: 4554 -> 3921 lines.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
The IEventStore contract now defines the seams a store implementation
needs instead of having the relay layer decide for it:
- NIP-50 search extensions: LiveEventStore no longer strips key:value
tokens before the store sees them. Filter.search reaches every store
verbatim, and each implementation decides which extensions it
supports — the store, not the middleware, is the only component that
knows whether sort:rank is a directive or noise. The built-in SQLite
and filesystem stores strip at their own boundary (their FTS engines
would otherwise error on / literally match the tokens), preserving
the NIP-50 'ignore unsupported extensions' behavior end to end.
Extension-aware stores need no side channel to recover the raw
string anymore. Fs delete now checks emptiness on the stripped
filter so an extensions-only search cannot wipe the store.
- Caller identity: new StoreQueryContext coroutine-context element,
installed by LiveEventStore around every REQ/COUNT store call when
the connection has NIP-42-authenticated pubkeys. Observer-relative
stores (web-of-trust ranking, for-you relevance) read it off the
coroutine context; ranking context only, never match-set changes.
- Negentropy liveness: snapshotIdsForNegentropy gains an optional
onProgress hook so mirrors syncing huge corpora get a running count
through the interface type instead of a concrete-class overload.
SQLite reports from its row loop; the interface default streams and
reports too.
- FtsReindexProgress.cursor documented as opaque and store-defined so
resumable-reindex callers never assume id semantics.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hH4RY2AUwfMZ54RkMiT45
justConsumeInnerInner was one when(event) with ~290 branches, of which
172 were identical single-call bodies routing to consumeBaseReplaceable
or consumeRegularEvent, and ~55 more were single-line Buzz consumer
calls. Since all four shared consumers take a plain Event, the
boilerplate branches are now comma-grouped into one branch per
consumer (replaceable/addressable, regular, Buzz timeline, Buzz
store-only), keeping every branch with per-kind logic exactly as it
was.
Dispatch is provably unchanged: none of the 289 event classes has a
supertype among the classes in any other branch group, so reordering
cannot shadow a branch, and the old and new type-to-consumer mappings
were compared exhaustively and are identical. The else branch still
rejects unlisted kinds, preserving the supported-kinds allowlist.
LocalCache.kt: 5155 -> 4554 lines.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012sJgKJ4FAjcZqvkMc7U3EA
RelayObserver is a RelayConnectionListener, so on its own it can only
report on relays something opened a websocket to. On a large fan-out that
is a small minority, and it is the wrong minority: the cheap checks that
decide NOT to dial — a TCP probe, a DNS failure, a host struck out after
repeated silence — are precisely the ones that learn a relay is gone, and
their findings had nowhere to go.
Measured on a 16,507-relay list: 104 records published. Everything else
was ruled out before the client ever saw it, so the monitor had nothing
to say about 99% of the relays it had just formed an opinion on.
record() takes those findings. Same rules as the connection path — a
relay that answered is not demoted by one failed probe, and a reachable
relay with no measured time is published with no time rather than a
fabricated zero.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Nip42AuthDmDeliveryTest stalled for its full 10s timeout on CI while
passing locally. The stall is a race in InProcessWebSocket.connect():
server.connect() runs the session's connect-time policies synchronously,
so FullAuthPolicy's AUTH challenge reached the client's listener before
the socket assigned its `incoming` channel and before onOpen fired —
breaking the WebSocketListener contract (no onMessage before onOpen).
RelayAuthenticator answers that challenge on its own coroutine. When the
signed AUTH reply hit send() before the connect thread reached the
`incoming` assignment, send() returned false and the reply was silently
dropped. Nothing recovers from that: the challenge is already dedup'd as
answered, and an EVENT rejected with OK-false `auth-required:` never
re-triggers auth (only a CLOSED does), so the pending gift wrap was
never resent — exactly the CI signature (10.011s, no auth activity
between the authenticator's Init and Destroy logs).
Server->client frames now go through an outbound channel drained by a
coroutine started only after onOpen, so every connect-time frame reaches
the listener with the socket fully wired. Order is preserved by the
single drainer, same as the existing inbound path.
Both new InProcessWebSocketTest cases fail deterministically without the
reorder (the challenge always outran onOpen; a reply sent from the first
onMessage was always rejected) and pass with it, on top of the full
:geode:test and :quartz:jvmTest suites.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Bf1Y91sfjxwi2ig4ymGTA9
Native targets reject a comma inside a backticked name, so five tests
that read fine on JVM broke every Kotlin/Native build. Renamed without
them.
The override parameters now match RelayConnectionListener — pingMillis,
compressed, cmdStr, cmd, msg, errorMessage — which silences six warnings
and, more to the point, fixes a misreading: onConnected's second and
third parameters are the connection's ping and whether it is compressed,
and I had them named attempt and success.
Both were missed the same way: jvmTest passes without ever compiling the
native TEST sources. All five targets now compile, main and test.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
commonMain, so it compiled on JVM and broke every native target. Sorted
into a LinkedHashMap instead, which is the same output everywhere.
Found by CI on iosSimulatorArm64 because I had only compiled the JVM
target locally; all five now build.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A monitor normally probes — opens connections purely to measure, then
throws them away. A client that is already subscribing, fetching and
publishing has better data for free: measured under real load, against
the relays it actually uses, at the concurrency it actually runs.
RelayObserver is a RelayConnectionListener, so it sees every connection
whichever code path opened it and none of them has to report anything:
rtt-open onConnecting to onConnected
rtt-read first REQ to its EOSE
rtt-write first EVENT to its OK
reachable it opened, or served something
auth-required it sent AUTH, or CLOSED saying so
the error, verbatim, when it never opened
Everything is OBSERVED. Nothing is copied from a relay's NIP-11: that is
the relay's own claim, available to anyone who asks, and republishing it
under a monitor's signature adds nothing but a chance to go stale. Where
the two disagree — a relay advertising open reads that then challenges
us — the observation is the half worth having, and copying the claim
would erase it. It also keeps quartz free of an HTTP dependency.
RelayMonitor is the whole wiring: construct one and connections are
measured, signed as 30166s on an interval, and folded into a cheap
in-memory isKnownDead for picking relays. That read has to be cheap — an
outbox picker runs per event — so it answers from a snapshot refreshed on
an interval, never a store query.
The signer is required. Measuring relay quality and letting others check
it IS NIP-66, and an optional signer would just add the failure mode this
library keeps designing out: configured, silent, doing nothing. A client
that should not publish does not construct one.
RelayObserver also replaces the CLI's RelayDiagnostics, which was the
same listener minus the timings. Porting it surfaced a bug both shared:
substringBefore(':') returns the WHOLE string when there is no colon, so
a relay's free-form CLOSED prose became its own tally key and the map
grew with the number of distinct sentences relays wrote. The colon is
now required.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
javap showed the hexToByte/byteToHex field re-loaded on every use inside
these methods (16 times per readLong call) — the JVM/ART doesn't reliably
prove the load loop-invariant. Hoisting it into a local measured ~25%
faster for decode and ~10% for isEqual and readLong on the JVM
(4096 random 32-byte ids, best-of-150 rounds, 3 repeats); encode was
neutral on HotSpot but is hoisted too since ART is historically worse
at this (see the internalIsHex comment).
Branchless variants of isHex/isHex64 were also measured and were a
wash-to-slightly-worse than the branchy early-exit versions on valid
input, so those keep their current implementations.
Also adds the new exact-size codecs to the on-device HexBenchmark
(decode64, decode64OrNull, encode64, decode128, encode128, toLong256,
and the old isHex64+decode two-pass for comparison) so ART numbers can
be collected with the existing benchmark harness.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hwv6XwT9mwGUQc57zH4ky4