Follow-up to the crash fix, which changed what cancellation costs.
Inferences can no longer be recalled: awaitDetached() detaches instead of
cancelling, because cancelling the future is what killed the process. So
abandoning a running batch no longer stops anything — it leaves seven rewrites
burning on-device compute for text the user has already moved past, and since
precomputeAiResults() runs on every keystroke, each later pause stacked seven
more on top with nothing bounding the pile.
The composer now coalesces instead of abandoning. The debounce window stays
freely cancellable (nothing has reached the model yet), but once a batch's
inferences are under way it is left to finish and the newest draft text is
stashed in aiPendingText, picked up when that batch ends. In-flight work is
bounded at one batch however fast the user types, and per-batch latency is
untouched — the seven tones still run concurrently.
MLKitImageLabelService moves off ListenableFuture.get() onto awaitDetached().
Describing an image takes seconds, and get() held an IO thread for all of it
uninterruptibly, so backing out of the composer left the thread pinned until
AICore answered. This needs a CancellationException rethrow ahead of the
existing catch-all: now that the awaits suspend, a cancelled caller lands there
and must not be swallowed as "no suggestion".
Also drops MIN_CONFIDENCE/MAX_LABELS, which nothing has referenced since the
keyword image-labeling path was removed, and corrects the class KDoc that still
described that fallback.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E1mgCe29aaWUwGmGHKnFKo
Cancelling a `genai-rewriting` 1.0.0-beta1 inference future kills the process
from a thread we don't own:
Thread: AiCoreClientWorker-thread-5
java.lang.NullPointerException: Attempt to invoke interface method
'void com...mlkit_genai_rewriting.zzp.zzd()' on a null object reference
at com...mlkit_genai_rewriting.zzby.zzk
at com...mlkit_genai_rewriting.zzbt.run
at java.util.concurrent.ThreadPoolExecutor.runWorker
Disassembling the library pins it down exactly. `zzw.zzf` — the
`IMagicRewriteService` AIDL proxy — reads the returned `ICancellationCallback`
with `Parcel.readStrongBinder()`, which yields null when AiCore answers without
one, and passes that null on. `zzbh.attachCompleter` then registers it as the
future's cancellation listener with no null check
(`addCancellationListener(new zzbt(handle), ...)`), so cancelling the future
runs `zzby.zzk(null)` → `null.zzd()`. `zzk` catches only `RemoteException`, and
it all happens on ML Kit's own worker pool, so nothing we wrap can see it: the
NPE reaches the default uncaught handler and takes the app down.
The composer cancelled these routinely — a keystroke replaces the in-flight
batch of seven tones via `aiComputeJob.cancel()`, and leaving the composer
cancels `viewModelScope` — which turned a beta-library race into a routine
crash.
There is nothing to upgrade to: genai-rewriting, genai-proofreading and
genai-image-description have each published exactly one version. So the future
bridge now detaches instead of cancelling — `awaitDetached()` drops
`invokeOnCancellation { cancel(true) }` and skips reading the result once the
caller is gone. A cancelled batch's inferences finish with nobody listening,
which spends a little on-device compute where cancelling spent the process; the
composer's 1s debounce already keeps most stale batches from starting.
MLKitImageLabelService blocks on `.get()` and never cancels, so it is unaffected.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01E1mgCe29aaWUwGmGHKnFKo
The chip required the sender and the author to publish the same protocol,
capped the row at two, and shipped opt-out. All three go.
Symmetry was a proxy for "I can actually pay this way", and it is the wrong
proxy: paying a Monero address needs a wallet, not a published address of one.
What the sender happens to say about themselves never determined whether the
hand-off would work — the installed-app probe does, and it was already running.
So `PayToRailMatcher.match` no longer takes the sender's list, `selectFor`
drops the `senderTargets` gate, and `canOpen` becomes the substantive filter
with the rest as preconditions.
Dropping symmetry moves the probe set. It used to be the sender's own target
list, which is why `warm()` could replace the cache wholesale; it is now the
targets of whichever author's picker is open. So `warm()` merges instead of
replacing — replacing would evict what was learned about every other author the
moment a second picker opened — and the `LaunchedEffect` keys on the author's
observed kind:10133 rather than on `paymentTargetsState`.
MAX_CHIPS existed because symmetry could pass several protocols at once with
nothing else narrowing them. Discovery narrows them: a target with no installed
app never reaches the picker, so the cap was bounding a row that discovery
already bounds, and an arbitrary two-chip truncation would now hide a target
the user can genuinely pay.
`showPayToZapChip` defaults on for the same reason. The opt-out was justified
by fiat handles carrying legal names, but the chip only ever surfaces a target
its author chose to publish, to a device that can already open it.
The setting's copy said "when you and the author both publish the same payment
method" and the toggle read "Offer shared payment methods" — both described the
gate that no longer exists, so both are rewritten.
Tests follow the contract rather than the old shape: symmetry cases become
capability cases, `everyOpenableTargetIsOfferedWithNoCap` replaces the cap
assertion, and one new case pins the inverse of the rule that was removed — a
target the sender does not publish is still offered. The lazy-read test keeps
its guarantee, minus the sender-empty branch that no longer exists.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
The Crowdin sync (a7e7ace985) reintroduced Android escaping into composeResources:
2,068 escaped apostrophes and 749 escaped quotes across 20 locale files, every one
of which was clean at f3a72e26e0. Compose does not resolve \' or \", so those
strings render with a literal backslash.
The affected locales are the apostrophe-heavy regional variants -- uz-rUZ 949,
fr-rFR 341, fr-rCA 326, tr-rTR 189 -- while their base locales stayed clean.
Re-applies the conversion with --no-unwrap-quotes, since these files are already
migrated: escape conversion is idempotent, quote-unwrapping is not, and a second
unwrap would strip the real display quotes from strings like import_follows_tips.
Diff verified as pure escape conversion: 2,002 lines changed, none unexplained.
This will recur on every sync until the conversion moves into the Crowdin
pipeline. See tools/strings-migrate/fix_escapes.py.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1CzYQvWyHfipSW7x3j4Yo
`tools:` attributes are an Android-lint construct. They arrived with strings moved
out of amethyst/src/main/res/, whose <resources> root declares xmlns:tools --
composeResources roots do not, so the prefix was unbound and the XML malformed:
97 occurrences across 49 locale files, none of them declaring the namespace.
Nothing was visibly broken, because Compose parses namespace-unaware and drops the
unknown attribute (no .cvr contains it). But nothing should rely on that, and
Android lint never runs on composeResources, so the attribute carried no meaning
there either.
migrate.py now strips tools: attributes as it moves each element, so the remaining
migration waves cannot reintroduce them.
Also fixes a hazard in fix_escapes.py found while doing this: quote-unwrapping is
NOT idempotent. Android wraps a value in quotes to protect whitespace, but once
\" has been converted to ", a legitimately quoted value is indistinguishable from
a wrapped one, and a second pass strips the real quotes -- it silently damaged 10
`import_follows_tips` translations before this was caught. Unwrapping is now
opt-out via --no-unwrap-quotes for repair runs over already-migrated files, and
documented as run-exactly-once.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1CzYQvWyHfipSW7x3j4Yo
Strings moved from res/values/ into composeResources/values/ kept Android's
escaping, which Compose does not interpret the same way, so the login screen
rendered `Don\'t have a Nostr account?` with a literal backslash and the terms
line showed stray quotes.
Compose 1.11.1 handleSpecialCharacters resolves only \uXXXX, \n and \t (and
collapses \\). It leaves \' \" \? \@ alone, and renders Android's quote-wrapping
-- used to preserve leading/trailing spaces, e.g. " Following" -- literally.
Convert those four escapes and unwrap the quotes, leaving \n, \t, \uXXXX and \\
untouched so Compose still resolves them. 3,717 entries across 56 locale files;
translations were hit far harder than English (Uzbek 964, French ~340 per
variant, Turkish ~208) because those languages use apostrophes heavily.
migrate.py now applies the same conversion as it moves each element, so the next
wave cannot reintroduce this; fix_escapes.py repairs what is already migrated and
is idempotent.
Verified on a Pixel 9 emulator: "Event is loading or can't be found in your relay
list" now renders with a real apostrophe, and no visible text node contains a
literal backslash escape.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1CzYQvWyHfipSW7x3j4Yo
Icon(imageVector = …) calls rememberVectorPainter, and a VectorPainter rasterises
its paths into a cached graphics layer per instance, so the feed re-rasterised the
same glyphs once per card. A font glyph is a blit from the shared text atlas,
shared across every call site for free.
tools/icon-font/build_icon_font.py converts the Kotlin ImageVector DSL to SVG paths
and builds a TTF with fontTools. Font metrics mirror the bundled Material Symbols
font (upem 960, ascent 1056, descent -96, advance 960) so glyphs align with existing
call sites; generated outlines land within a few units of Google's own.
Measured on the uniform-corpus feed benchmark (SM-T220, three arms A/B/A, 0.2%
identical-arm noise floor, gate 18/18/18 cards):
frame duration P90 -10.7%
frame overrun P90 -17.4%
DrawReactions 114.8 -> 76.7 ms/iteration
For reference, ablating the reaction icons entirely gives frame P90 -13.5%, so this
captures ~84% of the available headroom. It supersedes the shared-VectorPainter
approach (-8.2%), which needed CompositionLocal plumbing and hand-scoping to avoid
cross-size cache thrashing; glyphs are atlas-shared automatically.
Artwork is unchanged: this converts Amethyst's existing vectors rather than
substituting Google's glyphs. Verified on device by pixel comparison -- unconverted
icons are 0-diff, and the converted ones differ only by sub-pixel antialiasing
between the text and vector rasterisers.
Stroked icons are deliberately NOT converted. A glyph outline can only be filled, so
converting Zap (strokeLineWidth 1.2) turned a thin outline bolt into a solid one; the
build script now detects a stroke and skips the icon, leaving Following, Zap and
ZapSplit on their ImageVectors.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1CzYQvWyHfipSW7x3j4Yo
Conflict in DisplayPaymentTargets.kt, where #4040 and this branch changed the
same hand-off path from opposite ends and converged on the same idea.
main extracted a shared PaymentTargetPill and routed every hand-off through one
new paymentTargetUri(target), still backed by the uriFor lambda on
PaymentTargetStyle. This branch had deleted that lambda, moving the scheme
table to commons so the zap picker and the installed-app probe could share it.
Kept main's structure — the pill and paymentTargetUri are the better shape, and
PaymentButton already calls the latter — and backed paymentTargetUri with
PaymentTargetTypes.uriFor. One hand-off entry point, one scheme table, no
behaviour change on either side.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
OnchainSection kept its own composable-local UTXO fetch and sum, so after
the zap picker gained a cached balance there were two paths to the same
number. Point the card at the shared account state instead.
- OnchainWalletState gains a `status` flow (UNAVAILABLE / LOADING / READY
/ ERROR) so the card keeps its four display states, and a `totalSats`
for the figure it shows (settled + mempool, matching what it summed
before). ERROR is reported only when there is no snapshot at all: once
a balance is known, a failed refresh keeps the last good number on
screen rather than blanking it.
- The card's private BalanceState enum is gone; it renders the model's
status directly.
Opening the wallet screen now warms the balance the zap chips read, and
a send invalidates the snapshot for both surfaces at once.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015jsupTzY576d2iWbqbzH4k
Two gaps from moving the toggle to the Zaps screen.
Settings search indexes the catalog entry's keywords, not the screen's
contents, so after the move nothing matched "venmo", "payto" or "paypal" — the
words someone would actually type to find this. Widened zaps_search_keywords.
ZapAmountChoicePopupPreview exercises four rail combinations but never
payToTargets, so the new chip had no preview at all in a file that otherwise
covers this component carefully. Adds a row with two hand-offs; since no app
resolves in a preview it also exercises the brand-coloured glyph fallback,
which is what a device without the app installed shows.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
Conflicts:
- DisplayPaymentTargets.kt: main's model.User import superseded by the
commons User import; setText import dropped (main's rewrite no longer
uses it).
- strings.xml: kept only main's genuinely new notify_block_relay key;
thread_title and send_the_seller_a_message already migrated to commons.
Also re-added the R import in NotifyRequestDialog.kt for the new
R.string.notify_block_relay usage.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
It was on Profile settings, under a section literally titled "profile
sections" (badges, app recommendations, zap-received feed, followers feed).
The toggle has no profile-visible effect at all — it decides whether a chip
appears in the zap picker — so it was filed by association with
showOnchainWallet, which sits there for the same weak reason but at least puts
a chip on profiles.
The Zaps screen is where it belongs: it is the zap picker's configuration
surface, reached from the picker's own "change amount" action, and it already
renders previewRailsFor for the very chip row this setting adds to.
Wired through UpdateZapAmountViewModel rather than applied instantly, because
that screen is a Save/Cancel form: load() reads it, hasChanged() reports it,
sendPost() commits it and cancel() reverts it. An instant-apply switch on a
form with a Cancel button that did not revert it would read as a bug.
Strings move out of the profile_ui_ namespace to zap_payto_*, and the
explainer now states the two things the chip does not do: the other app asks
for the amount, and nothing is published, so the note's zap count is unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
Audit follow-ups to the pill format in the payment-targets dialog:
- The row's three icon buttons left the pill 112dp on a 320dp dialog, which
is exactly the width of the icon + type label: the shortened address was
measured at 0dp and never drawn. The pill already pays on tap and copies
on long-press (same as the profile), so the redundant bolt button goes and
the address gets 45dp on a 320dp dialog, 97dp on a 372dp one.
- Cap the chip label at one line: a long type ("BITCOINCASH") wrapped the
pill to two lines in narrow hosts.
- The dialog handed off to "payto://<type>/<authority>" for every type while
the identical pill on the profile uses the type's own scheme, so the same
pill reached a different app depending on where it was tapped. Both now go
through paymentTargetUri(), which keeps payto:// as the unknown-type
fallback.
- Drop FLAG_ACTIVITY_NEW_TASK|CLEAR_TASK from that handoff: CLEAR_TASK wiped
whatever the wallet app already had open, and the dialog runs from an
activity context that needs neither flag.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01We35qZJEhp8bSbPUHo6Koc
Audit of the previous commit. Four findings, all reachable in normal use.
The probe was stricter than the hand-off it predicts. It carried
CATEGORY_BROWSABLE and queried with flags=0, while the hand-off goes through
startActivity, which implies CATEGORY_DEFAULT and nothing else.
IntentFilter.matchCategories returns the first category on the *intent* the
filter lacks, so each category added to a query narrows the match: any app
declaring only DEFAULT was invisible to the probe and its chip was hidden even
though tapping it would have worked. The probe now carries no category and uses
MATCH_DEFAULT_ONLY, resolving exactly the set startActivity would. The
<queries> entries lose the category for the same reason — there it narrows
package visibility itself.
The chip snapshotted the probe result with remember(target.type), so it never
saw the probe finish. A web target is offered before any probe runs, since any
browser opens https, so that snapshot pinned the fallback glyph and the real
app icon could not appear until the picker was closed and reopened — the Venmo
and PayPal case the icon exists for. It now collects the availability flow.
peek() built the recipient's target list eagerly, walking the kind:10133 tag
array on every call, including the one-tap zap path with the feature switched
off. selectFor now takes it as a lambda behind the cheap gates, pinned by a
test that counts reads.
warm() runs on each picker open so resolution stays fresh when the user
installs an app and comes back, but it also re-read each APK's resources and
re-rasterised its icon to answer the same question. Decoded icons are now kept
across warms, keyed by package and size, and the browser control probe only
runs when a web target is actually present.
Also: the icon failure log kept its message but dropped the throwable; it now
passes it. Removes the unused clear().
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
The button had no test behind its central claim. NotifyRequestsCacheTest covered
the prompt bookkeeping and BlockedRelayFilteringClientTest the enforcement, but
nothing exercised BlockedRelayListState.addRelay — the step that decides what the
published block list contains.
That step is worth pinning because BlockedRelayListEvent.updateRelayList replaces
every relay tag with what it is handed, so addRelay must read the current list
before writing. Get it wrong and the second tap silently wipes the first block —
a data-loss bug the UI gives no sign of, since the dialog closes either way.
Drives the real thing: a real keypair, real NIP-51 encryption, LocalCache, and
the production decryption cache. AccountSettings is stubbed only because it reads
Resources.getSystem() for spoken languages, which is null outside an Android
runtime; Looper is mocked as the neighbouring LocalCache tests already do.
Covers: the list is created on the first block; the second block keeps the first;
re-blocking is idempotent; and the relays stay in encrypted private tags, never
public ones — a leak there would publish which paid relays the user walked away
from. Confirmed the wipe case fails when addRelay is reverted to writing only the
new relay.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U2GsUAheZmAXv6vk4m7m9T
When the sender and the note's author both publish a payment target of the
same protocol, the zap picker now offers a chip that hands off to the app that
owns it. Gated on a new opt-in setting (default off), on the note carrying no
NIP-57 zap split, and on an installed app actually resolving the URI.
The chip carries no amount. Zap presets are sats and there is no rate anywhere
in the repo to turn them into a Venmo or IBAN figure, so no number is shown and
no RFC-8905 amount= is emitted; the receiving app asks. It ends in OpenInNew
rather than the send arrow every amount segment uses, and long-press copies the
authority instead of opening the sat-preset editor, which would mean nothing
here. Nothing is published, so the zap counter does not move and none of the
zap progress state is touched.
It renders beside the amount pills rather than inside each pill's rail toggle.
Carrying no amount, it would otherwise repeat identically once per preset, and
keeping it out of the toggle leaves ZapRail a plain enum instead of forcing it
into a data-carrying sealed interface.
Discovery needs the new <queries> entries: targetSdk is 37, so Android 11+
package visibility returns nothing from queryIntentActivities for an undeclared
scheme, and the chip would be invisible on every modern device. Unknown types
all fall back to payto://<type>/<authority>, so one payto entry covers the
open-ended tail of the vocabulary. Specific <intent> filters, never
QUERY_ALL_PACKAGES.
The mark is the resolved app's own icon, from the same ResolveInfo the probe
already holds, decoded once at the chip's size during the warm step and masked
round the way a launcher draws it. It falls back to the brand-coloured glyph
paymentTargetStyleFor already assigns when the hand-off would open a chooser or
merely a browser: https targets resolve to any browser, so a control probe
against an unownable host separates a real app handler from Chrome.
The availability cache is keyed on scheme plus host, not scheme, because an app
may declare host="iban" and a scheme-only hit would wrongly claim payto://upi
is handled. It is warmed from the sender's own target list when the picker
opens, so it is bounded by how many ways the user says they can be paid rather
than growing with the feed, and it is a StateFlow because a plain map write is
invisible to Compose.
Shared plumbing moves to commons: PaymentTargetTypes now owns the alias and
scheme tables that were duplicated inside the profile UI file, and
PayToRailMatcher holds the matching and the gate decision as pure functions,
free of Note, Context and the availability singleton so the gates are testable
on their own. RailCapability gains a defaulted payToTargets, and peek gains
defaulted parameters so zapClick's one-tap fast path stays Lightning-only.
PaymentTarget becomes a data class: without value equality it compares by
identity, which breaks list keys and dedupe.
25 new tests in commons; amethyst, commons and quartz suites all pass.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
Replaces the onBlocked callback parameter added to AccountViewModel.blockRelay
with the pattern the rest of the app already uses for "sign, then clean up the
UI only if it worked" — accountViewModel.launchSigner { … } around both steps at
the call site, as in AwardBadgeScreen's launchSigner { sendPost(); popBack() }.
There are 187 such direct uses in ui/, so a bespoke callback parameter on the
ViewModel was the odd one out.
Behaviour is unchanged: blockRelay was itself defined as `= launchSigner { … }`,
so the press already ran inside one and the dismissal already waited on a
successful signature. This just drops a layer and the now-unused ViewModel
method rather than leaving dead API behind.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U2GsUAheZmAXv6vk4m7m9T
The zap picker offered the on-chain rail for every preset at or above
MIN_ONCHAIN_ZAP_SATS regardless of what our own Taproot address held, so
a user with an empty (or merely small) on-chain wallet was shown amounts
that could only end in an insufficient-funds failure at send time.
Gate the rail on the sender's balance:
- OnchainZapBuilder.maxSpendableSats() answers "what is the largest
amount this UTXO set can actually pay?" against the exact greedy
selection the builder uses — prefix sums of the value-descending list,
plus the last-chance no-change branch — so an amount that clears it is
one build() will not reject. Tests pin the boundary: max is buildable,
max + 1 throws.
- OnchainWalletState caches that figure per account (one explorer round
trip per minute at most, failures back off too, invalidated after a
spend), computed at the fee rate the send dialog defaults to.
- RailCapability.canPayOnchain() folds the three gates — recipient
payable, amount over the minimum, wallet can cover it — into one place
the chip calls. An unknown balance stays optimistic: a flaky explorer
should not silently remove a payment option.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015jsupTzY576d2iWbqbzH4k
Follow-up to the Block Relay button, from a review of that change.
Dismiss-before-block. The button called blockRelay() fire-and-forget and then
dismissed every prompt from the relay. reportSignerErrors swallows a refused or
timed-out signature (ManuallyUnauthorizedException, TimedOutException,
CouldNotPerformException) with a log line and no toast, so rejecting the signer
prompt closed the dialog, left the relay unblocked, and gave the user nothing to
tell them so — and the prompts were in the dismissal set for good. The dismissal
now runs from a callback that only fires after account.blockRelay() returns;
leaving the prompt up is the feedback when it doesn't. This also shrinks the
race window, since sendMyPublicAndPrivateOutbox consumes the kind-10006 into
LocalCache synchronously before publishing.
Non-atomic cache mutations. NOTIFYs are filed from the relay's socket coroutine
while dismissals run from the UI, so addPaymentRequestIfNew's `value +=`
read-modify-write could drop one of two concurrent edits, and dismissAllFrom
read the pending set before updating it — a prompt arriving in between was
removed without ever being recorded as dismissed. Both now go through
update/getAndUpdate.
Also avoids a copy on a hot path in BlockedRelayFilteringClient: every REQ,
COUNT and publish went through filterKeys/minus whenever the block list was
non-empty, allocating a full copy of the targets just to reproduce them
unchanged. A blocked relay is by definition one the app has stopped aiming at,
so it now checks whether any target is actually blocked before copying. This
matters more now that blocking is one tap from the dialog rather than a trip to
the settings screen, so non-empty block lists become the norm.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U2GsUAheZmAXv6vk4m7m9T
Answers whether the chip can wear the icon of the app it hands off to: it can,
and the codebase already does it. ExternalSignerButton renders installed NIP-55
signers from loadLabel/loadIcon off getExternalSignersInstalled, which is the
same queryIntentActivities call discovery already makes, so the ResolveInfo we
keep to answer "can anything open this?" also carries the mark and the label.
Argues against bundling brand logos instead: a trademark question rather than a
licence one, an unbounded free-text type space no bundled set can cover, and a
call the codebase already made by pairing brand colours with a generic wallet
glyph. Keeps that pairing as the fallback.
Records four things the existing precedent gets away with and this would not:
loadIcon is I/O and belongs in the off-main warm step caching an ImageBitmap
rather than in a recomposing item; adaptive icons need sizing and a round mask
or the logo floats in launcher bleed at 18dp; a multi-handler URI resolves to
ResolverActivity and has no single app to name; and a full-colour raster cannot
join the tinted glyph scheme.
Promotes the https control probe from a later refinement into v1: it never
gated the chip, but without it a browser-only Venmo target resolves to Chrome,
and a Chrome icon on a Venmo chip is worse than no icon.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
A paid relay answers a rejected AUTH with a NOTIFY asking for payment, and
until now the only thing the prompt offered was "OK" — which dismisses it and
lets the same relay ask again on the next AUTH. The user's actual intent
("stop talking to this relay") had to be carried out by hand on the Blocked
Relays screen.
Adds a "Block Relay" action to the dialog that publishes the relay into the
account's NIP-51 kind:10006 blocked list. Enforcement is the existing one:
BlockedRelayFilteringClient strips blocked relays from every REQ, COUNT and
publish, so the pool drops the socket once the subscriptions that wanted the
relay are recomputed.
- BlockedRelayListState.addRelay / Account.blockRelay add one relay without
rebuilding the list from a caller-held snapshot — the kind-10006 list is
shared across clients and may have grown since.
- NotifyRequestsCache.dismissAllFrom drops every queued prompt from the
blocked relay, not just the one on screen: a paid relay files one NOTIFY per
rejected AUTH, so dismissing them singly would immediately re-open the dialog.
- NotifyCoordinator drops NOTIFYs from an already-blocked relay, closing the
window where frames still in flight could re-open the prompt.
- The button is hidden for read-only accounts, which cannot sign the list.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01U2GsUAheZmAXv6vk4m7m9T
The dialog behind the payment-target button listed each target as a
titlecased type over the full wallet id on a second line. It now renders
the same pill the profile page uses — type icon, tinted type label and
the shortened authority, with long-press to copy the full value.
Extracts that pill as PaymentTargetPill and rebuilds PaymentTargetChip on
top of ProfilePaymentChip, so the profile rail and the dialog (both from
the profile button and from ReactionsRow) share one implementation
instead of duplicating the Surface/Row layout.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01We35qZJEhp8bSbPUHo6Koc
Drops amounts, in-app payment and receipts from the first cut. The chip
carries no number and hands the amount to the external app, because there is
no FX service in the repo to convert a sat preset into a fiat figure.
Adds Intent-based discovery so only protocols an installed app can actually
handle are offered. Records the constraint that decides it: targetSdk 37 means
Android 11+ package visibility returns nothing from queryIntentActivities
without a <queries> declaration, and the current block covers only nostrsigner,
TTS, Health Connect and Tor. One payto entry covers every generic type, since
unknown types all fall back to payto://<type>/<authority>; https targets are
exempt because a browser always resolves them.
Keys the discovery cache on scheme+host rather than scheme, and warms it from
the sender's own target list instead of lazily per post: the symmetry gate
means only protocols the sender declares can ever be shown, so the probe set is
a handful of entries and feed rendering never triggers one. The cache has to be
a StateFlow, not a plain map, or the chip stays invisible until an unrelated
recomposition.
Moves the chip beside the amount pills instead of inside the per-amount rail
toggle: an amount-less rail would repeat identically in every pill, and keeping
it out of the toggle leaves ZapRail a plain enum, deleting the sealed-interface
refactor and its recompose-key breakage.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
Design doc for surfacing a NIP-A3 payment target as a selectable segment in
the zap amount chip when the sender and recipient share a pay-to protocol and
the note carries no NIP-57 zap split.
Anchors the design on what is already in the tree: kind:10133 already rides
in UserMetadataForKeyKinds beside kind:0, so no new subscription is needed;
RailCapabilityResolver.peek already computes the zap splits the gate needs;
and UnifiedZapAmountChip is already a segmented rail toggle.
Calls out the constraints that shape it: there is no FX service in the repo,
so the handoff segment carries no sat amount and emits no RFC-8905 amount=;
lightning/bitcoin payto types must map onto the existing rails rather than
render a second Bolt icon; ZapRail has to become a sealed interface to carry
which target; and the handoff produces no kind:9735, so it must stay out of
the zap state machine.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JXKZeV6FNhXF9BBjgEtfvS
Two small independent fixes found while profiling the feed.
Splash colour
-------------
The system builds the launch splash from the manifest theme *before the process
starts*, resolving it against the system light/dark configuration. The in-app
ThemeType can be pinned to the opposite, so the splash flashed the wrong colour
before the UI appeared: white before a dark UI for someone who pins DARK on a
light system, black before a light UI for the reverse. No app-side code can fix
that first frame — it is painted before onCreate runs.
Pinning `windowSplashScreenBackground` to the brand colour already used for the
status bar makes the splash read as intentional in every combination. Only the
API 31+ splash attribute is set; `windowBackground` is deliberately left alone,
so the window stays opaque (clearing it measured ~17% worse at frame P90,
because a non-opaque window costs SurfaceFlinger the chance to skip the layers
beneath it) and pre-31 behaviour is unchanged.
Verified on an SM-T220 by recording a cold start and sampling frames: launcher
-> purple splash (63,12,181 ≈ #3700B3) -> dark UI, with no white frame.
Night-mode writes
-----------------
`AmethystTheme` set `UiModeManager.nightMode` to force the device night mode for
a pinned DARK/LIGHT theme. Changing it requires MODIFY_DAY_NIGHT_MODE, which the
manifest does not declare, so the call silently no-ops for a normal app — while
running a device-state write from inside composition on every recomposition of
the theme. The pinned choice already takes effect through the colour scheme
selected immediately below, which is what was actually doing the work.
Audit finding, and a real defect in the striped table two commits back.
A striped hash table is only sound when the stripe is a function of the bucket.
lockFor picked bits 16-19 of the hash while the bucket index used the low bits,
so the 16 locks did not partition the table: two keys could share a bucket while
holding different locks, and two writers would then read the same chain head and
both publish over it. One insert silently disappears while entryCount counts
both. The same window loses an overwrite, and loses entries through remove's
chain rebuild. That is precisely the class of bug this work set out to remove
from the copy-on-write version it replaced.
Stripe now comes from `hash and (STRIPES - 1)`. Because STRIPES and every
capacity are powers of two with STRIPES <= capacity, those are exactly the low
bits of the bucket index, so same bucket implies same stripe at every size. It
stays derived from the hash rather than the capacity, so a key keeps its stripe
across a resize, which is what lets growTable exclude writers by taking all of
them. INITIAL_CAPACITY is now defined as STRIPES so raising one cannot silently
break the invariant.
That definition also fixes a memory regression the audit caught: the table
allocated 1024 slots eagerly, about 8 KB, per instance. LargeCache is not only
the one big LocalCache — EphemeralRoom, RelaySession, PoolRequests and others
build one per room, per connection and per subscription set, so a client holds
hundreds that stay nearly empty. An empty instance goes from ~8 KB to ~970
bytes. Growth is geometric, so a table that does fill to 100k pays the same ~2n
node rebuilds either way; re-measuring the shipped code confirms it (fill 16ms,
overwrite 4ms, reads 1ms, 20 scans 16ms, mixed 86ms, 1 GC — unchanged within
noise). The KDoc table is updated to those numbers.
Adds LargeCacheStripingTest, which builds keys that share a bucket while
differing in bits 16-19 and drives four workers at them behind a start barrier,
with few enough buckets that chains grow long and each insert holds its lock for
a while. It is documented for what it is: a stress test of the concurrent
same-bucket path, not a deterministic reproducer — it did not fail against the
broken striping in the runs attempted, which makes that race rare rather than
absent. The fix rests on reading the stripe selection against the bucket index,
not on a red test.
Remaining known cost, noted in the KDoc rather than changed here: those ~970
bytes are nearly all the 16 PlatformLocks, two objects each. Folding them into
one AtomicIntArray would reach ~250 bytes, but hand-rolling the spin wants its
own review rather than a change on the way to merge.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HxQ1QuyzSkR38iFHbREjoS
Introduces decideNavigationStyle/decideNotificationPanel with the shape
rule from #4024, plus unit tests for the whole behaviour table. Not wired
up yet - rememberScreenLayoutSpec is unchanged, so behaviour is identical.
PoolEventOutboxScaleTest tripped its 5x ratio on the macos-latest
runner: a single 2k-publish timing window is one GC pause away from a
false positive on a shared 3-core VM - the same GC-dominance reasoning
cd344ac0 used when it retired this assertion on Apple targets. Each
side now takes the minimum of three consecutive windows, which filters
stop-the-world pauses while keeping the intent: a real per-entry cost
slows every window, a pause only one.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
`updateTransition` and `AnimatedContent` allocate a Transition, its animation
list and its seeking state on *first* composition — but first composition has
nothing to animate, because target and initial state are the same value. In a
feed that is waste: every card scrolled in built six of them, and during a scroll
essentially none ever ran, since reaction counts and icons do not change in the
second a card is on screen.
`DeferredCrossfade` and `DeferredAnimatedContent` render the plain content until
the target actually moves, then build the transition seeded at the *original*
value via `MutableTransitionState` and immediately re-target it — so the first
real change still animates exactly as before, and later changes animate through
the now-live transition normally. The existing `isPerformanceMode()` branch,
which genuinely drops the animation, is untouched and still takes precedence.
Measured on an SM-T220 against a frozen corpus served by a local relay (a real
capture: 105 notes, 68 profiles, 501 reactions, 75 boosts, 22 zaps), interleaved
with the unmodified build, two runs per arm:
frame duration P90 27.53 -> 26.90 -2.3% (baseline spread 0.1%)
frame overrun P90 21.65 -> 17.44 -19.4% (baseline spread 6.3%)
frame duration P50 -1.1% (inside a 1.7% spread)
Modest at the frame level by nature: on this device the main thread sits blocked
in `postAndWait` on the RenderThread for roughly two-thirds of every frame, so
composition savings largely do not surface. Removing 24 flow subscriptions per
card, every clickable, or every counter each moved `postAndWait` by only ~2%.
`DeferredAnimationTest` drives the clock manually and asserts the outgoing and
incoming content coexist mid-transition, which only a running animation does; a
regression turning the deferral into a snap fails it.
Both native targets delegated UrlEncoder to
net.thauvin.erik.urlencoder.UrlEncoderUtil, which implements RFC 3986
percent-encoding. The JVM/Android actual is java.net.URLEncoder/URLDecoder,
which implements application/x-www-form-urlencoded. Different specifications,
and the difference was observable:
JVM/Android UrlEncoderUtil
encode(" ") "+" "%20"
encode("*") "*" "%2A"
decode("a+b") "a b" "a+b"
This is not cosmetic. encode() builds strings that leave the device —
TorrentEvent puts it in magnet links, Nip54InlineMetadata in inline metadata,
Nip47DeepLink in the callback/appname/value parameters of NWC deep links — so
Android and iOS emitted different bytes for the same title. The decode row is
worse: a link written by Android carries '+' for its spaces, and reading it on
iOS or desktop-native gave back literal plus signs, silently, with no error.
Replaced with one UrlEncoder.native.kt in nativeMain, shared by linuxX64 and
every Apple target, matching URLEncoder/URLDecoder exactly — unreserved set is
alphanumerics plus -_.* (note '*' survives and '~' does not, the opposite of
RFC 3986), space to '+', uppercase %XX of UTF-8 bytes otherwise, and '+' back
to space on the way in. Escape runs are encoded and decoded as runs so surrogate
pairs and multi-byte sequences survive, and both directions short-circuit on a
string with nothing to change, as the java.net pair does.
UriParser.linux now delegates to UrlEncoder.decode rather than carrying its own
copy of the decoder added in the previous commit.
The new UrlEncoderTest lives in commonTest, so it pins every target against the
JVM's answers — it is what found all three rows above, by passing on jvmTest and
failing three of ten on linuxX64.
net.thauvin.erik:urlencoder-lib had no other user and is removed from both
source sets and the version catalog.
One deliberate edge difference from the JVM, documented at the call site: an
unpaired UTF-16 surrogate encodes as %EF%BF%BD rather than %3F.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HxQ1QuyzSkR38iFHbREjoS
RelayAuthPolicyEverywhereTest (from #4033) resolved UserAuthChoice,
RelayAuthPermissionLedger, RelayAuthSessionGrants and
InMemoryRelayAuthPermissionStore via same-package visibility; those
classes moved to commons relayClient.auth on this branch, so the merged
tree needs explicit imports.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Two findings from an audit of this PR's own diff.
BUG. The kind 2473 branch dropped the `alt` tag whenever commonName()
parsed one out of it, on the reasoning that the alt is only Birdstar's
boilerplate wrapper around the two species names. But commonName()
matches a PREFIX and then cuts at the last " (", so a publisher can
write anything after the parenthetical and it parses just the same:
"Bird detection: Purple Gallinule (Porphyrio martinica) at Lake
Merritt, 7am" yielded "Purple Gallinule" and the tail reached NO role,
while indexableContent() still carried it. That is exactly the drift
against the flat form this PR exists to remove, introduced by the PR
itself. The alt now always reaches the summary tier: the duplicate it
repeats there lands in the weakest role, whereas the drop cost recall
outright.
PERFORMANCE. Extraction runs once per stored event and per full
reindex, and the funnel allocated a throwaway list per role whether or
not the role had anything in it. The single-value tiers() overload
wrapped each of its three values in a list only for cleanAll() to build
another; cleanAll() allocated even when every value was null; the
hashtag role called hashtags(), which allocates unconditionally, on
every event including the great majority carrying no `t` tag; and
locationValues() allocated a list per event to hold, almost always,
nothing.
Both overloads now end in one build() -- so hashtags and locations are
still filled in a single place no branch can forget -- and each
collector allocates lazily. Measured with getThreadAllocatedBytes over
1M extractions, JIT-warm:
kind 1, no tags 160 -> 40 B/event
kind 1, six tags 528 -> 168 B/event
kind 30023 title+summary 272 -> 88 B/event
The hash of every extracted value is unchanged across the A/B, and the
guard added before hashtags() is HashtagTag.parse's own acceptance
test, so it cannot skip a tag the accessor would have returned.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GznRZiv3zS7V9c2QQ9aMk9
The merge of main resurrected ~23.4k locale entries for migrated keys
(Crowdin's full sync rewrote regions git couldn't see as conflicting)
and re-added 14 migrated keys to the app default. Reconciled: every
locale entry whose key lives in commons moved there, keeping Crowdin's
fresher text (23,113 replacements); duplicate default keys removed from
app res, except podcast_value_for_value which legitimately lives in
both trees (a toastManager.toast(Int) call site needs the Android id).
RelayAuthPromptHost keeps main's relabeled-button behavior with mixed
addressing - new keys via R.string, migrated ones via Res.string - and
its RelayAuthPrompt/UserAuthChoice imports now point at the commons
relayClient.auth home. Orphan gate green, both apps compile.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
The 78 failures on this target were not 78 unimplemented actuals. Two root
causes accounted for all of them.
TestResourceLoader.linux was a TODO(), so every vector-driven suite failed
before it reached any production code: the full MLS interop set, NIP-44, the
NIP-01 hint indexer, the SQLite store's large-DB tests and the Bolt12 payer
proofs — 69 tests. Implemented over platform.posix (linuxX64 has no Foundation
for the Apple actual's NSData path), resolving against the same
TEST_RESOURCES_ROOT that build.gradle.kts already exports onto every
KotlinNativeTest task. The read is one ftell-sized allocation filled by fread,
so a vector file costs exactly one ByteArray — less than the JVM actual's
bufferedReader().readText(), which grows a StringBuilder as it goes.
UriParser.linux never URL-decoded query values or fragments, though the JVM
actual runs both through URLDecoder.decode(.., "UTF-8"). Every NIP-47 failure
was one symptom of that: relay=wss%3A%2F%2Frelay.damus.io reached
RelayUrlNormalizer still percent-encoded and came back "Invalid relay Url" (6
tests), and the deep-link round trips compared an encoded string against a plain
one (3 tests). Added a decoder matching URLDecoder where the behaviour is
observable — '+' to space, a run of consecutive %XX decoded as one UTF-8
sequence, malformed escapes throwing IllegalArgumentException — with the same
short-circuit URLDecoder makes, returning the original instance when there is
nothing to decode.
Two other divergences fixed while there: getQueryParameter returned an empty
list where the JVM returns null for an absent parameter, and the query string
was re-split on every call rather than parsed once into a lazy map, so a URI
read for four parameters was parsed four times.
With those, linuxX64Test is 3495 tests, 0 failures, so the CI leg added
alongside the LargeCache work drops its cache-package filter and runs the whole
:quartz suite.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HxQ1QuyzSkR38iFHbREjoS
Audited all ~70 branches of SearchFieldExtractor.base() against the file's
own stated invariant -- "each explicit branch splits exactly the accessors
that kind's indexableContent() concatenates" -- for all 133 searchable
kinds. Nothing tested it, and it had drifted three ways. The full table is
in the PR description; this commit is what it turned up. 19 kinds gain a
branch.
1. A title in the wrong tier. 17 kinds fell through to the catch-all, which
dumps the whole indexableContent() into the body role, so their titles
could never reach the title band a weighted backend gives one. The
marketplace family (30017/30018/30019/30020) and the Podcasting 2.0 pair
(30054/30055) are the sharpest -- a stall name and an episode title are
what people actually type. Kind 9002 is the tell-tale: it edits the very
metadata kind 39000 publishes, and 39000 had a branch while 9002 did
not. Also branched: 1010, 1065, 1068, 1163, 1985, 2473, 6969, 12473,
38192, 38383. Every kind still falling through is now body-only -- its
whole searchable text really is a body (a chat message, a zap comment, a
git patch, a DVM prompt) -- so no title is left stranded.
2. A role the branch forgot. hashtags and locations are filled systemically
by the tiers() funnel, but websites is per-branch, and four kinds with a
public URL were not passing one: GitRepositoryEvent (clones(), the URL
most people would search a repo by), MeetingSpaceEvent (endpoint(), the
same `streaming` tag kind 30311 already carries), and both nSite kinds
(source()). Image, icon and infrastructure URLs stay out on purpose.
3. Drift against indexableContent(). Six kinds concatenated their `t` tags
INTO the flat blob while the funnel also carried them as hashtags, so
the same words were indexed twice, in the weakest role -- exactly the
shape most likely to skew a term-frequency ranker. Fixed by their new
branches (1111, 1311, 9002, 30018, 30020, 30054), the same treatment
InterestSetEvent and ContactCardEvent already had.
Two of those branches avoid creating the same duplication they remove:
kind 2473's `alt` is Birdstar's boilerplate wrapper around the two species
names, so it is indexed only when commonName() proves it is NOT that
shape; kind 12473 is a life LIST, so its unbounded species collection sits
in the secondary tier rather than claiming the title band once per bird.
Also writes down the PROFILE XOR TIERED contract in the IndexableFields
KDoc. The sealed type enforces it, and weighted backends already depend on
it: a ranker that scores the two role groups independently and sums them
stays correct only while no document can answer from a naming column in
each group. A shape filling Profile.name and Tiered.primary at once would
claim the top band twice -- measured downstream at ~260 000 against the
~130 000 a whole-field title match earns, i.e. one word per column
outranking a document that IS the query. Saying so makes a future
both-shapes kind a decision with a known cost rather than an accident.
This is derived data: consumers must re-run
IEventStore.reindexFullTextSearch() after upgrading.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GznRZiv3zS7V9c2QQ9aMk9
The HAMT was the wrong structure for this workload. LocalCache fills on the
order of 100,000 entries in a few seconds, and a persistent map allocates a
fresh path of ~4-5 nodes for every write — including overwrites, which change
no structure at all — then discards it. Over a 100k fill plus scans that is 24
GC cycles.
Replace it with a chained hash table: lock-free reads, striped-lock writes.
This is ConcurrentHashMap's shape, which Kotlin/Native does not ship. Adding a
key prepends one node; overwriting one is a single volatile store into the node
already there, allocating nothing; a scan walks the buckets in place. Chain
nodes hold `next` immutably so a reader never sees it change, which is what lets
reads take no lock at all — structural edits publish a new bucket head, and a
resize rebuilds nodes rather than relinking them.
Measured on linuxX64 (-opt), 100,000 String keys of event-id length:
fill overwrite reads 20 scans mixed GCs heap
HAMT + CAS 70 78 6 117 676 24 67MB
lock + HashMap 13 6 3 71 1197 36 51MB
striped 15 3 3 13 64 1 43MB
"mixed" is a full fill with a whole-table scan every 1000 writes — the shape
LocalCache actually has. Copy-on-write, the original, is off the scale: 20k
entries alone took 18s to fill.
Every bulk operation now walks the table directly instead of a snapshot, so
scans allocate nothing beyond the result and caller lambdas run outside any
critical section — a LocalCache predicate that reaches back into the cache
cannot deadlock, and there is no ConcurrentModificationException window.
getOrCreate and createIfAbsent are now the JVM actual's bodies verbatim over the
same putIfAbsent contract.
Honest difference from the JVM actual: ConcurrentSkipListMap is fully
non-blocking, whereas writers here block writers hashing to the same one of 16
stripes, for a bucket walk of a few nodes. ConcurrentHashMap makes the same
trade. Readers block for nothing.
Adds LargeCacheCollisionTest, which forces every key into one bucket so the
chain paths — in particular removal, which clones the nodes ahead of the target
onto its tail — run deterministically rather than only on a chance collision.
ConcurrentHashCache.linux moves onto the same table.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HxQ1QuyzSkR38iFHbREjoS
Relabelling the prompt's buttons collided with the confirmation behind
them: with the remember switch on, the prompt says "Always log in" for one
relay while the confirmation for "Always, all relays" said "Always log in"
too, one tap apart and meaning every relay. Same for "Never" against "Never
log in". The confirmation now echoes the link that opened it — "Always, all
relays" / "Never, all relays" — so the scope is stated exactly where the
account-wide answer is committed. No new strings.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013NTYFnqWcwLVPNNSr5kusd
Follow-up to the previous commit, which fixed the O(n) write by putting a
PlatformLock around a mutable map. That traded one problem for another: the
JVM/Android actual is a ConcurrentSkipListMap, where readers never block and
writers publish with a CAS, and a global lock is a step down from that — worse,
the linux PlatformLock is a spin lock, so a reader could burn a core waiting on
a writer that had been descheduled.
Keep copy-on-write's shape instead — an immutable map behind an AtomicReference,
which is what made reads free in the first place — and fix the two things that
were actually wrong with it. Copying a LinkedHashMap is O(n); a HAMT's putting()
shares structure and copies only the path to the changed key, O(log32 n). And
the read-copy-write was not a CAS loop, so concurrent writers dropped each
other's entries; now they retry.
Reads (get/containsKey/size/keys/values) are a single atomic load plus a lookup.
Bulk operations iterate that same immutable map with no copy, so caller lambdas
run outside any critical section and a LocalCache predicate that reaches back
into the cache cannot deadlock. Writes are a CAS retry.
This is already the house pattern for shared mutable state in commonMain —
FilterIndex and nip86 BanStore hold state in one AtomicReference over persistent
collections and mutate it with the same loop — and kotlinx-collections-immutable
is already a quartz commonMain dependency.
Measured on linuxX64 (-opt, ms per loop), vs copy-on-write and vs the lock
variant this replaces:
n=20,000 fill reads 20 scans mixed
copy-on-write 17,949 2 13 25,278
lock+HashMap 1 0 12 35
HAMT+CAS 14 0 19 28
n=200,000 fill reads 20 scans mixed
lock+HashMap 44 9 177 6,736
HAMT+CAS 197 12 237 2,486
Write-only, the lock wins ~4x. But LocalCache interleaves full-cache scans with
arriving events, and there the lock must rebuild an O(n) read snapshot per write
epoch: it loses by 2.7x at 200k. So the non-blocking design also wins the
workload that matters.
ConcurrentHashCache.linux gets the same treatment; iteration order becomes hash
order (as on Apple) rather than insertion order. Nothing depends on it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HxQ1QuyzSkR38iFHbREjoS
With the switch on, "Not now" wrote a permanent DENY and "Log in" wrote a
permanent ALLOW while both still read as one-off answers. The switch is the
scope of the answer, so the buttons now state the answer they actually
give: "Never" and "Always log in". The refusal takes the error colour with
it while the switch is on, which is the weight the removed red "Never
allow" button used to carry.
This closes the mis-tap the switch's new binding opened: flipping it for
"log in", then changing your mind and pressing what still said "Not now",
blocked the relay for good with nothing on screen saying so.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013NTYFnqWcwLVPNNSr5kusd
LocalCache's linuxX64 store kept a LinkedHashMap inside an AtomicReference
and replaced it wholesale on every write, so each put was O(n) in the size
of the cache and filling it was O(n^2). It was not thread-safe either: the
read-copy-write was not a CAS loop, so concurrent writers silently dropped
each other's entries.
Replace it with a mutable map guarded by PlatformLock plus a lazily rebuilt
read snapshot. Point operations (get/put/remove/containsKey/size) are O(1)
under the lock; bulk operations run against a point-in-time copy rebuilt at
most once per write epoch, which also keeps caller-supplied lambdas out of
the critical section — PlatformLock is not reentrant here and LocalCache
predicates call back into the cache.
Two behaviour fixes fall out of matching the JVM actual's putIfAbsent:
createIfAbsent now reports true only when this call inserted (it previously
returned get(key) != null, which also reported true when another thread had
just created the entry), and getOrCreate publishes atomically.
ConcurrentHashCache.linux gets the same treatment. Its only caller,
CachingEventDecoder, writes once per event arriving from a relay, so the
per-write map rebuild was the worst-placed copy of the three.
None of this was caught because no CI job compiled or ran linuxX64. Add
LargeCacheTest to commonTest as a cross-target contract for the ~40 methods
each actual reimplements by hand, a linuxTest suite covering the concurrency
this actual now has to get right on its own, and a CI leg that runs both on
Linux Native.
That leg is scoped to the cache and concurrency packages: the full
linuxX64Test suite is 3,490 tests with 78 pre-existing failures, nearly all
TODO() stubs in linux actuals that were never written (MLS crypto, the
SQLite driver, NIP-44, Bolt12). Filling those in is its own project; the
filter keeps the job meaningful and green, and widening it later is one line.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HxQ1QuyzSkR38iFHbREjoS
Audit of the two commits before this one turned up two ways the new
"Always/Never, all relays" answers could be given and not take effect.
A prompt's answer window is 60s from the dialog appearing, and the
confirmation dialog spends it: a user who reads the warning, thinks, and
confirms past the minute hits a resolved deferred, where complete() is a
no-op. The AUTH was already lost at that point — fine, the socket cannot
wait — but the *setting* was lost with it, silently, which is not. The
policy write moves to AuthCoordinator.applyPolicyEverywhere, called by the
prompt the moment the user confirms; the answer path calls the same
function, so there is still one writer and it is idempotent. A confirmation
that lands late now still sets the policy, and the relay's next challenge
is answered by it.
The other one: prompts queued behind the dialog were decided before the
policy existed, so "all relays" was immediately followed by a question
about relay B. They are now answered with the same choice. That needs
markShown() as well as respond() — an unshown prompt is parked in the
five-minute queue-wait window and does not read an answer dropped into its
deferred until that window ends, which would have left a relay
unauthenticated for five minutes after the user answered for it.
RelayAuthPromptBusTest pins the timing; it fails at 300000ms without the
markShown.
Also retires the comments in the ledger, Account and the resolver that
still explained a DENY as the "never allow" button, which no longer exists.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013NTYFnqWcwLVPNNSr5kusd
PoolEventOutboxScaleTest failed on iosSimulatorArm64. The outbox is not at
fault: on Apple targets LargeCache wraps charlietap's CacheMap, whose
LeftRight `mutate` applies each write to both of its two maps under a lock.
That is O(1) per put with no copying, so the quadratic this test exists to
catch cannot occur there.
What the test actually measures on Kotlin/Native is the GC. It keeps 60k
entries alive on purpose, so the late window runs against a heap ~30x larger
than the early one. A generational collector does not rescan that old
generation on a young collection and the growth stays invisible; Kotlin/
Native's non-generational tracing GC does rescan it, and the ratio reports
the collector instead of the outbox.
Measured on Kotlin/Native (linuxX64, -opt), publishing the same 60k events
into structures that are O(1) per put by construction:
retains nothing ratio 0.51 - 0.80
one HashMap, 60k live ratio 1.93 - 3.39
two HashMaps per put, 60k live ratio 2.28 - 5.21
The last row is the Apple path's actual work, and it crosses the test's 5.0
threshold on a loaded machine — which is how a shared CI runner turns a
healthy implementation red. The first row is the control: same allocations,
nothing retained, curve flat.
So move the timing assertion to jvmAndroidTest, where LargeCache is a
ConcurrentHashMap and a wall-clock ratio is a valid instrument. The guard it
provides is unchanged: reintroducing a copy-on-write map or a per-publish
full scan in this class still fails it. The test body is untouched; only its
source set and its KDoc change.
The relay-set bookkeeping half was platform-independent logic, not a
measurement, so it stays in commonTest as PoolEventOutboxRelaySetTest and
keeps running on every target.
Worth a separate look: linuxX64's LargeCache actual is genuinely
copy-on-write (LinkedHashMap(mapRef.value) per mutation), so it really is
O(N) per put. No CI job runs linuxX64Test today, and the numbers above show
a wall-clock ratio cannot report that reliably anyway.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F4Z1E5JJkYXqZznqVsYex6
"Remember for this relay" was read only by the Log in button. Pressing "Not
now" with the switch on wrote nothing at all — no exception, not even a
session-scoped no — so the same dialog came back on the relay's next
reconnect, while the switch sat there claiming otherwise. The one way to
say "stop asking about this relay" was the red "Never allow" button beside
it.
The switch is now the scope of whichever answer is given, so the two
buttons times the switch are the four per-relay UserAuthChoice values: log
in once or always, refuse once or for good. That makes "Never allow"
exactly "Not now" with the switch on, written twice, so it goes.
Its slot becomes the missing half of the account-wide pair: "Never, all
relays" sets RelayAuthPolicy.NEVER opposite "Always, all relays". Both
confirm first, sharing one confirmation that names the consequence of each
direction — the never side warns that relays will refuse to serve, which is
the part a link label cannot carry. It routes through
Account.changeDefaultRelayAuthPolicy, which drops this run's session grants
along with the flip; a grant left behind outranks the policy, so "never log
in" would have gone on authenticating the relays just answered "log in".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013NTYFnqWcwLVPNNSr5kusd
Root cause of the recurring DesktopBlossomServerListTest CI failures,
finally caught by the diagnostic added last round (flow=[], getter=null,
no verification warning): DesktopLocalCache.addressableNotes holds notes
via SoftReference (LargeSoftCache). Under CI memory pressure a GC evicts
the consumed note between cache.consume() and the state's
getOrCreateAddressableNote(), which then mints a fresh EMPTY note - the
flow can never surface the servers. Production is immune because
BlossomServerListState pins blossomListNote as a field for its lifetime;
the tests just never held a strong reference across that window. All
three tests now pin the note before consuming, and the state test
asserts the event landed before construction so an eviction fails fast
at the source.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
The prompt's bottom row had one standing answer, "Never allow", and a link
out to the settings screen. The opposite standing answer — "just log in
everywhere, stop asking" — was only reachable by finding Settings ▸ Relay
login, so the fast way to stop a run of prompts was to block relays one at
a time.
"How Amethyst decides" is replaced by "Always, all relays", which switches
the asking account to RelayAuthPolicy.ALWAYS and answers the pending
challenge. It is the one action here that writes an account-wide setting,
so it confirms first: the label cannot carry the fact that it applies to
every relay that ever asks, and a mis-tap would reveal that npub to all of
them.
The write lands in AuthCoordinator, not the dialog, because the policy
belongs to the account the prompt named — one socket serves every
logged-in account, so the screen's account is not necessarily that one. No
per-relay exception is stored alongside it: the policy already answers this
relay, and an exception would outlive a later switch back to "decide per
relay". Blocked relays and existing "never" exceptions still outrank it,
which is what the confirmation promises.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013NTYFnqWcwLVPNNSr5kusd
Four were confirmed with throwaway probe tests against the branch.
An HLS master labelled `audio/x-mpegurl` or `audio/mpegurl` was read as a
separate audio track and dropped. Those are two of the four playlist MIMEs
this repo already recognises in isHlsMimeType and MediaItemCache — legacy
aliases naming the manifest format, not a claim about the content. A master
labelled that way lost to a 360p rung; when every entry used it the candidate
list emptied and selection fell through to the poster JPEG, handed to the
video player. The HLS test now precedes the audio test.
withLadderMetadataFrom filled `dimension` from every imeta, poster included,
so a 16:9 thumbnail beside a vertical short produced a 16:9 master and
JustVideoDisplay laid the box out at 16:9. Only entries that could be the
video may describe its shape; the poster still supplies the still image.
isHlsPlaylist treated any declared MIME as authoritative, so `master.m3u8`
served as application/octet-stream — a server default, not a claim — was not
HLS and lost to a correctly labelled low rung.
The metered 480px cap had no fullscreen exemption, so tapping into fullscreen
on mobile data pinned 480p and put a ceiling the quality menu's "Auto" could
not exceed. The cap exists to hold back feeds that autoplay unasked; someone
who tapped fullscreen asked.
The PiP gate skipped the viewport push entirely until isInPictureInPictureMode
turned true, with no retry. Since demoteToCold clears track overrides but not
the viewport, a pooled player kept whatever its previous view pushed if PiP was
never entered (per-app PiP off, no FEATURE_PICTURE_IN_PICTURE). It now caps the
pre-shrink measurement instead of skipping it, so a viewport is always pushed
and can never be a stale full-screen one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQs7TP2WeXNR8SwUNLgmUC
Follow-up to @davotoula's review on #4028. Sizing the ladder to the player
is right on wifi, but it removed the app's only bandwidth lever and put
nothing back: on mobile data a full-width card would pull most of the ladder,
with only the ConnectivityType autoplay gate — which decides whether to play,
not how much to pull — standing between a scroll and the data bill.
Clamp the pushed viewport to a 480px short side while
isMobileOrMeteredConnection is true, preserving aspect so the viewport still
describes the player's shape. It stays one lever at the single setViewportSize
call rather than a policy per call site, and it keeps the "quality
proportional to the player" behaviour on wifi. Connectivity changes do not
relayout, so a LaunchedEffect re-pushes with the last measured size when the
ceiling flips; before the first measurement the existing zero-size guard makes
that a no-op.
Also from the same review: processIntentForPiP calls enterPictureInPictureMode
from composition (PiPFromIntents), so the first layout pass can measure the
activity at full screen before the window shrinks, handing the selector a
full-screen viewport for the opening seconds of a PiP that is a few inches
wide. RenderPipVideo now withholds the push until isInPictureInPictureMode is
true; the shrink relayouts and pushes the real size. The pre-T makeBasic()
path still wants an on-device look.
clampViewportShortSide rounds up so a rounding artifact can never ask for 479
and drop a rung that sits exactly at the cap.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQs7TP2WeXNR8SwUNLgmUC
Review catch from @davotoula on #4028. The selector checked "any HLS entry
without a dim" before comparing declared resolutions, so a dim-less entry
won outright. That reads the wrong shape: the sloppy-publisher case is not
"master without dim, renditions with dim" but the reverse — a master that
declares its top resolution beside a rendition that forgot one. There the
old order picked the single-rung media playlist, which is the exact bug this
selector exists to fix, silently.
Tag order now decides only when no HLS entry declares a dim at all;
otherwise the largest declared dim wins. That fails the other way instead:
worst case we take the top rendition and lose adaptation, never the bottom
one.
Also from the same review: presentation metadata was filled from the
playable candidates only, so a poster published as its own image/* imeta —
which canBeTheVideo() excludes — never reached the chosen entry. Fill from
every imeta, and take an image sibling's own url as the poster when no entry
carries one in `image`, which is where the notification big-picture path
looks.
Restore the rendition diagnostics that went with the old fixed-policy
selector: every viewport push and the rung adaptive selection actually
landed on, against the ladder on offer, under the VideoQuality tag. The
listener is registered only when the trace can be emitted (debug sets
Log.minLevel = DEBUG, benchmark/release ERROR), so the release path keeps
the no-listener-per-player property.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQs7TP2WeXNR8SwUNLgmUC
The [ExtraTranslation] failure that took main red in 1ce583ec92 was not
documented anywhere. amethyst/src/main/res/CLAUDE.md and the
find-missing-translations skill both mention the lint rule, but only inside
one narrow case (converting a <string> to <plurals>). Neither stated the
general rule: removing or renaming a key in the default values/strings.xml
orphans every locale entry that still declares it.
Nor would running lint have caught it in practice. The only pre-push gate is
pre-push-spotless.sh, which runs spotlessApply and nothing else, and
:amethyst:lintFdroidBenchmark takes ~19 minutes on a warm daemon, so it is
not a per-commit check.
Add both halves:
- amethyst/src/main/res/CLAUDE.md gains a "Renaming or removing a string key"
section stating the same-commit rule and why Crowdin is not a cleanup step
CI waits for. The trap is that Crowdin is *partly* reliable — it cleaned 32
of 47 locales — so the tree looks correct in whichever files you open.
Retitled the file (it is no longer plural-only) and marked the existing
sections as the plural-specific ones they always were.
- orphan_strings_check.py scans every locale's resource names against its
tree's default values/, across both Crowdin-managed resource systems: the
Android res trees and the commons Compose-Multiplatform catalog. 0.17s
against the full repo. pre-push-orphan-strings.sh wraps it as a PreToolUse
gate on git push / create_pull_request, reusing the shell-tokenizing
push-detection from pre-push-spotless.sh so "push" inside a commit message
is not mistaken for the subcommand.
- find-missing-translations gains a Common Mistakes entry pointing at both.
Verified: clean on the current tree; exit 2 listing the orphans when
route_video is reintroduced in two locales and a retired key is seeded in the
Compose catalog; gate fires on git push and create_pull_request, stays quiet
on a commit whose message contains "push" and on non-Bash tools.
d6d5a72e49 renamed route_video -> route_media and new_short -> new_media
in the default locale, on the assumption that Crowdin would retire the
old keys on its next sync. The sync merged right after (7a4dc1b378)
cleaned 32 of the 47 locales but left both stale keys in 15 of them.
Android lint runs on the pushed tree, not on Crowdin's next round, so
those 2 keys x 15 locales became 30 [ExtraTranslation] errors and failed
:amethyst:lintFdroidBenchmark on main:
values-th/strings.xml:515: Error: "route_video" is translated here but
not found in default locale [ExtraTranslation]
Delete the orphaned entries. A diff of all 4540 default keys against
every locale confirms these were the only two orphans;
:amethyst:lintFdroidBenchmark now passes.
Third CI failure mode for this test, and the first that was real: with
CoroutineScope(SupervisorJob()) the stateIn(Eagerly) collector needs a
Dispatchers.Default worker (4 on CI), and another desktop test in the
shared JVM leaking a blocked Default thread starves it - the flow then
never surfaces the servers and the 30s timeout fires. Unconfined starts
the collector synchronously and resumes it on the flowOn(IO) producer
thread, so the test depends only on the 64+-thread IO pool. Timeout now
fails with the flow/getter state for diagnosis instead of a bare
TimeoutCancellationException.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Every key whose usages are all composable stringRes/stringResource
calls, with no XML references, no bare %s/%d, only %N$s/%N$d args and
no inline markup, moves from the app's res/ to commons Compose
resources (~105,800 locale entries across 57 locales, translations
preserved byte-for-byte for Crowdin). 568 app files repointed to
Res.string via the stringRes bridge overloads.
The app keeps 1,866 keys that are genuinely Android-bound: ctx-based
call sites, Int-typed id storage (maps/whens), @string/ XML references,
and non-positional format args.
Tool fix folded in: Crowdin emits some entries with attributes before
name= (xmlns:ns0=... name="key") - the extraction regex now matches
any attribute order; the six entries the old pattern missed (zh,
nl-rBE, es x account_backup_tips{2,3}_md) are relocated, and 11 in-file
duplicates from keys that already existed in commons are removed.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
- commons/ui/StringRes.kt: the Compose-resources twin of the app's
stringRes family (composable, formatted, plural, and suspend
loadStringRes variants). Thin delegates - compose-resources caches
parsed locale files process-wide, so the Android-style LruCache is
unnecessary here.
- App StringResourceCache.kt gains stringRes(StringResource) overloads
delegating to the bridge, so a file can mix migrated and unmigrated
keys under its existing single import; migrating a key is just
R.string.x -> Res.string.x.
- tools/strings-migrate: moves keys from app res to commons
composeResources across all locales byte-for-byte (both trees are
Crowdin-managed with the same android mapping); refuses keys using
bare %s/%d since compose-resources only formats positional args.
- Exemplar: profile_banner - the single string blocking the ui/layouts
cluster - migrated across 57 locales, all 7 call-site files repointed.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Move NappletLaunchRegistry back to :amethyst - CLAUDE.md's napplet
security model relies on the broker-side registry being unimportable
from :nappletHost, and its only consumers live in :amethyst anyway.
Hoist PlatformImage.toSkiaBitmap() into a new skikoMain source set
(desktop JVM + iOS, both Skiko-backed) instead of duplicating it in the
two CoilImageBridge actuals; add skikoMain to the KMP purity gate.
Update the migration plan's handoff notes: audit findings 1/2/3/5/6
fixed, baseline-profile regeneration is the one open item.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
AppModules' constructor eagerly builds both OkHttp factories, whose
dispatchers read HttpClientEnvironment.isEmulator at construction time.
Setting the flag after AppModules left the emulator-safe limits dead.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
The move to commons changed every subclass's kotlinx default serial name
(the FQN), which is the polymorphic type discriminator JsonMapper writes
into the per-account DEFAULT_*_FOLLOW_LIST preferences. Decode failures
are swallowed by parseTopFilterOrDefault, so without this every user's
~30 saved tab selections silently reset on upgrade. @SerialName pins the
old names; TopFilterSerialNameTest pins them (and legacy-JSON decoding)
on JVM and iOS.
Also annotate the nativeMain Address actual @Serializable to match the
jvm/android actuals: @Contextual properties only get the plugin's
compile-time fallback on targets whose actual is serializable, so
encoding an address-carrying TopFilter threw on iOS.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
BlossomServerListState.flow hops through real Dispatchers.IO (flowOn)
into a stateIn collector. Under runTest both the awaiting coroutine and
the stateIn scope sit on the virtual-time scheduler, and the IO handoff
can park while that scheduler is idle - runTest then aborts with
UncompletedCoroutinesError, which is exactly how the previous hardening
(await-the-flow-first) failed on the Linux DEB CI job. runBlocking with
a private cancellable scope keeps every dispatcher real, and withTimeout
bounds a genuine hang with a clear error instead.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
The rendition policy this branch added was two named cases — LOWEST for
inline media, AUTO for the media-card feeds — with the choice threaded
through VideoView, ZoomableContentView and every call site. Both cases
were guessing at the same underlying quantity: how big the player
actually is.
ExoPlayer already filters renditions by a viewport; its default is the
physical display size (TrackSelectionParameters.Builder.init sets
isViewportSizeLimitedByPhysicalDisplaySize), which is why AUTO on a
thumbnail fetched a display-resolution rung and why LOWEST had to exist
as a counterweight. Handing it the measured size instead answers the
question directly: a full-width short gets the top of the ladder, a
small inline player gets the rung matching its pixels, PiP gets a small
one because its window is small, and all of them still adapt to the
connection under that ceiling.
setViewportSize is safe where setMaxVideoSize would not be:
DefaultTrackSelector derives its retain threshold from an actual
rendition and leaves the group untouched when nothing covers the
viewport, so a small player can never filter every track away. Manual
picks from the quality menu still win, since overrides are re-applied
after constraint-based selection.
The measurement rides the onSizeChanged RenderVideoPlayer already had
for double-tap seeking, so no new layout observation and no
recomposition; a guard keeps a settling layout pass from re-running
track selection over IPC. VideoQualityPolicy, ApplyInitialVideoQuality
and findLowestResolutionTrackIndex are gone, and VideoView and
ZoomableContentView are back to byte-identical with main.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQs7TP2WeXNR8SwUNLgmUC
PR #4026 retired the route_video and new_short keys from the default
locale (the mixed media feed is no longer labelled "Shorts"), expecting
the next Crowdin sync to drop the retired keys from the translations.
The sync merged in #4027 didn't, so 15 locales still carry them and
:amethyst:lintFdroidBenchmark fails ExtraTranslation with 30 errors
(15 locales x 2 keys) on main and on every branch that merges it.
Same cleanup as e4d288a9 did for the orphaned AI-writing keys.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
The compose-ui-test job failed once on this test (green locally and on
every re-run): BlossomServerListState's flow is stateIn over
Dispatchers.IO, so asserting the synchronous getter before the flow had
settled raced the IO hop on fast runners. Await the flow first - it
settling proves the state finished wiring - then assert the getter.
This PR does not otherwise touch nipB7Blossom; the test predates it
(#3918).
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
NIP-71 video events (kinds 34235/34236) carry a whole HLS ladder in their
imeta tags: one entry for the master playlist, which enumerates every
rendition, plus one per rendition, each locked to a single resolution.
Two separate things kept playback at the bottom of that ladder.
Renderers took `imetaTags()[0]` blindly. That only works because our own
publisher emits the master first (HlsVideoEventBuilder); a client that
orders the tags differently pinned us to one rung, with no adaptive
bitrate and no quality menu either, since a media playlist exposes a
single video track and VideoQualityButton hides itself below two. The
feed filters already accepted an event when *any* imeta was playable,
so the tag the card rendered was not necessarily the one that made it
pass. A new `VideoEvent.selectVideoTrack()` in commons prefers HLS over
a progressive file, then the master among the HLS entries (largest
declared dim, earliest tag winning a tie; a dim-less manifest ahead of
dimensioned rungs), skipping the separate audio track NIP-71 PR #2255
allows and any poster image. Presentation metadata is ladder-wide, so
whatever the chosen entry is missing is filled in from its siblings and
the blurhash, poster and aspect ratio survive the switch.
Even with the master selected, VideoViewInner derived its rendition
policy from `isFullscreen` alone, so everything outside the fullscreen
dialog was pinned to LOWEST. That is right for a video attached to a
note, but the shorts, video and longs feeds render the video full-width
as the post itself — a portrait short fills most of the screen at 360p.
The policy is now an explicit parameter, defaulting to today's behaviour
everywhere, and the media-card feeds pass AUTO so ExoPlayer adapts.
Notification big pictures go through the same selector, so a ladder that
declares `image` on only some rungs gets a poster instead of falling back
to a playlist URL Coil cannot decode.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SQs7TP2WeXNR8SwUNLgmUC
BootRelayDiagnostics -> commonMain. The concurrency review found it
already fully non-blocking: per-relay atomic counters on the hot
per-message path and get-or-create maps, no locks. Swaps: stdlib
kotlin.concurrent.atomics, quartz ConcurrentMap, TimeUtils.nowMillis,
and the daemon dump thread became a coroutine that completes after the
last scheduled census instead of parking a thread for process lifetime.
Blurhash/Thumbhash/Base64 fetchers -> commonMain over a new
CoilImageBridge expect (PlatformImage.toCoilImage +
base64DataUriToCoilImage; android actual = Bitmap.asImage, jvm/ios
actuals = Skia N32 premul from the ARGB pixel buffer, iOS base64 via
Image.makeFromEncoded). desktopApp deletes its three hand-rolled clone
fetchers and registers the shared ones - the first UI-adjacent
duplication the migration removes outright.
BuzzInviteMinter drops Jackson for kotlinx-serialization but stays
jvmAndroid: its OkHttp pin is load-bearing, since the NIP-98 u tag is
signed over OkHttp's canonical URL string and the transport must not
drift from the canonicalizer. PodcastRemoteContent is reclassified to
the OkHttp tier - the object IS a capped HTTP GET; injecting the fetch
would leave an empty shell.
Verified: verifyKmpPurity, JVM, iosArm64 compile + test-compile,
Android, desktop, and the quartz/commons/cli test suites.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Tier 1 of the jvmAndroid promotability audit: the seven relay-AUTH model
files, EncryptionKeyCache, and HttpClientEnvironment have no JVM-only
API usage - a pure source-set move. Verified against verifyKmpPurity,
JVM, iOS (compile + test-compile), Android, and desktop.
NWCPaymentWatcherSubAssembler turned out to reference
NWCPaymentQueryState, declared same-package in the OkHttp-pinned
assembler, so it is reclassified to Tier 2 in the audit table.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Tier-by-tier table of the 59 files Waves 0-1 placed in jvmAndroid or
androidMain: the exact JVM pin per file and which in-repo KMP
replacement (KmpLock, TimeUtils, stdlib atomics, quartz ConcurrentMap,
RandomInstance, okio, kotlinx-serialization, PlatformImage) unlocks it.
11 move with no code change, 17 with one-line swaps, 6 with small
refactors, 5 wait on a dependency, 20 are the OkHttp engine that stays
until quartz has a KMP transport.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
CI's test-quartz-ios job compiles commons for iosSimulatorArm64, which
my JVM-only local checks never exercised. Four fixes:
- BitcoinExplorerEndpoint and OtsSettings reference quartz's JVM-only
OkHttpBitcoinExplorer -> relocated commonMain to jvmAndroid
- GeohashListDecryptionCache, GenericRelayListCache, OutboxLoaderState
now import kotlinx.coroutines.IO, the commonMain-visible extension
(plain Dispatchers.IO is internal on Native)
- TorCircuitHealthTracker uses TimeUtils.nowMillis() instead of
System.currentTimeMillis()
- TopFilter's Address properties are @Contextual: Address is an expect
class with no serializer, and nothing in the repo actually serializes
TopFilter, so deferring to a contextual lookup is behavior-preserving
Verified locally: :commons:compileKotlinIosArm64 and
compileTestKotlinIosArm64 now pass (after repairing the sandbox's
corrupted Kotlin/Native gcc toolchain), along with JVM/Android/desktop
compiles, verifyKmpPurity, and spotless.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
The move to commons commonMain put two JVM-only synchronized() blocks
behind the verifyKmpPurity gate, which failed CI's lint job. Guard the
streak fields with the commons KmpLock instead, matching the pattern
EOSEAccountFast already documents.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Two different destinations in the bottom-bar picker showed the same
"Shorts" label with different icons and different content:
- Main > NavBarItem.VIDEO (Route.Video, VideoFeedFilter) is the combined
media feed: NIP-68 pictures, NIP-94 file headers and every NIP-71 video
kind (normal, horizontal, vertical, short), scoped by the "stories"
follow list. This is the one that also shows images.
- Feeds > NavBarItem.SHORTS (Route.Shorts, ShortsFeedFilter) is vertical
video only (kinds 22 and 34236), scoped by the "shorts" follow list.
Relabel the first one "Media", which is accurate for its contents and
doesn't collide with the neighbouring Pictures / Videos / Shorts feed
entries. The FAB on that screen was described as "New Shorts: images or
videos" for the same reason, so it becomes "New Media: image or video".
Both are new string keys rather than edits in place: all 47 locales had
translated the old keys as "Shorts", and those translations would be
wrong for the new meaning. Crowdin drops the retired keys on its next
sync and the label falls back to English until retranslated.
The NavBarItem enum constants are serialized into user settings by name,
so VIDEO keeps its name — only the display label changes.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ya9C9GkvkRHLRqrPCAa4WA
Amethyst already notifies on NIP-34 issues (1621), patches (1617), pull
requests (1618), and PR updates (1619), but the four remaining
participant-facing kinds arrive on the device and go nowhere:
- **1622 GitReplyEvent** — legacy comment. Deprecated by NIP-22 but still
in the wild (any old-shape ngit/gitworkshop event, and freshly-signed
ones from clients that haven't migrated). Was fetched by
`NotificationsPerKeyKinds2` and stored in `LocalCache`, but no
notification-tab kind-gate and no push consumer branch.
- **1630 / 1631 / 1632 / 1633 GitStatus{Open,Applied,Closed,Draft}** —
merged, closed, reopened, drafted. Not fetched at all: no relay
subscription anywhere in the app asks for them for the current user,
and no repo-scoped fetch pulls them for a visible PR either. As a
result `GitStatusIndex.latestByTarget` — the source of the
"closed/merged" pill on the repo listing — could only ever populate
for the local user's own drafts, since nothing else lands in cache.
Symptom on `main` today: someone merges your PR on a NIP-34 relay
(mine, in a recent example) and Amethyst is silent. No badge on the
notifications icon, no push, no pill on the repo row, nothing. Opening
the PR thread will surface the status through the reply pane's
engagement fetch, but the user has to know to look.
## Fix
Wire all five kinds through the four notification-plumbing layers they
have to pass through, matching the existing patch/issue/PR shape:
1. **`FilterNotificationsToPubkey.NotificationsPerKeyKinds2`** — add
the four status kinds so `#p`=me on inbox relays actually pulls
merges/closes for PRs and issues the user participates in. NIP-34
status events p-tag every prior participant of the target, so a
pubkey filter is the right primitive.
2. **`FilterRepliesAndReactionsToNotes.RepliesAndReactionsKinds2`** —
add PR-update (1619) and the four status kinds so when a repo,
PR, patch, or issue row is on screen the engagement `#e`=<target>
fetch pulls their status transitions and revision chain. This is
the wire that finally makes `GitStatusIndex` see data for anyone
who isn't a p-tagged participant.
3. **`NotificationFeedFilter.NOTIFICATION_KINDS`** + `tagsAnEventByUser`
short-circuit — add reply (1622) and the four status kinds so the
in-app Notifications tab renders them. Trust the p-tag relay gate
(same policy applied to patches/issues/PRs above), because chasing
a chain of prior status events to reconfirm participant relevance
would require walking events that aren't guaranteed to be in cache.
4. **`NotificationDispatcher.NOTIFICATION_KINDS`** — add the same five
kinds so `LocalCache.observeEvents` fires the push consumer. Flip
the constant from `private` to `internal` so the new contract test
can pin it against the in-app feed's set without opening it to the
whole world.
5. **`EventNotificationConsumer.consume()`** — route each of the five
kinds to `CodeNotification.notify(...)`, matching the existing
patch/issue/PR/PR-update branches.
6. **`CodeNotification`** — five new `notify(...)` overloads. Reply
uses a single title string. Status kinds pick their title from the
*target*'s kind so a 1631 on a kind-1618 PR reads "merged a pull
request" but the same 1631 targeting a kind-1617 patch reads
"applied a patch" (matches gitworkshop's conventions). Falls back
to a generic wording when the target isn't yet in cache — rare,
because the p-tag subscription pulls a status event regardless of
whether its target has ever been seen.
7. **`LocalCache.computeReplyTo`** — add `GitStatusEvent` and
`GitPullRequestUpdateEvent` branches so status/revision events
thread under their target patch/PR/issue in `Note.replies`. Only
the marked-`root` `e` tag (for status) / `parentPullRequestId()`
(for PR update); the repository `a` tag is not a reply target.
8. **`KindDisplayName`** — wire the four status kinds plus PR + PR-
Update into the kind→label mapping used by the relay debug screen
(the pre-existing `kind_git_pr` / `kind_git_pr_update` strings
already existed but weren't wired; the status labels are new).
9. **Strings** — new `app_notification_code_channel_message_reply`,
four `_status_open/applied/closed/draft` titles plus target-kind-
specialized applied/closed variants (`_status_applied_pr`,
`_status_applied_patch`, `_status_applied_issue`, and the closed
trio); new `kind_git_status_{open,applied,closed,draft}` labels.
`translatable="true"` (Crowdin's default) so translators can pick
up appropriate phrasing.
Nothing changes for events the user isn't p-tagged on: the relay-side
filter is still `#p`=me. Nothing changes for the four kinds already
covered: their existing branches are untouched.
## Tests
New `Nip34NotificationCoverageTest` pins the full NIP-34 collaboration
surface across the four independent kind lists that have to move
together (relay subscription, engagement fetch, in-app kind gate,
push kind gate). Miss any one and one specific transition silently
drops. Tests explain the failure mode in each assertion message.
Existing `NotificationKindsContractTest` and every other test under
`notifications/*` still passes.
`./gradlew :amethyst:compilePlayDebugKotlin` clean.
`./gradlew :amethyst:testPlayDebugUnitTest --tests
"…notifications.*"` all green (58 tests including the 4 new).
`./gradlew spotlessCheck` clean.
(cherry picked from commit 3f2c52b97a68e6e3274443682ddbeddb3dbd6fe9)
Applied from nostr proposal
819c0ccc881ced7753675f9ba6a262579eb9772d8b910d14727b5531ede52014
(branch feat/nip34-pr-notifications). Cherry-picked rather than merged via
`ngit pr merge` because that proposal is not surfaced by `ngit pr list` --
it is absent from every status and `ngit pr view` reports "proposal not
found", even though the event is well formed on relay.ngit.dev with the
correct a-tag, p-tag and r-tag.
One fix folded in on top of the original commit: the new test imported
`RepliesAndReactionsKinds2` from
`com.vitorpamplona.amethyst.service.relayClient.reqCommand.event.watchers`,
which no longer exists. `FilterRepliesAndReactionsToNotes.kt` moved to
`commons` (`com.vitorpamplona.amethyst.commons.relayClient.event.watchers`)
in the 537 commits since this branch's merge-base. Git followed the rename
for the production edit but not for the new test file's hardcoded import, so
the branch did not compile as submitted.
Verified on current main after that fix:
- Nip34NotificationCoverageTest: 4 tests, 0 failures.
- Full *notifications* unit-test package: 5 classes, 24 tests, 0 failures.
Premise confirmed against main before applying: NotificationsPerKeyKinds2
carried 1617/1618/1619/1621/1622 but no 1630-1633, and neither
NotificationFeedFilter.NOTIFICATION_KINDS nor
NotificationDispatcher.NOTIFICATION_KINDS listed the status kinds -- so a
merge/close on a thread you participate in was fetched nowhere and rendered
nowhere.
Open question left for follow-up, not a blocker: nothing checks that a status
event's author is a maintainer in the repo's kind-30617 announcement, so any
pubkey can p-tag you with a 1631 and produce a "merged a pull request"
notification. The notification strings name the actor, so the claim is at
least attributable.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GYVqQqpUY1xqYG5LUY6jQr
Add electrumx2.testls.space:50012 to DEFAULT_ELECTRUMX_SERVERS and
TOR_ELECTRUMX_SERVERS as a redundancy endpoint for the testls.space
operator. It runs on the same box as relay.testls.bit (23.158.233.10)
but terminates TLS at nginx with a publicly-trusted Let's Encrypt cert
(CN=electrumx2.testls.space, issuer LE YE1) instead of the self-signed
relay.testls.bit cert on the standard ports.
usePinnedTrustStore is left at the default (false) since the system
trust store is sufficient, same as electrum.nmc.ethicnology.com.
The same nginx vhost also exposes WSS on port 50014, making it the
second browser-viable public Namecoin ElectrumX endpoint (alongside
electrum.nmc.ethicnology.com) for pure-browser Nostr clients that
cannot use self-signed certs.
(cherry picked from commit 645382a95b9a314eb6a4e1221ba97dfc1c13f1ae)
Applied from nostr proposal
c0eb8d1a09651c377827f4aa97c1ed7a2f93fafceb823233c5650506b661b8ba
(branch feat/electrumx2-le-server). Cherry-picked rather than merged via
`ngit pr merge` because that proposal is not surfaced by `ngit pr list` --
it is absent from all statuses and `ngit pr view` reports "proposal not
found", though the event is well formed on relay.ngit.dev with the correct
a-tag and r-tag. It appears to collide with a stale earlier proposal for the
same branch name.
Endpoint verified before applying:
- electrumx2.testls.space resolves to 23.158.233.10, the same host as the
existing relay.testls.bit / 23.158.233.10 entries, as the commit claims.
- TLS on :50012 presents CN=electrumx2.testls.space issued by Let's Encrypt
(C=US, O=Let's Encrypt, CN=YE1), so usePinnedTrustStore = false is correct.
- server.version reports ElectrumX 1.16.0 and server.features reports
genesis_hash 000000000062b72c5e2ceb45fbc8587e807c155b0da735e6483dfba2f0a9c770,
i.e. it indexes Namecoin rather than Bitcoin.
Note this is the third default entry pointing at host 23.158.233.10, so it
adds certificate-path redundancy (works where a self-signed cert is stripped)
rather than host redundancy. Low risk: nameShowWithFallback tries servers
sequentially and returns on first success, and this entry is appended last in
both lists.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GYVqQqpUY1xqYG5LUY6jQr
Merges nostr proposal 91f762d3 into main:
- fix: narrow FileProvider external root to the app-specific dir
Replaces `<external-path path=".">` with `<external-files-path>`, so the
FileProvider no longer roots at /storage/emulated/0, and adds
FileProviderPathsTest to pin both directions on device.
Supersedes proposal a5d172d8.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GYVqQqpUY1xqYG5LUY6jQr
`<external-path path=".">` rooted the provider at
Environment.getExternalStorageDirectory() (/storage/emulated/0), which is far
broader than anything Amethyst hands out. The only external-storage consumer is
TakePicture's getPhotoUri/getVideoUri, both of which write into
getExternalFilesDir(...) — so `<external-files-path>` describes the actual
surface exactly.
Not a live vulnerability: the provider is exported="false", every
getUriForFile() call site builds its File from app-controlled constants under
cacheDir or getExternalFilesDir, and the one name derived from event content
(shareIcs) is passed through IcsExport.safeFilename, which strips '/' — so no
attacker-influenced path can reach the provider today. This is defence in
depth plus an accurate declaration.
Prefer external-files-path over hardcoding the path under
Android/data/<applicationId>/: the latter is wrong for the .debug and
.benchmark applicationIdSuffixes, while external-files-path resolves per
variant. The `external_files` name is kept so the generated content:// URI
shape does not change.
FileProviderPathsTest pins both halves on device: the capture URIs still
resolve under /external_files/, cacheDir still resolves under /cache/, and a
file at the external-storage root no longer maps. Against the old config that
last case fails with
content://com.vitorpamplona.amethyst.debug.provider/external_files/Download/not-ours.pdf.
Supersedes nostr proposal a5d172d8.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GYVqQqpUY1xqYG5LUY6jQr
- Extract the duplicated drive-the-save harness (temp file, runBlocking save,
success/error assertions) from both instrumented e2e tests into
MediaSaverTestSupport, following the AvifInstrumentedTestSupport precedent,
with UUID-based filenames per the existing convention.
- MediaSaverToDiskMediaStoreTest: record inserted rows as item Uris
(ContentUris.withAppendedId) instead of Pair + hand-built _ID selection; trim
the KDoc paragraph that re-quoted the MediaProvider rejection verbatim - the
canonical copy lives on MediaStoreTarget.
- MediaSaverToDiskLegacyStorageTest: derive watchedDirs from
MediaStoreTarget.entries instead of a third hand-maintained directory list;
move the exact run recipe (assemble, install -g, am instrument) into the class
KDoc and point the skip message at it; unfold the write-probe .also puzzle.
- MediaSaverToDisk: drop the outer withContext in saveDownloadingIfNeeded (both
delegates now dispatch themselves, leaving the decision in the leaf writers);
scope `val extension` to the pre-Q branch that uses it; drop the rot-prone
composable file name from save()'s KDoc.
Considered and left alone: isSaveableMimeType deriving from MediaStoreTarget.of
(kept - one definition of the accepted set beats re-spelling the prefix triple);
the nested Dispatchers.IO in save()/downloadAndSave (load-bearing for direct
call sites, fast-path no-op when nested); the redundant launch(Dispatchers.IO)
at two call sites outside this branch.
test: only ever delete MediaStore rows the test itself inserted
test: cover the pre-Q save path on API 26
test: cover #4009 end-to-end against a real MediaStore on API 29
MediaProvider validates the primary directory of RELATIVE_PATH against the
collection being inserted into. saveContentQ paired
MediaStore.Video.Media.EXTERNAL_CONTENT_URI with Environment.DIRECTORY_PICTURES,
so every video save built content://media/external/video/media +
"Pictures/Amethyst" and Android 10 rejected it with
IllegalArgumentException: Primary directory Pictures not allowed for
content://media/external/video/media; allowed directories are [DCIM, Movies]
Newer Android releases don't reject the mismatch, which is why the crash only
reproduces on older devices - but the file still landed under Pictures/ rather
than Movies/ everywhere, confirmed on a current device.
Collection and directory now travel together in a MediaStoreTarget enum, so the
two cannot drift apart again, and the catch-all falls through to Downloads
(which accepts any file) instead of the Video collection. The MIME type is
resolved above the SDK_INT fork and both writers route through the enum: the API
level now decides how a file is written, never which directory it belongs in, so
the pre-Q path stops filing videos and PDFs under Pictures/ too.
The directory names are spelled out as literals because Environment's DIRECTORY_*
are plain static fields that the unit-test android.jar nulls out. The JVM test
covers the routing; MediaStoreTargetInstrumentedTest pins the literals back to
the platform constants on-device.
Stop leaking a file descriptor and blocking the UI on local saves
fix(nwc): omit nulls one level down too, inside pay_keysend's TLV records
refactor(nwc): make the null-omission guard cover every method, on every target
Viewing transactions on one NWC wallet failed with
Invalid list_transactions params: from must be an integer
because Amethyst sent every optional parameter explicitly:
{"method":"list_transactions","params":{"from":null,"until":null,"limit":20,
"offset":0,"unpaid":false,"unpaid_outgoing":null,"unpaid_incoming":null,"type":null}}
NIP-47 marks those optional, and a wallet is free to type `from` as an integer
and refuse a null. Nothing in the request was wrong except the nulls.
The two serialization backends had disagreed since they were written.
Nip47RequestKSerializer builds every params object with
`params.x?.let { put("x", it) }`, so kotlinx has always omitted nulls; Jackson
serializes the params classes reflectively and wrote them. The same request was
two different documents depending on the platform, and only JVM/Android was
broken — which is why it survived: the tests that cover this shape run against
the backend that was already correct.
A Jackson mixin now applies NON_NULL to all twelve NIP-47 params classes. A
mixin rather than an annotation because the classes live in commonMain and
Jackson annotations are JVM-only.
The regression test asserts the property rather than the symptom: no request
type may emit a null param, and both backends must produce the same document.
The second is the one that would have caught this.
Not new to any recent change — the reflective serialization predates it. What
changed is that 24a8540ad9 surfaces a NIP-47 refusal instead of rendering it as
an empty list, so users now see the error rather than an empty transaction
screen. Older builds sent the same request and were refused just as silently.
Adds the imports the migration's same-package rewrites missed in test
source sets (moved topNavFeeds filters, okhttp classes, LargeSoftCache
address extensions, latestBuzzEdit), inlines the two multi-line
old-package FQNs in NewMessageTaggerKeyParseTest, and widens
NappletRelayCleartext.forDelivery with the rest of the object so its
test keeps calling it cross-module.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Kotlin review found the feature's own soundness property could be false on
the wire.
lnAddressInvoice drops the zap request for a provider that does not advertise
`allowsNostr` — `nostrRequest = if (allowsNostr) nostrRequest else null` — but
assembleInvoice set Payable.zapRequest unconditionally from the request it had
built. So paying a lightning address whose provider ignores `nostr=` still
attached metadata.nostr to the payment, for an invoice whose description_hash
commits to nothing about it. Every claim the feature makes — the KDoc, the
byte-identity test, the wallet-side binding check we asked BrollyZapper to
keep strict — rests on those bytes being what the callback hashed. Here they
were not.
A conformant wallet refuses such a row, so no false attribution was displayed;
what was wrong is that we asserted a binding we could not support, and spent
the 4096-char budget doing it. lnAddressInvoice now reports the request it
actually sent, and only that is carried forward.
The size estimate also counted raw string length for `comment`, which is free
text a user typed. JSON escaping expands it — a quote or backslash to two
characters, a control character to six — so an escaping-heavy comment could
breach the ceiling unnoticed, and NWC-06 makes the wallet drop the WHOLE
object then, taking recipient_data with it. escapedLength() counts what
actually reaches the wire; KEY_OVERHEAD drops to the fixed punctuation cost
now that escaping is no longer hiding inside it.
Both paths were untested and now have regression tests.
Not changed: dropMetadataIfUnsupported still mutates the caller's Request. The
review confirmed every current call site builds a fresh request inline, and
the contract is documented on both public send functions.
Verified: quartz + amethyst suites, commons/desktopApp/cli/geode compile,
spotless clean.
Cleanup pass over the squashed branch. Net -109 lines.
anyToJsonElement was a second copy of a private helper that already existed in
ClinkKSerializers, serializing the same Map<String, Any?> shape. Worse than
tidiness: RawJson is declared in nip01Core and registered globally for Jackson,
but the kotlinx half lived inside one NIP's package, so a RawJson routed
through Clink's copy would have been emitted as a quoted, escaped JSON string —
exactly the corruption RawJson exists to prevent. One declaration now, beside
the other kotlinx serializers at nip01Core level, and Clink picks up the RawJson
and Array branches its copy lacked.
The getFresh call in fetchTransactions is deleted. Its own KDoc claimed it
re-read capabilities "bypassing the info cache's TTL", and getFresh does no such
thing: it returns a fresh entry as-is, so the case it was written for — a wallet
that added `06` twenty minutes ago — was the one case it could not cover. It
also refreshed the SELECTED wallet while zaps read the DEFAULT one. The send
path's currentOrFetch already fetches on cold and background-refreshes on
stale, so nothing is lost. A real force-refresh would mean a relay request per
refresh press, which is a policy decision rather than a cleanup.
Three KDoc blocks documented behaviour their function no longer had after the
walletInfo refactor: prefersNip44 kept four paragraphs about waiting, and
supportsMetadata opened "WAITS ON A COLD CACHE" while doing neither. The
rationale now lives once, on the one function that waits, and supportsMetadata
is inlined into its only caller. Also deleted a comment claiming a metadata-free
method "returns before the info cache is consulted" — both call sites fetch
first, so it never did.
Smaller: RawJson becomes a data class; the unused metadata parameter comes off
PayInvoiceMethod.create(bolt11, amount); TransactionRowLabels drops a derivable
flag and a twice-computed fallback; KEY_OVERHEAD's comment now says what its
slack is for; the three blank-description tests become one loop; a test that
asserted the Kotlin stdlib now calls displayDescription(); and two test comments
had lost their backticked literal to a heredoc.
Verified: quartz + amethyst suites, commons/desktopApp/cli/geode compile,
spotless clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019upqJTtAMNNfxKCDV1xDn3
perf(nwc): read the wallet's info event once per send, not twice
fix(nwc): wait for the wallet's info event before deciding it lacks NWC-06
fix(nwc): send the zap request's own bytes, not a rebuild of it
Outgoing rows in the NWC wallet history showed an arrow, an amount and a
date, with an invisible blank line where the label should be. Two causes.
The row rendered an empty string. `tx.description ?: fallback` only catches
null, and wallets send `"description": ""` for a payment with no memo, so the
row got a `Text("")` — a line with the height of a real one and nothing in it.
NwcPaymentNotifier already guarded this; the screen did not. Resolution moves
out of the composable into a pure `TransactionRowLabels`, so the behaviour is
a unit test rather than a Compose one.
And we never told the wallet who we were paying. `PayInvoiceParams.metadata`
existed and nothing set it, while a NIP-57 invoice commits to a
description_hash rather than a memo — so the wallet had nothing to lift
either. ZapPaymentHandler held the signed zap request, the lightning address
and the message at the moment it fetched the invoice, and dropped all three.
Amethyst now sends NWC-06 metadata: the zap request, the recipient's address
and the comment. `nostr` is built from the event's TYPED fields, never by
re-parsing its JSON — a verifying wallet recomputes the event id from those
values, and toAnyValue() resolves numbers with toDoubleOrNull() BEFORE
toLongOrNull(), so a round-trip would emit "kind": 9734.0 on the kotlinx path
while the JVM path stayed correct. Over NWC-06's 4096-character ceiling the
zap request is dropped and the much smaller recipient_data/comment pair
survives, so the row still names the payee instead of arriving blank.
SENT ONLY TO A WALLET THAT ADVERTISES `06` in the info event's extensions tag,
which NwcInfoEvent now parses. Users pair with wallets we do not control, and
one that types metadata narrowly would accept today's "metadata": null but
refuse an object — costing a payment for a cosmetic field. The gate sits in
NwcSignerState where the request is built rather than at the call site, so no
caller can route round it, and "not yet fetched" reads as no. Every wallet
that has not advertised receives a request byte-identical to today's; there is
a test for exactly that.
The blank-string guard is what fixes existing history, for every wallet, with
no wallet change at all.
Adds an execution-status header: what landed on this branch, the
corrections found while executing (import-graph analysis undercounts
same-package coupling; ui/theme+layouts are not mechanically movable),
and the refined LocalCache move recipe with its one open IAccount
design question.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
kinds 30392-30395 and 30382 had no branch in SearchFieldExtractor, so
both fell through to the generic `is SearchableEvent ->` case, which puts
the whole of indexableContent() in the TERTIARY (body) tier.
For a Trusted List that whole content IS its title, and a title is not
body text. On a tiered backend the difference is large and measurable: on
search-staging, a 30392 titled exactly "Verified Human" matched the query
`Verified Human` on the same rung as a profile whose bio happens to say
"humans are amazing" - 550 against 130 000 on that schema's ladder, a
236x discount - and reached the title only through trigram substring
rather than the prefix/typo columns a title normally gets.
A contact card decomposes the same way every other kind in this file
does: petname() is a trust provider's NAME for a person - the direct
analogue of kind 0's `name`, and what a people search is looking for -
and summary() is the description beside it.
The card's topics change ROLE, and that is the one behaviour change here.
topics() is TopicTag, which is the `t` tag under another name - same
predicate, same array - so the tiers() funnel already carries every topic
as a hashtag. The old fallback therefore indexed them TWICE, once inside
the concatenated body and once in the hashtag role; they are now carried
once, in the role, and whether that is tokenized or kept as keywords is
the backend's call per IndexableFields. Since build() puts petname and
summary in the NIP-44 content, topics are the only public text on a card
this library authors, so that shape is pinned by its own test - including
that a hashtags-only extraction does not normalize to None.
Nothing else changes what is indexed, only which tier each accessor lands
in. indexableContent() is untouched, so the SQLite and filesystem stores
(the only in-tree consumers, both of which index the flat form) are
bit-identical. SearchFieldExtractor has no in-tree consumer at all - it
is the protocol surface external tiered backends read - so the app, both
flavours, and every feed are unaffected by construction.
The encrypted half of a contact card stays out of the index as before:
petName()/summary() read the public tag array only.
Follow-ups from the branch audit:
- Adds commons/util/JsonTreeUtils.kt: one shared set of total, null-safe
JsonObject accessors (parseJsonObjectOrNull, stringOrNull, intOrNull,
longOrNull, doubleOrNull, booleanOrNull, objectOrNull, withString) for
ad-hoc JSON trees. Replaces the two near-identical private sets this
branch had introduced (nappletHost's JsonEnvelope.kt, now deleted, and
EmbeddedImeBridge's file-local helpers) and FeedDefinitionSerializer's
identical bool/int/long copies. FeedDefinitionSerializer keeps its
deliberately stricter isString-guarded string(), now documented, and
NappletProtocolJson keeps its throwing accessors (rejecting malformed
input at the trust boundary is its job). Quartz's copies stay: quartz
cannot depend on commons.
- Adds EmbeddedImeBridgeTest (16 JVM tests) pinning parseImeEvent /
parseSelectionGeometry: per-event parsing, defaulting of absent fields,
the total-accessor behavior for mistyped fields, and the ime.resync
envelope. This parser became JVM-testable when it moved off Android's
org.json; the browser suite in tools/ime-test still owns the page side.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVcZwp65oybotmq5o66foW
The two-line poison edge the migration sweep identified:
IFeedTopNavFilter.toPerRelayFlow/startValue hard-coded the concrete
LocalCache, which kept all 23 implementors app-side even though they
only call relayHints and getOrCreateAddressableNote. The signatures now
take the commons ICacheProvider port (checkGetOrCreateAddressableNote
gains a default implementation there, mirroring LocalCache's).
With that edge cut, this moves to commons/model/topNavFeeds:
- IFeedTopNavFilter, IFeedFlowsType, OutboxRelayLoader/State,
CommunityRelayLoader, UsingRelayUnwrapper, FeedDecryptionCaches
- the TopNavFilter/FeedFlow pairs for allFollows, allUserFollows,
global, hashtag, mine, relay, aroundMe (geohash), noteBased
(community/author/muted), favoriteAlgoFeeds filters, unknown
- TopFilter itself, extracted out of AccountSettings.kt where it never
belonged (persisted by its code string, so the move is wire-safe)
- the nip51 geohash list card + decryption cache they depend on
Still app-side, each named by its real blocker: FeedTopNavFilterState
(Account/AccountSettings wiring), AllFollows/AllUserFollows feed flows
(serverList MergedFollowListsState), Kind3UserFollowsFeedFlow
(nip02FollowLists), AroundMeFeedFlow (LocationState), favoriteAlgoFeeds
flows (algoFeeds orchestrator).
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Batch 3 of the commons migration sweep: IHttpClientManager, the dual
direct/Tor client managers, both OkHttp factories, all interceptors
(Blossom read-auth, encrypted blob, local-cache redirect, onion
location/rewrite, content type, logging), both event listeners,
OnionLocationCache, EncryptionKeyCache, OkHttpDebugLogging, plus the
role-based client builders from model/privacyOptions.
Two small seams so the shared code stays Android-free:
- MediaCallEventListener.verboseLogging replaces the app isDebug read;
the app sets it at startup.
- HttpClientEnvironment.isEmulator replaces the Build-fingerprint call
in the factories; the app sets it at startup, desktop stays false.
- EncryptionKeyCache now uses androidx.collection.LruCache (KMP) with an
explicit null-url guard where android.util.LruCache would have thrown.
Desktop's hand-rolled DesktopHttpClient can now adopt these factories
and gain the interceptors it currently lacks.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Removes the backwards-compat re-export shims (Note, User, HashtagIcon,
TorRelaySettings/Evaluation, FeedFilters, ChangesFlowFilter, FeedStates,
BundledUpdates, BookmarkListState, ChatroomFeedFilter, UserFinderShims)
and the typealias lines inside the five mixed shim files, rewriting all
1,165 imports to the canonical commons FQNs. Renames the two files whose
remaining single class no longer matched the filename.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
Sweeps the last org.json usages out of the Kotlin sources and moves them
to kotlinx.serialization's JSON tree API (already the project standard):
- nappletHost: bridge/broker envelope handling in NappletHostActivity,
NappletHostService, NappletBrowserActivity, NappletBrowserService and
NappletFaviconSniffer now parses with Json.parseToJsonElement via new
total helpers in JsonEnvelope.kt (absent/mistyped fields degrade to
empty/false instead of throwing, matching the old opt* semantics).
Adds the kotlinx-serialization-json runtime to the module (tree API
only, so no serialization plugin needed).
- amethyst embed IME relay: EmbeddedImeBridge parses ime.* envelopes
with JsonObject accessors; RemoteImeView and EmbeddedTabLayer build
their outgoing envelopes with buildJsonObject.
- tools/ime-test: drops the now-stale "org.json is stubbed in JVM unit
tests" rationale from the README and shim-events.mjs header.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AVcZwp65oybotmq5o66foW
Audit of all 2,347 Kotlin files in amethyst/src/main via import
classification + transitive-closure analysis plus six per-area deep
audits. Key findings: 509 files are movable today with no refactoring;
the dominant blockers are Account/LocalCache/AccountViewModel and the
string-resource bridge, not Android APIs; LocalCache itself has only
three trivial Android-dirty deps and moving it deletes the 1,173-line
DesktopLocalCache; a two-line IFeedTopNavFilter signature fix unlocks
the app half of topNavFeeds. Includes MOVE-NOW batches, blocker-tagged
MOVE-AFTER tables, a desktop-duplication catalog, and a six-wave
migration sequence.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011S1vbFWVVAMFDT8PTgdibV
6f97faf1 removed ai_writing_help, ai_tone_more_direct and ai_tone_punchy
from the default locale when it reworked the restored AI writing helper,
but left them in all 55 translated strings.xml files. Android Lint's
ExtraTranslation reports one error per (key, locale), so
:amethyst:lintFdroidBenchmark fails with exactly 3 x 55 = 165 errors —
the count CI reports — and main has been red since #4015 merged.
Mirrors a5e2aae9, the original removal of these same keys, which touched
56 files: the default locale and all 55 translations. Nothing in Kotlin
references any of the three, so there is nothing to restore instead.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017shnUK5t71BkBXgTAcACbA
build-desktop runs five test suites (:quartz:jvmTest, :commons:jvmTest,
:nestsClient:jvmTest, :cli:test, :desktopApp:test) across three OSes and
was the only test-running job with no failure reporting — test-geode,
test-quartz-ios and test-and-build-android all upload on failure.
When a test failed there, the console printed the test name and the
exception class and nothing else, and the reports died with the runner.
Run 10540's macOS leg is the case in point:
NostrClientNegentropySyncTest[jvm] >
multiRoundReconcileStreamsEveryEventThrough[jvm] FAILED
com.vitorpamplona.quartz...NegentropySyncException at
NostrClientNegentropySyncTest.kt:146
Line 146 is the runBlocking frame, so all that survives is "something
threw". NegentropySyncException carries a `detail` naming which of the
four branches fired — connect timeout, idle silence mid-reconcile,
NEG-ERR, or disconnect — and that string is what says whether the run
hit a real protocol fault or lost a race against a loaded runner. It
was unrecoverable.
Two steps, mirroring the Android job: the same pinned
mikepenz/action-junit-report annotates the failing assertion inline
(annotate_only keeps this working under `permissions: contents: read`
and on fork PRs), and the HTML reports upload on failure for the full
stack traces the annotations truncate. Artifacts are named per-OS
because the three matrix legs share a run.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017shnUK5t71BkBXgTAcACbA
Bugs
- Emptying the composer left the proposals on screen. precomputeAiResults
early-returned on short text without clearing state, and cancel() — which
runs after a post is sent — resets every other suggestion source but not
this one. The freshly emptied composer kept showing proposals for the note
just published, and "Use This" pasted it back in.
- The client caches were plain HashMaps written by the nine tone coroutines
at once. Two tones mapped to the same rewriter, so every batch raced on the
same key and orphaned a Rewriter nothing would close. They are now
ConcurrentHashMaps built through computeIfAbsent, and close() drains them.
- The assistant held the Activity context inside a ViewModel that outlives it.
It now keeps the application context, and the screen passes that too, as
MLKitImageLabelService already does.
- DOWNLOADABLE was folded into "unavailable" and nothing ever called
downloadFeature(), so on a device whose model had not been fetched the
feature could never start. Status is now re-read (throttled) while it is not
ready, and the model is requested once when the user has the setting on.
- lastComputedText was stamped before inference, so a cancelled run marked
that text as done and returning to it showed nothing. It is stamped after
the run completes.
- The Settings toggle was read as a plain StateFlow value, so turning it off
did not hide the panel. The screen collects it now.
- precomputeAiResults/showAiPanel touch a lateinit accountViewModel; they now
guard it like the functions above them.
Performance
- Language detection ran once per tone over identical text; it is memoized per
text, so a batch detects once instead of nine times.
- MORE_DIRECT and PUNCHY issued the same request as PROFESSIONAL and SHORTER
— ML Kit has no other output type for them — so two of nine inferences were
wasted and two chip pairs rendered identical text. Both tones are dropped.
- Applying a proposal cleared lastComputedText, and the programmatic edit
re-entered onMessageChanged, so accepting a suggestion immediately queued a
fresh batch over it. It now remembers the applied text.
- Inference blocked on future.get(), which coroutine cancellation cannot stop,
so abandoned batches kept running. Futures are awaited through
suspendCancellableCoroutine and cancelled with the coroutine.
- Drafts under 20 characters no longer spend the model at all, and proposals
identical to the draft are dropped instead of becoming a chip.
Cleanup
- Deletes MockWritingAssistant (shipped in main behind a dead flag, carrying
its own "remove before shipping" note) and the unused AiWritingHelpButton.
- Hides the Settings tile on F-Droid, where the assistant is a no-op.
- Panel takes an ImmutableMap; the ML Kit language constants are mapped
explicitly instead of relying on the two APIs numbering them alike.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YRfjXrjHdJ435kQwyp2HnL
Review feedback on the PR: created_at has second resolution, so nothing
on nostr can replace an address more than once per second — and a client
that keeps out-stamping the previous version drifts a second further into
the future per republish, which relays may reject.
That is right, and it points at a better guard than `+ 1`. One second is
the real floor on how often an address can be replaced, so a client that
replaces one faster should wait for the clock rather than invent a
timestamp. awaitCreatedAtToSupersede suspends until the second the
previous version claimed has passed, then stamps the real time — the new
version still wins, and no event is ever dated ahead of the clock.
The wait is bounded (MAX_SUPERSEDE_WAIT_SECONDS). A version further ahead
than that came from another device's skewed clock rather than this
client's own burst, and sleeping it out could take hours, so past the
bound out-stamping is still the only way to supersede.
Applied to the two paths that can accumulate drift across repeated edits
and were already suspending under a mutex: the NIP-78 settings blob and
the per-d-tag app recommendations. RoomParticipantActions keeps the
non-suspending form — it is reached from Compose click handlers, and its
stamp derives from the single event being acted on, so it sits at most one
second ahead and cannot drift.
Note the debounce added earlier already keeps the settings pickers from
publishing sub-second at all (measured on device: 23 rapid toggles → 3
events, each stamped at the true wall-clock second, the `+ 1` never
firing). This makes that a guarantee rather than a consequence of timing,
and extends it to the settings paths that are deliberately not debounced.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Voa2KcknNffhvPqsRG92hx
This reverts commit a5e2aae960 (PR #3979),
bringing the on-device AI writing assistant back to the post composer:
- restores the WritingAssistant abstraction with its play (ML Kit GenAI /
Gemini Nano) and fdroid (no-op) implementations, the mock, and the
AiWritingHelp panel/button
- restores the AI state, the precompute job and the lifecycle wiring in
ShortNotePostViewModel and ShortNotePostScreen
- restores the genai-proofreading, genai-prompt and genai-rewriting
dependencies
- restores the "Propose text improvements" setting end to end: the Compose
Settings tile, automaticallyProposeAiImprovements in UiSettings /
UiSettingsFlow, the ui.propose_ai_improvements DataStore key, and the
ai_writing_* / ai_tone_* strings in every locale
The one deviation from a straight revert: initWritingAssistant now takes a
`Context` by its simple name instead of the inline fully-qualified name the
original had, since the file already imports it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YRfjXrjHdJ435kQwyp2HnL
java.util.concurrent.CancellationException extends IllegalStateException,
so reportSignerErrors' trailing `catch (e: IllegalStateException)` arm was
swallowing every cancelled signer coroutine and showing it to the user as
a "signer not found" toast carrying the raw exception text —
"JobCancellationException: StandaloneCoroutine was cancelled;
job=StandaloneCoroutine{Cancelled}@3ecbac".
Latent since the arm was written: nothing cancelled those jobs, so it
never fired. The navigation pickers' debounce cancels a superseded
publish on every rapid edit, which made it fire on essentially every
fast toggle — confirmed on device, and confirmed absent again with this
change. Swallowing it also broke structured concurrency, since the
cancellation never propagated.
Caught by device testing of the debounce, not by review
Closes#4010.
The drawer's section headings (You / Navigate / Feeds / Create / System)
fold away on tap, but CollapsibleSection kept that in a local
`remember { mutableStateOf(true) }`, so every heading sprang open again
on the next launch. The state is now hoisted out of the composable and
mirrored to the shared `ui.*` DataStore.
Device-global and never published: which headings you have folded is a
per-device view choice, unlike the hidden rows beside it in the same
drawer, which stay per-account and NIP-78-synced.
The preference stores the *collapsed* headings rather than the expanded
ones, for the same reason DrawerItemVisibility stores the hidden rows: a
heading nobody has ever collapsed simply isn't in the set, so a section
added in a later release opens expanded for everyone with no migration,
and the stored default is exactly the stock drawer. Names, not ordinals,
so reordering DrawerSectionId renames nothing by accident and a value
left by another build costs that one heading rather than the whole read.
DrawerSectionCollapsePreferences takes the DataStore rather than a
Context, which lets a plain unit test drive the full save/restore cycle
against a temp file: toggle, cancel the scope, then build a second
instance over the same file — what a relaunch does.
The peel added a check to the per-word segmenting loop, which every word of
every rendered note walks. Measured on a 68 KB / 12,992-word plain-prose note
(no brackets, no entities — where the check can only cost and never pay),
median of 3 JVM runs:
no check (main) 1,523,109 ns/op —
CharArray + `in` 1,601,363 ns/op +5.1%
`when` over char consts 1,536,011 ns/op +0.8%
`CharArray.contains` is a linear scan, and a miss — the answer for nearly every
word — compares against all twelve before rejecting, at ~6 ns/word. A `when`
over char literals compiles to one lookupswitch and lands inside run-to-run
noise (its three runs straddle main's).
Adds RichTextParserBenchmark alongside the existing prodbench suite so the
per-word loop has a standing guard.
`signOnce` retired the in-flight entry from `invokeOnCompletion`, which runs
when the job ends — after `fresh.complete()` has already resumed the awaiting
caller. In that window the map still holds a *completed* deferred, so the next
caller took the leader/follower branch and was handed the token that job had
already signed instead of signing a new one.
A caller whose token has just expired does exactly that: `header()` misses the
cache, reaches `signOnce`, and gets the expired token straight back.
`BlossomReadAuthTokenProviderTest.refreshesAfterExpiry` closes that window
immediately, so it hit the bug on every run and has been failing on main.
Remove the entry before completing it. `invokeOnCompletion` keeps its
now-idempotent removal as the cancellation safety net.
The test also asserted the re-signed header differed byte-for-byte from the
first. That cannot hold: the injected `clock` only drives the cache TTL, while
BlossomAuthorizationEvent takes `created_at` from `TimeUtils.now()`, so two
signings in the same second produce identical events. Count signatures instead,
which is what "must be re-signed" actually means.
`wordIdentifier` classifies a word by its first character, so a bare
`npub1…`/`@npub1…` glued behind an opening bracket or quote — as in the
kind 1111 comment `(@npub1hgvtv4z…)` — never reached
`startsWithNIP19Scheme` and rendered as plain text.
The `nostr:`-prefixed spelling was unaffected: the URL detector finds the
URI inside the parentheses and `fixMissingSpaces` splits it into its own
word. Bare entities are not URIs, so nothing separated them.
Peel a leading run of opening brackets/quotes off into its own
`RegularTextSegment` when a NIP-19 scheme follows, which is what the
`nostr:` path already produces. Trailing punctuation needs no handling —
it is already captured as the entity's `additionalChars`.
Correctness:
- ProfileCardPreview reused NoteHeaderMarkersPreview's pubkeys and metadata
event ids ("a"*64 / "e1"*32). LocalCache is process-wide across previews and
consuming a kind:0 no-ops on a duplicate id or a non-newer createdAt, so
whichever preview rendered first won and this one showed {"name":"Vitor"} —
the exact layout it exists to check. Now uses keys nothing else claims.
- "Follows you" now hides on your own card. A self-follow in your own kind:3
is common, and the chip had no isLoggedUser guard (the follow button did).
- The website chip passed `clickable` as Surface's outer modifier, above
Surface's own shape clip, so the ripple painted a square over the pill.
Clip first.
- Drop `profile_card_followers`; reuse the already-translated
`number_followers` ("%1$s Followers") instead of shipping a new key.
Allocation / recomposition:
- `pubkeyDisplayHex()` hex-decodes and bech32-encodes the key, and ran on
every recomposition whenever metadata hadn't arrived. Remembered.
- The banner's gradient Brush was rebuilt on every recomposition; remembered
on the background color. Static modifier chains hoisted to file scope, and
the "@handle" / "(pronouns)" concatenations remembered.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D17W8C3bYwwo2mWGm3QCnS
`FullBleedNoteCompose` (the thread/detail renderer behind `NoteMaster`)
keeps its own kind dispatch, separate from `RenderNoteRow`, so a kind:0
opened there still fell through to the raw-JSON text fallback. That path
is reachable: an inline `nostr:naddr…` pointing at a kind:0 navigates to
`Route.Note(aTag)`, and a NIP-22 comment rooted on a profile loads the
kind:0 as the thread's root.
Same `RenderProfileCard`, added at the head of the chain.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D17W8C3bYwwo2mWGm3QCnS
Audit of everything amy keeps under `~/.amy/` against what `status` showed.
Six gaps, all verified against a real data dir rather than reasoned about.
**No account selected.** With a stale `current` pin, or several accounts
and no pin, every verb but `use`/`status` dies at account resolution
("pins 'ghost' but … doesn't exist", "multiple accounts … pick one") —
and status, the command you run to find out why, showed nothing wrong.
It now leads with the cause and the fix. New `current_exists` in JSON.
**Relay config was invisible.** kind 10002/10050 are the first thing
`amy relay add` writes and every account has them, yet status said
nothing about where the account talks. Now `3 relays (2 write, 2 read)`
and `DM inbox on 1 relay`. The read/write split follows NIP-65, where a
bare `r` counts for both, so the two can exceed the total.
**Follows.** kind 3 — the other headline number of a nostr account.
All three come from the existing single multi-kind query on the account's
pubkey, so they cost no extra store round trips.
**"a published key package" was wrong.** It is backed by
`marmot/keypackages.bundle`, which is local private MLS material — the
old field name `key_package_published` had the same lie in it. Now "a
Marmot key package".
**Marmot messages.** `FileMarmotMessageStore` writes `<group>.messages`
in the `groups/` dir status already lists, so group chat history was
sitting there uncounted: `2 Marmot groups, 5 messages`. Counted by
streaming newlines, not by reading files in.
**The operator key.** `~/.amy/operator/` is a machine-level GrapeRank
signing identity that `listAccounts` skips as a reserved name — the one
thing under `~/.amy/` nothing reported. Now a footer line when present,
via a new read-only `OperatorKeys.peek` that needs no SecretStore and
mints nothing (the instance API creates a master on first use).
Considered and left out: decrypted DM counts (needs the signer, would
break the no-prompt promise); git repos, mute lists, bookmarks, search
relays (long tail — each is its own verb, and adding them all rebuilds
the wall of zeros this redesign removed); store size (that's
`amy store stat`); nutzap info (always published with the wallet).
Gathering moves behind `StatusReport.overview()`, which now returns an
`Overview` carrying selection state and the operator alongside the
accounts, so the command stays parse-call-emit.
JSON: adds `current_exists`, `operator`, and `saved.{follows, relays,
relays_write, relays_read, dm_relays, marmot_messages}`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AtKhnNBSr9CWnZyjTWu7dL
A kind:0 in the feed fell through to the generic text renderer, so it
showed up as the raw profile JSON — and tapping it opened the bare note
view. Both are now handled:
- New `RenderProfileCard` (amethyst/ui/note/types/ProfileCard.kt) renders
the metadata event the way the profile screen it opens does: banner
faded into the card background, a ringed avatar overhanging the banner,
the follow/unfollow (or unhide) action beside it, display name with
custom emoji + pronouns, the @handle, the NIP-05/status line, a
4-line bio, and a chip row for follower count, "follows you", website,
lightning address and the bot flag. Chips only appear when the profile
actually carries the data, so a name-only kind:0 stays clean. Tapping
anywhere on the card opens the profile.
- `routeForInner` now maps `MetadataEvent` to `Route.Profile`, so quotes
and `nostr:naddr` deep links to a kind:0 land on the person instead of
the generic note screen.
Everything reuses existing pieces (BannerImage, BaseUserPicture,
ObserveDisplayNip05Status, ShowFollowingOrUnfollowingButton) — the card
adds layout only, no new profile plumbing.
Adds a `ProfileCardPreview` over real notes seeded into LocalCache
(full profile / name-only / bot) so the layout can be reviewed in both
themes.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D17W8C3bYwwo2mWGm3QCnS
A busy account lists six or seven footprint items. Joined with `·` and
wrapped at 78 columns they read as one run-on sentence that has to be
parsed; a column of short lines scans in one pass:
saved: 128 events (newest 2h ago)
3 contacts
2 Marmot groups
a published key package
Drops the wrap machinery (`appendWrapped`, the fixed WIDTH) for a plain
hanging indent. `saved: nothing yet` is unchanged, and so is `--json`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AtKhnNBSr9CWnZyjTWu7dL
The old output was a generic key/value dump: 12 fields per account, most
of them `no` or `0`, plus a `store` block that was wrong on the default
backend — it always walked the FS store path (`shared/events-store`),
so a SQLite install (the default since AMY_STORE landed) reported
`events: 0` no matter how full the database was.
`status` now answers two questions and drops everything else:
alice (current)
Alice Jones · alice@example.com
npub1hje47kz5qeneyqrxc9nzgmz06ml6l9lguqv0qtsz4rkwqkmf636qvg4sz3
local key, in the login keychain
saved: 128 events (newest 2h ago) · 3 contacts · 2 Marmot groups
WHO: the profile name/NIP-05 amy holds locally (read from the account's
own kind:0 in the store — new), the npub, and one plain-English sentence
for the signer instead of three fields (`signer` + `key_storage` +
`can_sign`). Plaintext key storage is called out in yellow.
WHAT'S SAVED: the account's own events in the store and when the newest
one landed (new), contacts, Marmot groups, key package, Concord
communities (new — never reported before), Cashu wallet, DM cursor.
The rule that keeps it short is "absent is silent": anything an account
doesn't have is omitted rather than printed as `no`/`0`, so a fresh
account is four lines and says `saved: nothing yet`. Two accuracy fixes
fall out of that: the self-alias `init` writes is no longer counted as a
saved contact, and the Cashu wallet is detected from a real kind:17375
in the store rather than from `cashu.json`, which only ever held NUT-13
counters. A directory whose `identity.json` won't parse now says so
instead of suggesting `init`, which would mint a new key over it.
Event-store size, backend and kind histogram move out entirely — that is
`amy store stat`, which had its own (correct, backend-aware) version all
along.
Mechanics:
- `Output.emit(result) { color -> … }`, an internal overload for a command
with a purpose-built human rendering. JSON mode is untouched.
- `StoreFactory.openExistingShared(root)` opens the cross-account store
only if it already exists, so this read-only command never leaves an
empty database behind — covered by a test.
- `StoreCommands.fsStat` now calls `StoreStats.of`, which it had
duplicated line for line; `status` was `StoreStats`' only caller and no
longer needs it. Same output, ~50 fewer lines.
- Split into StatusCommand (dispatch) / StatusReport (data + JSON
contract) / StatusText (rendering) to stay under the module's file-size
convention.
JSON contract change (per DEVELOPMENT.md principle 5): `store` and
`account_count` are gone; `hex` is now `pubkey` per the documented
convention; per-account footprint fields move under `saved`; adds
`profile_name`, `nip05`, `saved.events`, `saved.newest_event_at`,
`saved.concord_communities`. No in-tree consumer read the old shape.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AtKhnNBSr9CWnZyjTWu7dL
assertTrue(entry?.isGeneric == true) smart-casts entry to non-null, so
the next line's ?. was dead and the build warned on it. Assert
non-nullness once up front and read the fields plainly.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MXpL2TPmSmxdv7eBwhWvJp
Three bugs, each one where a write could produce a tag the matching read
refuses -- so the entry can never be found again, and every later write
appends instead of replacing.
replaceTrustedListProvider matched only generic entries but wrote
whatever it was handed. A named write therefore deleted the kind's
generic delegation -- a live delegation, gone irrecoverably, since 10040
is replaceable -- while never finding its own entry, so it duplicated on
every call. Replace and remove now address an entry by kind AND name, the
pair the first element encodes.
TrustedListProviderTag and ServiceProviderTag both let a constructor
write a kind their own parse rejects: outside 30392-30395 for the first,
outside NIP-85's 30382-30385 for the second. Both now require it, making
the unreadable state unrepresentable rather than silently accumulating.
That second bound, added in the previous commit on the read side only,
had regressed `amy graperank register --service 30392:podcaster`: the
dedup probe reads through the parser, so it appended a fresh duplicate
per run, and unregister could never match one. The CLI now rejects a
non-assertion kind with bad_args instead of writing a 10040 that grows a
tag per invocation.
Performance: the member scans that return one entry per tag -- members(),
memberValues(), linkedPubKeys/EventIds/AddressIds -- go through a
presizing fastMapNotNullDense instead of the stdlib mapNotNull, whose
capacity-10 start costs ~20 array copies on a 5k-member list. Deliberately
NOT applied to the sparse scans beside them: picking two discovery tags
out of thousands would allocate a thousands-wide array to hold two, which
is worse than the growth it avoids. The operator's KDoc says so.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MXpL2TPmSmxdv7eBwhWvJp
A 10040 keeps half its delegations NIP-44 encrypted in content -- who you
trust to rank the network is itself sensitive -- and the previous commit
only reached the public tags. The parsing was never the gap: it is
TagArray-level, so a caller merging the halves (commons'
PrivateTagArrayEventCache, which is how the app reads NIP-85 providers)
already got private entries out of trustedListProviders(). What was
missing was the event-level surface.
Reading now splits explicitly. publicTrustedListProvider(kind) is the
public tags alone; trustedListProvider(kind, signer) merges both halves
and falls back to the public half with anyone else's signer rather than
failing, matching TrustProviderListEvent.privateTags. Public tags are
searched first, so a Map that violates the invariant across halves
resolves to its public entry.
Writing takes isPrivate and maintains the invariant ACROSS halves: at
most one generic entry per kind is a property of the Map, not of one
half, so the write also drops the entry from the other side. Moving a
delegation between public and private is one call instead of a two-step
that strands a twin -- shadowed on read, republished forever after.
That costs the property the earlier version had of never needing
decryption: a public write on a Map with a private half must open it,
because we cannot drop a twin we cannot read. It throws
UnauthorizedDecryptionException rather than publish a Map that breaks the
invariant. A Map with no private half needs no decryption either way.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MXpL2TPmSmxdv7eBwhWvJp
A 10040 delegates each assertion kind+metric with
["30382:rank", <pubkey>, <relay>]. Trusted Lists extend the Map with a
generic bare-kind entry, ["30392", <pubkey>, <relay>] (Tapestry ADR
tl-treasure-map/0001), where one entry delegates every list of that kind
and names are never enumerated. Quartz could not see it at all: parsing
went through ServiceType, which requires a `:`, so the entry fell out as
unparseable and the delegation was invisible.
Two further gaps came out of probing the same path:
An entry whose relay hint is the empty string -- what a publisher writes
when it has no relay configured, keeping the three-element shape -- was
dropped whole, taking the pubkey with it. The pubkey is the part a
consumer cannot do without, so relayUrl is nullable here and the
delegation stands without a hint.
A reserved named entry, ["30392:podcaster", ...], splits into two
segments exactly like "30382:rank" and was being handed to NIP-85
consumers as a live provider -- the one thing the spec says readers must
not do with them. ServiceProviderTag.parse is now bounded to NIP-85's own
assertion kinds (30382-30385), so those entries route to the Trusted List
parser instead of the rank/follower-count lookups. Nothing is lost, only
sorted: named entries parse, carry isGeneric = false, and drive nothing.
Readers resolve duplicate generic entries first-occurrence-wins, so two
readers of one Map pick the same publisher. Writers go through
replaceTrustedListProvider, which swaps the entry in place, collapses
duplicates for that kind, and preserves every other tag verbatim -- 10040
is replaceable, so anything dropped on an update is gone from the Map for
good. Content is carried across untouched, so the write needs no
decryption permission.
Kept in experimental/trustedLists/treasureMap rather than the NIP-85
package: this is a pre-NIP extension riding on that kind, and a NIP-85
consumer should stay unaware of it.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MXpL2TPmSmxdv7eBwhWvJp
The member tag has carried its score at index 3, right after the relay
hint, since the family landed -- but as a bare Int with no domain. A
number nobody agreed on the ceiling for cannot be compared across two
publishers, or even across two metrics of one publisher, which is the
whole reason a list carries scores instead of just membership.
Pin it to a percentage: an integer 0..100 inclusive, named once in
MemberTagFields.SCORE_RANGE and shared by `p`, `e`, `a` and `i`.
Write clamps into the range, so we never emit a value we would refuse to
read. Read drops anything outside it rather than clamping: a publisher
counting on some other scale (0..1, 0..1000, a raw endorsement tally) is
reporting a quantity this field cannot carry, and pinning 950 to 100
would rank that member above every honestly-scored peer. The member
itself still stands -- it is simply unscored, the same state as a tag
that carries no score at all.
Both bounds are real scores, not sentinels: 0 means "scored, and the
publisher has no confidence in this member", which is not the same as
unscored.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MXpL2TPmSmxdv7eBwhWvJp
The audit that produced the previous two commits used line-anchored greps, so
a call formatted across several lines was invisible to it. That selected for
short calls rather than expensive ones, and it shows: BootRelayDiagnostics had
three one-line banner calls converted while two Log.d calls in forEach loops
immediately below them — 25 and 20 iterations per census, each concatenating
five interpolated segments with nested joinToString — were left eager. Those
are the larger cost by a wide margin, and Log.d is dropped in every build.
Convert them, plus the multi-line census header and one in
AccountConcordActions. The three multi-line calls left in AccountCacheState
pass a throwable and carry static messages, so the eager form is correct there.
Also from review: extract the duplicated sort+join chain the two census
summaries shared; drop "${e.message}" from two AccountCacheState calls that
already pass the throwable (the inverse of the bug the first commit fixed, and
pre-existing); hoist refusalReason() in BlossomPaymentHandler, which computed
it twice on the same branch.
Record the rule in CONTRIBUTING-WITH-AI.md's existing Logging section, which
already owns the lambda-Log guidance — the previous commit put it only in the
skill, which is read only when the skill is invoked. Add a comment to
Amethyst's init block explaining why Log.minLevel is set there and not in
onCreate: init runs in every process, including the :napplet sandbox whose
onCreate early-returns, so moving it would leave that process at DEBUG.
The skill gains the multi-line step, and its own errors are fixed: it said
"Two" above a three-item list, Step 3 still used the anchored pattern and
short name list that Step 2 had just been corrected for, and the verify
command used grep -c, which counts lines and so undercounts. Step 4 becomes
Step 0 and moves above Step 1 — it gates the others, and saying so five times
in a document that ordered it last was the symptom.
refactor(logging): move the last android.util.Log users onto the quartz wrapper
fix(logging): use the lambda overload, and keep the throwable in a catch log
NIP-47 says a client "should always prefer nip44 if supported by the wallet
service", so prefersNip44() returning false has to mean "the wallet does not
offer NIP-44" — not "we have not asked yet". It meant both.
NwcInfoCache is per-account and in memory only, so it starts empty on every
app launch, and prefersNip44 read it without waiting. The first transaction
to each wallet after each launch therefore went out as NIP-04 even against a
wallet advertising nip44_v2 — a silent downgrade to deprecated encryption on
a payment request. The startup warm-up narrows the window but does not close
it: it only covers the default wallet, and it races the user's tap.
Add currentOrFetch(), which waits only when nothing at all is cached and
returns a stale entry as-is — staleness never caused the downgrade, since a
stale entry already says what the wallet advertises, so waiting on it would
buy nothing. prefersNip44 becomes suspend and uses it; both call sites were
already suspend.
Funnel every fetching path through one request per wallet. getFresh() went
straight to the network with no deduplication — only the background refresh
was guarded, and by a plain key set that could not be awaited. Without this,
making the payment path wait would have had it race the startup warm-up and
issue a second concurrent fetch for the same wallet.
Verified by mutation: reverting currentOrFetch to the old non-waiting read
fails the cold-cache tests, and removing the single-flight fails the
deduplication tests. The prefersNip44 call site itself is a two-line swap
covered by those cache tests — NwcSignerState has no test harness and
building one for it was out of proportion to the change.
Single-flight landed inside OkHttpLnurlEndpointResolver, which put the two
halves of one mechanism — "resolve this URL exactly once" — in two modules.
The flight map had to call LnurlForm.normalizeUrl purely to match a keying
detail private to LnurlEndpointCache in quartz. Nothing documented or
enforced that: if the cache changed its canonicalisation, the map would
silently stop deduplicating and no test would fail.
Move it onto the cache as getOrFetch(url, fetch). The key is now computed
once and shared by the lookup, the flight map and the store, so they cannot
disagree. Dedup also becomes process-wide, matching the resource it
protects — a stranger's /.well-known/ endpoint — rather than being scoped to
one resolver instance; clear() resets both maps. The resolver drops to a
one-line delegation and keeps only the HTTP half. Same shape as NwcInfoCache,
which already pairs a cache with an in-flight map and an injected fetch.
Mechanism tests move to quartz beside the cache, using delay() rather than
a blocking sleep. The commons test keeps the one claim it uniquely makes:
that the resolver really routes through the cache over a real OkHttp client.
No behaviour change. Verified by mutation: removing single-flight, keying
the flight map on the raw URL, never releasing the slot, and making the
resolver bypass the cache each fail exactly the test that covers them.
A zap-receipt burst hands OkHttpLnurlEndpointResolver one resolve() call
per receipt, each on its own coroutine from LocalCache.consume(LnZapEvent).
The resolver's read-through cache only helps once a fetch has landed, so
the whole burst missed together: N receipts for one lightning address made
N requests to that provider's /.well-known/lnurlp/ endpoint. A
lightning-address server observed ~20 per user action, with no zap sent.
Hold one CompletableDeferred per in-flight URL and let the rest await it.
The entry is keyed through LnurlForm.normalizeUrl, matching how
LnurlEndpointCache keys itself, so host case and a trailing slash share a
flight rather than starting two. The winner releases the slot in a finally
after the cache is populated, so a failed fetch is retried by the next
caller instead of being remembered as null, and awaiters are unblocked
even if the winner is cancelled.
The cache itself is unchanged.
Tested with a burst whose callers are released through a shared gate. The
gate is load-bearing: asserting "one fetch" while relying on every coroutine
reaching putIfAbsent before the winner's fetch returns makes a slow machine
fail the test rather than a regression. The burst test failed 20/1 before
this change.
Auditing every text-field call site against the view models that can accept
media turned up four more composers with an upload button and a full media
pipeline, but no `onContentReceived` — so a GIF inserted from the keyboard
silently did nothing there too:
- New public message: already called MessageFieldRow, which gained the
parameter in the previous commit; it just never passed one.
- Nests audio-room chat.
- Long-form markdown editor.
- Minichat, which routes through ChatFileUploadState instead of the view
model, so it also mirrors the gallery button's encryptFiles choice.
Two composers are deliberately left out. NewHighlightScreen has no media
pipeline at all, so a received GIF would have nowhere to go. EditPostView
uses OutlinedThinPaddingTextField, which has no contentReceiver — supporting
it there means changing that component, not passing an argument.
Only the keyboard commitContent path is addressed here. The chat composers
still lack the onNewIntent listener that catches a share-intent GIF (as
SwiftKey sends it), so sharing one from a chat continues to navigate out to
a new short-note composer; that is a larger change and is left for its own
pass.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMyN6Y7DsXFdPxDxLfgo3g
Replying to a kind-1 note opens ShortNotePostScreen, which wires both GIF
delivery paths. Replying to a comment (or a hashtag/geohash/url scope) opens
GenericCommentPostScreen, which wired neither, so GIFs silently did nothing:
- Gboard-style `commitContent` reaches the field only when the caller passes
`onContentReceived`; ThinPaddingTextField attaches the `contentReceiver`
modifier just for those, and MessageField defaults the parameter to null.
The comment composer never passed one.
- SwiftKey delivers a GIF as a fresh ACTION_SEND. ShortNotePostScreen catches
it with its own onNewIntent listener; the comment composer had none, so the
global share router in AppNavigation handled it instead — and since its
guard only recognised Route.NewShortNote, it answered a GIF by starting a
brand-new short-note composer and discarding the reply in progress.
Wire both paths into GenericCommentPostScreen, which covers all four of its
entry points (comment, hashtag, geohash and url replies), and widen the
onNewIntent guard via consumesSharesInPlace() so a redelivered share no longer
throws away the draft. The launch-intent guard is left alone: a share that
starts the activity has no composer listening yet, so it must still navigate.
The root cause is copy-paste drift between composers, so also pull the four
identical addToMessage() bodies up into IMessageField as a default, and pass
onContentReceived on the other two composers with a working media pipeline
(new product, new group DM). NewHighlightScreen has no media pipeline and
EditPostView uses OutlinedThinPaddingTextField, which has no content receiver
— both left as-is.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CMyN6Y7DsXFdPxDxLfgo3g
Hanging up during a screen share opened the front camera for ~350ms before
closing it again. CallMediaManager.dispose() calls stopScreenShare(), which
restores the pre-share camera state, and only then calls stopCamera(). On an
SM-T220:
22:07:46.389 MediaProjection: Dispatch stop to 0 callbacks
22:07:46.432 CameraCapturer: startCapture: 1280x720@30
22:07:46.438 Camera2Session: Opening camera 1
22:07:46.433 CameraCapturer: Stop capture: Waiting for session to open
22:07:46.765 Camera2Session: Stop done
so the user sees the camera privacy indicator flash on hangup, and the teardown
blocks waiting for the capture session it just started. It also churned the
local video track and source through recreateCameraResources() purely to
dispose them a few lines later.
stopScreenShare() takes restoreCamera, defaulting to true so the user-initiated
stop is unchanged; dispose() passes false.
Verified on device. Hangup while sharing: camera opens once for the call, closes
when sharing starts, and is never reopened during teardown — no startCapture and
no "Opening camera" in the teardown window. Stopping the share with the button
still restores it (startCapture + CAMERA_STATE_ACTIVE, preview returns).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Awrm1ro4eQXSaXDoH8EW3z
A call that was up died as soon as Android reclaimed the backgrounded
MainActivity — reproducible on a Samsung SM-T220 a few hundred ms after
CallActivity enters picture-in-picture on HOME. Any screen share went
with it. Two independent causes:
1. Call state was owned by an Activity-scoped ViewModel.
AccountViewModel.onCleared() -> CallSessionBridge.clear() ->
CallManager.reset() -> CallState.Idle -> CallSession.close().
CallManager also ran on viewModelScope, so a surviving call would
still have been half-dead (signaling publishes silently no-oping).
CallSessionBridge.clear() assumed onCleared meant "logout or account
switch"; it fires on every MainActivity destruction.
2. CallForegroundService.onTaskRemoved hung up on the wrong task.
It fires for every task of the app, and MainActivity is
singleInstance while CallActivity launches with FLAG_ACTIVITY_NEW_TASK
— so they live in different tasks. The service treated the system
reclaiming MainActivity's task as the user swiping the call away
(transitionToEnded reason=HANGUP).
Fixes:
- Account owns callManager, built on account.scope, so it outlives the
UI and dies with the account.
- AccountViewModel references account.callManager; onCleared only drops
the ViewModel reference.
- CallSessionBridge exposes the app-scoped Account and splits teardown:
clearViewModel() (activity destroyed) vs clear() (real logout/switch).
- CallActivity binds its session to the Account; only its UI uses the
ViewModel.
- AccountSessionManager calls CallSessionBridge.clear() on switch/logoff,
mirroring the existing NestBridge.clear() hooks.
- AccountCacheState.removeAccount disposes callManager, whose watchdog
scope is independent of account.scope.
- onTaskRemoved only hangs up for CallActivity's own task; a null root
intent still hangs up so a swiped-away app cannot strand a call.
Verified on device: HOME during a call now keeps the call up (it ends
only on the legitimate 30s ring timeout), and a connected call with
screen sharing keeps streaming to the peer after the sharing device is
backgrounded.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Awrm1ro4eQXSaXDoH8EW3z
CallMediaManager.stopScreenShare() returns ScreenShareResources and
disposeScreenShareResources() takes it, but the class was declared
internal, so :amethyst:compilePlayDebugKotlin failed:
'public' function exposes its 'internal' return type 'ScreenShareResources'
'public' function exposes its 'internal' parameter type 'ScreenShareResources'
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Awrm1ro4eQXSaXDoH8EW3z
A brand-new install routes 100% of its relay traffic over Tor by construction,
and that is a chicken-and-egg rather than a preference: `trustedRelays` is empty,
so `TorRelayEvaluation` falls through to `newRelaysViaTor` (default true) for
every url — and the kind:10002 that would populate it can only be fetched over
Tor. Measured on a Samsung SM-T220, same account, same login timing, fresh
install each: the first relay socket opened 2.3-2.9s *after* Tor became ready,
whenever that happened to be, and Arti's directory download ran 12.6-51.7s.
While an account's own lists are unknown, the defaults the app is already
dialling are now also classified for Tor purposes — as `assumed` relays, the
last branch before `newRelaysViaTor`:
first relay socket, vs when Tor became ready (n=3 each, counterbalanced)
before: login+5.87s / +7.89s — always 2.3-2.9s AFTER Tor Active
after: login+1.21s / +1.24s / +1.29s — independent of Tor entirely
events ingested by the 20s census, non-overlapping
before: 0 / 892 / 1159 / 2590
after: 3719 / 3997 / 4081 / 5311 / 6051
It resolves to `trustedRelaysViaTor`, not to a hardcoded false: the app's
stand-in for a list gets the policy the user chose for their own list, so
anyone who set that preference keeps Tor here with nothing new to discover. And
it sits below .onion, money-operation and DM in the precedence chain, so those
keep their own policy for free — the branch can only capture urls that would
have been treated as strangers.
The guess ends by itself. `assumedDefaults` keys on the *event* being absent —
never on a list being empty, which is a choice we honor — so each list's
contribution empties the moment that event lands, with no window, timeout or
per-account bookkeeping. Device log: `Guessed relays: 15 -> 10 -> 5 -> 0 (own
lists arrived; released to their real Tor policy)`, after which 28 relays
re-dialled and their connect latency moved from a median 116ms to 503ms — the
handover onto Tor circuits, visible in the timings.
Deliberately NOT merged into `TrustedRelayListsState`. That feeds
`Account.isInMyRelayList` -> `RelayAuthPermissionLedger` -> `RelayAuthResolver`,
i.e. the NIP-42 AUTH decision. Guessed relays must never make the app sign an
AUTH challenge as though they were the user's own; that would turn a timing
signal into a signed identity assertion. Tor routing is the only consumer.
Two supporting changes, both of which pay for themselves here:
`RelayClassification` groups the four category sets into one value. The
reconnect trigger in `RelayProxyClientConnector` used to compare them field by
field, so a new category meant remembering another `||` — and I had forgotten
it, which is exactly the silent failure it invites: relays keep a socket on a
transport the policy has already moved them off. It is now one structural
comparison. That also removes a `Pair` that existed only to squeeze past
`combineTransform`'s five-source limit. Regression test covers the case that
made the omission reachable: an *empty* arriving list, where `trusted` does not
change while `assumed` empties.
`AccountsTorStateConnector.unionAcrossAccounts` replaces four ~30-line copies of
the same per-account fold. The copies had already drifted — two carried an
`if (isEmpty)` guard that could never fire, since `ifEmpty` had just guaranteed
otherwise.
Verified byte-identical to the build these numbers were measured on, and
re-measured after the refactors: first socket 1.24s median vs 1.21s before,
fully overlapping.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BKYGEp22uGSzWrBDg8fAQ9
There are three states, and two of them were collapsed:
| we have | effective list |
|------------------------|---------------------------------------|
| no event for the user | app defaults — we do not know |
| an event, empty list | **empty** — they told us: nothing |
| an event with relays | those relays |
Every `WithBackup` helper keyed its fallback on the list being *empty* rather
than the event being *absent*, because `readRelaysNorm()`/`writeRelaysNorm()`
end in `.ifEmpty { null }` and the indexer/search helpers wrote
`?.ifEmpty { null } ?: DEFAULTS` outright. So a user who publishes a kind:10002
carrying only write relays silently acquired `Constants.bootstrapInbox` as their
*inbox* list, and a deliberately empty search or indexer list was replaced by
ours. That is the app overriding an explicit choice.
Only `normalizeNIP65AllRelayListWithBackup` was correct, and only by accident:
`relays()` has no `ifEmpty`, so its `?:` could fire only for a missing event.
The rule is now one named, tested primitive rather than an expression
open-coded at four call sites — three of which got it wrong the same way:
relayListOrDefaultsWhenUnknown(event, defaults) { it.readRelaysNorm()?.toSet() }
`Account.indexRelays()` loses its `.ifEmpty { DefaultIndexerRelayList }` too;
it re-applied the substitution a layer up and would have undone the fix.
Two things deliberately left alone. The `Precached` variants keep substituting
defaults: they read only *already decrypted* tags, so empty there can mean "not
decrypted yet" — an unbounded window for a NIP-46 signer — rather than "the user
chose nothing", and the primitive's KDoc records that as a non-goal. And the
`NoDefaults` flows keep returning `emptySet()` for both cases, since their job is
to show what the user published.
Note for callers: the indexer and search flows previously documented themselves
as **never empty** and that contract is gone. A user who publishes an empty
kind:10007 now gets no search relays, which is what their event says. The same
applies to NIP-65 write relays, where the old fallback meant posts went to six
hardcoded relays; if a safety net is wanted there it belongs at the publish site
as a visible decision, not as a silent list substitution.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BKYGEp22uGSzWrBDg8fAQ9
A brand-new install could stop connecting to Tor entirely. Not slowly —
permanently: exactly two bootstrap attempts, then silence. Reproduced on a
Samsung SM-T220 (benchmark build, fresh install, log in, 150s offline, network
back): Tor never reached Active in the following 600s, no profile, no relay
lists, "Feed is empty." With the fix, the same scenario recovers at net+51s.
Root cause: on a native bootstrap timeout `TorService.start()` deliberately
leaves status at Connecting and delegates the retry to `TorManager`'s watchdog,
but that watchdog was `status.transformLatest { if (Connecting) { delay(45s);
emit() } }` — it fires once per Connecting *span*, and a timeout produces no
status change, so no new span ever began and the signal was never re-armed.
Nothing else covered it: `onNetworkChange` fires only on a networkId *change*
and `AppModules` drops the first non-null one, so even a network arriving from
offline did not rescue it.
Lifecycle fixes:
- the watchdog re-arms while stuck instead of firing once per span;
- it skips an attempt that is genuinely running, so a reset can no longer
queue behind the blocking JNI call and tear down a client that just
succeeded;
- an install that has never bootstrapped retries on a 30s cooldown rather
than the 5-minute one meant to protect working state;
- `service.start()` is no longer awaited before `emitAll(service.status)`, so
the app observes Connecting when the attempt starts rather than when it
ends (on device the watchdog moved 105s -> 90s);
- a hard init failure and port exhaustion no longer set the terminal Off,
where neither the watchdog nor the failure dialog arms; both leave
Connecting to be retried. The init path also no longer wipes all Arti data
on any failure, which turned a transient "no network" into a lost guard
sample — with an escalation after 3 fruitless gentle resets so corrupt
state on a fresh install is still recovered.
Arti now bootstraps on demand. `create_bootstrapped` blocked the JNI call — and
the Kotlin lifecycle lock it holds — for the whole directory download (12.6s to
51.7s measured), during which `activePortOrNull` was null so every Tor-routed
dial fell back to 127.0.0.1:9050, the Orbot default, where nothing listens.
`create_unbootstrapped_async` + `BootstrapBehavior::OnDemand` returns in 124ms
and lets each stream wait for its own circuit. It does not make first paint
faster — the download is the real gate — but it removes the dead-port window
and the up-to-60s lock hold that also made "turn Tor off" appear frozen.
That forced a state split, and it is the load-bearing part. `Active` was
carrying two facts that used to coincide: "proxy routable" and "circuits
buildable". Android's `TorServiceStatus` gains `Bootstrapping(port)` plus
`socksPort` / `isFullyBootstrapped`, so callers state which they mean instead of
matching a variant that looks right for both. Commons gets the accessors only —
the desktop backend drives an external Tor and never sees the window, and a
variant nothing emits is dead weight.
Watchdogs are judged on forward progress, not elapsed time. Measured cold
downloads ran 12.6, 13.4, 14.0, 15.6, 17.9, 19.7, 19.8, 20.0, 34.4 and 51.7s on
one device and network, so no fixed patience separates slow from stalled: short
enough kills healthy downloads — and a reset discards the partial consensus, so
firing early can stop one ever finishing — while long enough sits uselessly on a
hang. A new `bootstrapProgressPermille()` exports `as_frac()`, and a download is
reset only after 60s with no movement at all, never with a state wipe. Device
run: a 51.7s download completed untouched where the previous code would have
reset and wiped its cache at 45s. `blocked()` is deliberately unused; Arti
documents it as best-effort and warns it misreports in both directions.
Readiness is read live (`bootstrap_status().ready_for_traffic()`) rather than
latching the one background `bootstrap()` result, which would report "not
bootstrapped" forever against a Tor that a later stream had already recovered.
`canDial` and `TorCircuitHealthTracker.isTorActive` gate on readiness, not
routability. Dialling on routability alone put ~190 relays into a backoff that
is never forgiven — the port is identical either side of Bootstrapping -> Active
so the transport never "changes" and `resetBackoff()` never runs — and it cost
nothing to wait: time-to-first-socket was unchanged by dialling early (n=3).
Both jniLibs ABIs rebuilt and verified reproducible from an upstream clone
(arm64 b53d20d2..., x86_64 36d41793...). `build-arti.sh`'s JNI symbol check
gained the new exports; it is a hardcoded list, and without them it silently
passed a stale .so.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BKYGEp22uGSzWrBDg8fAQ9
The `benchmark` build type is a release build (R8 + AOT) that exists purely to
be measured and is never shipped, but `DEFAULT_LOG_LEVEL` keyed on
`BuildConfig.DEBUG` and so pinned it to WARN. That dropped every INFO milestone
a boot narrative is made of — account load timings, Tor status transitions, the
BootRelayDiagnostics census — leaving the one variant whose numbers are
trustworthy as the one variant we could not read.
Key it on `isDebug` instead, which already covers the benchmark type
(DebugUtils.kt) and is what gates `BootRelayDiagnostics` itself, so the census
and the log level that lets it through can no longer disagree. Release is
unaffected and stays at WARN.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BKYGEp22uGSzWrBDg8fAQ9
Deleting a NIP-51 people list (kind 30000) or follow pack (kind 39089)
left a null-event AddressableNote behind — and the persisted per-screen
TopFilter that still pointed at the address re-created that shell on
every start via getOrCreateAddressableNote, so the deleted list kept
showing in the top-bar feed filter, its name falling back to the dTag
(UUID) once the event was gone.
- PeopleListsState / FollowListsState: exclude addressables without an
event from the picker options (generalizes the earlier block-list-only
filter to every list, and adds it for follow packs).
- deleteFollowSet() now resets any persisted default*FollowList that
still points at the deleted address back to that screen's default, so
no dangling filter survives a restart.
Fixes#3949
Merges nostr proposal 12762d29 into main:
- NotificationDispatcher gains lastRequestError so the OS's own message
(e.g. UNErrorDomain "Notifications are not allowed for this application")
reaches the settings UI instead of a generic "denied".
- NucleusNotificationDispatcher bounds requestPermission with a 90s timeout,
so an auto-dismissed macOS permission banner no longer parks the coroutine
and the "Requesting..." spinner forever.
- sendMac waits up to 10s for the UNUserNotificationCenter.add ack and
reports Failed on a non-blank OS error instead of a phantom Delivered.
- NotificationSettingsScreen surfaces the error text and offers "Ask again".
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PUzAFtZJYBUr8wvFdqM2Mb
fix(nwc): close the last silent path and drop the success-type guessing hazard
refactor(nwc): fold the repeated failure-message logic into shared helpers
Field report (BrollyZapper, 2026-08-25): a QUOTA_EXCEEDED on pay_invoice and a
RESTRICTED on list_transactions both reached the phone and showed nothing at
all — no toast, no dialog, no error state. The action simply looked like it had
not happened. Three separate defects produce that symptom.
1. The zap path had no user-visible timeout. NwcSignerState's 60s safety net
only dropped the relay subscription: it never cleaned the tracker entry and
never told anyone. A response lost in transit (the same trip measured
relay.damus.io refusing 40% of websocket upgrades) was therefore permanent
silence. The timeout now retires the request and fires an onTimeout callback
that every interactive caller renders. NwcPaymentTracker.cleanup returns
whether it was the one to remove the entry, so a timeout racing a real
response stays quiet rather than overwriting the wallet's own answer.
2. WalletTransactionsScreen never read walletViewModel.error. The ViewModel set
it correctly on both the refusal and the timeout paths; the view branched on
isLoading/isEmpty only and rendered "No transactions yet" over the top of it.
3. Consumers matched on PayInvoiceErrorResponse, which the deserializer only
produces when result_type == "pay_invoice". NIP-47 does not require a wallet
to echo result_type on an error, and an error for any other method takes the
generic NwcErrorResponse branch — so those refusals were dropped without a
word, and the DVM screen went as far as thanking the user for a payment that
had just been refused. All of them now match IErrorResponseLike, and the
remaining else branches report an unreadable response instead of nothing.
Also: errorMessage() falls back to the code name when a wallet sends `code`
without `message` (message is optional in NIP-47), and stale wallet errors are
cleared when a transaction fetch or page load succeeds.
`accept="video/*" capture` handed the page a 0-byte file. The recording was
fine — we deleted it before the page could read it.
parseResult assumes a camera signals success by filling the EXTRA_OUTPUT file
and returning no URI. ACTION_IMAGE_CAPTURE does exactly that.
ACTION_VIDEO_CAPTURE on GoogleCamera does not: it writes the file *and* echoes
the output URI back in the result. That echo lands in `picked`, which makes
`captured` null, and the cleanup loop then treats every capture as unused:
if (capture !== captured) NappletCaptureFiles.discard(context, capture.file)
So the one file whose URI was on its way to the page was the one file deleted.
The page opened it, found nothing, and a "successful" upload carried no bytes.
Captures whose URI is being returned are now excluded from the discard sweep,
whichever way they got there — echoed back in the result, or found by the
fill check. Untouched capture files are still deleted immediately, so a
dismissed or unused camera option leaves nothing behind.
An echoed URI is also no longer trusted on its face: if the file behind it is
empty the URI is dropped, and the request falls through to the same emptiness
rules as before rather than reporting a capture that never happened. URIs that
are not ours are never second-guessed.
Verified on device (Pixel 8 / Android 17), after the fix:
- video: 28,135,304-byte mp4 delivered and readable, was 0 bytes before
- image: 781,853-byte jpeg with EXIF intact — unchanged, no regression
- grants on the capture authority: 0 before, 1 while the camera holds it,
0 again once the result is in, for both media
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Completing a pick on either embedded surface crashed the whole app, every
time. parseResult resolved the picked URIs through
`WebChromeClient.FileChooserParams.parseResult`, which is a WebView *static*:
it boots Chromium in whichever process calls it. WebFileChooserActivity — the
main-process chooser host that exists precisely because the `:napplet`
providers are windowless and have no Activity to launch a picker from —
declares no `android:process`, so that call ran in main while `:napplet`
already held the WebView data directory. AwDataDirLock then threw
Using WebView from more than one process at once with the same data
directory is not supported
as a FATAL EXCEPTION on main. Reproduced on a Pixel 8 / Android 17: the
picker opens, the user selects, and on Done the process dies before the page
is ever handed its file.
The two Activity-owning hosts never hit it because they are themselves
`android:process=":napplet"`, where WebView is already initialised — which is
why the full-screen browser picked files correctly throughout. Cancelling did
not hit it either, so "the picker opened" was never enough to catch this.
The URIs are now read off the result Intent directly. The platform
implementation reads exactly the same two fields (ClipData items, else the
data URI, only on RESULT_OK), so behaviour is unchanged for the single-URI,
multi-select and camera shapes; it just no longer drags WebView into a
process that must not have it.
This also plugs a grant leak. releaseGrants runs *inside* parseResult, after
the line that was throwing, so every crashed capture left the camera apps
holding a live write grant on the capture URI that nothing would ever revoke.
Verified on device after the fix:
- embedded pick: no crash, page reads back all 94,976 bytes of the chosen
PNG with its header intact — so a URI granted to the main process is
readable by the WebView in `:napplet` with no re-granting, as designed
- camera capture: 892,681-byte JPEG with EXIF intact (full resolution, so
EXTRA_OUTPUT is doing its job), delivered under the same name as the
granted URI
- grant/revoke: 0 outstanding grants on the capture authority, 1 while the
camera holds it, 0 again once the result is in
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Two deviations from BUD-11, both predating the read-auth rework and both
carried forward by it.
The `x` tag defeated the per-host token cache. BUD-11 lists `x` as
optional for `GET /<sha256>`, but its Tag scoping rule is strict about
what including one means: "When `x` tags are present, the token is only
valid for operations on the specified blob hashes." Tokens are cached per
host and replayed for every blob on it, so from the second image onward we
were sending a token scoped to some other blob's hash. The old comment had
the reasoning backwards — it kept `x` "for servers that check it", which is
precisely the case that rejects a reused token. createGetAuth now takes a
nullable hash, and the read-auth path passes null: the `server` tag alone
scopes the token, which is what makes reuse legitimate. That widens the
grant from one blob to any blob on the host for the token's hour, which is
the inherent price of caching and is the shape BUD-11 sanctions.
The token encoding was standard Base64. BUD-11: "MUST be encoded as Base64
URL-safe without padding (Base64url, as used by JWTs)". In practice the
alphabets coincide — a token's JSON is printable ASCII and a sextet only
reaches 62/63 when the third byte of its group is `>`, `~`, `?` or DEL, so
`+` and `/` never appeared across 600 sampled tokens — but padding did, on
52% of them. NIP-98's encoder is deliberately left alone; it specifies no
variant.
Nothing in the tree decodes a Blossom auth header, so the encoding change
is client-side only.
Tests pin both rules at the event level and end-to-end on the token this
path actually mints, with several content lengths for the padding case
since whether padding appears depends on the JSON length mod 3.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TYrDf5Z8TE4uivADuFwPFz
BlossomReadAuthInterceptor bridged the suspend signer with runBlocking so
it could retry an auth-gated blob with a signed BUD-01 token. intercept()
runs on an OkHttp dispatcher thread, so that wait held one of the 16
per-host slots for the whole signing window — up to the 8s timeout, and
with a NIP-55 external signer a real IPC round trip. A feed's first burst
against a gated host could occupy every slot and stall every other image
from it.
Interceptor.intercept() is synchronous by contract, so the wait cannot be
made cheap in place; it has to move to a caller that already suspends.
Coil's Fetcher.fetch() is that caller:
- BlossomReadAuthTokenProvider.header() is now suspend, and signs on an
injected scope. Concurrent callers collapse onto one CompletableDeferred,
so a cold burst mints one signature instead of N — the token cache alone
could not do that, being populated only after a signature returned.
cachedHeader() stays a pure map read for callers that cannot suspend.
- BlossomReadAuthFetcher carries the anonymous -> 401 -> signed retry,
catching the HttpException that Coil's NetworkFetcher raises for a
non-2xx and re-issuing with Authorization injected into options'
httpHeaders. Wrapped around all three network-backed Coil factories.
- The interceptor now only attaches an already-cached token for a
known-gated host and fires the mint off-thread, so video and other
non-Coil callers still pick a token up on their next request.
Measured on the same signer and host, signature latency 2000ms:
waiting for it cost 2003ms on the calling thread, intercept() now returns
in 0ms. With 16 concurrent callers and a 300ms signature: 1 signature,
all callers done in 303ms.
Behaviour for images is unchanged — anonymous first, signed retry, host
learned so later blobs are signed up front. The one narrowing: a gated
host reached first by the video datasource cannot mint its own token and
must wait for the warm to land.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TYrDf5Z8TE4uivADuFwPFz
Swap the deprecated persistent-collection mutators in PollResponsesCache
for their kotlinx-collections-immutable 0.5 replacements (add -> adding,
remove -> removing, put -> putting), drop two safe calls on receivers the
compiler already smart-casts to non-null, and rename the test stub's
override parameter to match ICacheProvider.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014B22CbhBupxD3DZcac8jMi
isStranded describes the window's insets listener, not any single layout, so
every call site in a window has to read the same flag. Each one built its
own, with its own IME_STRAND_GRACE_MS timer, and nothing made two of them
agree.
DisappearingScaffold is where that bit. It held two: one behind the root
modifier's padding and one whose value is subtracted from the nav-bar
reservation, with a comment asserting "the two have to agree" that the code
did not back. It also called imePaddingSafe() inside both arms of
`if (canHideBars)`, putting the call in two composition groups — so a
window-size-class change disposed and rebuilt the instance, dropping
isStranded back to false and putting the stale gap back on screen until a
fresh watchdog re-detected it.
SafeImeInsets is now cached per view, keyed exactly the way Compose keys
WindowInsetsHolder itself, and its constructor is internal so the cache
cannot be bypassed. Keying on the view is also what keeps a Dialog on its
own window's reading — a CompositionLocal would have handed it the host
activity's, which is why one was rejected earlier. The scaffold resolves the
instance once above the branch and passes it to ScaffoldLayout, so the value
it pads with is the same object the subtraction reads.
Call sites still park a watchdog each. They now write one shared flag from
the same two sources, so they cannot disagree; collapsing them to a single
watchdog would need either a scope outliving every call site (strongly
holding the view, defeating the weak cache) or a hand-off when the owning
site leaves the composition — both cost more than the coroutine they save.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bqpAeyLAxHzw5XsnRUtjD
This was the last screen still reading the raw animated IME inset, so it was
the one place `imePaddingSafe()`'s recovery could not reach. `union` takes the
max per side: with the inset wedged at the keyboard height and navigationBars
at ~48px, the union stays at the keyboard height and the bottom bar sits a
keyboard up with no keyboard on screen — permanently, because nothing else
pulls it back down.
The lift itself is correct and stays: `AddMuteWordTextField` has to clear the
keyboard. Only the source of the IME term changes.
Confirmed on a Pixel 8 that the wedge is real and does not self-correct: with
the workaround disabled the inset pinned at 957px for 85s while the window
reported the keyboard gone. See b/552500419 and SafeImeInsets.
No raw `WindowInsets.ime` reads remain in amethyst/ or commons/.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
The first pass swapped Modifier.imePadding() call sites, which missed this
one: it reaches WindowInsets.ime through a union with the nav-bar inset
instead. A stranded inset leaves the add-word bar floating a keyboard's
height above the navigation bar, the same symptom by a different route.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bqpAeyLAxHzw5XsnRUtjD
Self-audit of the picker and camera work. Four correctness bugs and one
robustness gap, none of them reachable by the happy path, all of them reachable.
A malformed accept entry became the picker's filter. `accept="image/"` passed
the "contains a slash, so it is a MIME type" test and went straight into
Intent.setType, where it matches no provider — an empty picker with nothing to
choose and no way out. A slashed token is now only a MIME type when both halves
are actually present; otherwise it is unnameable and widens to everything, the
same as an unknown extension. Test first, watched it fail.
The main-process chooser host never reported when the system destroyed it
without finish() — a low-memory kill while the picker is on top. The page's
file input would then wait forever on a result nobody was left to send (dead for
the life of the page), and the coordinator would hold the reply callback, and
the controller behind it, for good. Reporting from onDestroy covers it. A
recreated host now releases the input immediately too, instead of silently
swallowing a pick it can no longer route.
A second file input asking before the first pick returned overwrote the
in-flight request. The page's own callback was already released, but the
superseded request still owned camera scratch files and the URI grants handed
to every camera app — nothing would ever come back for them, so they sat until
the daily sweep. Superseding now runs the cancel path on the old request, and
the same cleanup runs when a host is torn down mid-pick.
Capture filenames were built from a clock and a per-object sequence. The main
and `:napplet` processes each hold their own copy of that object, so the
sequences run independently and two picks started in the same millisecond could
name the same file, one capture silently overwriting the other. createTempFile
removes the question.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FxfdHeR9Ry4qALXHT5Sf1Q
Completes the file-input support: a page that accepts photos or video can now
reach the camera, not only files already on the device. `accept="image/*"` on a
mobile browser means "take one or pick one"; until now Amethyst could only do
the second half, which is the wrong half for the common case of uploading a
photo.
How it decides, mirroring a mobile browser: a bare file input offers stills and
video, an image-only accept offers just the camera, a document accept offers
neither. Resolved by FileChooserAccept.captureMedia, pure and unit-tested.
Unlike the type filter this does NOT widen on an extension the platform cannot
name — widening there would put a camera in front of a page that never asked
for one.
Permission handling is the part worth reading. ACTION_IMAGE_CAPTURE throws
SecurityException for an app that declares CAMERA without holding it, and
Amethyst declares it, so the grant has to exist before the chooser is built.
When the page set `capture` the permission is requested first — the user tapped
a control whose entire purpose is to take a photo. Without `capture` the camera
is offered only if permission is already held, so opening a document upload
never raises a camera prompt out of nowhere. A denial is not a failure: the
picker still opens, minus the camera.
A camera needs somewhere to put a full-resolution shot (EXTRA_OUTPUT; without
one it returns a thumbnail, useless as an upload), so each option gets an empty
scratch file in cacheDir behind its own FileProvider — a dedicated one with its
own authority and paths file, exposing a single subdirectory rather than the
everything the app's general-purpose provider exposes. It needs its own
subclass because the manifest merger keys providers by android:name and would
otherwise collide with the app's.
A chooser entry supplied via EXTRA_INITIAL_INTENTS is started by the system,
not by us, and the URI grant flags on it are not reliably carried across that
hop, so every resolved camera package is granted write access up front — none
of them can be ruled out before the user chooses. That grant is taken back the
moment the outcome is known, for the kept capture as well as the discarded
ones, revoked per package rather than per URI so it cannot clip this app's own
read of its own provider. Unfilled scratch files are deleted immediately; a
kept one cannot be (the page may not read it until the form is submitted) and
is swept on a later request instead.
The three Activity-owning surfaces — the full-screen browser, the full-screen
napplet/nSite sandbox, and the main-process host that serves both embedded
surfaces — now share one WebFileChooserLauncher, so filtering, multi-select,
capture and the permission flow cannot drift between them. The embedded
providers pass the input's `capture` flag across the existing Messenger
contract rather than having the main process re-derive it.
Every path still ends in exactly one call to the page's filePathCallback,
including a denied permission, a dismissed camera, and a device with no camera
app at all.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FxfdHeR9Ry4qALXHT5Sf1Q
DeDupeConcurrentRequestStrategy coordinates through a map of in-flight
fetches that the strategy instance owns. All three network-backed Coil
factories built a fresh one inside create(), i.e. one per image request,
so the map never held more than the current caller: shouldWait was always
false and the de-dupe was inert. Coil's own NetworkFetcher.Factory holds
it as a field for exactly this reason.
The cost showed up wherever a feed asks for the same URL twice at once —
an author's avatar repeated down the rows, an image carried by both the
original note and its boost, or a row scrolled off and back on before the
first fetch had written to the disk cache. Every one of those was a full
second download competing for the same link instead of a waiter that
reads the cache once the leader lands.
Hoists a single strategy into ImageLoaderSetup.setup() and threads it
through OkHttpFactory, BlossomFetcher.Factory and
ProfilePictureFetcher.Factory, so a blob reached as an https URL, as a
`blossom:` URI, or as a profile picture all coordinate on one key. The
per-create CacheStrategy.DEFAULT wrappers are hoisted alongside.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TYrDf5Z8TE4uivADuFwPFz
The grace was 400ms, and once a window wedges its IME animation that full
400ms is paid on *every* dismissal, on every screen — which reads as the
padding lagging behind the keyboard rather than as a bug being corrected.
400ms was never protecting against anything real. `collectLatest` + `delay`
already means "no movement for X ms", because each animation frame emits a
new sample and cancels the pending wait. So the grace only has to outlast
the dead time between the target flipping and the animation's first
onProgress — not the animation. Measured over 12 real Gboard transitions on
a Pixel 8: that dead time is 17-36ms (closes 24-36, opens 17-23), and every
frame after it lands within 11ms across a ~264ms animation. 120ms clears the
worst case by ~3.3x. Set too low this degrades to a cosmetic snap, never to
wrong padding, since the target is always the truthful reading.
Also records what the workaround is working around. The defect is upstream:
a cancelled IME animation never delivers onEnd, so
`InsetsListener.runningAnimation` stays set, `onApplyWindowInsets` matches
neither branch, and `composeInsets.update()` is never called again —
`WindowInsets.ime` is dead for the life of the window. Bisected to
foundation-layout 1.4.0 (1.3.0 updated unconditionally and could not wedge),
still present in 1.12.0 and 1.13.0-alpha01. Compose's self-heal is scoped to
`SDK_INT == R`, and `WindowInsetsHolder.resetState()` only runs when the
holder's accessCount goes 0 -> 1 — which never happens in a single-Activity
app whose shell always reads insets. Filed as b/552500419.
Confirmed on-device that the bug is real and permanent underneath: with both
treatments disabled the inset pinned at 957px for 85s while the window
reported the keyboard gone, and `imeAnimationTarget` stayed correct
throughout — which is why reading it works.
ComposeImeInsetWedgeTest reproduces that upstream state deterministically in
~3s and is the repro attached to the bug. The failing half is @Ignore'd so
CI stays green; re-run it by hand after a Compose upgrade, and when it
passes, SafeImeInsets can be retired. The passing half is left enabled on
purpose: it guards the premise this fix depends on, so if a future Compose
release stopped keeping imeAnimationTarget current we would hear about it
instead of silently reading a second dead value.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Two fidelity gaps in the accept handling, both of which hid files a real
browser would have let the user pick.
An extension Android's MimeTypeMap cannot name was silently dropped from the
filter. That is harmless when it is the only entry (the filter is already
`*/*`), but `accept=".png,.sqlite3"` resolved to image/png alone — the picker
then showed PNGs and no way at all to reach the .sqlite3 the page also asked
for. MimeTypeMap is a fixed table and does not cover every extension a page
might list, so one unresolvable name now widens the whole filter to `*/*`.
`accept` is a hint in HTML, never an enforced restriction, so showing more than
asked is always recoverable and showing less is not.
MODE_OPEN_FOLDER (a `webkitdirectory` input) fell through to a single-file
pick. Android has no picker that hands a WebView the contents of a directory —
ACTION_OPEN_DOCUMENT_TREE returns a tree handle, not the file URIs the page's
callback takes — so it now opens a multi-select instead. The page loses
webkitRelativePath, but the user can finish the upload rather than being
capped at one file. Resolved in one shared helper so the two Activity hosts
and the two embedded providers cannot drift on it.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FxfdHeR9Ry4qALXHT5Sf1Q
The Trusted List family (30392-30395) shipped with a `title` tag and no
`SearchableEvent`, so a list published as "Podcaster" could not be found by
name -- the only way to reach one was to already know its address. Nothing
recorded that as a decision; the feature commit wired the kinds into
EventFactory and KindNames and never touched search.
Implements SearchableEvent on the TrustedListEvent base, so all four kinds
inherit it, and indexes the title alone:
override fun indexableContent() = title() ?: ""
Nothing else in the family is human-authored prose. `metric` names a
computation and `d` identifies the list -- machine ids, kept out so a search
for a common word in one doesn't return every list that ran the same job. The
member tags are hex ids and `content` is a JSON echo of the same membership,
so indexing either would put thousands of identifiers into the full-text
index for no lookup a #p/#e/#a/#i filter doesn't already serve better. A list
with no title indexes the empty string rather than throwing, since
indexableContent() runs inside the store's insert transaction.
The kinds are already registered in EventFactory, so the store's kind
pre-filter and the reindex scan pick them up with no further wiring.
Covered by unit tests over all four kinds (including the titleless case) and
a SQLite store test asserting the title is searchable while the metric, the
list id and the membership are not. Documents the indexing rule in the
package README and adds the rows to the searchable-kinds reference table that
external search engines mirror.
Note for existing databases: rows written before this change keep their
missing FTS text until IEventStore.reindexFullTextSearch() runs (`amy store
reindex-fts` drives it).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G1vXqHYHWXeni4xim66vvf
Tapping `<input type="file">` anywhere in Amethyst was a silent no-op: no
picker, no error, nothing logged. An Android WebView shows no chooser of its
own — the app must override `WebChromeClient.onShowFileChooser`, and none of
the four WebView hosts did. The base implementation returns false, and for a
target of API 21+ there is no legacy fallback, so every file upload in the
in-app browser, in nSites and in napplets was impossible.
All four hosts now open the picker:
- NappletBrowserActivity (full-screen browser) and NappletHostActivity
(full-screen napplet/nSite sandbox) own an Activity, so they run the picker
directly through an ActivityResultLauncher.
- NappletBrowserService and NappletHostService render an embedded surface from
a windowless Service in the keyless `:napplet` process and have no Activity
to launch from. They send the request's *description* — accept list,
multi-select, title — to the main process over the existing Messenger
contract; WebFileChooserCoordinator builds the Intent there and collects the
result in the throwaway WebFileChooserActivity. Shipping data instead of a
ready-made Intent keeps the sandbox able to ask the trusted process for a
file picker and for nothing else. URI read grants are per-UID, so the picked
`content://` URIs are readable by the WebView in `:napplet` with no
re-granting, and allowContentAccess stays off.
Two details that decide whether this actually works in practice:
- The page's `filePathCallback` must fire on every path. WebView keeps a file
input busy until it does, so a dropped callback (user cancelled, session torn
down, no app to handle the Intent) leaves that input permanently dead for the
life of the page. PendingFileChooser guarantees exactly-once delivery and
carries a request id so a result that outlived its request is dropped rather
than fed to whichever input is waiting now.
- Android's own FileChooserParams.createIntent() keeps only the first `accept`
entry and drops multi-select, so `accept="image/png,image/jpeg" multiple`
would offer PNGs only, one at a time. FileChooserAccept resolves the whole
list — extensions included — into a type plus EXTRA_MIME_TYPES, widening to a
family wildcard rather than narrowing below what the page asked for. It is
pure and unit-tested in commonMain.
NappletHostService had no chrome client at all, so it gains one. Its WebView is
built from a Service context with no window token to attach a dialog to, so the
new client also dismisses JS alert/confirm/prompt instead of opting into the
default dialog handling.
Camera capture (`accept` with `capture`) and getUserMedia still fall back to
the picker; `onPermissionRequest` remains unimplemented and is left for a
separate change.
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FxfdHeR9Ry4qALXHT5Sf1Q
The chrome reserved `systemBarsIgnoringVisibility` -- the space the bars would
occupy whether or not they were on screen. On a punch-hole device that is 142px
(54dp, not the usual 24dp: the status bar is sized to clear the camera), so the
controls sat ~64dp below the screen edge permanently, and the gap looked like a
bug because most of the time nothing was in it.
Reserving it was not gratuitous. `BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE` paints
a peeked bar OVER the content and dispatches no insets at all: measured on a
Pixel-class emulator, `statusBars` reads 0 and `isVisible` reads false for the
entire time the bar is on screen, byte-identical to the hidden state. With no
signal to react to, permanently reserving the space is the only way to keep the
buttons from being covered -- which is why the previous code was written that
way, and why two attempts to shrink the inset while keeping transient bars both
failed on device.
So change the premise: ask for BEHAVIOR_DEFAULT. The bars then dispatch real
insets (statusBars 0 -> 142, navigationBars 0 -> 63, both `isVisible` flipping),
and the chrome can follow them:
- `animatedViewerChromeInset()` takes `systemBars` for the relevant edge, floors
it at 16dp, and animates. Hidden: the row sits 16dp in (measured top=69).
Shown: it moves clear of the bar (142). The floor is not arbitrary -- this
display has 132px rounded corners, and a button whose left edge is x=39 needs
y >= 38 to stay inside the visible area.
- The top display-cutout inset is dropped. Android reports it full-width, but
the hole is `Rect(485,0,595,142)` -- 110px of 1080, dead centre. The
edge-anchored buttons never overlap it; honouring it pushed them down by the
height of a camera they are nowhere near. Horizontal cutout insets stay, for
a landscape notch.
The animation snaps for 350ms after the chrome appears. Opening moves the inset
twice for reasons the user did not cause -- the window has not been told its
insets yet (they read 0, indistinguishable from "hidden"), and the immersive
effect hides the bars from a DisposableEffect that runs after composition --
and animating either played a slide on open.
Two things had to move because they were riding the same inset:
- The PDF page counter sat dead centre, which on a punch-hole device put it
*under the camera*: measured overlap 56x36px against the lens circle. It now
lives along the bottom edge, clear of the cutout, still screen-centred, and
tracking the navigation bar.
- The image dialog's page dots used `navigationBarsPadding()`. That tracks the
bar correctly but moves in a single frame, which read as a jump next to the
top controls sliding. They now share the same animated inset.
`ViewerControlsRow`'s KDoc described the transient-bar behaviour and the
touch-swallowing it worked around. Neither is true of this code any more, so it
is rewritten rather than left to mislead.
One measurement that did NOT support this change, recorded so it is not
rediscovered as evidence: probing the reserved strip with injected taps found
12/12 points from y=8 to y=165 reaching the app, at all three button columns --
the "system swallows touches there" premise did not reproduce. But
`tappableElement` reports 142px, injected events are not a finger, and the
overlap problem above is reason enough on its own.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Five fixes, all in the chrome the two viewers now share:
The PDF page swallowed its own tap. `zoomable` consumes the gesture before the
full-screen box underneath sees it, which is why the image path hangs its
toggle off `onTap` rather than a parent `clickable` -- so the page does too.
Without it the chrome auto-hid after two seconds and no tap could bring it
back, stranding the reader with no way out but the system gesture.
The auto-hide timer now races the controls going away instead of sleeping
through it: hiding and re-showing the chrome inside the two-second window used
to leave the original timer running, so it wiped controls the user had just
tapped back up. It also waits for the media to arrive (`armed`), because a PDF
that took longer than the delay to fetch rendered its first page with the
chrome already gone and nothing left to re-arm.
The save button ran on `rememberCoroutineScope` while living inside the
`AnimatedVisibility` that the auto-hide collapses two seconds later -- so the
chrome fading out cancelled the download it had just started, leaving no file
and no error. It now uses the view model's scope and the application context,
matching the download row in `ShareMediaAction`.
The page counter no longer slides sideways when the buttons fade: it sits in
its own centred row, anchored to the screen rather than to the space the
asymmetric button groups leave behind.
The back button also survives the loading and unreadable-PDF states, which had
inherited hidden system bars from the immersive effect without keeping a way
back out.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PQscXLTMHXHwYyKh4xcKC
`geode` can never be a homebrew-core formula: `formula_renames.json` maps
"geode" -> "apache-geode", so the token is permanently reserved and
`brew info --formula geode` resolves to Apache Geode. The previous commit
recorded that as a blocker; this removes it.
- `geode/packaging/homebrew/geode.rb` -> `geode-relay.rb`, `class Geode` ->
`class GeodeRelay` (Homebrew requires the class to track the filename).
- `bump-homebrew-geode-formula.yml` follows the path, and the three sibling
workflows' header comments now name the formula correctly.
- `geode/README.md` points at the new file and the new tap install line.
**The binary is still `geode`.** Users type `geode`, not `geode-relay`. That is
safe rather than sloppy: apache-geode installs `gfsh`, so nothing collides on
PATH. Formula token and binary name differ deliberately, which the header now
states so nobody "fixes" it later.
Verified: `brew style` clean on the renamed file (it validates class-vs-filename
agreement, so this catches a bad rename), `brew info --formula geode-relay`
resolves to this relay rather than Apache Geode, `ruby -c` passes, and replaying
the bump workflow's `sed` still changes exactly the two intended lines.
`geode/plans/2026-07-24-geode-release.md` is left alone — a dated design doc,
not live configuration.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Checked while asking whether the amethyst-nostr cask's review feedback applied
to the two formulae. It does not — but running homebrew-core's own linter over
them turned up a real defect neither had been checked for.
**The style violation, in both files.** `brew style` flags
Homebrew/FormulaPathMethods: Use formula_opt_prefix("openjdk")
instead of Formula["openjdk"].opt_prefix
on the `write_env_script` line. Fixed in `amy.rb` and `geode.rb`; both now
report no offenses. It would have been raised on submission.
**A duplicated sentence.** amy.rb opened with "Reference Homebrew formula for
`amy`, the Amethyst CLI." twice, once on line 1 and again on line 3.
**Why they must NOT be made to match the cask.** The cask lost its `livecheck`
block and inline comments on review, so the obvious next step is to do the same
here. That would be wrong, and the header now says so with the evidence:
homebrew-cask and homebrew-core differ. Sampling the live core tap, 127 of 300
formulae with GitHub-release URLs declare `livecheck` (62 using
`:github_latest`), and 109 of 200 carry indented inline comments. `livecheck`
is load-bearing in core — it is what lets BrewTestBot open version-bump PRs, so
stripping it would disable exactly the automation the block exists for.
**geode cannot be submitted under that name.** homebrew-core's
`formula_renames.json` maps "geode" -> "apache-geode", so the token is
permanently reserved and `brew info --formula geode` resolves to Apache Geode.
Submitting needs a different token (`geode-relay`, `amethyst-geode`) plus a
matching change to bump-homebrew-geode-formula.yml. Recorded as a blocker in
the header rather than discovered at PR time.
**amy is unblocked but not ready.** The one-open-AI-PR limit that gated it is
cleared now the cask has merged; the ~70 MB bundle from `:commons` pulling
Compose/Skiko onto the CLI classpath is still the likely review objection, and
`brew audit --new --formula` has not been run end to end.
Verified the enlarged headers cannot confuse the bump workflows: both anchor on
`^ url ` / `^ sha256 ` at a two-space indent, each matches exactly once, and
replaying their `sed` changes those two lines only. `ruby -c` passes on both.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Blocker + high-severity fixes from multi-agent review:
- liveNowForBar: route through LiveActivitySorting.sortDescending so the
comparator reads a snapshotted rank, not the live channel.info var — the
previous inline comparator could hit TimSort's "contract violation" crash
when a 30311 was swapped from a relay thread mid-sort.
- LiveWatchScreen: stop playback (GlobalMediaPlayer.stopVideo) on close via
DisposableEffect — audio/decoding was leaking after the overlay closed.
- LiveNowBar: take the follow Set (stable identity) instead of a fresh .toList()
per recompose, so its subscription + snapshot don't churn.
- Chat auto-scroll keys on the newest message id, not size (kept working once
the 500-cap prune holds size flat).
- Remove the dead profile-nav affordance in the watch header/chat (was wired to
a no-op); real profile nav from the overlay is a follow-up.
- generateSubId appends a per-process atomic counter so same-millisecond subs
can't collide (one unsubscribe tearing down another's REQ).
- stopVideo also cancels the in-flight open job.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
"Sometimes lives don't start" had no trace because kdroidFilter reports
playback state only via Compose state, never the log.
- GlobalMediaPlayer.playVideo now cancels any in-flight openUri before starting
a new one, so two rapid track switches can't interleave openUri on the single
shared engine (the race that left the surface stuck/black).
- Reuse the engine only when it's on the same URL AND had no error; a prior
transient error (dead segment / 403 / just-went-live) now re-opens instead of
showing a stuck surface.
- Log playVideo (REUSE/OPEN), playback errors (url + reason), and each watch
open (address, status, streaming/recording URL) so failures are diagnosable.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Addresses watch-screen player feedback:
- Hide the seek slider for live streams (the HLS is non-seekable, so a scrubber
was inert/misleading). VOD recordings keep the normal seekable bar.
- Replace the "time / duration" readout with a single LIVE pill + one elapsed
timer for live streams (no fixed end to show).
- Watch top bar: more top margin, less start margin (tighter to the X).
DesktopVideoPlayer/VideoControls gain an isLive flag; LiveWatchScreen sets it
from the 30311 status (live vs recording).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Clicking a live stream (Discover card or the per-column bar) now opens a
full-window watch overlay: HLS player left, live chat right.
- LiveWatchController: app-level singleton holding the watched stream address;
overlay rendered once at the composition root in Main.kt (mirrors
GlobalFullscreenOverlay), so any live surface opens it without threading a
callback through the deck/single-pane tree.
- LiveWatchScreen: DesktopVideoPlayer for the HLS stream + header (LIVE badge,
host, viewer count, summary) + reactive kind-1311 chat (reverseLayout,
auto-scroll at bottom) + composer that signs & publishes a 1311 with the
stream's root `a` tag.
- FeedScreen/DiscoverScreen onOpenLive defaults now open the overlay.
UI polish from testing feedback: Discover "LIVE NOW" shows only genuinely-live
streams (no planned/ended), capped at 2 rows so "From the pack" stays visible;
feed live bar gets rounded inset + breathing room.
Follow-ups: live-vs-VOD seek suppression + stall watchdog, zap-the-stream,
mute/block chat filtering, online-probe downgrade.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Tags each section LIVE / PARTIAL / PENDING so it's usable against the current
branch, with concrete step→expected tables for the testable Discover + live-bar
surfaces and a "test right now" quick path.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Pins a compact bar at the top of the Following and Global feed columns showing
the single most-watched live host in that column's audience, with a "+N live ›"
dropdown for the rest. Hidden when nobody in scope is live.
- LiveNowBar: own 30311 subscription scoped to the column (follows for Following,
global for Global); reads the shared liveNowForBar ranking (viewers-first);
click opens the watch screen via onOpenLive.
- FeedScreen: pinned above the feed LazyColumn for FOLLOWING/GLOBAL modes only.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Surfaces NIP-53 live streams in Discover: subscribes to kind 30311 while
visible, ranks via the shared LiveActivitySorting (live > planned > ended,
follow-participation, viewers), and filters client-side by title/host/hashtag.
- FilterBuilders.liveActivities / liveActivityChat + createLiveActivitiesSubscription
/ createLiveChatSubscription.
- LiveActivityRanking: maps channels to the shared snapshot rank; liveNowForBar
(viewers-ranked) prepared for the per-column bar.
- LivesSection: subscription + search box + responsive card grid (thumbnail,
LIVE/scheduled badge, host, viewer count). Card click -> onOpenLive(address)
(wired to the watch screen in the next commit).
Online-probe downgrade (OnlineChecker) still to be wired; ranks treat all
status=live as online for now.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Stands up Desktop's first channel cache (liveChatChannels) so live streams
and their chat have somewhere to live (getAnyChannel returned null before).
- getOrCreateLiveActivityChannel + LiveActivitiesChannel per stream address.
- Route kind 30311: replaceable supersession in addressableNotes, attach info
to the channel, bump liveActivityVersion (drives Lives grid / live bar).
- Route kind 1311: attach to its stream channel by root `a` tag; cap retained
chat at 500 via pruneOldMessages (Desktop had no pruning).
- Skip 1311 write-through to the local relay store (avoid unbounded chat replay
on next launch); 30311s still hydrate.
- getAnyChannel resolves a 1311/30311 note back to its channel.
- snapshotLiveActivities() for reactive recomputation.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Foundation for Desktop Live Media (NIP-53) consume+discover feature.
- LiveActivitySorting: pure, CLI-safe status-order / freshness / ranking
helpers with a snapshot-map sort API so Android + Desktop order live
streams identically and no comparator reads volatile state mid-sort
(avoids the TimSort "contract violation" the Android filters guard against).
- Unit tests (green): status ordering, offline-live downgrade, 15-min
live-bar freshness, overdue-planned detection, multi-key sort + tiebreaks,
and stability under concurrent key mutation.
- Deepened plan (7 review agents) + brainstorm + full manual testing sheet.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The cask went live in Homebrew/homebrew-cask on 2026-08-24. A maintainer
removed three things during review that this reference copy still carried, so
the file now documents a shape Homebrew rejected:
- the `livecheck do url :url; strategy :github_latest end` block, which is
redundant — Homebrew infers the strategy from a GitHub release URL
- the inline `conflicts_with` comment
- the inline `zap` rationale comment
The body below the header is now byte-identical to upstream, so `diff`-ing the
two is meaningful again.
The removed rationale was worth keeping, just not upstream, so it moves into
the header — which `scripts/bump-winget.sh`-style stripping never applies here
anyway, because this file is only ever read, never copied. Notably the `zap`
paths, re-derived from source rather than trusted from the old comment:
`AccountManager.kt` for `~/.amethyst` (accounts and KEYS), `DesktopTorManager.kt`
for the Application Support path, and `DesktopImageLoaderSetup.kt` whose macOS
`cacheDir()` branch resolves to `~/Library/Caches`. Also why the shared Java
prefs plist is deliberately excluded: `java.util.prefs` writes every Java app's
preferences into that one file.
The header also corrects a scope claim. It implied this file is what ships;
it is not. `scripts/bump-homebrew-cask.sh` bumps upstream through
`brew bump-cask-pr`, which edits the upstream cask in place and only reads
version + sha256 from here.
Verified the enlarged header cannot confuse either bumper: both anchor on the
two-space indent (`^ version "` / `^ sha256 "`), each matches exactly once,
and replaying the workflow's `sed` against this file changes those two lines
and nothing else. `ruby -c` passes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
Both viewers open the same way -- tap a media card in a feed -- so the
difference in how their chrome behaved was arbitrary from the user's side, and
a PDF is a reading surface where controls parked over the page cost more than
they do over a photo.
The PDF viewer now goes immersive, toggles its controls on tap, auto-hides
them, anchors the share sheet to its button instead of the window root, and
gains the save-to-gallery button the image viewer already offered for PDFs.
The page counter is wayfinding rather than a control, so it does not simply
vanish with the buttons: it also flashes on its own for a moment after every
page turn, which is why the shared row holds a button's height whatever it
carries.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PQscXLTMHXHwYyKh4xcKC
The zoomable dialog goes immersive, which drops the status-bar inset to zero
and lands the back/share/save buttons against the top edge of the screen. That
strip stays owned by the system while BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE is
set -- it is the area watching for the swipe that peeks the bars back -- so
touches there never reach the buttons and only their lower halves respond.
There is no API to turn that region off, so reserve the space the bars would
occupy even while they are hidden (systemBarsIgnoringVisibility, unioned with
the display cutout for notched devices in landscape). As a bonus the controls
no longer jump when the user swipes the bars back in.
Extracts the chrome the PDF viewer is about to share: the immersive effect, the
auto-hiding visibility state (which collapses the dialog's two duplicate
auto-hide effects into one), the control row, and the three buttons.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014PQscXLTMHXHwYyKh4xcKC
The on-device AI writing assistant (ML Kit GenAI proofreading/rewriting via
Gemini Nano) proposed tone rewrites under the text field on the new post,
reply and quote screens. Removes the feature end to end:
- deletes the WritingAssistant abstraction and its play (ML Kit) and fdroid
(no-op) implementations, the mock, and the AiWritingHelp panel/button
- strips the AI state, precompute job and lifecycle wiring out of
ShortNotePostViewModel and ShortNotePostScreen
- drops the genai-proofreading, genai-prompt and genai-rewriting
dependencies, which nothing else used
The composer was the only reader of the "Propose text improvements"
setting, so that goes too: the Compose Settings tile, the
automaticallyProposeAiImprovements field in UiSettings/UiSettingsFlow, the
ui.propose_ai_improvements DataStore key, and the ai_writing_*/ai_tone_*
strings in every locale.
The ML Kit image-description service that backs alt-text suggestions lives
in the same package and is untouched.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvNaegVegSy5tZ4y3M7B4b
Android auto-expands a notification when it is the only one in the shade,
and offers no way to opt out. The per-job relay breakdown was attached as a
BigTextStyle on every post, so for anyone whose shade was otherwise empty
the full list of what each relay is doing *was* the default view — the
opposite of the "expanded only" intent it was written with.
The breakdown is now opt-in: the notification is built with no expanded
style at all, so the card is always just "Connected to X relays", and a
"Show details" action posts it back with the breakdown plus a "Hide
details" action that returns to the bare count. As a side effect the
per-relay request walk only runs while the details are on screen, instead
of once a second whether or not anyone is looking.
All three were found by following the docs during the v1.14.0 release and
hitting reality instead.
1. The Homebrew cask bootstrap command cannot work. BUILDING.md told the
maintainer to run `brew bump-cask-pr amethyst-nostr` for the *one-time
initial PR*, but that subcommand updates an existing cask. Against a name
not in the tap it fails outright:
Error: Cask 'amethyst-nostr' is unavailable: No Cask with this name exists.
Verified by dry-run. A first submission is a new-cask PR — `brew create
--cask`, `brew audit --new --cask`, then a hand-opened PR — so the section
now documents that flow, notes the notarized+stapled precondition Homebrew
enforces, and says where `bump-cask-pr` *does* apply (the later bumps).
This is plausibly why the bootstrap never happened.
2. RELEASE_OPS claimed the release holds 31 assets. It holds 47. The windows-
arm64 and linux-arm64 legs added this cycle took desktop 8 -> 14, amy 5 ->
10 and geode 5 -> 10. BUILDING.md had already been updated; RELEASE_OPS had
not, in two places (the § 2 breakdown and the § 6 checklist). A maintainer
following it would read a correct release as broken. The breakdown now
points at BUILDING.md, which carries the per-leg detail and the reasons for
the two gaps, rather than restating it and drifting again. Also drops the
geode Docker image from the count — it goes to the registry, not the
release.
3. RELEASE_OPS § 3 said to verify "Intel + ARM DMGs are both present" while
§ 2 and § 6 said macOS is arm64-only. Only the arm64 DMG exists, so § 3 was
the wrong one.
Also replaces the "neither has ever been submitted upstream" line with a
per-channel table: Winget is now submitted (microsoft/winget-pkgs#422752,
pending CLA), both Homebrew packages are not. Since that is a snapshot that
will age, it carries the one-call check that answers it live.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gs2gi3sZfQ7SHrVm2njLMw
After a while, the back gesture would dismiss the keyboard but leave a
keyboard-sized gap behind it, app-wide and permanently — only killing the
activity cleared it.
Compose keeps one InsetsListener per window in WindowInsetsHolder. It sets
runningAnimation in onPrepare and clears it only in onEnd, plus an
onApplyWindowInsets fallback gated to API 30. While that flag is set,
onApplyWindowInsets deliberately skips update(insets) and waits for
onProgress instead. An IME animation that is prepared and then cancelled
without ever delivering onEnd — which the back gesture can cause, since the
predictive-back window animation races the IME's own close animation —
leaves the flag set for good, and every WindowInsets in the window freezes
at its last animated value.
Nothing recovers from that on its own: the listener is only reset when the
holder's access count goes 0 -> 1, and the app reads WindowInsets.ime
continuously, so the count never reaches zero while the activity lives.
Nav's ImeSettler already prevents this for in-app navigation, but the
system's own back gesture never reaches Nav — the first back press with a
keyboard up is consumed by the IME — so prevention alone can't close it.
The escape hatch is that onApplyWindowInsets publishes imeAnimationTarget
before it consults that flag, so the target keeps tracking reality while the
animated value is frozen. SafeImeInsets watches both: when they disagree and
then stop moving for longer than any real animation frame gap, the animated
value is stale and the target is the truth. That corrects the freeze in both
directions — a gap left behind by a keyboard that is gone, and missing
padding under a keyboard that has come back.
Modifier.imePadding() is replaced with imePaddingSafe() across the app, and
keyboardAsState(), rememberImeSettler() and DisappearingScaffold's nav-bar
subtraction now read the corrected inset too — the stuck reading also left
the bottom navigation bar hidden and made every navigation burn the full
settle timeout.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bqpAeyLAxHzw5XsnRUtjD
The "Enable OS notifications" button still fails on macOS even after
e9475dd0 + the auto-enable follow-up, and the failure mode gives the
user nothing to act on:
1. Nucleus's requestAuthorization callback carries the OS error string
(UNErrorDomain), but the dispatcher discarded it ({ granted, _ -> })
and mapped every non-grant to PermissionState.Denied. The settings UI
then showed "Enable in System Settings → Notifications → Amethyst" —
a dead end when macOS refused the request outright ("Notifications
are not allowed for this application"), because a refused app never
gets a System Settings entry.
2. On recent macOS the permission prompt is an auto-dismissing banner.
If the user misses it, UNUserNotificationCenter may never invoke the
completion handler, leaving requestPermission()'s
suspendCancellableCoroutine parked forever and the UI stuck on
"Requesting…".
Fixes:
- requestPermission() now captures the OS error string and exposes it
via NotificationDispatcher.lastRequestError (new interface property,
null-defaulted so other implementations are unaffected).
- The request is wrapped in withTimeoutOrNull(90s); on timeout the
coroutine returns, the spinner clears, and lastRequestError tells the
user to watch for the banner and retry.
- The Denied branch of NotificationSettingsScreen gains an "Ask again"
button (re-request re-surfaces the banner) and both branches render
the raw OS error when one is present.
- sendMac() now uses Nucleus's add(request, callback) overload and
reports SendResult.Failed with the OS error instead of unconditionally
returning Delivered for a request the notification center may have
rejected. Timeout without an ack still counts as delivered (the
request was queued).
Reproduced the hang + the silent-error path on macOS 26.4 with a
minimal Nucleus harness: first requestAuthorization call from a
freshly-installed bundle never fired its callback (30s timeout),
subsequent calls returned granted=false with "Notifications are not
allowed for this application" — neither observable from the Amethyst
UI before this change.
@@ -540,6 +540,7 @@ When adding translated strings to locale files:
- **Pasting the union set of missing keys into every locale → duplicate keys** — the union is the right set to *translate*, but the wrong set to *insert*. A key missing in only some locales, inserted into all of them, duplicates in the ones that already had it. Drive each file's insertion off its own per-locale diff (see Step 6). In `commons`, a duplicate key is build-breaking: `convertXmlValueResourcesForCommonMain` fails with `Duplicated key '…'`. **Always run the post-insertion duplicate + XML-wellformedness gate in Step 6 before declaring done.** (Happened 2026-07-21 with `ps1_save_block` / `podcast_value_for_value` / `chats_history_relays`.)
- **Declaring the pass done without running `:amethyst:lintPlayBenchmark`** — the duplicate-key + XML + `convertXmlValueResourcesForCommonMain` gate is necessary but nowhere near sufficient. `MissingQuantity` and `ImpliedQuantity` are errors, there is no lint baseline, and `abortOnError` is on, so a change that compiles and passes every check in Step 6's first half can still take CI red. Compiling is not evidence. (Happened 2026-08-13: 3 lint errors after a clean duplicate/XML gate and a green `compileFdroidDebugKotlin`.)
- **Converting a `<string>` to `<plurals>` with `other` only** — "Crowdin fills the rest" is false; `MissingQuantity` errors immediately and CI fails before any sync. Supply every category the locale uses at conversion time, and re-check the declension rather than reusing the old text for `one`.
- **Renaming or removing a key in `values/strings.xml` without deleting it from every locale in the same commit** — the surviving locale entries become orphans, and `ExtraTranslation` is an error. "Crowdin drops retired keys on its next sync" is the same false belief as the `other`-only shortcut above: lint runs on the tree you push. Worse, it's *partly* true — the sync cleans some locales and silently leaves others, so the files you happen to open look fine. Scan with the sub-second `.claude/hooks/orphan_strings_check.py` instead of the ~19-minute lint; see `amethyst/src/main/res/CLAUDE.md`, "Renaming or removing a string key". (Happened 2026-08-31: `route_video`/`new_short` left in 15 of 47 locales, 30 errors, red `main`.)
- **Putting `tools:ignore` on a locale file** — Crowdin strips it on the next export. Suppressions belong on the source entry in `values/strings.xml`, which propagates. The `tools:ignore="Typos"` copies visible in cs/de/ar/eo/bn are the *result* of that propagation, not proof that locale-file attributes survive. (Happened 2026-08-13; it broke `main`.)
- **Suppressing a lint rule on a key nothing references** — check `grep -rn "<key>" --include='*.kt'` first. `poll_results_voters` was a bare noun with no count, zero call sites, and an unlocalizable shape; deleting it retired the problem outright where a suppression would only have muted it.
- **Comparing placeholders without a `(?<!\\)` guard** — `\%2$d` is an escaped literal to lint, but a naive `%\d+\$[sd]` regex matches the placeholder inside it and reports the string clean. A parity sweep missing this guard will certify a broken translation. Also treat a *repeated* index (`%1$s` twice where the base has it once) as legitimate — German does this where English says "They".
description:Use when auditing or migrating Log calls — flags both interpolated Log.d/i/w/e that should use the lambda overload (allocation hygiene) and catch-block Log.w/e that interpolate ${e.message} but drop the throwable (lost stack traces)
description:Use when auditing or migrating Log calls — flags interpolated Log.d/i/w/e that should use the lambda overload (allocation hygiene), catch-block Log.w/e that interpolate ${e.message} but drop the throwable (lost stack traces), and files still importing android.util.Log (no lambda overload, bypasses Log.minLevel)
---
# Find Non-Lambda Log Calls
## Overview
Two related logging hygiene issues:
Three related logging hygiene issues:
1.**Lambda overload missing.**`Log.d/i/w/e` calls that use string interpolation without the lambda overload waste string allocation when the log level is filtered out in release builds.
2.**Throwable dropped in catch blocks.**`Log.w/e` calls inside `catch (e: ...)` blocks that interpolate `${e.message}` but don't pass `e` lose the stack trace, and log nothing useful when `e.message` is null (NPE, IOException with no message, etc.).
3.**Still on `android.util.Log`.** Files importing the platform logger bypass `Log.minLevel` and the `LogSink`, and have no lambda overload — so neither fix above can be applied to them. Step 0 finds these; the last section migrates them.
**Important:** Tags can be string literals (`"Tag"`) or variables (`tag`, `LOG_TAG`). Run both patterns for each step.
**The throwable-name alternation, used by Steps 2 and 3** — define it once and reuse it, rather than writing a shorter list in one step and a longer one in another:
**Filter the noise before counting**, or the totals mislead: drop `/build/`, `/androidTest/` and `/src/test/` (release filtering doesn't apply to tests), and drop lines whose first non-space character is `//` or `*` — commented-out calls and KDoc examples both match these patterns. A `grep -vE ':[0-9]+: *(//|\*)'` handles the last one.
### Step 0: Find files still on `android.util.Log` (run this first)
**Two patterns — the fully-qualified one alone is a false negative.** Almost nobody writes `android.util.Log.w(...)` at the call site; they `import android.util.Log` and then write `Log.w(...)`, which is indistinguishable from the wrapper by call shape. The import is the reliable signal:
On 2026-08-28 the fully-qualified pattern reported **0** while the import pattern found **16 production files** (9 in `nappletHost`, the rest in amethyst's `favorites/` and `napplet/`). Exclude `PlatformLog.android.kt`, which is the wrapper implementation and must call `android.util.Log`.
These bypass the `Log.minLevel` filter and the `LogSink` indirection entirely, and — the practical consequence for this skill — **they have no lambda overload**, so Steps 1–3 cannot be applied to them until they are migrated. Subtract these files from the Step 1–3 candidate lists, or migrate them first (see the last section).
### Step 0b: The patterns are line-anchored — sweep multi-line calls separately
Every `pattern:` in Steps 1–3 matches a call written on one line. A call formatted as
is **structurally invisible** to them. That biases the audit towards short calls and away from expensive ones — the multi-line form is what long, heavily interpolated messages look like, and those are exactly the ones worth deferring. A 2026-08-28 sweep converted three one-line banner calls in `BootRelayDiagnostics.kt` while walking past two `Log.d` calls in `forEach` loops immediately below them, running 25 and 20 iterations per census with nested `joinToString` in each — strictly the larger cost, three lines away.
Catch them with the open-paren-at-EOL form, then read each hit:
**Prioritise call sites inside loops over one-liners.** A `Log.d` in a 25-iteration `forEach` discards 25 built strings per pass; a one-line banner discards one.
Then **manually exclude** lines where a throwable is passed as third argument (ending with `, e)`, `, throwable)`, etc.). Check the actual line — a catch block catching `e` doesn't mean `e` is passed to the Log call.
Then **manually exclude** lines where a throwable is passed as third argument. Check the actual line — a catch block catching `e` doesn't mean `e` is passed to the Log call.
**`it` is the name you will miss.** `Result.onFailure { ... }` is the dominant shape in this repo, so most correct calls end `, it)`, not `, e)`. Excluding only `e`/`throwable` inflates the result badly — a 2026-08-28 pass reported 23 hits where the real number was 8, because 14 of them were `.onFailure { Log.w(TAG, "...", it) }` and already correct. Also note the throwable is not always last on the line (`}.onFailure { Log.w(...) }.getOrDefault(false)`), so anchoring the exclusion to `$` misses them:
Then for each hit, open the file and confirm the line is **inside a `catch (e: ...)` block** and **does not pass `e` (or the matching name) as a third argument**. False positives: extension functions / helpers that accept an `e: SomeError` parameter and forward it elsewhere.
Note this deliberately omits the `\)$` anchor and includes `it` — same reasons as Step 2. Then for each hit, open the file and confirm the line is **inside a `catch (e: ...)` block** and **does not pass `e` (or the matching name) as a third argument**. False positives: extension functions / helpers that accept an `e: SomeError` parameter and forward it elsewhere.
Both Step 2 and Step 3 may flag the same line — handle Step 3 first (different fix), then apply Step 2 to whatever remains.
### Step 4: Verify no android.util.Log leakage
```
pattern: android\.util\.Log\.(d|i|w|e|v)\(
type: kotlin
```
These bypass the `Log.minLevel` filter entirely. Exclude `PlatformLog.android.kt` which is the wrapper implementation.
## Fix Patterns
### Lambda overload (Step 1 + Step 2)
@@ -106,7 +153,7 @@ Switch to `(tag, msg, throwable)` — the lambda overload does **not** accept a
```kotlin
// Before — stack trace lost, prints "...failed: null" if e.message is null
@@ -120,6 +167,25 @@ Trade-off: the message string is allocated eagerly even when warn is filtered, b
## Do NOT Convert
- **To lambda:** calls passing a `Throwable` parameter — the lambda overload `(tag) { message }` has no throwable parameter.
- **To lambda: any call in a file that imports `android.util.Log`.** The platform `Log` has no lambda overload, so the conversion fails to compile with `None of the following candidates is applicable`. Either migrate the file first (below) or leave the call alone. (Hit on 2026-08-28: three edits in two files had to be reverted.)
- Static string calls with no `$` interpolation — no allocation benefit.
- Commented-out log calls.
- Informational/intentional log of `e.message`*outside* a catch block (rare; usually means the exception was already handled and only the message is meaningful).
## Migrating a file off `android.util.Log`
This is what unlocks Steps 1–3 for the files Step 0 finds. It is a behaviour change, so check it rather than assuming — but in this repo the check has come out safe, and here is the reasoning to redo:
1.**Which levels does the file use?**`grep -hoE 'Log\.[a-zA-Z]+' <files> | sort | uniq -c`. The wrapper has `d/i/w/e` only — **no `v`**, and no `getStackTraceString`. A `Log.v` call has no direct equivalent and needs a decision, not a rename.
2.**Would the gate drop them?**`LogLevel { DEBUG, INFO, WARN, ERROR }`, the gate is `minLevel <= <level>`, and `Amethyst.DEFAULT_LOG_LEVEL` is INFO in debug, **WARN in release** (deliberately — so relay-protocol refusals stay visible in the field). The wrapper's own default is `DEBUG`. So `Log.w` and `Log.e` survive in every build type and in every process, including before `Amethyst.init` runs — which matters for `:napplet`. `Log.d`/`Log.i`**would** go silent in release; those need a conscious call.
3.**Does the output move?** No. `PlatformLogSink` on Android delegates to `android.util.Log`, so lines land in logcat unchanged.
4.**Can the module see quartz?**`nappletHost` already has `implementation(project(":quartz"))`. Check before assuming.
Then: swap `import android.util.Log` → `import com.vitorpamplona.quartz.utils.Log`, run `./gradlew spotlessApply` (import order changes), and convert only the interpolated no-throwable calls to the lambda form. Calls that already pass a throwable keep the eager three-arg shape — the wrapper's `w(tag, msg, throwable)` matches exactly, so only the import moves.
**Verify the throwables survived**, since a careless rewrite can drop the third argument silently:
| 30382 | ContactCardEvent | nip85TrustedAssertions/users | `(listOfNotNull(petName(), summary()) + topics())` NL — public tags only, never the NIP-44 content |
| 30392 | UserTrustedListEvent | experimental/trustedLists/users | inherited `TrustedListEvent`: `title() ?: ""` — the label only; `metric`/`d` are machine ids and `content` is a JSON echo of the membership |
@@ -533,7 +533,7 @@ reads an optional per-release changelog from
## Bootstrap runbook (one-time)
> **Status as of v1.14.0: neither Homebrew nor Winget has been bootstrapped.**
> **Status as of v1.14.0:** Winget has been submitted — [microsoft/winget-pkgs#422752](https://github.com/microsoft/winget-pkgs/pull/422752), pending CLA + review. Neither Homebrew package (`amethyst-nostr` cask, `amy` formula) has been submitted yet.
> `https://formulae.brew.sh/api/cask/amethyst-nostr.json` and
> `microsoft/winget-pkgs/manifests/v/VitorPamplona/Amethyst` both 404, so
> **Amethyst does not currently ship through either channel.** The bump
@@ -618,15 +618,33 @@ that is needed.
### Homebrew cask (one-time initial PR)
> `brew bump-cask-pr` **cannot** do this step. It *updates* an existing cask —
> against a name that isn't in the tap yet it fails outright:
> `Error: Cask 'amethyst-nostr' is unavailable: No Cask with this name exists.`
> The first submission is a **new-cask** PR, which is a different flow:
# Upstream issue draft — Compose `WindowInsets.ime` permanently wedges after a cancelled IME animation
Target: Google IssueTracker → **component 612128 (Jetpack Compose)**.
The library-specific component the docs link to (856989, from the "Create a new issue" button on
the Compose Foundation release notes) does not grant public Create Issues permission, so this is
filed one level up with a routing request at the top of the body.
Status: **FILED as https://issuetracker.google.com/issues/552500419 (b/552500419)** on 2026-08-25,
against component 612128 with a routing request. Remaining open item: the AOSP commit that introduced `runningAnimation`
between 1.3.0 and 1.4.0-alpha01 has not been identified (android.googlesource.com returned 403
to automated fetch). Adding the commit link before filing would help triage.
---
## Title
`WindowInsets.ime` stops updating permanently when an IME animation is cancelled without `onEnd` (regression in 1.4.0, still present in 1.13.0-alpha01)
## Routing
Please reassign to the owner of **`androidx.compose.foundation` / `foundation-layout`**
(WindowInsets). Filing here because component 856989 — the target of the "Create a new issue"
button on the [Compose Foundation release notes](https://developer.android.com/jetpack/androidx/releases/compose-foundation)
— does not grant Create Issues permission to external accounts. That documented path being
unusable by the public is arguably a separate docs bug worth fixing.
## Affected versions
* **Broken:** `androidx.compose.foundation:foundation-layout`**1.4.0 → 1.12.0 (current stable) and 1.13.0-alpha01**
* **Not broken:** 1.3.0 and earlier
* Verified by inspecting published `-sources.jar` for 1.2.0, 1.3.0, 1.4.0-alpha01…rc01, 1.4.0,
| `commons/commonTest` | `PayToRailMatcherTest` | empty sender → empty; no overlap → empty; `ln` vs `lightning` → empty (wallet-covered); `Venmo` vs `venmo` → match; dedupe by type |
| `amethyst/test` | sibling of `RailCapabilityCashuStatusTest` | split present → empty; setting off → empty; no author → empty; unavailable scheme → empty; https target → shown without probe; **existing rails unaffected** |
| `amethyst/test` | `PayToAppAvailabilityTest` | key is scheme+host, not scheme; probe count == sender's target count, independent of post count; `ResolverActivity` default → null icon; browser-only https → null icon (control probe) |
| Manual | | chip appears once (not per pill); tap opens the app; **counter does not move**; split note shows no chip; install app → background → foreground → chip appears; adaptive icon is masked round, not floating in padding; https target with no app shows the glyph, not Chrome |
---
## 8. Open decisions
1.**Chip placement** — sibling vs inside the toggle (§2). Recommend sibling:
renders once and deletes the whole `ZapRail` refactor. Flagged because it
diverges from the original sketch.
2.**Default for `showPayToZapRail`** — recommend **off**, matching how
`ReactionRowAction.Pay` already ships disabled.
3.**Private rumors** — on-chain is suppressed there (it would e-tag the
rumor). A payto handoff publishes nothing, so it is arguably safe.
Recommend **allow**, noting the divergence from the on-chain precedent.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.