feat(desktop): relay power tools — dashboard, config editors, subscription wiring

- Relay Dashboard as new DeckColumnType.Relays with Monitor + Configure tabs
- Monitor tab: live 1Hz session metrics, NIP-11 detail panels, reconnect
- Configure tab: collapsible editors for Connected, NIP-65 (R/W/Both toggles),
  DM (kind 10050), Search (kind 10007), Blocked (kind 10006)
- Compose Relay Picker: expandable relay selection in note compose dialog
- Nip11Fetcher: fail-closed HTTP client, 256KB limit, Mutex dedup
- RelayMetrics: separate StateFlow (1Hz) to avoid relayStatuses churn
- Bootstrap subscription: fetches user's relay config on login (kinds 10002/10050/10007/10006)
- DesktopRelayCategories aggregator: feedRelays, searchRelays, notificationRelays, dmRelays
  with fallback logic, blocked subtraction, 1s debounce
- LocalRelayCategories CompositionLocal (matches LocalTorState pattern)
- FeedScreen uses NIP-65 outbox relays, SearchScreen uses search relays
- "X relays connected" on feed is clickable → opens Relay Dashboard
- URL validation: requires domain with dot, blocks ws:// unless .onion
- Auto-add pending input on Save, empty list protection
- Thread-safe created_at dedup (AtomicLong) in DesktopAccountRelays
- DisposableEffect cleanup for bootstrap subscription

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
nrobi144
2026-04-22 10:15:44 +03:00
co-authored by Claude Opus 4.6
parent 3bfeac885a
commit 66962d360d
32 changed files with 3349 additions and 122 deletions
@@ -74,10 +74,12 @@ import androidx.compose.ui.window.rememberWindowState
import com.vitorpamplona.amethyst.desktop.account.AccountManager
import com.vitorpamplona.amethyst.desktop.account.AccountState
import com.vitorpamplona.amethyst.desktop.cache.DesktopLocalCache
import com.vitorpamplona.amethyst.desktop.model.DesktopDmRelayState
import com.vitorpamplona.amethyst.desktop.model.DesktopAccountRelays
import com.vitorpamplona.amethyst.desktop.model.DesktopIAccount
import com.vitorpamplona.amethyst.desktop.model.DesktopRelayCategories
import com.vitorpamplona.amethyst.desktop.network.DefaultRelays
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.amethyst.desktop.service.highlights.DesktopHighlightStore
import com.vitorpamplona.amethyst.desktop.service.images.DesktopImageLoaderSetup
import com.vitorpamplona.amethyst.desktop.service.media.VlcjPlayerPool
@@ -103,10 +105,18 @@ import com.vitorpamplona.amethyst.desktop.ui.media.LocalAwtWindow
import com.vitorpamplona.amethyst.desktop.ui.media.LocalIsImmersiveFullscreen
import com.vitorpamplona.amethyst.desktop.ui.media.LocalWindowState
import com.vitorpamplona.amethyst.desktop.ui.profile.ProfileInfoCard
import com.vitorpamplona.amethyst.desktop.ui.relay.LocalRelayCategories
import com.vitorpamplona.amethyst.desktop.ui.relay.RelayStatusCard
import com.vitorpamplona.amethyst.desktop.ui.settings.MediaServerSettings
import com.vitorpamplona.quartz.nip01Core.relay.client.reqs.SubscriptionListener
import com.vitorpamplona.quartz.nip01Core.relay.filters.Filter
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent
import com.vitorpamplona.quartz.nip47WalletConnect.Nip47WalletConnect
import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent
import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent
import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent
import com.vitorpamplona.quartz.utils.Log
import com.vitorpamplona.quartz.utils.LogLevel
import kotlinx.coroutines.CoroutineScope
@@ -116,6 +126,8 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.time.Duration.Companion.seconds
private val isMacOS = System.getProperty("os.name").lowercase().contains("mac")
@@ -225,6 +237,8 @@ fun main() {
},
)
}
// Callback set by App() for single pane navigation from MenuBar
var navigateToScreen by remember { mutableStateOf<((DeckColumnType) -> Unit)?>(null) }
Window(
onCloseRequest = ::exitApplication,
@@ -351,6 +365,26 @@ fun main() {
},
onClick = { showAppDrawer = !showAppDrawer },
)
Item(
"Relay Dashboard",
shortcut =
if (isMacOS) {
KeyShortcut(Key.R, meta = true, shift = true)
} else {
KeyShortcut(Key.R, ctrl = true, shift = true)
},
onClick = {
if (layoutMode == LayoutMode.DECK) {
if (deckState.hasColumnOfType(DeckColumnType.Relays)) {
deckState.focusExistingColumn(DeckColumnType.Relays)
} else {
deckState.addColumn(DeckColumnType.Relays)
}
} else {
navigateToScreen?.invoke(DeckColumnType.Relays)
}
},
)
Separator()
Item(
if (layoutMode == LayoutMode.DECK) "\u2713 Deck Layout" else "Deck Layout",
@@ -467,6 +501,7 @@ fun main() {
Item("Global Feed", onClick = { deckState.addColumn(DeckColumnType.GlobalFeed) })
Item("Profile", onClick = { deckState.addColumn(DeckColumnType.MyProfile) })
Item("Chess", onClick = { deckState.addColumn(DeckColumnType.Chess) })
Item("Relays", onClick = { deckState.addColumn(DeckColumnType.Relays) })
}
}
}
@@ -511,6 +546,7 @@ fun main() {
torTypeFlow = torTypeFlow,
externalPortFlow = externalPortFlow,
initialTorSettings = torSettings,
onNavigateToScreen = { navigateToScreen = it },
)
}
}
@@ -538,10 +574,16 @@ fun App(
torTypeFlow: kotlinx.coroutines.flow.MutableStateFlow<com.vitorpamplona.amethyst.commons.tor.TorType>,
externalPortFlow: kotlinx.coroutines.flow.MutableStateFlow<Int>,
initialTorSettings: com.vitorpamplona.amethyst.commons.tor.TorSettings,
onNavigateToScreen: ((DeckColumnType) -> Unit) -> Unit = {},
) {
val singlePaneState = remember { SinglePaneState() }
val pinnedNavBarState = remember { PinnedNavBarState(workspaceManager).also { it.loadFromWorkspace() } }
// Register single pane navigation callback for MenuBar shortcuts
LaunchedEffect(singlePaneState) {
onNavigateToScreen { screen -> singlePaneState.navigate(screen) }
}
// Always reload from prefs — after key() rebuild, prefs have the latest saved settings
var torSettings by remember {
mutableStateOf(
@@ -631,6 +673,12 @@ fun App(
}
val relayManager = remember(httpClient) { DesktopRelayConnectionManager(httpClient) }
val nip11Fetcher = remember { Nip11Fetcher() }
// Start 1Hz metrics snapshot for relay dashboard
LaunchedEffect(relayManager) {
relayManager.startMetricsSnapshot(this)
}
// Subscriptions coordinator — uses default relay URLs for metadata indexing.
// Feed subscriptions (inside MainContent) drive actual relay pool connections.
@@ -755,6 +803,7 @@ fun App(
account = account,
nwcConnection = nwcConnection,
subscriptionsCoordinator = subscriptionsCoordinator,
nip11Fetcher = nip11Fetcher,
appScope = scope,
torStatus = currentTorStatus,
onShowComposeDialog = onShowComposeDialog,
@@ -850,6 +899,7 @@ fun MainContent(
account: AccountState.LoggedIn,
nwcConnection: Nip47WalletConnect.Nip47URINorm?,
subscriptionsCoordinator: DesktopRelaySubscriptionsCoordinator,
nip11Fetcher: Nip11Fetcher,
appScope: CoroutineScope,
torStatus: com.vitorpamplona.amethyst.commons.tor.TorServiceStatus,
onShowComposeDialog: () -> Unit,
@@ -871,6 +921,23 @@ fun MainContent(
DesktopIAccount(account, localCache, relayManager, dmSendTracker, scope)
}
// Centralized relay state for all categories (DM, search, blocked)
val accountRelays =
remember(account, relayManager, scope) {
DesktopAccountRelays(account.pubKeyHex, relayManager, scope)
}
// Aggregated relay categories (feed, notifications, search, DM)
val relayCategories =
remember(iAccount.nip65RelayList, accountRelays, relayManager) {
DesktopRelayCategories(
nip65State = iAccount.nip65RelayList,
accountRelays = accountRelays,
connectedRelays = relayManager.connectedRelays,
scope = scope,
)
}
val highlightStore = remember { DesktopHighlightStore(appScope) }
val draftStore =
remember {
@@ -878,19 +945,58 @@ fun MainContent(
.DesktopDraftStore(appScope)
}
// Bootstrap subscription: fetch relay config events (kinds 10002, 10050, 10007, 10006)
// Uses DisposableEffect to clean up subscription on account change
DisposableEffect(accountRelays) {
val bootstrapSubId = "bootstrap-relay-config"
scope.launch {
val connected =
withTimeoutOrNull(30.seconds) {
relayManager.connectedRelays.first { it.isNotEmpty() }
}
if (connected != null) {
val filter =
Filter(
kinds =
listOf(
AdvertisedRelayListEvent.KIND,
ChatMessageRelayListEvent.KIND,
SearchRelayListEvent.KIND,
BlockedRelayListEvent.KIND,
),
authors = listOf(account.pubKeyHex),
limit = 4,
)
relayManager.subscribe(
subId = bootstrapSubId,
filters = listOf(filter),
listener =
object : SubscriptionListener {
override fun onEvent(
event: com.vitorpamplona.quartz.nip01Core.core.Event,
isLive: Boolean,
relay: NormalizedRelayUrl,
forFilters: List<Filter>?,
) {
// Route through localCache for NIP-65 sync
localCache.consume(event, relay)
// Route to accountRelays for kinds without cache-backed state
accountRelays.consumeIfRelevant(event)
}
},
)
}
}
onDispose { relayManager.unsubscribe(bootstrapSubId) }
}
// Subscribe to incoming DMs and process into chatroomList
LaunchedEffect(account) {
relayManager.connectedRelays.first { it.isNotEmpty() }
val dmRelayState =
DesktopDmRelayState(
dmRelayList = kotlinx.coroutines.flow.MutableStateFlow(emptySet()),
connectedRelays = relayManager.connectedRelays,
scope = scope,
)
subscriptionsCoordinator.subscribeToDms(
userPubKeyHex = account.pubKeyHex,
dmRelayState = dmRelayState,
dmRelayState = accountRelays.dmRelays,
onDmEvent = { event, relay ->
// Store raw event in cache
val note = localCache.getOrCreateNote(event.id)
@@ -984,91 +1090,104 @@ fun MainContent(
val isImmersive by com.vitorpamplona.amethyst.desktop.ui.media.LocalIsImmersiveFullscreen.current
Box(Modifier.fillMaxSize()) {
Column(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxSize().weight(1f)) {
when (layoutMode) {
LayoutMode.SINGLE_PANE -> {
val lastRelayEvent by subscriptionsCoordinator.lastEventAt.collectAsState()
SinglePaneLayout(
relayManager = relayManager,
localCache = localCache,
accountManager = accountManager,
account = account,
iAccount = iAccount,
nwcConnection = nwcConnection,
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
appScope = appScope,
singlePaneState = singlePaneState,
pinnedNavBarState = pinnedNavBarState,
onOpenAppDrawer = onShowAppDrawer,
onShowComposeDialog = onShowComposeDialog,
onShowReplyDialog = onShowReplyDialog,
onZapFeedback = onZapFeedback,
signerConnectionState = signerConnectionState,
lastPingTimeSec = lastPingTimeSec,
lastRelayEventAt = lastRelayEvent,
modifier = Modifier.weight(1f),
)
}
LayoutMode.DECK -> {
if (!isImmersive) {
DeckSidebar(
onAddColumn = onShowAppDrawer,
onOpenSettings = {
if (deckState.hasColumnOfType(DeckColumnType.Settings)) {
deckState.focusExistingColumn(DeckColumnType.Settings)
} else {
deckState.addColumn(DeckColumnType.Settings)
}
},
CompositionLocalProvider(
LocalRelayCategories provides relayCategories,
) {
Box(Modifier.fillMaxSize()) {
Column(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxSize().weight(1f)) {
when (layoutMode) {
LayoutMode.SINGLE_PANE -> {
val lastRelayEvent by subscriptionsCoordinator.lastEventAt.collectAsState()
SinglePaneLayout(
relayManager = relayManager,
localCache = localCache,
accountManager = accountManager,
account = account,
iAccount = iAccount,
nwcConnection = nwcConnection,
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
nip11Fetcher = nip11Fetcher,
appScope = appScope,
singlePaneState = singlePaneState,
pinnedNavBarState = pinnedNavBarState,
onOpenAppDrawer = onShowAppDrawer,
onShowComposeDialog = onShowComposeDialog,
onShowReplyDialog = onShowReplyDialog,
onZapFeedback = onZapFeedback,
signerConnectionState = signerConnectionState,
lastPingTimeSec = lastPingTimeSec,
torStatus = torStatus,
lastRelayEventAt = lastRelayEvent,
modifier = Modifier.weight(1f),
)
VerticalDivider()
}
DeckLayout(
deckState = deckState,
relayManager = relayManager,
localCache = localCache,
accountManager = accountManager,
account = account,
iAccount = iAccount,
nwcConnection = nwcConnection,
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
appScope = appScope,
onShowComposeDialog = onShowComposeDialog,
onShowReplyDialog = onShowReplyDialog,
onZapFeedback = onZapFeedback,
modifier = Modifier.weight(1f),
)
LayoutMode.DECK -> {
if (!isImmersive) {
DeckSidebar(
onAddColumn = onShowAppDrawer,
onOpenSettings = {
if (deckState.hasColumnOfType(DeckColumnType.Settings)) {
deckState.focusExistingColumn(DeckColumnType.Settings)
} else {
deckState.addColumn(DeckColumnType.Settings)
}
},
signerConnectionState = signerConnectionState,
lastPingTimeSec = lastPingTimeSec,
torStatus = torStatus,
)
VerticalDivider()
}
DeckLayout(
deckState = deckState,
relayManager = relayManager,
localCache = localCache,
accountManager = accountManager,
account = account,
iAccount = iAccount,
nwcConnection = nwcConnection,
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
nip11Fetcher = nip11Fetcher,
appScope = appScope,
onShowComposeDialog = onShowComposeDialog,
onShowReplyDialog = onShowReplyDialog,
onZapFeedback = onZapFeedback,
onNavigateToRelays = {
if (deckState.hasColumnOfType(DeckColumnType.Relays)) {
deckState.focusExistingColumn(DeckColumnType.Relays)
} else {
deckState.addColumn(DeckColumnType.Relays)
}
},
modifier = Modifier.weight(1f),
)
}
}
}
} // end Row
} // end Row
// Persistent media control bar
// Persistent media control bar
com.vitorpamplona.amethyst.desktop.ui.media
.NowPlayingBar()
} // end Column
// Global fullscreen video overlay
com.vitorpamplona.amethyst.desktop.ui.media
.NowPlayingBar()
} // end Column
.GlobalFullscreenOverlay()
// Global fullscreen video overlay
com.vitorpamplona.amethyst.desktop.ui.media
.GlobalFullscreenOverlay()
// Snackbar for zap feedback
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp),
)
}
// Snackbar for zap feedback
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp),
)
}
} // end CompositionLocalProvider
}
@Composable
@@ -25,10 +25,13 @@ import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent
import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent
import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.concurrent.atomic.AtomicLong
/**
* Manages relay state for a desktop account.
@@ -55,6 +58,19 @@ class DesktopAccountRelays(
private val _dmRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val dmRelayList: StateFlow<Set<NormalizedRelayUrl>> = _dmRelayList.asStateFlow()
/** User-configured search relays from kind 10007 events */
private val _searchRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val searchRelayList: StateFlow<Set<NormalizedRelayUrl>> = _searchRelayList.asStateFlow()
/** User-configured blocked relays from kind 10006 events */
private val _blockedRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val blockedRelayList: StateFlow<Set<NormalizedRelayUrl>> = _blockedRelayList.asStateFlow()
// Track created_at to prevent stale overwrites (thread-safe)
private val lastDmCreatedAt = AtomicLong(0L)
private val lastSearchCreatedAt = AtomicLong(0L)
private val lastBlockedCreatedAt = AtomicLong(0L)
/** Aggregated DM relay state (DM relays + fallback to connected relays) */
val dmRelays =
DesktopDmRelayState(
@@ -63,32 +79,65 @@ class DesktopAccountRelays(
scope = scope,
)
/**
* Processes a ChatMessageRelayListEvent (kind 10050) to update DM relays.
* Call this when receiving kind 10050 events from relay subscriptions.
*/
fun consumeDmRelayList(event: ChatMessageRelayListEvent) {
/** Routes kind 10050 to DM relay state. Use consumeIfRelevant() for external callers. */
private fun consumeDmRelayList(event: ChatMessageRelayListEvent) {
if (event.pubKey != userPubKeyHex) return
val relays = event.relays().toSet()
_dmRelayList.value = relays
_dmRelayList.value = event.relays().toSet()
}
/**
* Processes any event that might be a DM relay list.
* Returns true if the event was consumed as a DM relay list.
* Routes relay config events (kinds 10050, 10007, 10006) to the appropriate handler.
* Returns true if the event was consumed.
* Uses created_at checking to prevent stale overwrites.
*/
fun consumeIfDmRelayList(event: Event): Boolean {
if (event.kind == ChatMessageRelayListEvent.KIND && event is ChatMessageRelayListEvent) {
consumeDmRelayList(event)
return true
fun consumeIfRelevant(event: Event): Boolean {
if (event.pubKey != userPubKeyHex) return false
return when (event.kind) {
ChatMessageRelayListEvent.KIND -> {
if (event is ChatMessageRelayListEvent && event.createdAt > lastDmCreatedAt.get()) {
lastDmCreatedAt.set(event.createdAt)
_dmRelayList.value = event.relays().toSet()
}
true
}
SearchRelayListEvent.KIND -> {
if (event is SearchRelayListEvent && event.createdAt > lastSearchCreatedAt.get()) {
lastSearchCreatedAt.set(event.createdAt)
_searchRelayList.value = event.publicRelays().toSet()
}
true
}
BlockedRelayListEvent.KIND -> {
if (event is BlockedRelayListEvent && event.createdAt > lastBlockedCreatedAt.get()) {
lastBlockedCreatedAt.set(event.createdAt)
_blockedRelayList.value = event.publicRelays().toSet()
}
true
}
else -> {
false
}
}
return false
}
/**
* Manually sets DM relays (e.g., from saved preferences).
*/
fun setDmRelays(relays: Set<NormalizedRelayUrl>) {
lastDmCreatedAt.set(Long.MAX_VALUE)
_dmRelayList.value = relays
}
fun setSearchRelays(relays: Set<NormalizedRelayUrl>) {
lastSearchCreatedAt.set(Long.MAX_VALUE)
_searchRelayList.value = relays
}
fun setBlockedRelays(relays: Set<NormalizedRelayUrl>) {
lastBlockedCreatedAt.set(Long.MAX_VALUE)
_blockedRelayList.value = relays
}
}
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.model
import com.vitorpamplona.amethyst.commons.model.nip65RelayList.Nip65RelayListState
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.stateIn
import kotlin.time.Duration.Companion.seconds
/**
* Aggregates relay categories for desktop subscriptions.
*
* Each category combines user-configured relays with fallbacks and subtracts blocked relays.
* Debounced to prevent subscription thrashing at startup.
*/
@OptIn(FlowPreview::class)
class DesktopRelayCategories(
nip65State: Nip65RelayListState,
accountRelays: DesktopAccountRelays,
connectedRelays: StateFlow<Set<NormalizedRelayUrl>>,
scope: CoroutineScope,
) {
/** NIP-65 outbox (write) relays, falls back to connected relays, minus blocked */
val feedRelays: StateFlow<Set<NormalizedRelayUrl>> =
combine(
nip65State.outboxFlow,
connectedRelays,
accountRelays.blockedRelayList,
) { outbox, connected, blocked ->
(outbox.ifEmpty { connected }) - blocked
}.debounce(1.seconds)
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, connectedRelays.value)
/** NIP-65 inbox (read) relays, falls back to connected relays, minus blocked */
val notificationRelays: StateFlow<Set<NormalizedRelayUrl>> =
combine(
nip65State.inboxFlow,
connectedRelays,
accountRelays.blockedRelayList,
) { inbox, connected, blocked ->
(inbox.ifEmpty { connected }) - blocked
}.debounce(1.seconds)
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, connectedRelays.value)
/** Search relays (kind 10007), falls back to relay.nostr.band, minus blocked */
val searchRelays: StateFlow<Set<NormalizedRelayUrl>> =
combine(
accountRelays.searchRelayList,
accountRelays.blockedRelayList,
) { search, blocked ->
(search.ifEmpty { DEFAULT_SEARCH_RELAYS }) - blocked
}.debounce(1.seconds)
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, DEFAULT_SEARCH_RELAYS)
/** DM relays — aggregated DM state minus blocked */
val dmRelays: StateFlow<Set<NormalizedRelayUrl>> =
combine(
accountRelays.dmRelays.flow,
accountRelays.blockedRelayList,
) { dm, blocked -> dm - blocked }
.debounce(1.seconds)
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, accountRelays.dmRelays.flow.value)
companion object {
val DEFAULT_SEARCH_RELAYS =
setOfNotNull(RelayUrlNormalizer.normalizeOrNull("wss://relay.nostr.band"))
}
}
@@ -0,0 +1,101 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.network
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.toHttp
import com.vitorpamplona.quartz.nip11RelayInfo.Nip11RelayInformation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import okhttp3.Request
import java.util.concurrent.ConcurrentHashMap
/**
* Fetches and caches NIP-11 relay information documents.
* Session-only cache (no disk persistence).
*
* Uses fail-closed HTTP client to prevent IP leaks during Tor bootstrap.
* Limits response body to 256KB to prevent DoS from malicious relays.
* Deduplicates concurrent fetches via per-URL Mutex.
*/
class Nip11Fetcher {
private val cache = ConcurrentHashMap<NormalizedRelayUrl, Nip11RelayInformation>()
private val locks = ConcurrentHashMap<NormalizedRelayUrl, Mutex>()
companion object {
private const val MAX_RESPONSE_BYTES = 256 * 1024L
private val SEMAPHORE = Semaphore(5)
}
suspend fun fetch(url: NormalizedRelayUrl): Nip11RelayInformation? {
cache[url]?.let { return it }
val mutex = locks.getOrPut(url) { Mutex() }
return mutex.withLock {
cache[url]?.let { return it } // double-check after lock
SEMAPHORE
.withPermit {
withContext(Dispatchers.IO) {
fetchFromNetwork(url)
}
}?.also { info ->
cache[url] = info
}
}
}
private fun fetchFromNetwork(url: NormalizedRelayUrl): Nip11RelayInformation? {
// FAIL-CLOSED: use currentClient() not getHttpClient()
val client = DesktopHttpClient.currentClient()
val httpUrl = url.toHttp()
val request =
Request
.Builder()
.url(httpUrl)
.header("Accept", "application/nostr+json")
.build()
return try {
client.newCall(request).execute().use { response ->
if (response.isSuccessful) {
val source = response.body.source()
source.request(MAX_RESPONSE_BYTES) // buffer up to limit
val body = source.readUtf8()
Nip11RelayInformation.fromJson(body)
} else {
null
}
}
} catch (_: Exception) {
null
}
}
fun getCached(url: NormalizedRelayUrl): Nip11RelayInformation? = cache[url]
fun clearCache() {
cache.clear()
}
}
@@ -25,15 +25,27 @@ import com.vitorpamplona.quartz.nip01Core.relay.client.NostrClient
import com.vitorpamplona.quartz.nip01Core.relay.client.listeners.RelayConnectionListener
import com.vitorpamplona.quartz.nip01Core.relay.client.reqs.SubscriptionListener
import com.vitorpamplona.quartz.nip01Core.relay.client.single.IRelayClient
import com.vitorpamplona.quartz.nip01Core.relay.commands.toClient.EventMessage
import com.vitorpamplona.quartz.nip01Core.relay.commands.toClient.Message
import com.vitorpamplona.quartz.nip01Core.relay.commands.toRelay.Command
import com.vitorpamplona.quartz.nip01Core.relay.filters.Filter
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
import com.vitorpamplona.quartz.nip01Core.relay.sockets.WebsocketBuilder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap
data class RelayMetrics(
val eventCount: Long = 0,
val lastEventAt: Long? = null,
)
/**
* Manages Nostr relay connections, subscriptions, and status tracking.
@@ -55,10 +67,30 @@ open class RelayConnectionManager(
val connectedRelays: StateFlow<Set<NormalizedRelayUrl>> = _client.connectedRelaysFlow()
val availableRelays: StateFlow<Set<NormalizedRelayUrl>> = _client.availableRelaysFlow()
// Relays explicitly removed by user — suppress status updates from pool callbacks
private val removedRelays = ConcurrentHashMap.newKeySet<NormalizedRelayUrl>()
// Hot metrics — written on every event, no StateFlow emission
private val rawMetricsMap = ConcurrentHashMap<NormalizedRelayUrl, RelayMetrics>()
// Throttled snapshot — 1Hz emission for UI
private val _relayMetrics = MutableStateFlow<Map<NormalizedRelayUrl, RelayMetrics>>(emptyMap())
val relayMetrics: StateFlow<Map<NormalizedRelayUrl, RelayMetrics>> = _relayMetrics.asStateFlow()
init {
_client.addConnectionListener(this)
}
/** Start 1Hz metrics snapshot. Call once after connect(). */
fun startMetricsSnapshot(scope: CoroutineScope) {
scope.launch {
while (isActive) {
delay(1_000)
_relayMetrics.value = HashMap(rawMetricsMap)
}
}
}
fun connect() {
_client.connect()
}
@@ -69,12 +101,14 @@ open class RelayConnectionManager(
fun addRelay(url: String): NormalizedRelayUrl? {
val normalized = RelayUrlNormalizer.Companion.normalizeOrNull(url) ?: return null
removedRelays.remove(normalized)
updateRelayStatus(normalized) { it.copy(connected = false, error = null) }
return normalized
}
fun removeRelay(url: NormalizedRelayUrl) {
_relayStatuses.value = _relayStatuses.value - url
removedRelays.add(url)
_relayStatuses.update { it - url }
}
fun addDefaultRelays() {
@@ -167,13 +201,13 @@ open class RelayConnectionManager(
private fun updateRelayStatus(
url: NormalizedRelayUrl,
update: (RelayStatus) -> RelayStatus,
transform: (RelayStatus) -> RelayStatus,
) {
_relayStatuses.value =
_relayStatuses.value.toMutableMap().apply {
val current = this[url] ?: RelayStatus(url, connected = false)
this[url] = update(current)
}
if (url in removedRelays) return
_relayStatuses.update { current ->
val existing = current[url] ?: RelayStatus(url, connected = false)
current + (url to transform(existing))
}
}
override fun onConnecting(relay: IRelayClient) {
@@ -212,7 +246,14 @@ open class RelayConnectionManager(
msgStr: String,
msg: Message,
) {
// Events are handled by subscription listeners
// Only count EVENT messages, not EOSE/OK/NOTICE/AUTH
if (msg !is EventMessage) return
rawMetricsMap.compute(relay.url) { _, m ->
RelayMetrics(
eventCount = (m?.eventCount ?: 0) + 1,
lastEventAt = System.currentTimeMillis(),
)
}
}
override fun onSent(
@@ -57,10 +57,13 @@ import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.service.upload.DesktopUploadOrchestrator
import com.vitorpamplona.amethyst.desktop.service.upload.DesktopUploadTracker
import com.vitorpamplona.amethyst.desktop.service.upload.UploadResult
import com.vitorpamplona.amethyst.desktop.ui.compose.ComposeRelayPicker
import com.vitorpamplona.amethyst.desktop.ui.compose.RelayPickerState
import com.vitorpamplona.amethyst.desktop.ui.media.ClipboardPasteHandler
import com.vitorpamplona.amethyst.desktop.ui.media.DesktopFilePicker
import com.vitorpamplona.amethyst.desktop.ui.media.MediaAttachmentRow
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.tags.events.ETag
import com.vitorpamplona.quartz.nip01Core.tags.events.eTag
import com.vitorpamplona.quartz.nip01Core.tags.hashtags.hashtags
@@ -104,6 +107,15 @@ fun ComposeNoteDialog(
var selectedServer by remember { mutableStateOf(DesktopPreferences.preferredBlossomServer) }
var postAsPicture by remember { mutableStateOf(false) }
// Relay picker state
val connectedRelays by relayManager.connectedRelays.collectAsState()
val allRelays by relayManager.availableRelays.collectAsState()
val pickerState =
remember(allRelays, connectedRelays) {
RelayPickerState(allRelays = allRelays, connectedRelays = connectedRelays)
}
var selectedRelays by remember(connectedRelays) { mutableStateOf(connectedRelays) }
// Drag-and-drop state
var isDragOver by remember { mutableStateOf(false) }
val dropTarget =
@@ -255,7 +267,22 @@ fun ComposeNoteDialog(
)
}
Spacer(Modifier.height(16.dp))
Spacer(Modifier.height(8.dp))
ComposeRelayPicker(
pickerState = pickerState,
selectedRelays = selectedRelays,
onToggleRelay = { url ->
selectedRelays =
if (url in selectedRelays) {
selectedRelays - url
} else {
selectedRelays + url
}
},
)
Spacer(Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
@@ -316,6 +343,7 @@ fun ComposeNoteDialog(
images = pictureMetas,
account = account,
relayManager = relayManager,
relays = selectedRelays,
)
} else {
val imetaTags = buildIMetaTags(uploadResults)
@@ -325,6 +353,7 @@ fun ComposeNoteDialog(
relayManager = relayManager,
replyTo = replyTo,
imetaTags = imetaTags,
relays = selectedRelays,
)
}
onDismiss()
@@ -468,6 +497,7 @@ private suspend fun publishPicture(
images: List<com.vitorpamplona.quartz.nip68Picture.PictureMeta>,
account: AccountState.LoggedIn,
relayManager: DesktopRelayConnectionManager,
relays: Set<NormalizedRelayUrl>,
) {
withContext(Dispatchers.IO) {
if (account.isReadOnly) {
@@ -483,7 +513,7 @@ private suspend fun publishPicture(
}
val signedEvent = account.signer.sign(template)
relayManager.broadcastToAll(signedEvent)
relayManager.publish(signedEvent, relays)
}
}
@@ -493,6 +523,7 @@ private suspend fun publishNote(
relayManager: DesktopRelayConnectionManager,
replyTo: Event?,
imetaTags: List<IMetaTag> = emptyList(),
relays: Set<NormalizedRelayUrl>,
) {
withContext(Dispatchers.IO) {
if (account.isReadOnly) {
@@ -516,6 +547,6 @@ private suspend fun publishNote(
}
val signedEvent = account.signer.sign(template)
relayManager.broadcastToAll(signedEvent)
relayManager.publish(signedEvent, relays)
}
}
@@ -20,6 +20,7 @@
*/
package com.vitorpamplona.amethyst.desktop.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -80,6 +81,7 @@ import com.vitorpamplona.amethyst.desktop.subscriptions.generateSubId
import com.vitorpamplona.amethyst.desktop.subscriptions.rememberSubscription
import com.vitorpamplona.amethyst.desktop.ui.media.LightboxOverlay
import com.vitorpamplona.amethyst.desktop.ui.note.NoteCard
import com.vitorpamplona.amethyst.desktop.ui.relay.LocalRelayCategories
import com.vitorpamplona.amethyst.desktop.viewmodels.DesktopFeedViewModel
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip18Reposts.GenericRepostEvent
@@ -267,6 +269,7 @@ fun FeedScreen(
onNavigateToProfile: (String) -> Unit = {},
onNavigateToThread: (String) -> Unit = {},
onZapFeedback: (ZapFeedback) -> Unit = {},
onNavigateToRelays: () -> Unit = {},
) {
val relayStatuses by relayManager.relayStatuses.collectAsState()
val connectedRelays by relayManager.connectedRelays.collectAsState()
@@ -275,6 +278,10 @@ fun FeedScreen(
// Available relay URLs — subscribe triggers connection on-demand
val allRelayUrls = remember(relayStatuses) { relayStatuses.keys }
// Feed relays from relay categories (NIP-65 outbox, minus blocked, with fallback)
val relayCategories = LocalRelayCategories.current
val feedRelays by relayCategories.feedRelays.collectAsState()
var replyToEvent by remember { mutableStateOf<Event?>(null) }
var lightboxState by remember { mutableStateOf<LightboxState?>(null) }
var feedMode by remember { mutableStateOf(initialFeedMode ?: DesktopPreferences.feedMode) }
@@ -295,13 +302,13 @@ fun FeedScreen(
}
// Subscribe to feed events (kind 1) — populates cache via coordinator
rememberSubscription(allRelayUrls, feedMode, followedUsers, relayManager = relayManager) {
if (allRelayUrls.isEmpty()) return@rememberSubscription null
rememberSubscription(feedRelays, feedMode, followedUsers, relayManager = relayManager) {
if (feedRelays.isEmpty()) return@rememberSubscription null
when (feedMode) {
FeedMode.GLOBAL -> {
createGlobalFeedSubscription(
relays = allRelayUrls,
relays = feedRelays,
onEvent = { event, _, relay, _ ->
subscriptionsCoordinator?.consumeEvent(event, relay)
},
@@ -312,7 +319,7 @@ fun FeedScreen(
val follows = followedUsers.toList()
if (follows.isNotEmpty()) {
createFollowingFeedSubscription(
relays = allRelayUrls,
relays = feedRelays,
followedUsers = follows,
onEvent = { event, _, relay, _ ->
subscriptionsCoordinator?.consumeEvent(event, relay)
@@ -489,6 +496,7 @@ fun FeedScreen(
},
onRefresh = { relayManager.connect() },
onCompose = onCompose,
onNavigateToRelays = onNavigateToRelays,
)
Spacer(Modifier.height(8.dp))
@@ -597,6 +605,7 @@ private fun FeedHeader(
onFeedModeChange: (FeedMode) -> Unit,
onRefresh: () -> Unit,
onCompose: () -> Unit,
onNavigateToRelays: () -> Unit = {},
) {
FlowRow(
modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp),
@@ -635,7 +644,9 @@ private fun FeedHeader(
Text(
"${connectedRelays.size} relays connected",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = MaterialTheme.colorScheme.primary,
modifier =
Modifier.clickable { onNavigateToRelays() },
)
if (feedMode == FeedMode.FOLLOWING) {
Text(
@@ -100,6 +100,7 @@ import com.vitorpamplona.amethyst.desktop.subscriptions.createMetadataSubscripti
import com.vitorpamplona.amethyst.desktop.subscriptions.createSearchPeopleSubscription
import com.vitorpamplona.amethyst.desktop.subscriptions.generateSubId
import com.vitorpamplona.amethyst.desktop.subscriptions.rememberSubscription
import com.vitorpamplona.amethyst.desktop.ui.relay.LocalRelayCategories
import com.vitorpamplona.amethyst.desktop.ui.search.AdvancedSearchPanel
import com.vitorpamplona.amethyst.desktop.ui.search.SearchResultsList
import com.vitorpamplona.amethyst.desktop.ui.search.SearchSyncBanner
@@ -131,6 +132,8 @@ fun SearchScreen(
val connectedRelays by relayManager.connectedRelays.collectAsState()
val relayStatuses by relayManager.relayStatuses.collectAsState()
val allRelayUrls = remember(relayStatuses) { relayStatuses.keys }
val relayCategories = LocalRelayCategories.current
val searchRelays by relayCategories.searchRelays.collectAsState()
val displayText by state.displayText.collectAsState()
// Track TextFieldValue locally to preserve cursor position
var textFieldValue by remember { mutableStateOf(TextFieldValue(displayText)) }
@@ -171,9 +174,9 @@ fun SearchScreen(
}
}
// NIP-50 people search subscription (use allRelayUrls — subscribe will connect)
rememberSubscription(connectedRelays, debouncedQuery, relayManager = relayManager) {
if (allRelayUrls.isEmpty() || debouncedQuery.isEmpty) {
// NIP-50 people search subscription (use searchRelays from relay categories)
rememberSubscription(searchRelays, debouncedQuery, relayManager = relayManager) {
if (searchRelays.isEmpty() || debouncedQuery.isEmpty) {
return@rememberSubscription null
}
if (bech32Results.isNotEmpty()) return@rememberSubscription null
@@ -183,7 +186,7 @@ fun SearchScreen(
}
createSearchPeopleSubscription(
relays = allRelayUrls,
relays = searchRelays,
searchQuery =
debouncedQuery.text.ifBlank {
QuerySerializer.serialize(debouncedQuery)
@@ -212,9 +215,9 @@ fun SearchScreen(
)
}
// NIP-50 advanced note search subscription (use allRelayUrls)
rememberSubscription(connectedRelays, debouncedQuery, relayManager = relayManager) {
if (allRelayUrls.isEmpty() || debouncedQuery.isEmpty) {
// NIP-50 advanced note search subscription (use searchRelays from relay categories)
rememberSubscription(searchRelays, debouncedQuery, relayManager = relayManager) {
if (searchRelays.isEmpty() || debouncedQuery.isEmpty) {
return@rememberSubscription null
}
if (bech32Results.isNotEmpty()) return@rememberSubscription null
@@ -225,7 +228,7 @@ fun SearchScreen(
SubscriptionConfig(
subId = generateSubId("adv-search"),
filters = filters,
relays = allRelayUrls,
relays = searchRelays,
onEvent = { event, _, relay, _ ->
if (event.kind == MetadataEvent.KIND) return@SubscriptionConfig
if (state.trackRelayEvent(relay.url, event.id)) {
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.compose
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
@Immutable
data class RelayPickerState(
val allRelays: Set<NormalizedRelayUrl>,
val connectedRelays: Set<NormalizedRelayUrl>,
) {
companion object {
val EMPTY = RelayPickerState(emptySet(), emptySet())
}
}
@Composable
fun ComposeRelayPicker(
pickerState: RelayPickerState,
selectedRelays: Set<NormalizedRelayUrl>,
onToggleRelay: (NormalizedRelayUrl) -> Unit,
modifier: Modifier = Modifier,
) {
var expanded by remember { mutableStateOf(false) }
Column(modifier = modifier.fillMaxWidth()) {
// Collapsed header
Row(
modifier = Modifier.clickable { expanded = !expanded }.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
if (expanded) Icons.Default.ExpandMore else Icons.Default.ChevronRight,
contentDescription = null,
)
Spacer(Modifier.width(4.dp))
Text(
"Relays (${selectedRelays.size} of ${pickerState.allRelays.size})",
style = MaterialTheme.typography.bodyMedium,
)
}
// Collapsed: show chips
if (!expanded) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.padding(start = 28.dp),
) {
items(selectedRelays.toList().sortedBy { it.url }, key = { it.url }) { url ->
AssistChip(
onClick = {},
label = { Text(url.displayUrl(), style = MaterialTheme.typography.labelSmall) },
)
}
}
}
// Expanded: scrollable checkboxes
AnimatedVisibility(expanded) {
val sortedRelays =
remember(pickerState.allRelays) {
pickerState.allRelays.sortedBy { it.url }
}
LazyColumn(
modifier = Modifier.padding(start = 28.dp).heightIn(max = 200.dp),
) {
items(sortedRelays, key = { it.url }) { url ->
val connected = url in pickerState.connectedRelays
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = url in selectedRelays,
onCheckedChange = { onToggleRelay(url) },
enabled = connected,
)
Text(
url.displayUrl(),
color =
if (connected) {
LocalContentColor.current
} else {
MaterialTheme.colorScheme.outline
},
)
if (!connected) {
Text(
" (disconnected)",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.outline,
)
}
}
}
}
}
}
}
@@ -48,6 +48,7 @@ import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material.icons.filled.Groups
@@ -114,6 +115,7 @@ enum class ScreenCategory(
DISCOVERY("Discovery", Icons.Default.Explore),
IDENTITY("Identity", Icons.Default.Person),
PLAY("Play", Icons.Default.SportsEsports),
NETWORK("Network", Icons.Default.Dns),
}
// -- Extensions on DeckColumnType --
@@ -143,6 +145,8 @@ fun DeckColumnType.category(): ScreenCategory =
DeckColumnType.Chess -> ScreenCategory.PLAY
DeckColumnType.Relays -> ScreenCategory.NETWORK
// Deep-link types — not in LAUNCHABLE_SCREENS but need a category for exhaustiveness
is DeckColumnType.Profile,
is DeckColumnType.Thread,
@@ -181,6 +185,7 @@ val LAUNCHABLE_SCREENS: List<DeckColumnType> =
DeckColumnType.Bookmarks,
DeckColumnType.MyProfile,
DeckColumnType.Settings,
DeckColumnType.Relays,
DeckColumnType.Chess,
)
@@ -33,6 +33,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Article
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Extension
import androidx.compose.material.icons.filled.Home
@@ -132,6 +133,7 @@ fun DeckColumnType.icon(): ImageVector =
DeckColumnType.MyProfile -> Icons.Default.Person
DeckColumnType.Chess -> Icons.Default.Extension
DeckColumnType.Settings -> Icons.Default.Settings
DeckColumnType.Relays -> Icons.Default.Dns
is DeckColumnType.Article -> Icons.AutoMirrored.Filled.Article
is DeckColumnType.Editor -> Icons.AutoMirrored.Filled.Article
DeckColumnType.Drafts -> Icons.AutoMirrored.Filled.Article
@@ -44,6 +44,7 @@ import com.vitorpamplona.amethyst.desktop.cache.DesktopLocalCache
import com.vitorpamplona.amethyst.desktop.chess.ChessScreen
import com.vitorpamplona.amethyst.desktop.model.DesktopIAccount
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.amethyst.desktop.service.drafts.DesktopDraftStore
import com.vitorpamplona.amethyst.desktop.service.highlights.DesktopHighlightStore
import com.vitorpamplona.amethyst.desktop.subscriptions.DesktopRelaySubscriptionsCoordinator
@@ -60,6 +61,7 @@ import com.vitorpamplona.amethyst.desktop.ui.ThreadScreen
import com.vitorpamplona.amethyst.desktop.ui.UserProfileScreen
import com.vitorpamplona.amethyst.desktop.ui.ZapFeedback
import com.vitorpamplona.amethyst.desktop.ui.chats.DesktopMessagesScreen
import com.vitorpamplona.amethyst.desktop.ui.relay.RelayDashboardScreen
import com.vitorpamplona.quartz.nip47WalletConnect.Nip47WalletConnect.Nip47URINorm
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
@@ -99,10 +101,12 @@ fun DeckColumnContainer(
subscriptionsCoordinator: DesktopRelaySubscriptionsCoordinator,
highlightStore: DesktopHighlightStore,
draftStore: DesktopDraftStore,
nip11Fetcher: Nip11Fetcher,
appScope: CoroutineScope,
onShowComposeDialog: () -> Unit,
onShowReplyDialog: (com.vitorpamplona.quartz.nip01Core.core.Event) -> Unit,
onZapFeedback: (ZapFeedback) -> Unit,
onNavigateToRelays: () -> Unit = {},
modifier: Modifier = Modifier,
) {
val navState = remember(column.id) { ColumnNavigationState() }
@@ -141,6 +145,7 @@ fun DeckColumnContainer(
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
nip11Fetcher = nip11Fetcher,
appScope = appScope,
compactMode = true,
onShowComposeDialog = onShowComposeDialog,
@@ -150,6 +155,7 @@ fun DeckColumnContainer(
onNavigateToThread = { navState.push(DesktopScreen.Thread(it)) },
onNavigateToArticle = { navState.push(DesktopScreen.Article(it)) },
onNavigateToEditor = { navState.push(DesktopScreen.Editor(it)) },
onNavigateToRelays = onNavigateToRelays,
)
if (currentOverlay != null) {
Surface(
@@ -191,6 +197,7 @@ internal fun RootContent(
subscriptionsCoordinator: DesktopRelaySubscriptionsCoordinator,
highlightStore: DesktopHighlightStore? = null,
draftStore: DesktopDraftStore? = null,
nip11Fetcher: Nip11Fetcher,
appScope: CoroutineScope,
compactMode: Boolean = false,
onShowComposeDialog: () -> Unit,
@@ -200,6 +207,7 @@ internal fun RootContent(
onNavigateToThread: (String) -> Unit,
onNavigateToArticle: (String) -> Unit = {},
onNavigateToEditor: (String?) -> Unit = {},
onNavigateToRelays: () -> Unit = {},
) {
val scope = rememberCoroutineScope()
@@ -216,6 +224,7 @@ internal fun RootContent(
onNavigateToProfile = onNavigateToProfile,
onNavigateToThread = onNavigateToThread,
onZapFeedback = onZapFeedback,
onNavigateToRelays = onNavigateToRelays,
)
}
@@ -282,6 +291,7 @@ internal fun RootContent(
onNavigateToProfile = onNavigateToProfile,
onNavigateToThread = onNavigateToThread,
onZapFeedback = onZapFeedback,
onNavigateToRelays = onNavigateToRelays,
)
}
@@ -323,6 +333,25 @@ internal fun RootContent(
)
}
DeckColumnType.Relays -> {
val accountRelays =
remember(iAccount, relayManager, scope) {
com.vitorpamplona.amethyst.desktop.model.DesktopAccountRelays(
iAccount.pubKey,
relayManager,
scope,
)
}
RelayDashboardScreen(
relayManager = relayManager,
nip11Fetcher = nip11Fetcher,
nip65State = iAccount.nip65RelayList,
accountRelays = accountRelays,
signer = iAccount.signer,
onPublish = { event -> relayManager.broadcastToAll(event) },
)
}
is DeckColumnType.Profile -> {
UserProfileScreen(
pubKeyHex = columnType.pubKeyHex,
@@ -43,6 +43,8 @@ sealed class DeckColumnType {
object Settings : DeckColumnType()
object Relays : DeckColumnType()
data class Profile(
val pubKeyHex: String,
) : DeckColumnType()
@@ -79,6 +81,7 @@ sealed class DeckColumnType {
MyProfile -> "Profile"
Chess -> "Chess"
Settings -> "Settings"
Relays -> "Relays"
is Article -> "Article"
is Editor -> "New Article"
Drafts -> "Drafts"
@@ -100,6 +103,7 @@ sealed class DeckColumnType {
MyProfile -> "my_profile"
Chess -> "chess"
Settings -> "settings"
Relays -> "relays"
is Article -> "article"
is Editor -> "editor"
Drafts -> "drafts"
@@ -45,6 +45,7 @@ import com.vitorpamplona.amethyst.desktop.account.AccountManager
import com.vitorpamplona.amethyst.desktop.account.AccountState
import com.vitorpamplona.amethyst.desktop.cache.DesktopLocalCache
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.amethyst.desktop.service.highlights.DesktopHighlightStore
import com.vitorpamplona.amethyst.desktop.subscriptions.DesktopRelaySubscriptionsCoordinator
import com.vitorpamplona.amethyst.desktop.ui.ZapFeedback
@@ -64,10 +65,12 @@ fun DeckLayout(
subscriptionsCoordinator: DesktopRelaySubscriptionsCoordinator,
highlightStore: DesktopHighlightStore,
draftStore: com.vitorpamplona.amethyst.desktop.service.drafts.DesktopDraftStore,
nip11Fetcher: Nip11Fetcher,
appScope: CoroutineScope,
onShowComposeDialog: () -> Unit,
onShowReplyDialog: (com.vitorpamplona.quartz.nip01Core.core.Event) -> Unit,
onZapFeedback: (ZapFeedback) -> Unit,
onNavigateToRelays: () -> Unit = {},
modifier: Modifier = Modifier,
) {
val columns by deckState.columns.collectAsState()
@@ -118,10 +121,12 @@ fun DeckLayout(
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
nip11Fetcher = nip11Fetcher,
appScope = appScope,
onShowComposeDialog = onShowComposeDialog,
onShowReplyDialog = onShowReplyDialog,
onZapFeedback = onZapFeedback,
onNavigateToRelays = onNavigateToRelays,
)
}
}
@@ -298,6 +298,7 @@ class DeckState(
"my_profile" -> DeckColumnType.MyProfile
"chess" -> DeckColumnType.Chess
"settings" -> DeckColumnType.Settings
"relays" -> DeckColumnType.Relays
"drafts" -> DeckColumnType.Drafts
"highlights" -> DeckColumnType.MyHighlights
"editor" -> DeckColumnType.Editor(param)
@@ -102,6 +102,7 @@ class PinnedNavBarState(
DeckColumnType.Notifications,
DeckColumnType.MyProfile,
DeckColumnType.Chess,
DeckColumnType.Relays,
DeckColumnType.Settings,
)
@@ -52,6 +52,7 @@ import com.vitorpamplona.amethyst.desktop.account.AccountManager
import com.vitorpamplona.amethyst.desktop.account.AccountState
import com.vitorpamplona.amethyst.desktop.cache.DesktopLocalCache
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.amethyst.desktop.service.highlights.DesktopHighlightStore
import com.vitorpamplona.amethyst.desktop.subscriptions.DesktopRelaySubscriptionsCoordinator
import com.vitorpamplona.amethyst.desktop.ui.ZapFeedback
@@ -73,6 +74,7 @@ fun SinglePaneLayout(
subscriptionsCoordinator: DesktopRelaySubscriptionsCoordinator,
highlightStore: DesktopHighlightStore,
draftStore: com.vitorpamplona.amethyst.desktop.service.drafts.DesktopDraftStore,
nip11Fetcher: Nip11Fetcher,
appScope: CoroutineScope,
singlePaneState: SinglePaneState,
pinnedNavBarState: PinnedNavBarState,
@@ -190,6 +192,7 @@ fun SinglePaneLayout(
subscriptionsCoordinator = subscriptionsCoordinator,
highlightStore = highlightStore,
draftStore = draftStore,
nip11Fetcher = nip11Fetcher,
appScope = appScope,
onShowComposeDialog = onShowComposeDialog,
onShowReplyDialog = onShowReplyDialog,
@@ -198,6 +201,7 @@ fun SinglePaneLayout(
onNavigateToThread = { navState.push(DesktopScreen.Thread(it)) },
onNavigateToArticle = { navState.push(DesktopScreen.Article(it)) },
onNavigateToEditor = { navState.push(DesktopScreen.Editor(it)) },
onNavigateToRelays = { singlePaneState.navigate(DeckColumnType.Relays) },
)
if (currentOverlay != null) {
Surface(
@@ -0,0 +1,206 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun BlockedRelayEditor(
localRelays: SnapshotStateList<NormalizedRelayUrl>,
signer: NostrSigner,
onPublish: (Event) -> Unit,
modifier: Modifier = Modifier,
) {
val scope = rememberCoroutineScope()
var newRelayUrl by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var savedMessage by remember { mutableStateOf<String?>(null) }
Column(modifier = modifier.fillMaxWidth()) {
Text(
"Relays you want to avoid connecting to.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 4.dp),
)
Text(
"Existing blocked relay list is not loaded yet — saving will publish a new list.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error.copy(alpha = 0.7f),
modifier = Modifier.padding(bottom = 8.dp),
)
// Add relay input
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = newRelayUrl,
onValueChange = {
newRelayUrl = it
error = null
},
label = { Text("wss://relay.example.com") },
singleLine = true,
isError = error != null,
supportingText = error?.let { { Text(it) } },
modifier =
Modifier
.weight(1f)
.onPreviewKeyEvent { event ->
if (event.key == Key.Enter && event.type == KeyEventType.KeyDown) {
error = tryAddSimpleRelay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
true
} else {
false
}
},
)
Spacer(Modifier.width(8.dp))
IconButton(
onClick = {
error = tryAddSimpleRelay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
},
) {
Icon(Icons.Default.Add, contentDescription = "Add relay")
}
}
// Relay list
if (localRelays.isNotEmpty()) {
Text(
"${localRelays.size} relay(s) configured",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 4.dp),
)
}
localRelays.toList().forEach { url ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
url.displayUrl(),
style = MaterialTheme.typography.bodyMedium,
)
IconButton(onClick = { localRelays.remove(url) }, modifier = Modifier.size(28.dp)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove",
modifier = Modifier.size(16.dp),
)
}
}
}
Spacer(Modifier.height(8.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Button(
onClick = {
// Auto-add pending input
if (newRelayUrl.isNotBlank()) {
val addError = tryAddSimpleRelay(newRelayUrl, localRelays)
if (addError != null) {
error = addError
return@Button
}
newRelayUrl = ""
}
if (localRelays.isEmpty()) {
error = "Add at least one relay before saving"
return@Button
}
scope.launch {
try {
val event = BlockedRelayListEvent.create(localRelays.toList(), signer)
onPublish(event)
savedMessage = "Published ${localRelays.size} relay(s)"
} catch (e: Exception) {
savedMessage = "Failed: ${e.message}"
}
delay(3000)
savedMessage = null
}
},
) {
Text("Save")
}
savedMessage?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
}
@@ -0,0 +1,210 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
@Composable
fun DmRelayEditor(
dmRelays: StateFlow<Set<NormalizedRelayUrl>>,
signer: NostrSigner,
onPublish: (Event) -> Unit,
onDmRelaysUpdated: (Set<NormalizedRelayUrl>) -> Unit,
modifier: Modifier = Modifier,
) {
val scope = rememberCoroutineScope()
val currentDmRelays by dmRelays.collectAsState()
val localRelays = remember { mutableStateListOf<NormalizedRelayUrl>() }
var newRelayUrl by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var savedMessage by remember { mutableStateOf<String?>(null) }
// Sync local state when upstream changes
LaunchedEffect(currentDmRelays) {
localRelays.clear()
localRelays.addAll(currentDmRelays.sortedBy { it.url })
}
Column(modifier = modifier.fillMaxWidth()) {
Text(
"These relays receive your encrypted direct messages.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 8.dp),
)
if (localRelays.isEmpty()) {
Text(
"No DM relays configured — DMs use all connected relays as fallback.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(bottom = 8.dp),
)
}
// Add relay input
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = newRelayUrl,
onValueChange = {
newRelayUrl = it
error = null
},
label = { Text("wss://relay.example.com") },
singleLine = true,
isError = error != null,
supportingText = error?.let { { Text(it) } },
modifier =
Modifier
.weight(1f)
.onPreviewKeyEvent { event ->
if (event.key == Key.Enter && event.type == KeyEventType.KeyDown) {
error = tryAddSimpleRelay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
true
} else {
false
}
},
)
Spacer(Modifier.width(8.dp))
IconButton(
onClick = {
error = tryAddSimpleRelay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
},
) {
Icon(Icons.Default.Add, contentDescription = "Add relay")
}
}
// Relay list
localRelays.toList().forEach { url ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
url.displayUrl(),
style = MaterialTheme.typography.bodyMedium,
)
IconButton(onClick = { localRelays.remove(url) }, modifier = Modifier.size(28.dp)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove",
modifier = Modifier.size(16.dp),
)
}
}
}
Spacer(Modifier.height(8.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Button(
onClick = {
// Auto-add pending input
if (newRelayUrl.isNotBlank()) {
val addError = tryAddSimpleRelay(newRelayUrl, localRelays)
if (addError != null) {
error = addError
return@Button
}
newRelayUrl = ""
}
scope.launch {
try {
val event = ChatMessageRelayListEvent.create(localRelays.toList(), signer)
onPublish(event)
onDmRelaysUpdated(localRelays.toSet())
savedMessage = "Published ${localRelays.size} relay(s)"
} catch (e: Exception) {
savedMessage = "Failed: ${e.message}"
}
delay(3000)
savedMessage = null
}
},
) {
Text("Save")
}
savedMessage?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.runtime.staticCompositionLocalOf
import com.vitorpamplona.amethyst.desktop.model.DesktopRelayCategories
val LocalRelayCategories =
staticCompositionLocalOf<DesktopRelayCategories> {
error("No DesktopRelayCategories provided")
}
@@ -0,0 +1,283 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.commons.model.nip65RelayList.Nip65RelayListState
import com.vitorpamplona.amethyst.desktop.network.DefaultRelays
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
import com.vitorpamplona.quartz.nip65RelayList.tags.AdvertisedRelayInfo
import com.vitorpamplona.quartz.nip65RelayList.tags.AdvertisedRelayType
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun Nip65RelayEditor(
nip65State: Nip65RelayListState,
signer: NostrSigner,
onPublish: (Event) -> Unit,
modifier: Modifier = Modifier,
) {
val scope = rememberCoroutineScope()
val localRelays = remember { mutableStateListOf<AdvertisedRelayInfo>() }
var loaded by remember { mutableStateOf(false) }
var newRelayUrl by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var savedMessage by remember { mutableStateOf<String?>(null) }
// React to NIP-65 flow changes (external updates)
val nip65NoteState by nip65State.getNIP65RelayListFlow().collectAsState()
val currentNip65Relays =
remember(nip65NoteState) {
nip65State.getNIP65RelayList()?.relays() ?: emptyList()
}
LaunchedEffect(currentNip65Relays) {
localRelays.clear()
localRelays.addAll(currentNip65Relays)
loaded = true
}
Column(modifier = modifier.fillMaxWidth()) {
if (loaded && localRelays.isEmpty()) {
Text(
"No NIP-65 relay list published yet.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 8.dp),
)
OutlinedButton(
onClick = {
localRelays.clear()
DefaultRelays.RELAYS.forEach { url ->
RelayUrlNormalizer.normalizeOrNull(url)?.let { normalized ->
localRelays.add(AdvertisedRelayInfo(normalized, AdvertisedRelayType.BOTH))
}
}
},
) {
Text("Populate from defaults")
}
Spacer(Modifier.height(8.dp))
}
// Add relay input
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = newRelayUrl,
onValueChange = {
newRelayUrl = it
error = null
},
label = { Text("wss://relay.example.com") },
singleLine = true,
isError = error != null,
supportingText = error?.let { { Text(it) } },
modifier =
Modifier
.weight(1f)
.onPreviewKeyEvent { event ->
if (event.key == Key.Enter && event.type == KeyEventType.KeyDown) {
error = tryAddNip65Relay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
true
} else {
false
}
},
)
Spacer(Modifier.width(8.dp))
IconButton(
onClick = {
error = tryAddNip65Relay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
},
) {
Icon(Icons.Default.Add, contentDescription = "Add relay")
}
}
// Relay list
localRelays.toList().forEachIndexed { index, relay ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
relay.relayUrl.displayUrl(),
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
FilterChip(
selected = relay.type == AdvertisedRelayType.READ,
onClick = {
localRelays[index] = AdvertisedRelayInfo(relay.relayUrl, AdvertisedRelayType.READ)
},
label = { Text("Read", style = MaterialTheme.typography.labelSmall) },
)
FilterChip(
selected = relay.type == AdvertisedRelayType.WRITE,
onClick = {
localRelays[index] = AdvertisedRelayInfo(relay.relayUrl, AdvertisedRelayType.WRITE)
},
label = { Text("Write", style = MaterialTheme.typography.labelSmall) },
)
FilterChip(
selected = relay.type == AdvertisedRelayType.BOTH,
onClick = {
localRelays[index] = AdvertisedRelayInfo(relay.relayUrl, AdvertisedRelayType.BOTH)
},
label = { Text("Both", style = MaterialTheme.typography.labelSmall) },
)
}
IconButton(onClick = { localRelays.remove(relay) }, modifier = Modifier.size(28.dp)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove",
modifier = Modifier.size(16.dp),
)
}
}
}
Spacer(Modifier.height(8.dp))
// Action buttons
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Button(
onClick = {
// Auto-add pending input
if (newRelayUrl.isNotBlank()) {
val addError = tryAddNip65Relay(newRelayUrl, localRelays)
if (addError != null) {
error = addError
return@Button
}
newRelayUrl = ""
}
if (localRelays.isEmpty()) {
error = "Add at least one relay before saving"
return@Button
}
scope.launch {
try {
val event = nip65State.saveRelayList(localRelays.toList())
onPublish(event)
savedMessage = "Published ${localRelays.size} relay(s)"
} catch (e: Exception) {
savedMessage = "Failed: ${e.message}"
}
delay(3000)
savedMessage = null
}
},
) {
Text("Save")
}
OutlinedButton(
onClick = {
localRelays.clear()
DefaultRelays.RELAYS.forEach { url ->
RelayUrlNormalizer.normalizeOrNull(url)?.let { normalized ->
localRelays.add(AdvertisedRelayInfo(normalized, AdvertisedRelayType.BOTH))
}
}
},
) {
Text("Reset to defaults")
}
savedMessage?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
}
private fun tryAddNip65Relay(
url: String,
existing: MutableList<AdvertisedRelayInfo>,
): String? {
val error = validateRelayUrl(url)
if (error != null) return error
val normalized = RelayUrlNormalizer.normalizeOrNull(url.trim())!!
if (existing.any { it.relayUrl.url == normalized.url }) {
return "Relay already added"
}
existing.add(AdvertisedRelayInfo(normalized, AdvertisedRelayType.BOTH))
return null
}
@@ -0,0 +1,188 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.commons.model.nip65RelayList.Nip65RelayListState
import com.vitorpamplona.amethyst.desktop.model.DesktopAccountRelays
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
@Composable
fun RelayConfigTab(
relayManager: DesktopRelayConnectionManager,
nip65State: Nip65RelayListState,
accountRelays: DesktopAccountRelays,
signer: NostrSigner,
onPublish: (Event) -> Unit,
searchRelayState: SnapshotStateList<NormalizedRelayUrl>,
blockedRelayState: SnapshotStateList<NormalizedRelayUrl>,
modifier: Modifier = Modifier,
) {
val statuses by relayManager.relayStatuses.collectAsState()
val connectedRelays by relayManager.connectedRelays.collectAsState()
Column(
modifier =
modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(top = 8.dp),
) {
// 1. Connected Relays (collapsed by default to show other sections)
CollapsibleSection(
title = "Connected Relays",
description = "Relays your client connects to — ${connectedRelays.size} of ${statuses.size} connected",
initiallyExpanded = false,
) {
RelayListEditor(
relays = statuses.keys.sortedBy { it.url },
connectedRelays = connectedRelays,
onAdd = { url -> relayManager.addRelay(url) },
onRemove = { url -> relayManager.removeRelay(url) },
)
}
Spacer(Modifier.height(16.dp))
// 2. NIP-65 Inbox/Outbox
CollapsibleSection(
title = "NIP-65 Inbox/Outbox",
description = "Relay list metadata (kind 10002) — tells other clients where to find your notes",
) {
Nip65RelayEditor(
nip65State = nip65State,
signer = signer,
onPublish = onPublish,
)
}
Spacer(Modifier.height(16.dp))
// 3. DM Relays
CollapsibleSection(
title = "DM Relays",
description = "Kind 10050 — where others send you encrypted messages",
) {
DmRelayEditor(
dmRelays = accountRelays.dmRelayList,
signer = signer,
onPublish = onPublish,
onDmRelaysUpdated = { accountRelays.setDmRelays(it) },
)
}
Spacer(Modifier.height(16.dp))
// 4. Search Relays
CollapsibleSection(
title = "Search Relays",
description = "Kind 10007 — relays used for NIP-50 full-text search",
) {
SearchRelayEditor(
localRelays = searchRelayState,
signer = signer,
onPublish = onPublish,
)
}
Spacer(Modifier.height(16.dp))
// 5. Blocked Relays
CollapsibleSection(
title = "Blocked Relays",
description = "Kind 10006 — relays you want to avoid",
) {
BlockedRelayEditor(
localRelays = blockedRelayState,
signer = signer,
onPublish = onPublish,
)
}
}
}
@Composable
private fun CollapsibleSection(
title: String,
description: String,
initiallyExpanded: Boolean = true,
content: @Composable () -> Unit,
) {
var expanded by remember { mutableStateOf(initiallyExpanded) }
Row(
modifier =
Modifier
.fillMaxWidth()
.clickable { expanded = !expanded }
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
if (expanded) Icons.Default.ExpandMore else Icons.Default.ChevronRight,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
Column(modifier = Modifier.padding(start = 8.dp)) {
Text(title, style = MaterialTheme.typography.titleSmall)
Text(
description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
AnimatedVisibility(expanded) {
Column(modifier = Modifier.padding(start = 8.dp, top = 8.dp)) {
content()
}
}
}
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import com.vitorpamplona.amethyst.commons.model.nip65RelayList.Nip65RelayListState
import com.vitorpamplona.amethyst.desktop.model.DesktopAccountRelays
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
enum class DashboardTab(
val label: String,
) {
MONITOR("Monitor"),
CONFIGURE("Configure"),
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RelayDashboardScreen(
relayManager: DesktopRelayConnectionManager,
nip11Fetcher: Nip11Fetcher,
nip65State: Nip65RelayListState,
accountRelays: DesktopAccountRelays,
signer: NostrSigner,
onPublish: (Event) -> Unit,
modifier: Modifier = Modifier,
) {
var selectedTab by remember { mutableStateOf(DashboardTab.MONITOR) }
// Hoisted state — survives Monitor ↔ Configure tab switches
val searchRelayState = remember { mutableStateListOf<NormalizedRelayUrl>() }
val blockedRelayState = remember { mutableStateListOf<NormalizedRelayUrl>() }
Column(modifier = modifier.fillMaxSize()) {
PrimaryTabRow(selectedTabIndex = DashboardTab.entries.indexOf(selectedTab)) {
DashboardTab.entries.forEach { tab ->
Tab(
selected = selectedTab == tab,
onClick = { selectedTab = tab },
text = { Text(tab.label) },
)
}
}
when (selectedTab) {
DashboardTab.MONITOR -> {
RelayMetricsTab(relayManager, nip11Fetcher)
}
DashboardTab.CONFIGURE -> {
RelayConfigTab(
relayManager = relayManager,
nip65State = nip65State,
accountRelays = accountRelays,
signer = signer,
onPublish = onPublish,
searchRelayState = searchRelayState,
blockedRelayState = blockedRelayState,
)
}
}
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.vitorpamplona.quartz.nip11RelayInfo.Nip11RelayInformation
@Composable
fun RelayDetailPanel(
nip11: Nip11RelayInformation?,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier.fillMaxWidth().padding(12.dp),
) {
HorizontalDivider(modifier = Modifier.padding(bottom = 8.dp))
if (nip11 == null) {
Text(
"Relay info unavailable",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
return@Column
}
// Description
nip11.description?.let { desc ->
Text(desc, style = MaterialTheme.typography.bodySmall)
Spacer(Modifier.height(8.dp))
}
// Software + version
nip11.software?.let { sw ->
val version = nip11.version?.let { " v$it" } ?: ""
DetailRow("Software", "$sw$version")
}
// Supported NIPs
nip11.supported_nips?.let { nips ->
if (nips.isNotEmpty()) {
DetailRow("NIPs", nips.joinToString(", "))
}
}
// Payment status
val paymentRequired = nip11.limitation?.payment_required == true
DetailRow("Payment", if (paymentRequired) "Paid" else "Free")
}
}
@Composable
private fun DetailRow(
label: String,
value: String,
) {
Text(
"$label: $value",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 2.dp),
)
}
@@ -0,0 +1,170 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.isOnion
@Composable
fun RelayListEditor(
relays: List<NormalizedRelayUrl>,
connectedRelays: Set<NormalizedRelayUrl>,
onAdd: (String) -> NormalizedRelayUrl?,
onRemove: (NormalizedRelayUrl) -> Unit,
modifier: Modifier = Modifier,
) {
var newRelayUrl by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
Column(modifier = modifier.fillMaxWidth()) {
// Add relay input
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = newRelayUrl,
onValueChange = {
newRelayUrl = it
error = null
},
label = { Text("wss://relay.example.com") },
singleLine = true,
isError = error != null,
supportingText = error?.let { { Text(it) } },
modifier =
Modifier
.weight(1f)
.onPreviewKeyEvent { event ->
if (event.key == Key.Enter && event.type == KeyEventType.KeyDown) {
error = tryAddRelay(newRelayUrl, relays, onAdd)
if (error == null) newRelayUrl = ""
true
} else {
false
}
},
)
Spacer(Modifier.width(8.dp))
IconButton(
onClick = {
error = tryAddRelay(newRelayUrl, relays, onAdd)
if (error == null) newRelayUrl = ""
},
) {
Icon(Icons.Default.Add, contentDescription = "Add relay")
}
}
// Relay list
relays.forEach { url ->
val isConnected = url in connectedRelays
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Default.Circle,
contentDescription = null,
modifier = Modifier.size(8.dp),
tint =
if (isConnected) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.outline
},
)
Spacer(Modifier.width(8.dp))
Text(
url.displayUrl(),
style = MaterialTheme.typography.bodyMedium,
)
if (url.isOnion()) {
Spacer(Modifier.width(4.dp))
Text(
".onion",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
}
IconButton(onClick = { onRemove(url) }, modifier = Modifier.size(28.dp)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove",
modifier = Modifier.size(16.dp),
)
}
}
}
}
}
private fun tryAddRelay(
url: String,
existing: List<NormalizedRelayUrl>,
onAdd: (String) -> NormalizedRelayUrl?,
): String? {
val error = validateRelayUrl(url)
if (error != null) return error
val normalized = RelayUrlNormalizer.normalizeOrNull(url.trim()) ?: return "Invalid relay URL"
if (existing.any { it.url == normalized.url }) {
return "Relay already added"
}
onAdd(url.trim())
return null
}
@@ -0,0 +1,176 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Circle
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.produceState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.amethyst.desktop.network.RelayMetrics
import com.vitorpamplona.amethyst.desktop.network.RelayStatus
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.isOnion
import com.vitorpamplona.quartz.nip11RelayInfo.Nip11RelayInformation
@Composable
fun RelayMetricCard(
status: RelayStatus,
metrics: RelayMetrics?,
isExpanded: Boolean,
onToggleExpand: () -> Unit,
nip11Fetcher: Nip11Fetcher,
modifier: Modifier = Modifier,
) {
// NIP-11 fetched per-card to avoid parent recomposition
val nip11 by produceState<Nip11RelayInformation?>(null, status.url) {
value = nip11Fetcher.fetch(status.url)
}
Card(modifier = modifier.fillMaxWidth()) {
Column(
modifier = Modifier.clickable { onToggleExpand() }.padding(12.dp),
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Row(verticalAlignment = Alignment.CenterVertically) {
// Status indicator
Icon(
Icons.Default.Circle,
contentDescription = if (status.connected) "Connected" else "Disconnected",
modifier = Modifier.size(10.dp),
tint =
if (status.connected) {
MaterialTheme.colorScheme.primary
} else if (status.error != null) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.outline
},
)
Spacer(Modifier.width(8.dp))
Column {
Text(
nip11?.name ?: status.url.displayUrl(),
style = MaterialTheme.typography.bodyMedium,
)
if (nip11?.name != null) {
Text(
status.url.displayUrl(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
// Ping + Tor badge
if (status.pingMs != null) {
Text(
"${status.pingMs}ms",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (status.url.isOnion()) {
Text(
".onion",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
// Event count
if (metrics != null && metrics.eventCount > 0) {
Text(
"${metrics.eventCount} events",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
// Last event relative time
if (metrics?.lastEventAt != null) {
val ago = formatRelativeTime(metrics.lastEventAt)
Text(
ago,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
// Error message
if (status.error != null) {
Text(
status.error,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
modifier = Modifier.padding(top = 4.dp),
)
}
}
AnimatedVisibility(isExpanded) {
RelayDetailPanel(nip11)
}
}
}
fun formatRelativeTime(epochMs: Long): String {
val diffMs = System.currentTimeMillis() - epochMs
val seconds = diffMs / 1000
return when {
seconds < 5 -> "just now"
seconds < 60 -> "${seconds}s ago"
seconds < 3600 -> "${seconds / 60}m ago"
seconds < 86400 -> "${seconds / 3600}h ago"
else -> "${seconds / 86400}d ago"
}
}
@@ -0,0 +1,110 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.vitorpamplona.amethyst.desktop.network.DesktopRelayConnectionManager
import com.vitorpamplona.amethyst.desktop.network.Nip11Fetcher
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@Composable
fun RelayMetricsTab(
relayManager: DesktopRelayConnectionManager,
nip11Fetcher: Nip11Fetcher,
modifier: Modifier = Modifier,
) {
val statuses by remember(relayManager) {
relayManager.relayStatuses
.map { it.values.toList().sortedBy { s -> s.url.url } }
.distinctUntilChanged()
}.collectAsState(emptyList())
val metrics by relayManager.relayMetrics.collectAsState()
val connectedCount = statuses.count { it.connected }
var expandedUrl by remember { mutableStateOf<NormalizedRelayUrl?>(null) }
Column(modifier = modifier.fillMaxSize().padding(top = 8.dp)) {
// Summary header
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"$connectedCount of ${statuses.size} connected",
style = MaterialTheme.typography.titleSmall,
)
IconButton(onClick = {
relayManager.disconnect()
relayManager.connect()
}) {
Icon(Icons.Default.Refresh, contentDescription = "Reconnect all")
}
}
Spacer(Modifier.height(4.dp))
LazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
items(statuses, key = { it.url.url }) { status ->
RelayMetricCard(
status = status,
metrics = metrics[status.url],
isExpanded = expandedUrl == status.url,
onToggleExpand = {
expandedUrl = if (expandedUrl == status.url) null else status.url
},
nip11Fetcher = nip11Fetcher,
)
}
}
}
}
@@ -0,0 +1,67 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer
/**
* Validates and adds a relay URL to a mutable list.
* Returns an error message string if validation fails, null on success.
*/
internal fun validateRelayUrl(url: String): String? {
val trimmed = url.trim()
if (trimmed.isBlank()) return "Enter a relay URL"
if (!trimmed.startsWith("wss://") && !trimmed.startsWith("ws://")) {
return "URL must start with wss:// or ws://"
}
if (trimmed.startsWith("ws://") && !trimmed.contains(".onion")) {
return "Use wss:// — unencrypted ws:// exposes traffic to observers"
}
// Must have a domain with at least one dot (foo is not a valid relay)
val host =
trimmed
.removePrefix("wss://")
.removePrefix("ws://")
.split("/")
.first()
if (!host.contains(".")) {
return "Invalid domain — must contain at least one dot (e.g., relay.example.com)"
}
if (RelayUrlNormalizer.normalizeOrNull(trimmed) == null) {
return "Invalid relay URL"
}
return null
}
internal fun tryAddSimpleRelay(
url: String,
existing: MutableList<NormalizedRelayUrl>,
): String? {
val error = validateRelayUrl(url)
if (error != null) return error
val normalized = RelayUrlNormalizer.normalizeOrNull(url.trim())!!
if (existing.any { it.url == normalized.url }) {
return "Relay already added"
}
existing.add(normalized)
return null
}
@@ -0,0 +1,206 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.desktop.ui.relay
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.dp
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl
import com.vitorpamplona.quartz.nip01Core.signers.NostrSigner
import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun SearchRelayEditor(
localRelays: SnapshotStateList<NormalizedRelayUrl>,
signer: NostrSigner,
onPublish: (Event) -> Unit,
modifier: Modifier = Modifier,
) {
val scope = rememberCoroutineScope()
var newRelayUrl by remember { mutableStateOf("") }
var error by remember { mutableStateOf<String?>(null) }
var savedMessage by remember { mutableStateOf<String?>(null) }
Column(modifier = modifier.fillMaxWidth()) {
Text(
"Add relays that support NIP-50 full-text search (e.g., relay.nostr.band).",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 4.dp),
)
Text(
"Existing search relay list is not loaded yet — saving will publish a new list.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.error.copy(alpha = 0.7f),
modifier = Modifier.padding(bottom = 8.dp),
)
// Add relay input
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
OutlinedTextField(
value = newRelayUrl,
onValueChange = {
newRelayUrl = it
error = null
},
label = { Text("wss://relay.example.com") },
singleLine = true,
isError = error != null,
supportingText = error?.let { { Text(it) } },
modifier =
Modifier
.weight(1f)
.onPreviewKeyEvent { event ->
if (event.key == Key.Enter && event.type == KeyEventType.KeyDown) {
error = tryAddSimpleRelay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
true
} else {
false
}
},
)
Spacer(Modifier.width(8.dp))
IconButton(
onClick = {
error = tryAddSimpleRelay(newRelayUrl, localRelays)
if (error == null) newRelayUrl = ""
},
) {
Icon(Icons.Default.Add, contentDescription = "Add relay")
}
}
// Relay list
if (localRelays.isNotEmpty()) {
Text(
"${localRelays.size} relay(s) configured",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(vertical = 4.dp),
)
}
localRelays.toList().forEach { url ->
Row(
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
url.displayUrl(),
style = MaterialTheme.typography.bodyMedium,
)
IconButton(onClick = { localRelays.remove(url) }, modifier = Modifier.size(28.dp)) {
Icon(
Icons.Default.Close,
contentDescription = "Remove",
modifier = Modifier.size(16.dp),
)
}
}
}
Spacer(Modifier.height(8.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Button(
onClick = {
// Auto-add pending input
if (newRelayUrl.isNotBlank()) {
val addError = tryAddSimpleRelay(newRelayUrl, localRelays)
if (addError != null) {
error = addError
return@Button
}
newRelayUrl = ""
}
if (localRelays.isEmpty()) {
error = "Add at least one relay before saving"
return@Button
}
scope.launch {
try {
val event = SearchRelayListEvent.create(localRelays.toList(), signer)
onPublish(event)
savedMessage = "Published ${localRelays.size} relay(s)"
} catch (e: Exception) {
savedMessage = "Failed: ${e.message}"
}
delay(3000)
savedMessage = null
}
},
) {
Text("Save")
}
savedMessage?.let {
Text(
it,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
}
@@ -0,0 +1,232 @@
---
title: "feat: Relay Config Parity — All Desktop-Relevant Categories"
type: feat
status: draft
date: 2026-04-21
parent: docs/plans/2026-04-20-feat-relay-power-tools-plan.md
---
# feat: Relay Config Parity — All Desktop-Relevant Categories
## Context
Phase 1-2 of Relay Power Tools shipped a dashboard with Monitor tab, a Configure tab with only Connected Relays (NIP-65/DM as placeholders), and a compose relay picker. This plan fills in all relay categories that desktop features actually consume.
## Scope: Feature-Driven Categories
Only categories where desktop has a feature that reads/writes them:
| Category | Kind | Desktop Feature | State Class | Priority |
|----------|------|----------------|-------------|----------|
| **NIP-65 Inbox/Outbox** | 10002 | Feeds, notifications, outbox publishing | `Nip65RelayListState` (commons) | P0 |
| **DM Relays** | 10050 | DMs (DesktopMessagesScreen) | `DesktopAccountRelays._dmRelayList` | P0 |
| **Search Relays** | 10007 | Search (SearchScreen, NIP-50) | — (new) | P1 |
| **Blocked Relays** | 10006 | Privacy/moderation | — (new) | P2 |
| **Connected Relays** | runtime | Everything (fallback pool) | `RelayConnectionManager` | ✅ Done |
### Explicitly Out of Scope
| Category | Kind | Why |
|----------|------|-----|
| Private Outbox | 10013 | Desktop drafts are local-only (`DesktopDraftStore`) |
| Indexer Relays | 10086 | Desktop uses connected relays for indexing |
| Proxy Relays | 10087 | No proxy relay feature on desktop |
| Broadcast Relays | 10088 | Compose picker already handles per-action relay selection |
| Trusted Relays | 10089 | No trust-scoring UI on desktop |
| Key Package | MIP-00 | No MLS/group messaging on desktop |
| Relay Sets | 30002 | No custom grouping UI |
| Wiki Relays | 10102 | No wiki feature |
| Relay Feeds | 10012 | No relay feeds feature |
| Local Relays | custom | No local relay feature |
## Technical Approach
### Architecture
```
Existing (Phase 1-2):
├── RelayConfigTab.kt # MODIFY: replace placeholders with real editors
├── RelayListEditor.kt # REUSE: generic add/remove/validate
├── DesktopAccountRelays.kt # MODIFY: add NIP-65 + search relay state
├── DesktopIAccount.kt # Already has Nip65RelayListState
New:
├── Nip65RelayEditor.kt # NEW: inbox/outbox editor with read/write toggles
├── DmRelayEditor.kt # NEW: DM relay editor with block-send-if-empty
├── SearchRelayEditor.kt # NEW: search relay editor
├── BlockedRelayEditor.kt # NEW: blocked relay editor
└── DesktopSearchRelayState.kt # NEW: search relay state (kind 10007)
```
### Phase 3a: NIP-65 Inbox/Outbox Editor (P0)
**Why P0:** Feeds, notifications, and publishing all depend on NIP-65. Without this, desktop uses hardcoded default relays.
**State:** `Nip65RelayListState` already exists in commons and is instantiated in `DesktopIAccount`. Desktop already has `outboxFlow` and `inboxFlow`.
**UI: `Nip65RelayEditor.kt`**
```kotlin
@Composable
fun Nip65RelayEditor(
nip65State: Nip65RelayListState,
relayManager: RelayConnectionManager,
onPublish: (AdvertisedRelayListEvent) -> Unit,
)
```
- Two-column or tagged list: each relay has Read/Write/Both toggle
- Uses `AdvertisedRelayInfo` with `type` (READ, WRITE, BOTH)
- "Save" button calls `nip65State.saveRelayList(relays)` → returns signed event → `onPublish` broadcasts
- Shows "Published to X of Y relays" confirmation
- "Reset to defaults" option restores `defaultOutboxRelays`/`defaultInboxRelays`
**Data flow:**
1. Read current: `nip65State.getNIP65RelayList()?.relays()` → list of `AdvertisedRelayInfo`
2. User edits in mutable local state
3. Save: `nip65State.saveRelayList(editedRelays)` → signed `AdvertisedRelayListEvent`
4. Broadcast: `relayManager.publish(event, connectedRelays)`
**Integration:**
- Replace "NIP-65 Inbox/Outbox — coming soon" placeholder in `RelayConfigTab`
- Thread `nip65State` from `DesktopIAccount` through to `RelayConfigTab`
### Phase 3b: DM Relay Editor (P0)
**Why P0:** Desktop has full DM support. DM relays control where encrypted messages are sent/received.
**State:** `DesktopAccountRelays._dmRelayList` already tracks kind 10050.
**UI: `DmRelayEditor.kt`**
```kotlin
@Composable
fun DmRelayEditor(
dmRelays: StateFlow<Set<NormalizedRelayUrl>>,
connectedRelays: StateFlow<Set<NormalizedRelayUrl>>,
signer: NostrSigner,
onPublish: (Event) -> Unit,
)
```
- Simple relay list (no read/write split — DM relays are all-or-nothing)
- Warning banner if empty: "No DM relays configured — DMs will use connected relays as fallback"
- "Save" builds `ChatMessageRelayListEvent` → sign → publish
- Security: highlight that these relays see your DM metadata
**Data flow:**
1. Read current: `accountRelays.dmRelayList` StateFlow
2. Save: build `ChatMessageRelayListEvent.create(relays, signer)` → publish
**Integration:**
- Replace "DM Relays — coming soon" placeholder in `RelayConfigTab`
- Thread `accountRelays` + `signer` through to `RelayConfigTab`
### Phase 3c: Search Relay Editor (P1)
**Why P1:** Desktop has a full search screen with NIP-50 support but currently searches all connected relays. Dedicated search relays improve result quality.
**State:** New `DesktopSearchRelayState` needed — simple `StateFlow<Set<NormalizedRelayUrl>>` backed by kind 10007 events.
**UI: `SearchRelayEditor.kt`**
- Same pattern as DM relay editor
- Explain to user: "These relays support NIP-50 full-text search"
- Default suggestion: `wss://relay.nostr.band` (common NIP-50 relay)
- "Save" builds `SearchRelayListEvent` → sign → publish
**Integration:**
- New section in `RelayConfigTab` after DM Relays
- Wire search relay state into `DesktopRelaySubscriptionsCoordinator` for search queries
### Phase 3d: Blocked Relay Editor (P2)
**Why P2:** Privacy feature — user can maintain a list of relays they don't want to connect to. Lower priority but simple to implement since pattern is identical.
**State:** New — kind 10006 `BlockedRelayListEvent`.
**UI: `BlockedRelayEditor.kt`**
- List of blocked relay URLs
- "Save" publishes kind 10006 event
- Integration: filter blocked relays from connection pool (future)
### Implementation Order
| Phase | What | Files | Depends On |
|-------|------|-------|------------|
| 3a | NIP-65 editor | `Nip65RelayEditor.kt`, modify `RelayConfigTab`, modify `DeckColumnContainer` (thread state) | `Nip65RelayListState` (exists) |
| 3b | DM relay editor | `DmRelayEditor.kt`, modify `RelayConfigTab` | `DesktopAccountRelays` (exists) |
| 3c | Search relay editor | `SearchRelayEditor.kt`, `DesktopSearchRelayState.kt`, modify `RelayConfigTab`, modify subscriptions coordinator | New state class |
| 3d | Blocked relay editor | `BlockedRelayEditor.kt`, modify `RelayConfigTab` | `BlockedRelayListEvent` (exists in quartz) |
### State Threading
`RelayConfigTab` currently receives only `relayManager`. It needs:
```kotlin
@Composable
fun RelayConfigTab(
relayManager: DesktopRelayConnectionManager,
nip65State: Nip65RelayListState, // Phase 3a
accountRelays: DesktopAccountRelays, // Phase 3b (DM relays)
signer: NostrSigner, // For signing relay list events
onPublish: (Event) -> Unit, // Broadcast signed events
modifier: Modifier = Modifier,
)
```
Thread through: `Main.kt``MainContent``DeckLayout`/`SinglePaneLayout``DeckColumnContainer``RootContent``RelayDashboardScreen``RelayConfigTab`
Alternative: pass `DesktopIAccount` (already threaded) which has `nip65State` + `signer`, and `accountRelays` (already created alongside).
### Shared `RelayListEditor` Pattern
All editors follow the same pattern — reuse `RelayListEditor` for the add/remove/validate part. Each editor wraps it with:
1. Category-specific header + description
2. Optional per-relay toggles (read/write for NIP-65)
3. Save button that builds the right event kind
4. Publish feedback
### Event Kind Reference (from quartz)
| Kind | Event Class | Tag Format |
|------|------------|------------|
| 10002 | `AdvertisedRelayListEvent` | `["r", "wss://...", "read"\|"write"]` |
| 10050 | `ChatMessageRelayListEvent` | `["relay", "wss://..."]` |
| 10007 | `SearchRelayListEvent` | `["relay", "wss://..."]` |
| 10006 | `BlockedRelayListEvent` | `["relay", "wss://..."]` |
## Acceptance Criteria
### Phase 3a: NIP-65
- [ ] NIP-65 section shows current inbox/outbox relays from user's kind 10002
- [ ] Each relay has Read/Write/Both toggle
- [ ] Can add/remove relays
- [ ] Save signs + publishes AdvertisedRelayListEvent
- [ ] Shows "Published to X of Y" confirmation
- [ ] Reset to defaults option
### Phase 3b: DM Relays
- [ ] DM section shows current kind 10050 relays
- [ ] Warning if empty
- [ ] Save signs + publishes ChatMessageRelayListEvent
- [ ] Shows publish confirmation
### Phase 3c: Search Relays
- [ ] Search section shows current kind 10007 relays
- [ ] Suggests relay.nostr.band if empty
- [ ] Save signs + publishes SearchRelayListEvent
- [ ] Search screen uses configured search relays
### Phase 3d: Blocked Relays
- [ ] Blocked section shows kind 10006 relays
- [ ] Save signs + publishes BlockedRelayListEvent
## Unanswered Questions
1. Should NIP-65 editor show relays from the user's existing event, or from `defaultOutboxRelays`/`defaultInboxRelays` if no event exists?
2. Should DM relay editor block fallback to connected relays (per original plan security decision) or just warn?
3. For search relays — should we auto-detect NIP-50 support via NIP-11 `supported_nips` field and suggest capable relays from the connected pool?
4. Should publishing relay list events use `connectedRelays` or the NIP-65 outbox relays? (Bootstrap problem if NIP-65 is empty.)
5. How to handle the threading of 4+ state objects through the composable tree — pass `DesktopIAccount` directly or keep explicit params?
@@ -0,0 +1,329 @@
---
title: "feat: Wire Relay Config Categories into Desktop Subscriptions"
type: feat
status: active
date: 2026-04-21
origin: docs/plans/2026-04-21-feat-relay-config-parity-plan.md
---
# feat: Wire Relay Config Categories into Desktop Subscriptions
## Overview
Desktop's relay config UI publishes relay list events (kinds 10002, 10050, 10007, 10006) but the app itself uses hardcoded defaults or all connected relays for every subscription. This plan wires each relay category into the features that consume it.
## Problem Statement
| Feature | Currently Uses | Should Use |
|---------|---------------|------------|
| Home feed | all connected relays | NIP-65 outbox (kind 10002 write) |
| Notifications | all connected relays | NIP-65 inbox (kind 10002 read) |
| Search | all connected relays | Search relays (kind 10007) |
| DMs | `emptySet()` fallback → connected | DM relays (kind 10050) |
| All features | no filtering | Minus blocked relays (kind 10006) |
**Root causes:**
1. `DesktopAccountRelays` is dead code — never instantiated in Main.kt
2. `DesktopDmRelayState` in Main.kt uses hardcoded `MutableStateFlow(emptySet())`
3. No desktop state holders for search or blocked relay lists
4. No bootstrap subscription fetches user's own relay config events at login
5. Screens pass `allRelayUrls` to all `rememberSubscription` calls
6. `DesktopRelaySubscriptionsCoordinator.indexRelays` is static
## Proposed Solution
4 phases, each independently shippable:
1. Bootstrap subscription + wire existing state objects
2. Create missing state holders + aggregate relay categories
3. Update screens to consume category relay sets
4. Persist relay lists to Preferences
## Technical Approach
### Architecture
```
New/Modified:
├── Main.kt # MODIFY: instantiate DesktopAccountRelays, bootstrap sub
├── model/
│ ├── DesktopAccountRelays.kt # MODIFY: add search + blocked relay tracking
│ ├── DesktopRelayCategories.kt # NEW: aggregator with fallback logic
│ └── DesktopDmRelayState.kt # UNCHANGED (already correct)
├── subscriptions/
│ ├── DesktopRelaySubscriptionsCoordinator.kt # MODIFY: accept reactive relay sets
│ ├── BootstrapSubscription.kt # NEW: fetch user's kind 10002/10050/10007/10006
│ └── SubscriptionUtils.kt # MODIFY: rememberSubscription keys
├── ui/
│ ├── FeedScreen.kt # MODIFY: use NIP-65 outbox relays
│ ├── SearchScreen.kt # MODIFY: use search relays
│ └── NotificationsScreen.kt # MODIFY: use NIP-65 inbox relays
```
### Design Decisions
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Outbox model | v1: all filters to all outbox relays | True per-relay filter maps requires SubscriptionConfig redesign — defer |
| Search fallback | Hardcoded NIP-50 relays (relay.nostr.band) | Most connected relays don't support NIP-50 |
| DM fallback | Connected relays (existing behavior) | Blocking send is too aggressive for desktop UX |
| Blocked subtraction | Utility function at call site | Centralized in `RelayConnectionManager.subscribe` is opaque and affects all callers |
| Relay set change → resub | Debounce 1s via `distinctUntilChanged()` on StateFlows | Prevents thrashing during startup when multiple kind events arrive |
| Auto-connect category relays | Yes, add to relay pool if not present | DM/search relays from events may not be in connected set |
| Persist relay lists | java.util.prefs.Preferences | Consistent with existing DesktopPreferences pattern |
| FeedMetadataCoordinator.indexRelays | Keep static, recreate coordinator when relays change | Avoids commons API change |
### Phase 1: Bootstrap + Wire Existing State
**Goal:** Fetch user's relay config on login. Wire `DesktopAccountRelays` into Main.kt so kind 10050 events actually update DM relay state.
**1a. Create `BootstrapSubscription.kt`**
Fetches user's own replaceable events (kinds 10002, 10050, 10007, 10006) from connected relays on login.
```kotlin
class BootstrapSubscription(
private val relayManager: RelayConnectionManager,
private val scope: CoroutineScope,
) {
fun subscribe(
userPubKeyHex: HexKey,
onEvent: (Event) -> Unit,
) {
val filter = Filter(
kinds = listOf(10002, 10050, 10007, 10006),
authors = listOf(userPubKeyHex),
limit = 4,
)
relayManager.subscribe(
subId = "bootstrap-relay-config",
filters = listOf(filter),
listener = object : SubscriptionListener {
override fun onEvent(event: Event, isLive: Boolean, relay: NormalizedRelayUrl, forFilters: List<Filter>?) {
onEvent(event)
}
},
)
}
}
```
**1b. Instantiate `DesktopAccountRelays` in Main.kt**
Replace the standalone `DesktopDmRelayState(MutableStateFlow(emptySet()), ...)` with `DesktopAccountRelays`:
```kotlin
// In Main.kt logged-in section (replace lines 924-929)
val accountRelays = remember(account, relayManager, scope) {
DesktopAccountRelays(account.pubKeyHex, relayManager, scope)
}
// Bootstrap: fetch user's relay config events
LaunchedEffect(accountRelays) {
relayManager.connectedRelays.first { it.isNotEmpty() }
BootstrapSubscription(relayManager, scope).subscribe(account.pubKeyHex) { event ->
accountRelays.consumeIfRelevant(event) // routes to appropriate handler
}
}
```
**1c. Expand `DesktopAccountRelays` to route all relay config events**
Add methods to consume kinds 10002, 10007, 10006 (currently only handles 10050):
```kotlin
// In DesktopAccountRelays
private val _searchRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val searchRelayList: StateFlow<Set<NormalizedRelayUrl>> = _searchRelayList.asStateFlow()
private val _blockedRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val blockedRelayList: StateFlow<Set<NormalizedRelayUrl>> = _blockedRelayList.asStateFlow()
fun consumeIfRelevant(event: Event): Boolean {
return when (event.kind) {
ChatMessageRelayListEvent.KIND -> { consumeDmRelayList(event as ChatMessageRelayListEvent); true }
SearchRelayListEvent.KIND -> { consumeSearchRelayList(event); true }
BlockedRelayListEvent.KIND -> { consumeBlockedRelayList(event); true }
else -> false
}
}
```
**1d. Thread `accountRelays` to MainContent and layouts**
Single instance created in Main.kt, passed through composable tree. Replace the per-column `DesktopAccountRelays` created in `DeckColumnContainer`.
### Phase 2: Relay Category Aggregator
**Goal:** Single source of truth for "which relays should feature X use?" with fallback logic.
**Create `DesktopRelayCategories.kt`**
```kotlin
class DesktopRelayCategories(
private val nip65State: Nip65RelayListState,
private val accountRelays: DesktopAccountRelays,
private val connectedRelays: StateFlow<Set<NormalizedRelayUrl>>,
scope: CoroutineScope,
) {
/** Relays for home feed / publishing. NIP-65 write → fallback to connected */
val feedRelays: StateFlow<Set<NormalizedRelayUrl>> = combine(
nip65State.outboxFlow,
connectedRelays,
) { outbox, connected -> outbox.ifEmpty { connected } }
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, connectedRelays.value)
/** Relays for receiving notifications. NIP-65 read → fallback to connected */
val notificationRelays: StateFlow<Set<NormalizedRelayUrl>> = combine(
nip65State.inboxFlow,
connectedRelays,
) { inbox, connected -> inbox.ifEmpty { connected } }
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, connectedRelays.value)
/** Relays for NIP-50 search. Search list → fallback to DEFAULT_SEARCH_RELAYS */
val searchRelays: StateFlow<Set<NormalizedRelayUrl>> = accountRelays.searchRelayList
.map { it.ifEmpty { DEFAULT_SEARCH_RELAYS } }
.distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, DEFAULT_SEARCH_RELAYS)
/** DM relays — already handled by DesktopDmRelayState with fallback */
val dmRelays: StateFlow<Set<NormalizedRelayUrl>> = accountRelays.dmRelays.flow
/** Blocked relays to exclude from all subscriptions */
val blockedRelays: StateFlow<Set<NormalizedRelayUrl>> = accountRelays.blockedRelayList
companion object {
val DEFAULT_SEARCH_RELAYS = setOf(
NormalizedRelayUrl("wss://relay.nostr.band/"),
)
}
}
```
### Phase 3: Update Screens
**3a. SearchScreen.kt**
Replace `allRelayUrls` with `relayCategories.searchRelays`:
```kotlin
// Current (line 175):
rememberSubscription(connectedRelays, debouncedQuery, relayManager = relayManager) {
// relays = allRelayUrls
// Target:
val searchRelays by relayCategories.searchRelays.collectAsState()
rememberSubscription(searchRelays, debouncedQuery, relayManager = relayManager) {
// relays = searchRelays
```
Thread `relayCategories` to SearchScreen via RootContent params.
**3b. FeedScreen.kt**
Replace `allRelayUrls` with `relayCategories.feedRelays`:
```kotlin
val feedRelays by relayCategories.feedRelays.collectAsState()
rememberSubscription(feedRelays, ..., relayManager = relayManager) {
// relays = feedRelays
```
**3c. NotificationsScreen.kt**
Use `relayCategories.notificationRelays` for incoming notification subscriptions.
**3d. Blocked relay subtraction**
Add utility:
```kotlin
// In RelayValidation.kt or new file
fun Set<NormalizedRelayUrl>.minusBlocked(
blocked: Set<NormalizedRelayUrl>
): Set<NormalizedRelayUrl> = this - blocked
```
Apply at each subscription site:
```kotlin
val effectiveRelays = feedRelays.minusBlocked(blockedRelays)
```
**3e. Make DM subscriptions reactive**
In Main.kt, replace one-shot `subscribeToDms()` with a collector:
```kotlin
LaunchedEffect(accountRelays) {
accountRelays.dmRelays.flow.collect { dmRelaySet ->
subscriptionsCoordinator.resubscribeToDms(account.pubKeyHex, accountRelays.dmRelays, onDmEvent)
}
}
```
### Phase 4: Persistence
**Goal:** Relay lists survive app restart without waiting for bootstrap fetch.
Save last-known relay lists to `DesktopPreferences`:
```kotlin
// On every relay list update
DesktopPreferences.nip65RelayList = mapper.writeValueAsString(outboxRelays)
DesktopPreferences.dmRelayList = mapper.writeValueAsString(dmRelays)
DesktopPreferences.searchRelayList = mapper.writeValueAsString(searchRelays)
DesktopPreferences.blockedRelayList = mapper.writeValueAsString(blockedRelays)
// On startup, before bootstrap fetch completes
val savedDmRelays = mapper.readValue<Set<String>>(DesktopPreferences.dmRelayList)
.mapNotNull { RelayUrlNormalizer.normalizeOrNull(it) }.toSet()
accountRelays.setDmRelays(savedDmRelays)
```
## Acceptance Criteria
### Phase 1: Bootstrap + Wire
- [ ] `DesktopAccountRelays` instantiated once in Main.kt, threaded to all screens
- [ ] Bootstrap subscription fetches kinds 10002, 10050, 10007, 10006 on login
- [ ] Kind 10050 events update `accountRelays.dmRelayList` (no longer hardcoded empty)
- [ ] Kind 10007 events populate `accountRelays.searchRelayList`
- [ ] Kind 10006 events populate `accountRelays.blockedRelayList`
- [ ] Remove per-column `DesktopAccountRelays` from DeckColumnContainer
### Phase 2: Aggregator
- [ ] `DesktopRelayCategories` exposes `feedRelays`, `notificationRelays`, `searchRelays`, `dmRelays`, `blockedRelays`
- [ ] Each StateFlow has appropriate fallback (connected, default search relays)
- [ ] `distinctUntilChanged()` on all flows to prevent subscription thrashing
### Phase 3: Screen Wiring
- [ ] SearchScreen uses `searchRelays` for NIP-50 subscriptions
- [ ] FeedScreen uses `feedRelays` for feed subscriptions
- [ ] NotificationsScreen uses `notificationRelays`
- [ ] Blocked relays subtracted from all subscription relay sets
- [ ] DM subscriptions reactive — resubscribe when dmRelays flow changes
- [ ] `rememberSubscription` keys on category relay sets
### Phase 4: Persistence
- [ ] Relay lists saved to Preferences on every update
- [ ] Loaded from Preferences on startup before bootstrap completes
- [ ] Bootstrap fetch overwrites saved data with fresh data from relays
## Dependencies & Risks
| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|------------|
| Subscription thrashing during startup | Medium | Medium | `distinctUntilChanged()` + 1s debounce on relay set changes |
| Bootstrap subscription returns stale events | Low | Low | Replaceable events — latest `created_at` wins |
| DM relays not in connected set | Medium | Medium | Auto-add to relay pool on relay set change |
| Blocked relay decryption fails (NIP-44) | Low | Low | Graceful fallback — empty blocked set |
| Coordinator recreation on relay change | Medium | Low | Debounce, only recreate when relay set structurally changes |
## Unanswered Questions
1. Should bootstrap subscription unsubscribe after receiving all 4 kinds, or stay open for live updates?
2. Should `DesktopRelayCategories` auto-add category relays to the relay pool (so they connect)?
3. For blocked relay decryption — can we use `signer.decrypt()` directly or need async handling for NIP-46?
4. Should we show a UI indicator when operating on fallback relays ("No NIP-65 published — using defaults")?
5. True outbox model (per-relay filter maps) — defer to separate plan or include as Phase 5?
@@ -0,0 +1,183 @@
---
title: "feat: Wire Relay Config Categories into Desktop Subscriptions"
type: feat
status: active
date: 2026-04-22
origin: docs/plans/2026-04-21-feat-relay-config-parity-plan.md
deepened: 2026-04-22
---
# feat: Wire Relay Config Categories into Desktop Subscriptions
## Enhancement Summary
**Deepened on:** 2026-04-22
**Review agents used:** nostr-expert, kotlin-coroutines, desktop-expert, performance-oracle, architecture-strategist, code-simplicity-reviewer
### Key Changes from Review
1. **2 phases, not 4** — merged aggregator into Phase 1, cut persistence (YAGNI)
2. **No new files for BootstrapSubscription or minusBlocked** — inline everything
3. **Keep DesktopRelayCategories** but provide via `LocalRelayCategories` CompositionLocal (matches `LocalTorState` pattern)
4. **Bake blocked subtraction + `debounce(1s)` into aggregator** — centralized, not per-call-site
5. **Route bootstrap through localCache** — keeps Nip65RelayListState in sync
6. **Kind 10006/10007 need NIP-51 decryption** — use `privateTags(signer)`
7. **`connectedRelays.first { isNotEmpty }` needs timeout** — `withTimeoutOrNull(30s)`
8. **Make FeedMetadataCoordinator.indexRelays mutable** — avoid recreation, preserve dedupe state
9. **Add `created_at` checking** in consumeIfRelevant to prevent stale overwrites
## Problem Statement
| Feature | Currently Uses | Should Use |
|---------|---------------|------------|
| Home feed | all connected relays | NIP-65 outbox (kind 10002 write) |
| Notifications | all connected relays | NIP-65 inbox (kind 10002 read) |
| Search | all connected relays | Search relays (kind 10007) |
| DMs | `emptySet()` fallback → connected | DM relays (kind 10050) |
| All features | no filtering | Minus blocked relays (kind 10006) |
## Technical Approach
### Phase 1: Wire State + Bootstrap (single PR)
**1a. Expand `DesktopAccountRelays.kt`**
Add search/blocked StateFlows + `consumeIfRelevant()` dispatcher with `created_at` dedup:
```kotlin
private val _searchRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val searchRelayList: StateFlow<Set<NormalizedRelayUrl>> = _searchRelayList.asStateFlow()
private val _blockedRelayList = MutableStateFlow<Set<NormalizedRelayUrl>>(emptySet())
val blockedRelayList: StateFlow<Set<NormalizedRelayUrl>> = _blockedRelayList.asStateFlow()
// Track created_at to prevent stale overwrites
private var lastSearchCreatedAt = 0L
private var lastBlockedCreatedAt = 0L
private var lastDmCreatedAt = 0L
fun consumeIfRelevant(event: Event): Boolean {
return when (event.kind) {
ChatMessageRelayListEvent.KIND -> {
if (event.createdAt > lastDmCreatedAt) {
lastDmCreatedAt = event.createdAt
consumeDmRelayList(event as ChatMessageRelayListEvent)
}
true
}
SearchRelayListEvent.KIND -> {
if (event.createdAt > lastSearchCreatedAt) {
lastSearchCreatedAt = event.createdAt
// NIP-51: try public tags first, then decrypt private
val relays = (event as? SearchRelayListEvent)?.publicRelays()?.toSet() ?: emptySet()
_searchRelayList.value = relays
}
true
}
BlockedRelayListEvent.KIND -> {
if (event.createdAt > lastBlockedCreatedAt) {
lastBlockedCreatedAt = event.createdAt
val relays = (event as? BlockedRelayListEvent)?.publicRelays()?.toSet() ?: emptySet()
_blockedRelayList.value = relays
}
true
}
else -> false
}
}
```
**1b. Create `DesktopRelayCategories.kt`** — aggregator with fallback + blocked subtraction + debounce
```kotlin
class DesktopRelayCategories(
nip65State: Nip65RelayListState,
accountRelays: DesktopAccountRelays,
connectedRelays: StateFlow<Set<NormalizedRelayUrl>>,
scope: CoroutineScope,
) {
val feedRelays: StateFlow<Set<NormalizedRelayUrl>> = combine(
nip65State.outboxFlow, connectedRelays, accountRelays.blockedRelayList,
) { outbox, connected, blocked ->
(outbox.ifEmpty { connected }) - blocked
}.debounce(1.seconds).distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, connectedRelays.value)
val notificationRelays: StateFlow<Set<NormalizedRelayUrl>> = combine(
nip65State.inboxFlow, connectedRelays, accountRelays.blockedRelayList,
) { inbox, connected, blocked ->
(inbox.ifEmpty { connected }) - blocked
}.debounce(1.seconds).distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, connectedRelays.value)
val searchRelays: StateFlow<Set<NormalizedRelayUrl>> = combine(
accountRelays.searchRelayList, accountRelays.blockedRelayList,
) { search, blocked ->
(search.ifEmpty { DEFAULT_SEARCH_RELAYS }) - blocked
}.debounce(1.seconds).distinctUntilChanged()
.stateIn(scope, SharingStarted.Eagerly, DEFAULT_SEARCH_RELAYS)
val dmRelays: StateFlow<Set<NormalizedRelayUrl>> = accountRelays.dmRelays.flow
companion object {
val DEFAULT_SEARCH_RELAYS = setOf(NormalizedRelayUrl("wss://relay.nostr.band/"))
}
}
```
**1c. Create `LocalRelayCategories.kt`** — CompositionLocal (matches `LocalTorState` pattern)
```kotlin
val LocalRelayCategories = compositionLocalOf<DesktopRelayCategories> {
error("No DesktopRelayCategories provided")
}
```
**1d. Wire in Main.kt**
- Instantiate single `DesktopAccountRelays` in logged-in section
- Create `DesktopRelayCategories` combining nip65State + accountRelays + connectedRelays
- Inline bootstrap subscription in `LaunchedEffect` (~10 lines)
- Route bootstrap events through `localCache` for NIP-65 sync
- Provide `LocalRelayCategories` via `CompositionLocalProvider`
- Use `withTimeoutOrNull(30.seconds)` on `connectedRelays.first { isNotEmpty }`
- Remove hardcoded `DesktopDmRelayState(emptySet())` and per-column `DesktopAccountRelays`
### Phase 2: Screen Wiring
Each screen collects from `LocalRelayCategories.current`:
**SearchScreen.kt:** `val searchRelays by LocalRelayCategories.current.searchRelays.collectAsState()` → use in `rememberSubscription`
**FeedScreen.kt:** `val feedRelays by LocalRelayCategories.current.feedRelays.collectAsState()` → replace `allRelayUrls`
**NotificationsScreen.kt:** `val notificationRelays by LocalRelayCategories.current.notificationRelays.collectAsState()`
**DM subscriptions:** Make reactive via `debounce(500).collect { resubscribe }` with Job tracking
## Files Modified
| File | Change |
|------|--------|
| `DesktopAccountRelays.kt` | Add search/blocked flows, consumeIfRelevant, created_at dedup |
| `DesktopRelayCategories.kt` | NEW: aggregator with debounce + blocked subtraction |
| `LocalRelayCategories.kt` | NEW: CompositionLocal (3 lines) |
| `Main.kt` | Wire accountRelays, relayCategories, inline bootstrap, CompositionLocalProvider |
| `DeckColumnContainer.kt` | Remove per-column DesktopAccountRelays creation |
| `FeedScreen.kt` | Use feedRelays from LocalRelayCategories |
| `SearchScreen.kt` | Use searchRelays from LocalRelayCategories |
| `NotificationsScreen.kt` | Use notificationRelays from LocalRelayCategories |
## Acceptance Criteria
- [ ] Bootstrap subscription fetches kinds 10002/10050/10007/10006 on login
- [ ] Events routed through localCache (NIP-65 stays in sync)
- [ ] SearchScreen uses search relays (falls back to relay.nostr.band)
- [ ] FeedScreen uses NIP-65 outbox relays (falls back to connected)
- [ ] Blocked relays subtracted from all category relay sets
- [ ] DM subscriptions reactive to relay changes
- [ ] No subscription thrashing at startup (debounce 1s)
- [ ] `connectedRelays.first` has 30s timeout
## Unanswered Questions
1. NIP-51 private tag decryption for kind 10007/10006 — defer to v2 or attempt now? (Public tags work for `create()`, but `updateRelayList()` moves to private)