AtlatestRepositorysigil-http3
sigil-http3 / tree / webphone.html
1
<!doctype html>2
<html lang="en">3
<meta charset="utf-8">4
<meta name="viewport" content="width=device-width, initial-scale=1">5
<title>Sigil network switch test</title>6
<link rel="icon" href="data:,">7
<style>8
:root { color-scheme: light dark; font: 16px system-ui, sans-serif; }9
body { max-width: 48rem; margin: auto; padding: 1rem; }10
h1 { font-size: 1.5rem; }11
label { display: block; margin: .8rem 0; }12
input[type=url], input[type=text] { box-sizing: border-box; width: 100%; padding: .65rem; font: inherit; }13
button { padding: .7rem; margin: .25rem; font: inherit; }14
dl { display: grid; grid-template-columns: 1fr 1fr; gap: .5rem; }15
dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }16
#state { font-weight: bold; }17
#network-banner { padding: 1rem; border: 3px solid currentColor; font-size: 1.25rem; font-weight: bold; }18
#network-banner[data-online="false"] { color: #c43c35; }19
pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 20rem; overflow: auto; font-size: .8rem; }20
.hint { opacity: .8; }21
canvas { display: block; width: 100%; height: 200px; border: 1px solid #888; border-radius: .4rem; }22
.stream-key { color: #278fe8; } .datagram-key { color: #d88b21; }23
</style>24
<h1>Sigil network switch test</h1>25
<p>For the public punch test, load this page fresh on cellular with Wi-Fi and VPN off. Confirm ONLINE and cellular below, start chrome://net-export, then follow the operator's control-first instructions. Keep the page visible.</p>26
<p id="network-banner" role="status" aria-live="polite">Checking browser network state…</p>27
<p class="hint">Connect is disabled while the browser reports offline. ONLINE is a browser hint, not proof that the target is reachable. Priming starts only on the control confirmation.</p>28
<p class="hint">Reconnect is manual. A surviving browser session needs matching server path and connection-ID logs to establish migration. WireGuard may hide the physical network switch from QUIC.</p>29
<form id="configuration">30
<label>WebTransport URL <input id="url" type="url" placeholder="https://test-address:port/echo" required></label>31
<label>Certificate SHA-256 (64 hex digits) <input id="hash" type="text" autocomplete="off" spellcheck="false" required></label>32
<label><input id="datagrams" type="checkbox" checked> Also send datagram pings</label>33
<button id="connect" type="submit">Connect</button>34
<button id="stop" type="button" disabled>Stop</button>35
<button id="mark" type="button">Mark network switch</button>36
<button id="uni" type="button" disabled>Test unidirectional echo</button>37
<button id="download" type="button">Save log</button>38
</form>39
<p>Configured target: <output id="target">Not configured</output></p>40
<dl aria-live="polite">41
<dt>Session state</dt><dd id="state">idle</dd>42
<dt>Connect attempts / reconnect attempts</dt><dd id="attempts">0 / 0</dd>43
<dt>Sessions opened / reopened</dt><dd id="sessions">0 / 0</dd>44
<dt>Stream echoes / sent</dt><dd id="stream">0 / 0</dd>45
<dt>Stream RTT / highest RTT</dt><dd id="rtt">—</dd>46
<dt>Time since last stream echo</dt><dd id="silence">—</dd>47
<dt>Longest stream echo gap</dt><dd id="gap">—</dd>48
<dt>Datagram echoes / sent</dt><dd id="datagram">0 / 0</dd>49
<dt>Datagram RTT</dt><dd id="datagram-rtt">—</dd>50
<dt>Unidirectional echoes / sent</dt><dd id="unidirectional">0 / 0</dd>51
<dt>Pending / expired pings</dt><dd id="pending">0 / 0</dd>52
<dt>Browser network hint</dt><dd id="network">—</dd>53
</dl>54
<p><strong>Live round-trip time</strong> · <span class="stream-key">Stream</span> · <span class="datagram-key">Datagram</span></p>55
<canvas id="rtt-graph" width="720" height="200" role="img" aria-label="Round-trip time over the last 60 seconds. Empty gaps mean no echo sample.">Live RTT graph; numeric RTTs are shown above.</canvas>56
<p id="graph-summary" class="hint">Waiting for echo samples. Network-switch marks appear as dashed lines.</p>57
<p><strong>Server path observations</strong></p>58
<p id="path-status" aria-live="polite">Waiting for authenticated server observations.</p>59
<pre id="path-log" aria-label="Server path and connection-ID events"></pre>60
<p class="hint">Server observations describe the path QUIC sees. Browser network hints below do not establish migration.</p>61
<p id="support" class="hint"></p>62
<pre id="log" aria-label="Session event log"></pre>63
<script>64
'use strict';65
(() => {66
const element = id => document.getElementById(id);67
const encoderKinds = { stream: 0x62, unidirectional: 0x75, datagram: 0x64 };68
const entries = [];69
const baseline = performance.now();70
const stats = { attempts: 0, sessions: 0 };71
let active = null;72
let sequence = 0;73
let pendingConnect = false;74
const options = new URLSearchParams(location.hash.slice(1));75
element('url').value = options.get('url') ?? '';76
element('hash').value = options.get('hash') ?? '';77
if (options.get('datagrams') === '0') element('datagrams').checked = false;78
const query = new URLSearchParams(location.search);79
let queryError;80
const queryTarget = ['host', 'port', 'hash'].some(name => query.has(name));81
if (queryTarget) {82
// A partial or ambiguous query never falls back to fragment credentials.83
element('url').value = '';84
element('hash').value = '';85
try {86
if (!['host', 'port', 'hash'].every(name => query.getAll(name).length === 1))87
throw new Error('Supply exactly one host, port and hash query parameter');88
const host = query.get('host');89
const port = query.get('port');90
const hash = query.get('hash');91
if (!/^[0-9]{1,5}$/.test(port) || String(Number(port)) !== port || Number(port) < 1 || Number(port) > 65535)92
throw new Error('Target port must be an integer from 1 to 65535');93
if (hash.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(hash))94
throw new Error('Certificate SHA-256 must be 64 hex digits');95
if (!host || host.length > 253) throw new Error('Invalid target host');96
let authorityHost = host;97
if (host.includes(':')) {98
const literal = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;99
if (!literal || /[^0-9a-fA-F:.]/.test(literal)) throw new Error('Invalid IPv6 target');100
authorityHost = `[${literal}]`;101
} else if (/[^a-zA-Z0-9.-]/.test(host) || !host.split('.').every(label =>102
/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(label))) {103
throw new Error('Invalid target host');104
}105
// URL parses IPv6 syntax; the allowlist above rejects credentials,106
// zone identifiers, paths, query/fragment delimiters and HTML characters.107
const target = new URL(`https://${authorityHost}:${Number(port)}/echo`);108
if (!host.includes(':') && target.hostname !== host.toLowerCase())109
throw new Error('Use a canonical hostname or IPv4 address');110
if (query.getAll('autoconnect').length > 1 ||111
(query.has('autoconnect') && !['0', '1'].includes(query.get('autoconnect'))))112
throw new Error('Autoconnect must be 0 or 1');113
element('url').value = target.href;114
element('hash').value = hash.toLowerCase();115
} catch (error) { queryError = error; }116
}117
element('target').textContent = element('url').value || 'Not configured';119
function event(kind, details = {}) {120
const entry = { utc: new Date().toISOString(), elapsedMs: +(performance.now() - baseline).toFixed(1), kind, ...details };121
entries.push(entry);122
if (entries.length > 2000) entries.shift();123
element('log').textContent = entries.slice(-80).map(item => JSON.stringify(item)).join('\n');124
return entry;125
}126
function state(value) { element('state').textContent = value; }127
function reportPage(kind, started, details = {}) {128
window.__result = { kind, milliseconds: performance.now() - started,129
secureContext: isSecureContext, userAgent: navigator.userAgent, ...details };130
}131
function network(change) {132
const hint = { online: navigator.onLine, effectiveType: navigator.connection?.effectiveType ?? 'unknown',133
type: navigator.connection?.type ?? 'unknown', rtt: navigator.connection?.rtt ?? null,134
downlink: navigator.connection?.downlink ?? null, saveData: navigator.connection?.saveData ?? null,135
visibility: document.visibilityState, source: change?.type ?? 'initial' };136
element('network').textContent = JSON.stringify(hint);137
element('network-banner').textContent = `${hint.online ? 'ONLINE' : 'OFFLINE'} · connection: ${hint.type} · ${hint.effectiveType}`;138
element('network-banner').dataset.online = String(hint.online);139
event('browser-network-hint', hint);140
controls();141
}142
function usable(run) { return active === run && !run.ended; }143
function drawGraph(run) {144
const canvas = element('rtt-graph');145
const ctx = canvas.getContext('2d');146
if (!ctx) return;147
const cssWidth = Math.max(240, Math.round(canvas.clientWidth));148
const ratio = Math.min(window.devicePixelRatio || 1, 2);149
if (canvas.width !== Math.round(cssWidth * ratio) || canvas.height !== Math.round(200 * ratio)) {150
canvas.width = Math.round(cssWidth * ratio); canvas.height = Math.round(200 * ratio);151
}152
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);153
const now = run.ended ? run.endedAt : performance.now();154
const from = now - 60000;155
run.samples = run.samples.filter(point => point.time >= from).slice(-512);156
run.marks = run.marks.filter(point => point.time >= from).slice(-32);157
const left = 48, top = 18, width = cssWidth - 66, height = 148;158
const maximum = Math.max(25, ...run.samples.map(point => point.rtt));159
const scale = Math.ceil(maximum / 25) * 25;160
const x = time => left + (time - from) / 60000 * width;161
const y = rtt => top + height - rtt / scale * height;162
ctx.clearRect(0, 0, cssWidth, 200);163
ctx.fillStyle = '#888'; ctx.strokeStyle = '#8888'; ctx.font = '12px system-ui'; ctx.lineWidth = 1;164
for (let index = 0; index <= 2; index++) {165
const value = scale * index / 2;166
ctx.fillText(`${Math.round(value)}`, 3, y(value) + 4);167
ctx.beginPath(); ctx.moveTo(left, y(value)); ctx.lineTo(left + width, y(value)); ctx.stroke();168
}169
ctx.fillText('ms', 4, 12); ctx.fillText('60 seconds ago', left, 190);170
ctx.fillText(run.ended ? 'ended' : 'now', left + width - 36, 190);171
for (const [kind, color] of [['stream', '#278fe8'], ['datagram', '#d88b21']]) {172
const points = run.samples.filter(point => point.kind === kind);173
canvas.dataset[`${kind}Points`] = String(points.length);174
ctx.strokeStyle = color; ctx.fillStyle = color; ctx.lineWidth = 2;175
ctx.beginPath();176
let previous;177
for (const point of points) {178
if (!previous || point.time - previous.time > 750) ctx.moveTo(x(point.time), y(point.rtt));179
else ctx.lineTo(x(point.time), y(point.rtt));180
previous = point;181
}182
ctx.stroke();183
for (const point of points) {184
ctx.beginPath(); ctx.arc(x(point.time), y(point.rtt), 2, 0, Math.PI * 2); ctx.fill();185
}186
}187
ctx.strokeStyle = '#a962cc'; ctx.lineWidth = 1; ctx.setLineDash([4, 4]);188
for (const mark of run.marks) {189
ctx.beginPath(); ctx.moveTo(x(mark.time), top); ctx.lineTo(x(mark.time), top + height); ctx.stroke();190
}191
ctx.setLineDash([]);192
element('graph-summary').textContent = `Last 60 seconds: ${canvas.dataset.streamPoints} stream / ${canvas.dataset.datagramPoints} datagram samples. Gaps are left blank. ${run.ended ? 'Stopped.' : 'Live.'}`;193
}194
function controls() {195
const busy = pendingConnect || (active && !active.ended);196
element('connect').disabled = !!busy || !navigator.onLine || !!queryError;197
element('stop').disabled = !busy;198
element('uni').disabled = !(active?.ready && !active.ended);199
for (const id of ['url', 'hash', 'datagrams']) element(id).disabled = !!busy;200
}201
function render() {202
element('attempts').textContent = `${stats.attempts} / ${Math.max(0, stats.attempts - 1)}`;203
element('sessions').textContent = `${stats.sessions} / ${Math.max(0, stats.sessions - 1)}`;204
if (!active) return;205
const now = performance.now();206
for (const [id, ping] of active.pending) {207
if (now - ping.sent > 30000) { active.pending.delete(id); active.expired++; }208
}209
for (const kind of Object.keys(encoderKinds)) {210
element(kind).textContent = `${active.received[kind]} / ${active.sent[kind]}`;211
}212
element('rtt').textContent = active.rtt === null ? '—' : `${active.rtt.toFixed(1)} / ${active.maxRtt.toFixed(1)} ms`;213
element('datagram-rtt').textContent = active.datagramRtt === null ? '—' : `${active.datagramRtt.toFixed(1)} ms`;214
const silence = !active.ready ? null : (active.ended ? active.endedAt : now) - (active.lastEcho ?? active.opened);215
element('silence').textContent = silence === null ? '—' : `${silence.toFixed(0)} ms`;216
element('gap').textContent = `${Math.max(active.maxGap, silence ?? 0).toFixed(0)} ms`;217
element('pending').textContent = `${active.pending.size} / ${active.expired}`;218
drawGraph(active);219
}220
function finish(run, kind, detail) {221
if (!usable(run)) return;222
run.ended = true;223
run.endedAt = performance.now();224
clearInterval(run.timer);225
clearTimeout(run.readyTimer);226
event(kind, { attempt: run.attempt, detail });227
state(kind);228
controls();229
render();230
}231
function failed(run, error) {232
event('webtransport-error', { attempt: run.attempt, error: errorDetails(error) });233
if (!usable(run)) return;234
const detail = `${error.name}: ${error.message}`;235
if (!run.ready) reportPage('failed', run.started, { name: error.name, message: error.message });236
finish(run, 'failed', detail);237
run.transport.close();238
}239
function errorDetails(error) {240
return { name: error?.name ?? null, message: String(error?.message ?? error).slice(0, 1024),241
source: error?.source ?? null, streamErrorCode: error?.streamErrorCode ?? null,242
closeCode: error?.closeCode ?? null, reason: error?.reason ?? null };243
}244
function packet(run, kind) {245
if (run.pending.size >= 128) { event('ping-skipped', { reason: 'pending limit', channel: kind }); return null; }246
const id = ++sequence;247
const bytes = new Uint8Array(16);248
bytes.set([0x53, 0x47, 0x48, encoderKinds[kind]]);249
const view = new DataView(bytes.buffer);250
view.setUint32(4, id);251
view.setFloat64(8, performance.now());252
run.pending.set(id, { bytes, sent: performance.now(), kind });253
run.sent[kind]++;254
return bytes;255
}256
function echoed(run, bytes, kind) {257
if (!usable(run)) return;258
if (bytes.length !== 16 || bytes[0] !== 0x53 || bytes[1] !== 0x47 || bytes[2] !== 0x48 || bytes[3] !== encoderKinds[kind]) {259
throw new Error(`Invalid ${kind} echo frame`);260
}261
const id = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(4);262
const ping = run.pending.get(id);263
if (!ping) { event('late-or-duplicate-echo', { channel: kind, id }); return; }264
if (ping.kind !== kind || !bytes.every((octet, index) => octet === ping.bytes[index])) throw new Error('Echo bytes differ');265
run.pending.delete(id);266
run.received[kind]++;267
const now = performance.now();268
const rtt = now - ping.sent;269
if (kind !== 'unidirectional') {270
run.samples.push({ time: now, rtt, kind });271
if (run.samples.length > 512) run.samples.shift();272
}273
if (kind === 'stream') {274
run.maxGap = Math.max(run.maxGap, now - (run.lastEcho ?? run.opened));275
run.lastEcho = now;276
run.rtt = rtt;277
run.maxRtt = Math.max(run.maxRtt, rtt);278
} else if (kind === 'datagram') run.datagramRtt = rtt;279
event('echo', { attempt: run.attempt, channel: kind, id, rttMs: +rtt.toFixed(1) });280
render();281
}282
function serverObservation(run, bytes) {283
if (++run.observationCount > 4096) throw new Error('Server observation lifetime budget exceeded');284
const record = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));285
const types = ['observation', 'peer', 'path-change', 'path-validated', 'path-rejected', 'cid-change'];286
if (!record || !types.includes(record.type) || !Number.isSafeInteger(record.seq) ||287
record.seq <= run.observationSequence || typeof record.serverTime !== 'string' || record.serverTime.length > 96)288
throw new Error('Invalid server observation record');289
const fields = ['peer', 'before', 'after', 'localCid', 'peerCid', 'status', 'detail'];290
if (Object.keys(record).some(key => !['type', 'seq', 'serverTime', ...fields].includes(key)) ||291
fields.some(key => key in record && (typeof record[key] !== 'string' || record[key].length > 256)))292
throw new Error('Invalid server observation fields');293
if ((record.type === 'path-change' && (!record.before || !record.after)) ||294
(['peer', 'path-validated', 'path-rejected'].includes(record.type) && !record.peer) ||295
(record.type === 'cid-change' && (!('localCid' in record) || !('peerCid' in record))) ||296
(record.type === 'observation' && !['available', 'unavailable'].includes(record.status)))297
throw new Error('Incomplete server observation');298
run.observationSequence = record.seq;299
run.observations.push(record);300
if (run.observations.length > 128) run.observations.shift();301
if (record.type === 'path-change') run.pathChanges++;302
if (record.type === 'cid-change') run.cidChanges++;303
element('path-status').textContent = record.status === 'unavailable'304
? `Server observation unavailable: ${record.detail ?? 'not supplied'}.`305
: `${run.pathChanges} path changes / ${run.cidChanges} CID changes. Latest: ${record.type}${record.peer ? ` ${record.peer}` : ''}.`;306
element('path-log').textContent = run.observations.slice(-20).map(item => JSON.stringify(item)).join('\n');307
event('server-observation', { attempt: run.attempt, observation: record });308
}309
async function receive(run, readable, kind, datagram = false, classifyUni = false) {310
const reader = readable.getReader();311
let remainder = new Uint8Array();312
let telemetry = false;313
try {314
while (usable(run)) {315
const { value, done } = await reader.read();316
if (!usable(run)) return;317
if (done) {318
if (remainder.length) throw new Error('Truncated echo frame');319
if (kind === 'stream' && usable(run)) throw new Error('Ping stream ended');320
if (telemetry) {321
element('path-status').textContent += ' Server observation updates ended.';322
event('server-observation-end', { attempt: run.attempt });323
}324
return;325
}326
if (value.length > 65536) throw new Error('Echo read exceeds limit');327
if (datagram) { echoed(run, value, kind); continue; }328
const joined = new Uint8Array(remainder.length + value.length);329
joined.set(remainder); joined.set(value, remainder.length);330
let offset = 0;331
if (classifyUni) {332
if (joined.length < 4) { remainder = joined; continue; }333
telemetry = joined[0] === 0x53 && joined[1] === 0x47 && joined[2] === 0x45 && joined[3] === 0x31;334
if (telemetry) {335
if (run.observationStream) throw new Error('Duplicate server observation stream');336
run.observationStream = true; offset = 4;337
}338
classifyUni = false;339
}340
if (telemetry) {341
let records = 0;342
while (offset + 2 <= joined.length) {343
const size = joined[offset] * 256 + joined[offset + 1];344
if (size < 1 || size > 1024) throw new Error('Server observation frame exceeds limit');345
if (offset + 2 + size > joined.length) break;346
if (++records > 64) throw new Error('Server observation read budget exceeded');347
serverObservation(run, joined.subarray(offset + 2, offset + 2 + size));348
offset += 2 + size;349
}350
} else {351
while (offset + 16 <= joined.length) { echoed(run, joined.subarray(offset, offset + 16), kind); offset += 16; }352
}353
remainder = joined.slice(offset);354
}355
} finally { reader.releaseLock(); }356
}357
async function incomingUni(run) {358
const reader = run.transport.incomingUnidirectionalStreams.getReader();359
let count = 0;360
try {361
while (usable(run)) {362
const { value, done } = await reader.read();363
if (!usable(run)) return;364
if (done) return;365
if (++count > 16) throw new Error('Unidirectional echo stream limit exceeded');366
receive(run, value, 'unidirectional', false, true).catch(error => failed(run, error));367
}368
} finally { reader.releaseLock(); }369
}370
async function writePing(run, writer, kind) {371
const key = `${kind}Writing`;372
if (!usable(run) || run[key]) return;373
run[key] = true;374
try {375
const bytes = packet(run, kind);376
if (bytes) await writer.write(bytes);377
} catch (error) { failed(run, error); }378
finally { run[key] = false; }379
}380
async function connect() {381
if (pendingConnect || (active && !active.ended)) return;382
const started = performance.now();383
try {384
network({ type: 'before-connect' });385
if (!navigator.onLine) throw new Error('Browser reports offline; wait for ONLINE before Connect');386
if (queryError) throw queryError;387
if (!isSecureContext) throw new Error('Open this page over HTTPS or as a trusted local file');388
if (!('WebTransport' in window)) throw new Error('This browser does not expose WebTransport');389
const url = new URL(element('url').value);390
if (url.protocol !== 'https:' || url.hash || url.username || url.password) throw new Error('Use an HTTPS URL without credentials or a fragment');391
const hash = element('hash').value;392
if (hash.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(hash)) throw new Error('Certificate SHA-256 must be 64 hex digits');393
element('target').textContent = url.href;394
pendingConnect = true;395
const transport = new WebTransport(url.href, { serverCertificateHashes: [{ algorithm: 'sha-256',396
value: Uint8Array.from(hash.match(/../g), byte => parseInt(byte, 16)) }] });397
const run = { transport, started, attempt: ++stats.attempts, ready: false, ended: false,398
pending: new Map(), expired: 0, sent: { stream: 0, datagram: 0, unidirectional: 0 },399
received: { stream: 0, datagram: 0, unidirectional: 0 }, rtt: null, maxRtt: 0,400
maxGap: 0, lastEcho: null, datagramRtt: null, opened: started,401
samples: [], marks: [], observations: [], observationSequence: -1,402
observationStream: false, observationCount: 0, pathChanges: 0, cidChanges: 0 };403
active = run;404
element('path-status').textContent = 'Waiting for authenticated server observations.';405
element('path-log').textContent = '';406
state('connecting'); controls(); render();407
event('connect-attempt', { attempt: run.attempt, url: url.href, hash: hash.toLowerCase(), datagrams: element('datagrams').checked });408
transport.closed.then(info => {409
const detail = { closeCode: info?.closeCode ?? null, reason: info?.reason ?? null };410
event('webtransport-closed', { attempt: run.attempt, ...detail });411
finish(run, 'closed', detail);412
}, error => {413
event('webtransport-closed-rejected', { attempt: run.attempt, error: errorDetails(error) });414
failed(run, error);415
});416
run.readyTimer = setTimeout(() => failed(run, new Error('Session ready deadline (18 seconds)')), 18000);417
await transport.ready;418
if (!usable(run)) return;419
clearTimeout(run.readyTimer);420
run.ready = true; run.opened = performance.now(); stats.sessions++;421
reportPage('ready', started);422
state('open'); controls(); render();423
event('session-open', { attempt: run.attempt, session: stats.sessions });424
incomingUni(run).catch(error => failed(run, error));425
const stream = await transport.createBidirectionalStream();426
if (!usable(run)) return;427
run.writer = stream.writable.getWriter();428
receive(run, stream.readable, 'stream').catch(error => failed(run, error));429
if (element('datagrams').checked) {430
run.datagramWriter = transport.datagrams.writable.getWriter();431
receive(run, transport.datagrams.readable, 'datagram', true).catch(error => failed(run, error));432
}433
const ping = () => {434
void writePing(run, run.writer, 'stream');435
if (run.datagramWriter) void writePing(run, run.datagramWriter, 'datagram');436
};437
run.timer = setInterval(ping, 250);438
ping();439
} catch (error) {440
if (active && !active.ended && active.started === started) failed(active, error);441
else if (!active || active.started !== started) {442
state('failed'); event('configuration-error', { detail: String(error) });443
reportPage('failed', started, { name: error.name, message: error.message });444
}445
} finally { pendingConnect = false; controls(); }446
}447
element('configuration').addEventListener('submit', event => { event.preventDefault(); void connect(); });448
element('stop').addEventListener('click', () => {449
if (!active || active.ended) return;450
finish(active, 'stopped', 'user requested');451
active.transport.close({ closeCode: 0, reason: 'Phone test stopped' });452
});453
element('uni').addEventListener('click', async () => {454
const run = active;455
if (!run?.ready || !usable(run) || run.uniWriting) return;456
run.uniWriting = true;457
try {458
if (run.sent.unidirectional >= 8) throw new Error('Eight unidirectional probes used; reconnect to reset the bounded test');459
const writable = await run.transport.createUnidirectionalStream();460
if (!usable(run)) return;461
const writer = writable.getWriter();462
const bytes = packet(run, 'unidirectional');463
if (bytes) await writer.write(bytes);464
await writer.close();465
writer.releaseLock();466
} catch (error) { failed(run, error); }467
finally { run.uniWriting = false; }468
});469
element('mark').addEventListener('click', () => {470
event('network-switch-mark', { attempt: active?.attempt ?? null });471
if (active && !active.ended) {472
active.marks.push({ time: performance.now() });473
if (active.marks.length > 32) active.marks.shift();474
render();475
}476
});477
element('download').addEventListener('click', () => {478
render();479
const snapshot = { capturedAt: new Date().toISOString(), userAgent: navigator.userAgent, secureContext: isSecureContext,480
stats, state: element('state').textContent, events: entries,481
session: active ? { attempt: active.attempt, sent: active.sent, received: active.received,482
rttMs: active.rtt, maxRttMs: active.maxRtt,483
maxEchoGapMs: Math.max(active.maxGap, active.ready ? (active.ended ? active.endedAt : performance.now()) - (active.lastEcho ?? active.opened) : 0),484
expired: active.expired, rttSamples: active.samples, serverObservations: active.observations,485
pathChanges: active.pathChanges, cidChanges: active.cidChanges } : null };486
const url = URL.createObjectURL(new Blob([JSON.stringify(snapshot, null, 2)], { type: 'application/json' }));487
const link = document.createElement('a'); link.href = url; link.download = `sigil-phone-${Date.now()}.json`; link.click();488
setTimeout(() => URL.revokeObjectURL(url), 1000);489
});490
for (const name of ['online', 'offline']) window.addEventListener(name, network);491
navigator.connection?.addEventListener('change', network);492
document.addEventListener('visibilitychange', network);493
element('support').textContent = `Secure context: ${isSecureContext}; WebTransport: ${'WebTransport' in window}. No automatic reconnect.`;494
network();495
setInterval(render, 250);496
if (queryError) {497
state('failed');498
event('configuration-error', { detail: queryError.message });499
reportPage('failed', baseline, { name: queryError.name, message: queryError.message });500
} else if ((queryTarget ? query.get('autoconnect') : options.get('autoconnect')) === '1') void connect();501
})();502
</script>503
</html>