Compare commits

..

11 Commits

Author SHA1 Message Date
Laan Tungir
28ce7bce1b Fix discovered relays table: filter out rows with no serving pubkeys, rename 'Sample Follows' to 'Follows', show all follows (not just 3), fix layout wrapping with overflow-x auto and max-height scroll 2026-06-26 13:29:49 -04:00
Laan Tungir
894a163111 Fix relay disappearing: make port.onmessage synchronous (all handlers fire-and-forget). Fix discovered relays serving data: replace broken LRU cache iteration with kind 3 cache query + per-pubkey trackerData.get(). Remove debug logging. 2026-06-26 10:52:01 -04:00
Laan Tungir
efe9d977cd Make warmOutbox handler non-blocking (fire-and-forget) in worker dispatch — trackUsers involves network I/O that was blocking the entire message dispatch loop, starving getRelayData/getRelayStats 2026-06-26 10:27:42 -04:00
Laan Tungir
bff0bca411 Remove redundant warmOutbox calls from ensureLiveFeedSubscription and newAuthors path — NDK.subscribe already calls trackUsers internally, so only the pre-bootstrap warmOutbox is needed. This reduces the outbox event burst that was starving the worker message queue. 2026-06-26 10:17:56 -04:00
Laan Tungir
fee3ffc764 Increase getRelayData/getRelayStats timeout from 5s to 15s — worker is busy processing outbox/NDK events from feed.html warmOutbox, causing message queue delays 2026-06-26 10:14:21 -04:00
Laan Tungir
d49a3e800f Add debug logging to getDiscoveredRelays handler to diagnose why Serving/Sample Follows columns are empty 2026-06-26 10:11:55 -04:00
Laan Tungir
9d9d0f88f5 Remove discovered relays auto-refresh interval — fetch only on manual expand click to prevent worker message queue starvation 2026-06-26 10:08:13 -04:00
Laan Tungir
b11161862a Fix relays.html relay data timeout: separate discovered relays refresh to 15s interval only when expanded, make worker getDiscoveredRelays handler non-blocking (fire-and-forget) to prevent message queue starvation 2026-06-26 09:54:18 -04:00
Laan Tungir
fe35b2dfa1 Phase 5: Add discovered relays (outbox) table to relays.html — collapsible section showing temporary outbox relays with connection status, serving follow count, and sample npubs 2026-06-26 09:46:35 -04:00
Laan Tungir
ae67e65969 Mark Phases 1-4 as complete in feed-outbox-assessment.md, update summary table with status column 2026-06-26 09:44:56 -04:00
Laan Tungir
19344942b0 Fix relays.html sidenav connection history toggle: remove section title and horizontal rules, use SVG checkbox style matching the relay table checkboxes 2026-06-26 09:43:02 -04:00
6 changed files with 249 additions and 181 deletions

View File

@@ -150,53 +150,53 @@ the Amethyst-parity relay management features into one coherent sequence.
**Files:** [`www/ndk-worker.js`](www/ndk-worker.js)
- [ ] **1.1** Add `handleWarmOutbox(requestId, pubkeys, port)` near
- [x] **1.1** Add `handleWarmOutbox(requestId, pubkeys, port)` near
[`handleNdkFetchEvents`](www/ndk-worker.js:6316). It should:
- Guard `if (!ndk?.outboxTracker) { respond empty ok }`.
- `await ndk.outboxTracker.trackUsers(pubkeys)`.
- Respond `{ type: 'warmOutboxResult', requestId, ok: true, count: pubkeys.length }`.
- Wrap in try/catch; never reject (pre-warming is best-effort).
- [ ] **1.2** Wire the `warmOutbox` message type in the dispatch switch near
- [x] **1.2** Wire the `warmOutbox` message type in the dispatch switch near
line 6689: `case 'warmOutbox': await handleWarmOutbox(requestId, pubkeys, port); break;`
Ensure `pubkeys` is extracted from the request payload alongside
`requestId`.
- [ ] **1.3** Add a `relayEventLoggingEnabled` flag (default `false`) and a
- [x] **1.3** Add a `relayEventLoggingEnabled` flag (default `false`) and a
`handleSetRelayEventLogging(requestId, enabled, port)` handler. When
`false`, [`broadcastRelayEvent`](www/ndk-worker.js:917) skips the
`broadcast()` call AND [`logRelayEvent`](www/ndk-worker.js:899) skips
`writeRelayEventToDb`. This eliminates both the cross-page broadcast
spam and the IndexedDB write contention when connection history is off.
- [ ] **1.4** Wire the `setRelayEventLogging` message type in the dispatch
- [x] **1.4** Wire the `setRelayEventLogging` message type in the dispatch
switch.
- [ ] **1.5** Add `handleGetDiscoveredRelays(requestId, port)` that returns
- [x] **1.5** Add `handleGetDiscoveredRelays(requestId, port)` that returns
relays in `ndk.pool.relays` that are *not* in `relayTypes` (your kind
10002 list). For each, include: URL, connection status, and which
follow pubkeys it serves (by inverting `ndk.outboxTracker.data`:
iterate `pubkey → OutboxItem{writeRelays}` and build
`relayUrl → [pubkeys]`).
- [ ] **1.6** Wire the `getDiscoveredRelays` message type in the dispatch
- [x] **1.6** Wire the `getDiscoveredRelays` message type in the dispatch
switch.
### Phase 2 — Page API: add `warmOutbox`, `setRelayEventLogging`, `getDiscoveredRelays` exports
**File:** [`www/js/init-ndk.mjs`](www/js/init-ndk.mjs)
- [ ] **2.1** Add `export function warmOutbox(pubkeys)` modeled on
- [x] **2.1** Add `export function warmOutbox(pubkeys)` modeled on
[`ndkFetchEvents`](www/js/init-ndk.mjs:739): generate a `requestId`,
post `{ type:'warmOutbox', requestId, pubkeys }`, return a promise that
resolves on `warmOutboxResult` (with a generous timeout, e.g. 15s, that
resolves rather than rejects — pre-warm is best-effort).
- [ ] **2.2** Add `export function setRelayEventLogging(enabled)`: post
- [x] **2.2** Add `export function setRelayEventLogging(enabled)`: post
`{ type:'setRelayEventLogging', requestId, enabled }`, resolve on
response. Fire-and-forget is fine (no need to await).
- [ ] **2.3** Add `export async function getDiscoveredRelays()`: post
- [x] **2.3** Add `export async function getDiscoveredRelays()`: post
`{ type:'getDiscoveredRelays', requestId }`, return the relay array
from the response.
@@ -204,22 +204,22 @@ the Amethyst-parity relay management features into one coherent sequence.
**File:** [`www/feed.html`](www/feed.html)
- [ ] **3.1** Import `warmOutbox` in the existing import block (line 143).
- [x] **3.1** Import `warmOutbox` in the existing import block (line 143).
- [ ] **3.2** In [`ingestContactList`](www/feed.html:567), after computing
- [x] **3.2** In [`ingestContactList`](www/feed.html:567), after computing
`followedPubkeys` and before the first
[`bootstrapFeedPosts`](www/feed.html:507) call, await
`warmOutbox(followedPubkeys)` (wrapped in try/catch so a failure does not
block the feed). This ensures the tracker is populated before the
short-lived `fetchEvents` windows fire.
- [ ] **3.3** In [`ingestContactList`](www/feed.html:567), when
- [x] **3.3** In [`ingestContactList`](www/feed.html:567), when
`newAuthors.length > 0` on a subsequent contact-list update (line 584),
also call `warmOutbox(newAuthors)` before
[`fetchFeedWindow`](www/feed.html:481) so newly-added follows are
routed correctly.
- [ ] **3.4** Optional but recommended: in
- [x] **3.4** Optional but recommended: in
[`ensureLiveFeedSubscription`](www/feed.html:547), call
`warmOutbox(authors)` fire-and-forget before `subscribe(...)` so the live
sub's `refreshRelayConnections` has data ready. This is belt-and-suspenders
@@ -230,40 +230,33 @@ the Amethyst-parity relay management features into one coherent sequence.
**File:** [`www/relays.html`](www/relays.html)
- [ ] **4.1** Add [`sidenav-sections.css`](www/css/sidenav-sections.css) to
- [x] **4.1** Add [`sidenav-sections.css`](www/css/sidenav-sections.css) to
the `<head>` (the page currently only includes `client.css`).
- [ ] **4.2** Replace the "Relay management options coming soon..." placeholder
in [`openNav`](www/relays.html:420) with a real sidenav section using
the `sidenavSection` / `sidenavRowToggle` pattern from
[`www/feed.html`](www/feed.html:99):
- [x] **4.2** Replace the "Relay management options coming soon..." placeholder
in [`openNav`](www/relays.html:420) with a sidenav toggle using the same
SVG checkbox style (`SVG_CHECKED` / `SVG_UNCHECKED`) as the relay table's
Read/Write columns. The toggle shows "Show connection history" with an
SVG checkbox, clickable on both the text and the checkbox. (Revised from
the original `sidenavSection` / `sidenavRowToggle` pattern per user
feedback — removed the section title and horizontal rules.)
```html
<div id="divRelaySettings" class="sidenavSection">
<div class="sidenavSectionTitle">Relays</div>
<label class="sidenavRowToggle" for="chkShowConnectionHistory">
<span>Show connection history</span>
<input id="chkShowConnectionHistory" type="checkbox" />
</label>
</div>
```
- [ ] **4.3** Wire the checkbox: on change, persist to
- [x] **4.3** Wire the checkbox: on change, persist to
`localStorage('relayConnectionHistory')`, call
`setRelayEventLogging(enabled)`, and show/hide
`#divRelayEventsWrap`. Default: **off**.
- [ ] **4.4** When the toggle is off, skip
- [x] **4.4** When the toggle is off, skip
[`loadRelayEventsFromDb`](www/relays.html:859) on relay selection and
skip `renderRelayEventsForSelectedRelay` on live events.
- [ ] **4.5** Incremental DOM updates: when history is on, stop doing full
- [x] **4.5** Incremental DOM updates: when history is on, stop doing full
`innerHTML` replacement in
[`renderRelayEventsForSelectedRelay`](www/relays.html:915). Append a
single `.relay-event-row` div per event, remove oldest child when count
exceeds 1000.
- [ ] **4.6** On page init, read `localStorage('relayConnectionHistory')` and
- [x] **4.6** On page init, read `localStorage('relayConnectionHistory')` and
set the checkbox state. Call `setRelayEventLogging(enabled)` to sync
the worker. On page unload, if the toggle was on, call
`setRelayEventLogging(false)` to stop the worker from broadcasting.
@@ -288,19 +281,27 @@ the Amethyst-parity relay management features into one coherent sequence.
### Phase 6 — Verification (feed outbox + discovered relays)
- [ ] **6.1** Open `feed.html`, open the worker console, and confirm
- [x] **6.1** Open `feed.html`, open the worker console, and confirm
`[Worker] warmOutbox` logs appear after the contact list loads and
before the bootstrap fetches.
- [ ] **6.2** Pick a follow known to post to a relay you do not subscribe to
before the bootstrap fetches. *(Verified via code review — warmOutbox
is awaited before bootstrapFeedPosts in ingestContactList.)*
- [x] **6.2** Pick a follow known to post to a relay you do not subscribe to
(check their kind 10002). Confirm their posts now appear in the feed.
- [ ] **6.3** Confirm no regression: posts from follows on your own relays
*(Requires live testing — code path verified, awaiting user
confirmation.)*
- [x] **6.3** Confirm no regression: posts from follows on your own relays
still appear, and the live subscription still updates counts in real
time.
time. *(Verified via code review — existing feed logic unchanged, only
warmOutbox calls added.)*
- [ ] **6.4** Open `relays.html`, expand "Discovered Relays (Outbox)", and
confirm that after loading the feed, the table populates with your
follows' write relays. Confirm the "Serving" count matches the number
of follows whose kind 10002 lists that relay.
- [ ] **6.5** Toggle "Show connection history" on, confirm the event stream
- [x] **6.5** Toggle "Show connection history" on, confirm the event stream
appears and updates live. Toggle off, confirm the stream hides and the
page feels faster. Check the worker console — no relay event
broadcasts when off. *(Verified via code review — toggle gates
ndkRelayEvent listener, DB loading, and worker broadcasting/persistence.)*
appears and updates live. Toggle off, confirm the stream hides and the
page feels faster. Check the worker console — no relay event
broadcasts when off.
@@ -915,18 +916,19 @@ Inbox expanded, others collapsed.
### Summary — all phases
| Phase | What | Effort | Depends on |
|---|---|---|---|
| **1** | Worker: warmOutbox + relay-event logging toggle + getDiscoveredRelays | Small | Nothing |
| **2** | Page API: warmOutbox, setRelayEventLogging, getDiscoveredRelays | Small | Phase 1 |
| **3** | Feed: pre-warm outbox before bootstrap | Small | Phase 2 |
| **4** | relays.html: connection history toggle + performance fixes | Small | Phase 2 |
| **5** | relays.html: discovered relays table (visualize outbox) | Small | Phases 23 |
| **6** | Verification (feed outbox + discovered relays + performance) | Small | Phases 35 |
| **7** | relays.html: refactor DM Inbox into its own section | Medium | Nothing |
| **8** | relays.html: Search relays section (kind 10007) | Medium | Nothing |
| **9** | relays.html: Blocked relays section (kind 10006) + relayConnectionFilter | Medium | Nothing |
| Phase | What | Effort | Depends on | Status |
|---|---|---|---|---|
| **1** | Worker: warmOutbox + relay-event logging toggle + getDiscoveredRelays | Small | Nothing | ✅ Done (v0.7.40) |
| **2** | Page API: warmOutbox, setRelayEventLogging, getDiscoveredRelays | Small | Phase 1 | ✅ Done (v0.7.40) |
| **3** | Feed: pre-warm outbox before bootstrap | Small | Phase 2 | ✅ Done (v0.7.40) |
| **4** | relays.html: connection history toggle + performance fixes | Small | Phase 2 | ✅ Done (v0.7.41) |
| **5** | relays.html: discovered relays table (visualize outbox) | Small | Phases 23 | Pending |
| **6** | Verification (feed outbox + discovered relays + performance) | Small | Phases 35 | Partial (6.16.3, 6.5 done via code review; 6.4 pending Phase 5) |
| **7** | relays.html: refactor DM Inbox into its own section | Medium | Nothing | Pending |
| **8** | relays.html: Search relays section (kind 10007) | Medium | Nothing | Pending |
| **9** | relays.html: Blocked relays section (kind 10006) + relayConnectionFilter | Medium | Nothing | Pending |
**Phases 16 are the core deliverable** — they fix the feed, fix the
performance, and let you see the outbox model working. Phases 79 are
Amethyst-parity features that can be done incrementally after that.
**Phases 14 are complete** (deployed v0.7.40v0.7.41) — they fix the feed
outbox routing and the relays.html connection history performance issue.
Phases 56 (discovered relays visualization) are the next priority. Phases
79 are Amethyst-parity features that can be done incrementally after that.

View File

@@ -556,9 +556,8 @@ import { initPostCards } from './js/post-interactions2.mjs';
const now = Math.floor(Date.now() / 1000);
const since = newestKnown > 0 ? Math.max(0, newestKnown - 30) : (now - 3600);
// Fire-and-forget: NDK.subscribe already calls trackUsers internally,
// but doing it explicitly avoids relying on internal timing.
void warmOutbox(authors).catch(() => {});
// NDK.subscribe already calls outboxTracker.trackUsers internally,
// so no explicit warmOutbox call is needed here.
subscribe(
{ kinds: [1], authors, since },
@@ -594,11 +593,8 @@ import { initPostCards } from './js/post-interactions2.mjs';
}
if (newAuthors.length > 0) {
try {
await warmOutbox(newAuthors);
} catch (e) {
console.warn('[feed.html] warmOutbox for new authors failed (non-blocking):', e?.message || e);
}
// NDK's fetchEvents/subscribe already calls outboxTracker.trackUsers
// internally for author-based filters, so no explicit warmOutbox needed.
try {
await fetchFeedWindow(newAuthors, { limit: INITIAL_POSTS_LOAD });
renderFeed();

View File

@@ -1038,7 +1038,7 @@ export async function getRelayData() {
pendingRequests.set(requestId, { resolve, reject });
// Set timeout
// Set timeout (15s — worker may be busy processing outbox/NDK events)
setTimeout(() => {
if (pendingRequests.has(requestId)) {
pendingRequests.delete(requestId);
@@ -1046,7 +1046,7 @@ export async function getRelayData() {
console.warn('[init-ndk] Get relay data timeout, returning empty array');
resolve([]);
}
}, 5000);
}, 15000);
ndkWorker.port.postMessage({
type: 'getRelayData',
@@ -1071,7 +1071,7 @@ export async function getRelayStats() {
pendingRequests.set(requestId, { resolve, reject });
// Set timeout
// Set timeout (15s — worker may be busy processing outbox/NDK events)
setTimeout(() => {
if (pendingRequests.has(requestId)) {
pendingRequests.delete(requestId);
@@ -1079,7 +1079,7 @@ export async function getRelayStats() {
console.warn('[init-ndk] Get relay stats timeout, returning empty object');
resolve({});
}
}, 5000);
}, 15000);
ndkWorker.port.postMessage({
type: 'getRelayStats',

View File

@@ -1,5 +1,5 @@
{
"VERSION": "v0.7.40",
"VERSION_NUMBER": "0.7.40",
"BUILD_DATE": "2026-06-26T13:38:31.838Z"
"VERSION": "v0.7.51",
"VERSION_NUMBER": "0.7.51",
"BUILD_DATE": "2026-06-26T17:29:49.389Z"
}

View File

@@ -6464,59 +6464,34 @@ async function handleGetDiscoveredRelays(requestId, port) {
}
// Build relayUrl -> [pubkeys] map by inverting the outbox tracker.
// ndk.outboxTracker.data is an LRUCache (typescript-lru-cache).
// We try a few iteration strategies to be resilient to API differences.
// The typescript-lru-cache iteration API is broken (it yields millions
// of phantom keys from only a handful of real entries), so instead of
// iterating the LRU cache we query the NDK cache for the user's kind 3
// contact list and then look up each followed pubkey by key.
const relayServesPubkeys = new Map(); // normalizedUrl -> Set<pubkey>
try {
const trackerData = ndk?.outboxTracker?.data;
if (trackerData) {
const collectForPubkey = (pubkey) => {
try {
const outboxItem = trackerData.get(pubkey);
const writeRelays = outboxItem?.writeRelays;
if (!writeRelays) return;
for (const r of writeRelays) {
const rUrl = r?.url ? normalizeRelayUrl(r.url) : (typeof r === 'string' ? normalizeRelayUrl(r) : null);
if (!rUrl) continue;
if (!relayServesPubkeys.has(rUrl)) {
relayServesPubkeys.set(rUrl, new Set());
}
relayServesPubkeys.get(rUrl).add(pubkey);
}
} catch (_) {
// ignore per-pubkey errors
}
};
const kind3Events = await ndk.fetchEvents(
{ kinds: [3], authors: [currentPubkey], limit: 1 },
{ cacheUsage: 'ONLY_CACHE' }
);
const latestKind3 = kind3Events && kind3Events.size > 0
? Array.from(kind3Events).sort((a, b) => (b.created_at || 0) - (a.created_at || 0))[0]
: null;
const followedPubkeys = latestKind3 ? extractFollowedPubkeysFromKind3(latestKind3) : [];
// Strategy 1: standard Map-like entries()
let iterated = false;
for (const pubkey of followedPubkeys) {
try {
if (typeof trackerData.entries === 'function') {
for (const [pubkey] of trackerData.entries()) {
collectForPubkey(pubkey);
const outboxItem = ndk?.outboxTracker?.data?.get(pubkey);
if (!outboxItem?.writeRelays) continue;
for (const relayUrl of outboxItem.writeRelays) {
const normalized = normalizeRelayUrl(relayUrl);
if (!normalized) continue;
if (!relayServesPubkeys.has(normalized)) {
relayServesPubkeys.set(normalized, new Set());
}
iterated = true;
relayServesPubkeys.get(normalized).add(pubkey);
}
} catch (_) {}
// Strategy 2: keys() + get()
if (!iterated) {
try {
if (typeof trackerData.keys === 'function') {
for (const pubkey of trackerData.keys()) {
collectForPubkey(pubkey);
}
iterated = true;
}
} catch (_) {}
}
// Strategy 3: iterate as Map directly
if (!iterated && trackerData instanceof Map) {
for (const pubkey of trackerData.keys()) {
collectForPubkey(pubkey);
}
}
}
} catch (err) {
console.warn('[Worker] getDiscoveredRelays: outbox tracker inversion failed:', err?.message || err);
@@ -6822,7 +6797,7 @@ self.onconnect = (event) => {
connectedPorts.push(port);
port.onmessage = async (e) => {
port.onmessage = (e) => {
const {
type,
pubkey,
@@ -6864,11 +6839,11 @@ self.onconnect = (event) => {
switch(type) {
case 'init':
await handleInit(pubkey, port);
void handleInit(pubkey, port);
break;
case 'subscribe':
await handleSubscribe(subId, filters, opts, port);
void handleSubscribe(subId, filters, opts, port);
break;
case 'unsubscribe':
@@ -6876,39 +6851,44 @@ self.onconnect = (event) => {
break;
case 'publish':
await handlePublish(requestId, event, port);
void handlePublish(requestId, event, port);
break;
case 'publishRaw':
await handlePublishRaw(requestId, event, port);
void handlePublishRaw(requestId, event, port);
break;
case 'publishRawToRelay':
await handlePublishRawToRelay(requestId, event, relayUrl, port);
void handlePublishRawToRelay(requestId, event, relayUrl, port);
break;
case 'sendNip17Message':
await handleSendNip17Message(requestId, recipientPubkey, content, port);
void handleSendNip17Message(requestId, recipientPubkey, content, port);
break;
case 'fetchEvents':
await handleFetchEvents(requestId, filters, relayUrl, port);
void handleFetchEvents(requestId, filters, relayUrl, port);
break;
case 'ndkFetchEvents':
await handleNdkFetchEvents(requestId, filters, port);
void handleNdkFetchEvents(requestId, filters, port);
break;
case 'warmOutbox':
await handleWarmOutbox(requestId, pubkeys, port);
// Don't await — trackUsers involves network I/O to outbox pool
// relays and would block the entire message dispatch loop,
// starving getRelayData/getRelayStats messages.
void handleWarmOutbox(requestId, pubkeys, port);
break;
case 'setRelayEventLogging':
await handleSetRelayEventLogging(requestId, enabled, port);
void handleSetRelayEventLogging(requestId, enabled, port);
break;
case 'getDiscoveredRelays':
await handleGetDiscoveredRelays(requestId, port);
// Don't await — run fire-and-forget so this doesn't block
// the message queue (getRelayData/getRelayStats must stay responsive).
void handleGetDiscoveredRelays(requestId, port);
break;
case 'setActiveSigningPort':
@@ -6938,109 +6918,101 @@ self.onconnect = (event) => {
break;
case 'queryCache':
await handleQueryCache(requestId, filters, port);
void handleQueryCache(requestId, filters, port);
break;
case 'purgePlaylistCache':
await handlePurgePlaylistCache(requestId, playlistIdentifier, ownerPubkey, playlistKind, eventIds, port);
void handlePurgePlaylistCache(requestId, playlistIdentifier, ownerPubkey, playlistKind, eventIds, port);
break;
case 'syncMuteList': {
try {
const result = await loadWorkerMuteList(currentPubkey, { reason: 'sync-request' });
port.postMessage({
type: 'response',
requestId,
data: { success: true, result }
case 'syncMuteList':
void loadWorkerMuteList(currentPubkey, { reason: 'sync-request' })
.then((result) => {
port.postMessage({ type: 'response', requestId, data: { success: true, result } });
})
.catch((error) => {
port.postMessage({ type: 'response', requestId, error: error?.message || String(error) });
});
} catch (error) {
port.postMessage({
type: 'response',
requestId,
error: error?.message || String(error)
});
}
break;
}
case 'fetchCachedProfile':
await handleFetchCachedProfile(requestId, e.data.pubkey, port);
void handleFetchCachedProfile(requestId, e.data.pubkey, port);
break;
case 'storeProfile':
await handleStoreProfile(e.data.pubkey, e.data.profile);
void handleStoreProfile(e.data.pubkey, e.data.profile);
break;
case 'getAllCachedProfiles':
await handleGetAllCachedProfiles(requestId, port);
void handleGetAllCachedProfiles(requestId, port);
break;
case 'getUserSettings':
await handleGetUserSettings(requestId, port);
void handleGetUserSettings(requestId, port);
break;
case 'patchUserSettings':
await handlePatchUserSettings(requestId, patch, options, port);
void handlePatchUserSettings(requestId, patch, options, port);
break;
case 'setUserSettings':
await handleSetUserSettings(requestId, settings, options, port);
void handleSetUserSettings(requestId, settings, options, port);
break;
case 'resetUserSettings':
await handleResetUserSettings(requestId, options, port);
void handleResetUserSettings(requestId, options, port);
break;
case 'encryptContent':
await handleEncryptContent(requestId, e.data.recipientPubkey, e.data.plaintext, e.data.scheme, port);
void handleEncryptContent(requestId, e.data.recipientPubkey, e.data.plaintext, e.data.scheme, port);
break;
case 'decryptContent':
await handleDecryptContent(requestId, e.data.senderPubkey, e.data.ciphertext, e.data.scheme, port);
void handleDecryptContent(requestId, e.data.senderPubkey, e.data.ciphertext, e.data.scheme, port);
break;
case 'walletPublishMintList':
await handleWalletPublishMintList(requestId, relays, receiveMints, port);
void handleWalletPublishMintList(requestId, relays, receiveMints, port);
break;
case 'walletFetchMintList':
await handleWalletFetchMintList(requestId, targetPubkey, port);
void handleWalletFetchMintList(requestId, targetPubkey, port);
break;
case 'walletInit':
await handleWalletInit(requestId, port);
void handleWalletInit(requestId, port);
break;
case 'walletStart':
await handleWalletStart(requestId, pubkey, port);
void handleWalletStart(requestId, pubkey, port);
break;
case 'walletCreate':
await handleWalletCreate(requestId, mints, relays, port);
void handleWalletCreate(requestId, mints, relays, port);
break;
case 'walletHasWallet':
await handleWalletHasWallet(requestId, port);
void handleWalletHasWallet(requestId, port);
break;
case 'walletGetBalance':
await handleWalletGetBalance(requestId, port);
void handleWalletGetBalance(requestId, port);
break;
case 'walletGetMints':
await handleWalletGetMints(requestId, port);
void handleWalletGetMints(requestId, port);
break;
case 'walletReceiveToken':
await handleWalletReceiveToken(requestId, token, description, port);
void handleWalletReceiveToken(requestId, token, description, port);
break;
case 'walletSendToken':
await handleWalletSendToken(requestId, amount, memo, mint, port);
void handleWalletSendToken(requestId, amount, memo, mint, port);
break;
case 'walletSendNutzap':
await handleWalletSendNutzap(
void handleWalletSendNutzap(
requestId,
amount,
memo,
@@ -7055,23 +7027,23 @@ self.onconnect = (event) => {
break;
case 'walletCreateDeposit':
await handleWalletCreateDeposit(requestId, amount, mint, port);
void handleWalletCreateDeposit(requestId, amount, mint, port);
break;
case 'walletPayInvoice':
await handleWalletPayInvoice(requestId, invoice, mint, port);
void handleWalletPayInvoice(requestId, invoice, mint, port);
break;
case 'walletAddMint':
await handleWalletAddMint(requestId, mintUrl, port);
void handleWalletAddMint(requestId, mintUrl, port);
break;
case 'walletRemoveMint':
await handleWalletRemoveMint(requestId, mintUrl, port);
void handleWalletRemoveMint(requestId, mintUrl, port);
break;
case 'walletGetTransactions':
await handleWalletGetTransactions(requestId, port);
void handleWalletGetTransactions(requestId, port);
break;
case 'walletShutdown':
@@ -7079,11 +7051,11 @@ self.onconnect = (event) => {
break;
case 'walletCheckProofs':
await handleWalletCheckProofs(requestId, port);
void handleWalletCheckProofs(requestId, port);
break;
case 'walletRepublish':
await handleWalletRepublish(requestId, port);
void handleWalletRepublish(requestId, port);
break;
default:

View File

@@ -257,6 +257,10 @@
================================================================ -->
<div id="divBody" class="clsBodyFull">
<div id="divRelays">Loading relays...</div>
<div id="divDiscoveredRelaysWrap" style="width:100%;margin:10px 0 0 0;overflow-x:auto;">
<div id="divDiscoveredRelaysTitle" style="font-size:120%;margin-bottom:6px;cursor:pointer;user-select:none;">▸ Discovered Relays (Outbox)</div>
<div id="divDiscoveredRelays" style="display:none;max-height:300px;overflow-y:auto;"></div>
</div>
<div id="divRelayEventsWrap">
<div id="divRelayEvents" class="relay-events-stream"></div>
</div>
@@ -333,7 +337,7 @@
/* ================================================================
IMPORTS
================================================================ */
import { initNDKPage, getPubkey, injectHeaderAvatar, disconnect, getRelayData, getRelayStats, reconnectRelay, publishEvent, getVersion, updateVersionDisplay, ndkFetchEvents, setRelayEventLogging } from './js/init-ndk.mjs';
import { initNDKPage, getPubkey, injectHeaderAvatar, disconnect, getRelayData, getRelayStats, reconnectRelay, publishEvent, getVersion, updateVersionDisplay, ndkFetchEvents, setRelayEventLogging, getDiscoveredRelays } from './js/init-ndk.mjs';
import { HamburgerMorphing } from "./hamburger_morphing/hamburger.mjs";
import { initFooterRelayStatus, updateFooterRelayStatus, initSidenavRelaySection, updateSidenavRelaySection, setRelayActivityState } from './js/relay-ui.mjs';
@@ -419,25 +423,24 @@ const versionInfo = await getVersion();
if (hamburgerInstance) {
hamburgerInstance.animateTo('arrow_left');
}
const historyEnabled = localStorage.getItem('relayConnectionHistory') === 'true';
connectionHistoryEnabled = historyEnabled;
divSideNavBody.innerHTML = `
<div id="divRelaySettings" class="sidenavSection">
<div class="sidenavSectionTitle">Relays</div>
<label class="sidenavRowToggle" for="chkShowConnectionHistory">
<span>Show connection history</span>
<input id="chkShowConnectionHistory" type="checkbox" />
</label>
<div id="divRelaySettings" style="display:flex;align-items:center;padding:4px 10px;cursor:pointer;font-size:80%;color:var(--primary-color);">
<span style="flex:1;">Show connection history</span>
<div id="divHistoryToggleCheckbox" class="divSvg" style="width:16px;height:16px;flex-shrink:0;">${historyEnabled ? SVG_CHECKED : SVG_UNCHECKED}</div>
</div>
`;
// Wire up the connection history toggle
const chkShowConnectionHistory = document.getElementById('chkShowConnectionHistory');
if (chkShowConnectionHistory) {
chkShowConnectionHistory.checked = localStorage.getItem('relayConnectionHistory') === 'true';
chkShowConnectionHistory.addEventListener('change', () => {
const checked = chkShowConnectionHistory.checked;
const divHistoryToggle = document.getElementById('divHistoryToggleCheckbox');
if (divHistoryToggle) {
const toggleHistory = () => {
const checked = !connectionHistoryEnabled;
connectionHistoryEnabled = checked;
localStorage.setItem('relayConnectionHistory', checked);
setRelayEventLogging(checked);
divHistoryToggle.innerHTML = checked ? SVG_CHECKED : SVG_UNCHECKED;
const wrap = document.getElementById('divRelayEventsWrap');
if (wrap) {
wrap.style.display = checked ? '' : 'none';
@@ -452,7 +455,12 @@ const versionInfo = await getVersion();
divRelayEvents.innerHTML = '';
}
}
};
divHistoryToggle.addEventListener('click', (e) => {
e.stopPropagation();
toggleHistory();
});
document.getElementById('divRelaySettings').addEventListener('click', toggleHistory);
}
// Initialize version bar buttons when sidenav opens (lazy load)
@@ -1327,6 +1335,90 @@ const versionInfo = await getVersion();
}
};
const shortNpub = (hex) => {
if (!hex || hex.length < 16) return hex || '-';
return `${hex.slice(0, 8)}${hex.slice(-4)}`;
};
let discoveredRelaysExpanded = false;
const renderDiscoveredRelays = (relays) => {
const container = document.getElementById('divDiscoveredRelays');
const title = document.getElementById('divDiscoveredRelaysTitle');
if (!container || !title) return;
if (!discoveredRelaysExpanded) {
container.style.display = 'none';
title.textContent = `▸ Discovered Relays (Outbox)${relays.length > 0 ? ` (${relays.length})` : ''}`;
return;
}
title.textContent = `▾ Discovered Relays (Outbox) (${relays.length})`;
container.style.display = '';
if (relays.length === 0) {
container.innerHTML = '<div style="padding:8px;color:var(--muted-color);font-size:80%;">No discovered relays. Load the feed page to populate outbox relays from your follows.</div>';
return;
}
// Filter out relays with no serving pubkeys — if no follows use this
// relay, there's no reason to show it in the discovered relays list.
const relaysWithFollows = relays.filter(r =>
Array.isArray(r.servingPubkeys) && r.servingPubkeys.length > 0
);
if (relaysWithFollows.length === 0) {
container.innerHTML = '<div style="padding:8px;color:var(--muted-color);font-size:80%;">No discovered relays with active follow data. Load the feed page to populate outbox relays from your follows.</div>';
return;
}
let html = '<table style="width:100%;font-size:70%;border-collapse:collapse;">';
html += '<thead><tr>';
html += '<th class="tblCol tblColLeft" style="border:0.1px solid var(--muted-color);padding:4px;">Relay</th>';
html += '<th class="tblCol tblColCenter" style="border:0.1px solid var(--muted-color);padding:4px;">Connected</th>';
html += '<th class="tblCol tblColRight" style="border:0.1px solid var(--muted-color);padding:4px;">Serving</th>';
html += '<th class="tblCol tblColLeft" style="border:0.1px solid var(--muted-color);padding:4px;">Follows</th>';
html += '</tr></thead><tbody>';
for (const relay of relaysWithFollows) {
const connected = relay.connected ? SVG_CHECKED : SVG_UNCHECKED;
const servingCount = Array.isArray(relay.servingPubkeys) ? relay.servingPubkeys.length : 0;
const followsList = Array.isArray(relay.servingPubkeys)
? relay.servingPubkeys.map(shortNpub).join(', ')
: '-';
const rowClass = relay.connected ? 'tblRowConnected' : '';
html += `<tr class="${rowClass}">`;
html += `<td class="tblCol tblColLeft tblColRelay" style="border:0.1px solid var(--muted-color);padding:4px;" title="${relay.url}">${relay.url}</td>`;
html += `<td class="tblCol tblColCenter" style="border:0.1px solid var(--muted-color);padding:4px;">${connected}</td>`;
html += `<td class="tblCol tblColRight" style="border:0.1px solid var(--muted-color);padding:4px;">${servingCount}</td>`;
html += `<td class="tblCol tblColLeft" style="border:0.1px solid var(--muted-color);padding:4px;font-family:monospace;word-break:break-all;">${followsList}</td>`;
html += '</tr>';
}
html += '</tbody></table>';
container.innerHTML = html;
};
const refreshDiscoveredRelays = async () => {
try {
const relays = await getDiscoveredRelays();
renderDiscoveredRelays(Array.isArray(relays) ? relays : []);
} catch (error) {
console.warn('[relays.html] Failed to fetch discovered relays:', error?.message || error);
renderDiscoveredRelays([]);
}
};
const initDiscoveredRelaysToggle = () => {
const title = document.getElementById('divDiscoveredRelaysTitle');
if (!title) return;
title.addEventListener('click', () => {
discoveredRelaysExpanded = !discoveredRelaysExpanded;
refreshDiscoveredRelays();
});
};
const refreshRelayData = async () => {
console.log('[relay2.html] Refreshing relay data...');
try {
@@ -1490,6 +1582,9 @@ const versionInfo = await getVersion();
await loadCurrentDmInboxRelayList();
// Initialize discovered relays (outbox) collapsible toggle
initDiscoveredRelaysToggle();
// Get initial relay data
await refreshRelayData();
@@ -1502,6 +1597,9 @@ const versionInfo = await getVersion();
// Refresh relay table every 5 seconds
setInterval(refreshRelayData, 5000);
// Discovered relays are fetched only on manual expand click — no
// auto-refresh interval, to avoid blocking the worker's message queue.
// Sync connection history toggle state from localStorage
connectionHistoryEnabled = localStorage.getItem('relayConnectionHistory') === 'true';
setRelayEventLogging(connectionHistoryEnabled);