Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/admin-probe-panel-refusals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

fix(admin): surface network probe refusal messages and invalid targets (#1323)
82 changes: 82 additions & 0 deletions crates/nostream-admin/tests/console_parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,3 +470,85 @@ fn a_missing_console_file_is_a_failure() {
assert!(!assets_dir().join(missing).exists());
let _ = ADMIN_BASE;
}

/// Every refusal from `POST /admin/network-health/run` (`409`, `400` + `invalid`, `502`, or a
/// non-JSON fallback) renders its message in the probe panel's sync line and empty state, and
/// the empty state never tells an operator to enable monitoring that may already be on (#1323).
#[test]
fn the_probe_panel_renders_each_refusal() {
let html = std::fs::read_to_string(dashboard_html()).expect("dashboard.html");
let empty_at = html
.find("id=\"network-health-empty\"")
.expect("network-health-empty element");
let empty_end = html[empty_at..].find("</div>").expect("closing </div>") + empty_at;
assert!(
!html[empty_at..empty_end].contains("Enable NIP-66"),
"empty state must not advise enabling monitoring: {}",
&html[empty_at..empty_end]
);

let script = r#"
const fs = require('fs');
class El {
constructor(tag) {
this.tagName = tag.toUpperCase();
this.children = [];
this.dataset = {};
this.listeners = {};
this.classList = { set: new Set(), add(c){this.set.add(c)}, remove(c){this.set.delete(c)}, contains(c){return this.set.has(c)}, toggle(){} };
this.id = ''; this.textContent = ''; this.disabled = false; this.value = ''; this.style = {};
}
set innerHTML(_) { throw new Error('innerHTML must not be used on network-health-sync'); }
replaceChildren(...nodes) { this.children = nodes; this.textContent = nodes.map((n) => n.textContent).join(''); }
addEventListener(ev, fn) { (this.listeners[ev] ||= []).push(fn); }
setAttribute() {} appendChild() {} querySelector() { return new El('div'); } querySelectorAll() { return []; }
}
const sync = new El('p');
const empty = new El('div');
const runBtn = new El('button');
const byId = { 'network-health-sync': sync, 'network-health-empty': empty, 'network-health-run-button': runBtn };
global.document = {
getElementById: (id) => (byId[id] ||= new El('div')),
createElement: (tag) => new El(tag),
createTextNode: (t) => ({ textContent: String(t) }),
querySelector: () => new El('div'), querySelectorAll: () => [], addEventListener() {}, body: new El('body'),
};
global.window = { __ADMIN_DASHBOARD__: { pathPrefix: '' }, addEventListener() {}, matchMedia: () => ({ matches: false, addEventListener() {} }), location: { search: '', pathname: '/admin/' } };
global.setInterval = () => 0; global.clearInterval = () => {}; global.EventSource = class { close() {} };
let nextRunResponse;
global.fetch = async (url) => String(url).endsWith('/session')
? { status: 200, ok: true, json: async () => ({ authenticated: false }) }
: nextRunResponse();
eval(fs.readFileSync(process.argv[1], 'utf8'));
const flush = () => new Promise((r) => setTimeout(r, 15));
const assertEq = (a, b) => { if (a !== b) throw new Error(`expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}`); };
(async () => {
const cases = [
[() => ({ status: 409, ok: false, json: async () => ({ error: 'NIP-66 monitoring is disabled' }) }), 'NIP-66 monitoring is disabled'],
[() => ({ status: 400, ok: false, json: async () => ({ error: 'No valid probe targets configured', invalid: ['not-a-relay', 'http://bad'] }) }), 'No valid probe targets configured (not-a-relay, http://bad)'],
[() => ({ status: 400, ok: false, json: async () => ({ error: 'No valid probe targets configured', invalid: [] }) }), 'No valid probe targets configured'],
[() => ({ status: 502, ok: false, json: async () => ({ error: 'Probe run produced no results' }) }), 'Probe run produced no results'],
[() => ({ status: 500, ok: false, json: async () => { throw new SyntaxError('bad json'); } }), 'manual probe failed (500)'],
];
for (const [resp, expected] of cases) {
nextRunResponse = resp;
runBtn.listeners.click[0]();
await flush();
assertEq(empty.textContent, expected);
assertEq(sync.textContent, `> probes: ${expected}`);
}
})().catch((err) => { console.error(err); process.exit(1); });
"#;
let output = std::process::Command::new("node")
.arg("-e")
.arg(script)
.arg(assets_dir().join("dashboard.js"))
.output()
.expect("run node probe panel harness");
assert!(
output.status.success(),
"node probe panel harness failed:\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
22 changes: 20 additions & 2 deletions resources/admin/assets/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,10 @@
return
}

networkHealthSync.innerHTML = `<span class="prompt-char">&gt;</span> probes: ${message}`
const prompt = document.createElement('span')
prompt.className = 'prompt-char'
prompt.textContent = '>'
networkHealthSync.replaceChildren(prompt, document.createTextNode(` probes: ${message}`))
}

const probeCheckStatusClass = (status, options = {}) => {
Expand Down Expand Up @@ -758,10 +761,25 @@
}

if (!response.ok) {
setNetworkHealthSyncLine('manual probe failed')
const payload = await response.json().catch(() => null)
const invalid = Array.isArray(payload?.invalid)
? payload.invalid.map((item) => String(item).trim()).filter(Boolean)
: []
const detail = invalid.length > 0 ? ` (${invalid.join(', ')})` : ''
const reason =
typeof payload?.error === 'string' && payload.error.trim()
? `${payload.error.trim()}${detail}`
: `manual probe failed (${response.status})`
setNetworkHealthSyncLine(reason)
if (networkHealthEmpty) {
networkHealthEmpty.textContent = reason
}
return
}

if (networkHealthEmpty) {
networkHealthEmpty.textContent = 'No external probe results yet.'
}
networkHealthHistoryPinned = false
selectedNetworkHealthRunAt = null
await refreshNetworkHealth()
Expand Down
2 changes: 1 addition & 1 deletion resources/admin/dashboard.html
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ <h2 class="section-title mb-0">Tor / I2P &amp; network probes</h2>
<button id="network-health-run-button" type="button" class="btn btn-console btn-sm" title="Run NIP-66 probe now">Run probe now</button>
</div>
<p id="network-health-sync" class="sync-line mb-3"><span class="prompt-char">&gt;</span> probes: waiting for snapshot…</p>
<div id="network-health-empty" class="panel-card admin-muted small">No external probe results yet. Enable NIP-66 relay monitoring to populate this panel.</div>
<div id="network-health-empty" class="panel-card admin-muted small">No external probe results yet.</div>
<div id="network-health-timeline-wrap" class="mb-3 d-none">
<p class="metric-label mb-2"><span class="module-code">HIST</span> Recent probe runs</p>
<div id="network-health-timeline" class="network-health-timeline" role="list" aria-label="Recent probe runs"></div>
Expand Down
Loading