Files
ukmesh/frontend/test/e2e/feed-virtualizer.spec.ts

414 lines
23 KiB
TypeScript

import { writeFile } from 'node:fs/promises';
import { expect, test, type Page } from '@playwright/test';
import { installMapRoutes, installTerrainRoutes } from './mapFixtures.js';
// Keep renderer/detail faults under page routing; cache cutover has its own lane.
test.use({ serviceWorkers: 'block' });
// Capture numerical geometry only, after a failure so observation cannot change
// scroll scheduling. Keep page content and network traffic out of CI artifacts.
test.afterEach(async ({ page }, testInfo) => {
if (testInfo.status === testInfo.expectedStatus || page.isClosed()) return;
const geometry = await page.evaluate(() => {
const list = document.querySelector<HTMLElement>('.uk-feed-packets-list');
const rows = list?.querySelectorAll('article');
function box(element: Element | null | undefined) {
if (!element) return null;
const { top, bottom, height } = element.getBoundingClientRect();
return { top, bottom, height };
}
return {
viewport: { width: innerWidth, height: innerHeight },
document: { scrollY, scrollHeight: document.scrollingElement?.scrollHeight },
list: list && {
...box(list), clientHeight: list.clientHeight, scrollHeight: list.scrollHeight,
scrollTop: list.scrollTop, scrollOwner: list.scrollHeight > list.clientHeight + 1 ? 'list' : 'document',
},
renderedRows: rows?.length ?? 0,
firstRow: box(rows?.[0]), lastRow: box(rows?.[rows.length - 1]),
topSpacer: box(list?.firstElementChild), bottomSpacer: box(list?.lastElementChild),
};
});
await writeFile(testInfo.outputPath('feed-geometry.json'), JSON.stringify(geometry, null, 2));
});
async function assertContiguous(page: Page) {
const geometry = await page.locator('.uk-feed-packets-list').evaluate(container => {
const rows = [...container.querySelectorAll('article')].map(row => row.getBoundingClientRect());
const top = (container.firstElementChild as HTMLElement).getBoundingClientRect();
const bottom = (container.lastElementChild as HTMLElement).getBoundingClientRect();
return { count: rows.length, gaps: rows.slice(1).map((row, i) => row.top - rows[i]!.bottom),
firstGap: rows[0]!.top - top.bottom, lastGap: bottom.top - rows.at(-1)!.bottom,
heights: rows.map(row => row.height) };
});
expect(geometry.count).toBeGreaterThan(1);
expect(geometry.count).toBeLessThan(50);
for (const gap of [...geometry.gaps, geometry.firstGap, geometry.lastGap]) expect(Math.abs(gap)).toBeLessThan(1);
// At wider breakpoints one additional metadata line is about 11.7px.
expect(Math.max(...geometry.heights) - Math.min(...geometry.heights)).toBeGreaterThan(10);
}
async function readAnchor(page: Page) {
return page.locator('.uk-feed-packets-list').evaluate(container => {
const internal = container.scrollHeight > container.clientHeight + 1;
const bounds = container.getBoundingClientRect();
const top = internal ? bounds.top : 0;
const bottom = internal ? Math.min(bounds.bottom, window.innerHeight) : window.innerHeight;
const row = [...container.querySelectorAll('article')].find(element => {
const rect = element.getBoundingClientRect();
return rect.bottom > top + 1 && rect.top < bottom;
});
return row ? { label: row.getAttribute('aria-label'), offset: row.getBoundingClientRect().top - top } : null;
});
}
async function anchor(page: Page): Promise<{ label: string | null; offset: number }> {
let current: Awaited<ReturnType<typeof readAnchor>> = null;
// Programmatic scrolling moves pixels before React commits its new row range.
// Require a visible row on the ordinary assertion deadline before capturing it.
await expect.poll(async () => {
current = await readAnchor(page);
return current !== null;
}).toBe(true);
return current!;
}
async function assertAnchor(page: Page, expected: Awaited<ReturnType<typeof anchor>>) {
// Browser scroll positions round fractional border-box offsets to pixels.
await expect.poll(async () => {
const current = await readAnchor(page);
return current !== null && current.label === expected.label && Math.abs(current.offset - expected.offset) < 1;
}).toBe(true);
}
async function scrollList(page: Page, position: number) {
await page.locator('.uk-feed-packets-list').evaluate((element, target) => {
if (element.scrollHeight > element.clientHeight + 1) element.scrollTop = target;
else window.scrollTo(0, window.scrollY + element.getBoundingClientRect().top + target);
}, position);
}
for (const width of [390, 1280]) {
test(`measured feed rows survive wrapping, enrichment, prepends and resize at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 800 });
const errors: string[] = [];
page.on('pageerror', error => {
errors.push(error.message);
console.error('[feed-virtualizer] page error:', error.message);
});
await page.route('**/api/**', route => {
const url = route.request().url();
return route.fulfill({ json: url.includes('runtime-config') ? { version: 1, packetArcs: false, heatmap: false, privacyGeneration: 1, refreshAfterSeconds: 30 }
: url.includes('/api/feed/regions') ? { network: 'ukmesh', observer: null, visibilityGeneration: 1, regions: ['ABC'] } : [] });
});
await page.addInitScript(() => {
localStorage.setItem('meshcore-cookie-consent-v1', '1');
const packets = Array.from({ length: 50 }, (_, index) => ({
packet_hash: index.toString(16).toUpperCase().padStart(64, 'A'),
time: new Date(Date.now() - index * 1000).toISOString(),
network: 'ukmesh', packet_type: 5, hop_count: index % 8,
observer_iatas: index % 3 === 0 ? Array.from({ length: 10 }, (_, i) => `REGION${i}`) : ['ABC'],
summary: `fixture ${index} ${'a wrapped message '.repeat(index % 3 === 0 ? 20 : 1)}${index === 0 ? '· MeshOS-signed' : ''}`,
}));
class FixtureWebSocket extends EventTarget {
static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3;
readyState = 0;
onopen: ((event: Event) => void) | null = null;
onmessage: ((event: MessageEvent) => void) | null = null;
send() {}
close() { this.readyState = 3; }
constructor() {
super();
let arrivals = 0;
const publish = () => this.onmessage?.(new MessageEvent('message', { data: JSON.stringify({
type: 'initial_state', data: { nodes: [], packets }, ts: Date.now(),
}) }));
Object.assign(window, {
enrichFeed: () => {
// Late observer enrichment changes the natural row height.
for (const packet of packets) packet.observer_iatas.push('EXTRA1', 'EXTRA2');
publish();
},
prependFeed: () => {
arrivals++;
packets.unshift({ ...packets[1]!, packet_hash: arrivals.toString(16).toUpperCase().padStart(64, 'F'),
time: new Date(Date.now() + arrivals * 1000).toISOString(), summary: `new arrival ${arrivals}` });
packets.pop();
publish();
},
});
setTimeout(() => { this.readyState = 1; this.onopen?.(new Event('open')); publish(); }, 0);
}
}
Object.defineProperty(window, 'WebSocket', { value: FixtureWebSocket, configurable: true });
});
await page.goto('/feed');
const list = page.locator('.uk-feed-packets-list');
// Initial code loading and runtime-config bootstrap can be cold in the
// full matrix. Keep the geometry checks on their normal assertion budget.
await expect(list.locator('article').first()).toBeVisible({ timeout: 15_000 });
await expect(list.locator('article').first().locator('.uk-feed-packet-row__summary'))
.toHaveText(/^fixture 0 .+ · MeshOS-signed$/);
await assertContiguous(page);
await scrollList(page, 1700);
await expect.poll(() => list.evaluate(element => element.scrollHeight > element.clientHeight + 1
? element.scrollTop : -element.getBoundingClientRect().top)).toBeGreaterThan(1600);
const beforeEnrichment = await anchor(page);
await page.evaluate(() => (window as unknown as { enrichFeed(): void }).enrichFeed());
await expect(list.locator('.uk-feed-packet-row__observer').first()).toContainText('EXTRA1');
await assertAnchor(page, beforeEnrichment);
await assertContiguous(page);
const beforePrepend = await anchor(page);
await page.evaluate(() => (window as unknown as { prependFeed(): void }).prependFeed());
await assertAnchor(page, beforePrepend);
// Filtering a desktop list until it no longer overflows must reset its
// own scroll position without scrolling the page past the search controls.
if (width === 1280) {
const pageScroll = await page.evaluate(() => window.scrollY);
await page.getByPlaceholder(/search/i).fill('new arrival');
await expect(list.locator('article')).toHaveCount(1);
await expect.poll(() => list.evaluate(element => element.scrollTop)).toBe(0);
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(pageScroll);
await page.getByPlaceholder(/search/i).fill('');
await expect(list.locator('article').first()).toBeVisible();
// Finish searching before capturing a browsing anchor across a resize.
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
await scrollList(page, 1700);
}
const beforeModeSwitch = await anchor(page);
const otherWidth = width === 390 ? 1280 : 390;
// Exercise both scroll owners after row heights and packet order change.
for (const nextWidth of [otherWidth, width, otherWidth]) {
await page.setViewportSize({ width: nextWidth, height: 650 });
await assertContiguous(page);
await expect.poll(async () => (await readAnchor(page))?.label).toBe(beforeModeSwitch.label);
}
await page.setViewportSize({ width: width === 390 ? 700 : 850, height: 650 });
await assertContiguous(page);
await scrollList(page, 100_000);
await expect.poll(() => list.locator('article').last().getAttribute('aria-label')).toContain('A30');
await expect.poll(() => list.locator('article').last().evaluate(element => element.getBoundingClientRect().bottom)).toBeLessThan(651);
await page.getByPlaceholder(/search/i).fill('new arrival');
await expect(list.locator('article')).toHaveCount(1);
await expect.poll(() => list.evaluate(element => element.scrollTop)).toBe(0);
// Empty filters must clear spacers, and restoring traffic must remount
// measured rows correctly in both internal and document scrolling modes.
await page.getByPlaceholder(/search/i).fill('no fixture matches this query');
await expect(list.locator('article')).toHaveCount(0);
await expect(list.locator('.dev-status-empty')).toBeVisible();
await page.getByPlaceholder(/search/i).fill('');
await expect(list.locator('article').first()).toBeVisible();
await assertContiguous(page);
await scrollList(page, 0);
await page.evaluate(() => (window as unknown as { prependFeed(): void }).prependFeed());
await expect(list.locator('article').first()).toHaveAttribute('aria-label', `Open packet ${'F'.repeat(63)}2`);
await expect(list.locator('article').first()).toBeVisible();
await expect.poll(() => list.evaluate(element => element.scrollHeight > element.clientHeight + 1
? element.scrollTop : -element.getBoundingClientRect().top)).toBeLessThan(1);
expect(errors).toEqual([]);
});
}
async function installQuietFeed(page: Page, deferSnapshot = false, capturedPath?: string[]) {
await installMapRoutes(page);
await installTerrainRoutes(page);
await page.route('**/api/**', route => {
const path = new URL(route.request().url()).pathname;
if (path === '/api/radio-stats' || (path.startsWith('/api/packets/') && path !== '/api/packets/recent')) {
return route.fulfill({ status: 404, json: { error: 'No retained details in the quiet-feed fixture' } });
}
return route.fulfill({ json: path === '/api/runtime-config'
? { version: 1, packetArcs: false, heatmap: false, regionScoping: true, privacyGeneration: 1, refreshAfterSeconds: 30 }
: path === '/api/feed/regions' ? { network: 'ukmesh', observer: null, visibilityGeneration: 1, regions: ['ABC'] } : [] });
});
await page.addInitScript(({ deferSnapshot, capturedPath }) => {
localStorage.setItem('meshcore-cookie-consent-v1', '1');
const count = { formats: 0 };
Object.assign(window, { feedFormatProbe: count });
const descriptor = Object.getOwnPropertyDescriptor(Intl.DateTimeFormat.prototype, 'format')!;
Object.defineProperty(Intl.DateTimeFormat.prototype, 'format', { ...descriptor, get() {
const format = descriptor.get!.call(this);
return (value: Date | number) => { count.formats++; return format(value); };
} });
const locale = Date.prototype.toLocaleString;
Date.prototype.toLocaleString = function (...args) { count.formats++; return locale.apply(this, args); };
const packets = Array.from({ length: 30 }, (_, i) => ({ packet_hash: i.toString(16).padStart(64, 'A'),
packet_type: deferSnapshot ? i % 5 + 1 : 5,
time: new Date(Date.now() - i * 1000 - (capturedPath ? 15_000 : 0)).toISOString(),
path_hashes: capturedPath, hop_count: capturedPath?.length,
observer_iatas: ['ABC'], summary: `[Public] Quiet feed fixture ${i}` }));
class FixtureWebSocket extends EventTarget {
static CONNECTING = 0; static OPEN = 1; static CLOSING = 2; static CLOSED = 3;
readyState = 0; onopen: ((event: Event) => void) | null = null; onmessage: ((event: MessageEvent) => void) | null = null;
send() {} close() { this.readyState = 3; }
constructor() {
super();
const publish = () => this.onmessage?.(new MessageEvent('message', { data: JSON.stringify({
type: 'initial_state', ts: Date.now(), data: { nodes: [], packets, messages: packets },
}) }));
if (deferSnapshot) Object.assign(window, { publishFeedSnapshot: publish });
setTimeout(() => {
this.readyState = 1;
this.onopen?.(new Event('open'));
if (!deferSnapshot) publish();
}, 0);
}
}
Object.defineProperty(window, 'WebSocket', { value: FixtureWebSocket, configurable: true });
}, { deferSnapshot, capturedPath });
}
for (const width of [320, 412]) {
test(`the first WebSocket snapshot leaves the mobile Feed layout in place at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 823 });
await installQuietFeed(page, true);
await page.goto('/feed');
const stats = page.locator('.uk-feed-stats');
await expect(stats.getByRole('status')).toHaveText('Connected · quiet', { timeout: 15_000 });
await page.evaluate(async () => { await document.fonts.ready; });
const geometry = () => stats.evaluate(panel => {
const coordinates = (element: Element) => {
const { top, left } = element.getBoundingClientRect();
return [top, left];
};
return {
chat: coordinates(document.querySelector('.uk-feed-chat')!),
labels: [...panel.querySelectorAll('.uk-feed-stats__label')].map(coordinates),
};
});
const before = await geometry();
await page.evaluate(() => (window as unknown as { publishFeedSnapshot(): void }).publishFeedSnapshot());
await expect(stats.getByRole('status')).toHaveText('Live');
await expect(page.locator('.uk-feed-packet-row').first()).toBeVisible();
const tags = stats.locator('.uk-feed-type-tag');
await expect(tags).toHaveCount(5);
for (const tag of await tags.all()) await expect(tag).toBeInViewport({ ratio: 1 });
expect(await geometry()).toEqual(before);
});
}
test('feed clocks leave packet timestamps untouched and suspend while hidden', async ({ page }) => {
await installQuietFeed(page);
await page.clock.install();
const scripts: string[] = [];
page.on('request', request => { if (request.resourceType() === 'script') scripts.push(request.url()); });
await page.goto('/feed');
await expect(page.locator('.uk-feed-packet-row').first()).toBeVisible();
await page.evaluate(async () => { await document.fonts.ready; });
await page.clock.fastForward(2000);
const before = await page.locator('.uk-feed-stats__row').textContent();
await page.evaluate(() => { (window as unknown as { feedFormatProbe: { formats: number } }).feedFormatProbe.formats = 0; });
await page.clock.fastForward(6000);
await expect.poll(() => page.locator('.uk-feed-stats__row').textContent()).not.toBe(before);
expect(await page.evaluate(() => (window as unknown as { feedFormatProbe: { formats: number } }).feedFormatProbe.formats)).toBe(0);
expect(scripts.filter(url => /maplibre|deck-|PacketPathMap|PacketDetailPanel/.test(url))).toEqual([]);
const visibleText = await page.locator('.uk-feed-stats__row').textContent();
await page.evaluate(() => { Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true }); document.dispatchEvent(new Event('visibilitychange')); });
await page.clock.fastForward(20_000);
expect(await page.locator('.uk-feed-stats__row').textContent()).toBe(visibleText);
await page.evaluate(() => { Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true }); document.dispatchEvent(new Event('visibilitychange')); });
await expect.poll(() => page.locator('.uk-feed-stats__row').textContent()).not.toBe(visibleText);
});
test('clearing packet filters preserves the chosen region and selection loads its map on demand', async ({ page }) => {
await installQuietFeed(page, false, ['AA', 'BB']);
const scripts: string[] = [];
let pathRequests = 0;
await page.route('**/api/path-lazy/resolve?*', route => {
pathRequests++;
return route.fulfill({ json: { packetHash: 'A'.repeat(63) + '0', observerCount: 0, paths: [] } });
});
page.on('request', request => { if (request.resourceType() === 'script') scripts.push(request.url()); });
await page.goto('/feed');
await expect(page.locator('.uk-feed-packet-row').first()).toBeVisible();
await page.getByRole('button', { name: 'ABC', exact: true }).click();
await page.getByRole('searchbox', { name: 'Search packets', exact: true }).fill('no matching packet');
await expect(page.getByText('No packets match the current filters in ABC.', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Clear filters', exact: true }).click();
await expect(page.locator('.uk-feed-packet-row').first()).toBeVisible();
await expect(page.getByRole('button', { name: 'ABC', exact: true })).toHaveClass(/--active/);
expect(scripts.filter(url => /maplibre|deck-|PacketPathMap|PacketDetailPanel/.test(url))).toEqual([]);
expect(pathRequests).toBe(0);
await page.locator('.uk-feed-packet-row').first().click();
await expect.poll(() => pathRequests).toBe(1);
await expect.poll(() => scripts.some(url => /PacketPathMap/.test(url))).toBe(true);
const supportsWebGL = await page.evaluate(() => {
const gl = document.createElement('canvas').getContext('webgl2');
gl?.getExtension('WEBGL_lose_context')?.loseContext();
return Boolean(gl);
});
const mapDisplay = supportsWebGL ? page.locator('.maplibregl-map') : page.getByText('Interactive map unavailable.');
await expect(mapDisplay).toBeVisible();
await page.setViewportSize({ width: 390, height: 844 });
await expect(mapDisplay).toHaveCount(1);
await page.getByRole('button', { name: 'Repeater tree', exact: true }).click();
await expect(page.getByRole('dialog', { name: 'Predicted repeater tree', exact: true })).toBeVisible();
expect(pathRequests).toBe(1);
expect(scripts.filter(url => /PacketDetailPanel/.test(url))).toEqual([]);
await page.keyboard.press('Escape');
const details = page.getByRole('button', { name: 'Packet details', exact: true });
await details.click();
await expect.poll(() => scripts.some(url => /PacketDetailPanel/.test(url))).toBe(true);
await expect(page.getByRole('dialog', { name: 'Packet details', exact: true })).toBeVisible();
await page.keyboard.press('Escape');
await expect(details).toBeFocused();
});
test('packet details stay readable when WebGL is unavailable and map initialization can be retried', async ({ page }) => {
await installQuietFeed(page);
await page.addInitScript(() => {
const getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function (this: HTMLCanvasElement, type: string, ...args: unknown[]) {
if (type.includes('webgl')) return null;
return Reflect.apply(getContext, this, [type, ...args]);
} as typeof getContext;
});
await page.goto('/feed');
await page.locator('.uk-feed-packet-row').first().click();
const retry = page.getByRole('button', { name: 'Retry map' });
await expect(retry).toBeVisible();
const canvasContainer = page.locator('.feed-detail__map-recovery').locator('..').locator(':scope > div').first();
await canvasContainer.evaluate(element => element.setAttribute('data-first-attempt', 'true'));
await retry.click();
await expect(canvasContainer).not.toHaveAttribute('data-first-attempt', 'true');
await expect(retry).toBeVisible();
await page.getByRole('button', { name: 'Packet details', exact: true }).click();
await expect(page.getByRole('dialog', { name: 'Packet details', exact: true })).toBeVisible();
});
for (const failure of [false, true]) {
test(`packet details remain dismissible when their module is ${failure ? 'unavailable' : 'pending'}`, async ({ page }) => {
await installQuietFeed(page);
let release!: () => void;
let requests = 0;
const gate = new Promise<void>(resolve => { release = resolve; });
await page.route(/\/assets\/PacketDetailPanel-[^/]+\.js/, async route => {
requests++;
if (failure) await route.abort('failed');
else { await gate; await route.continue(); }
});
try {
await page.goto('/feed');
await page.locator('.uk-feed-packet-row').first().click();
const trigger = page.getByRole('button', { name: 'Packet details', exact: true });
await trigger.click();
await expect.poll(() => requests).toBe(1);
const dialog = page.getByRole('dialog', { name: 'Packet details', exact: true });
await expect(dialog).toBeVisible();
if (failure) {
await expect(dialog.getByRole('alert')).toContainText('The packet details could not be loaded.');
await expect(dialog.getByRole('button', { name: 'Reload packet details', exact: true })).toBeVisible();
} else await expect(dialog.getByRole('status')).toBeVisible();
await page.keyboard.press('Escape');
await expect(dialog).toHaveCount(0);
await expect(trigger).toBeFocused();
await expect(page.locator('.uk-feed-packet-row').first()).toBeVisible();
release();
if (!failure) {
await trigger.click();
await expect(dialog.getByRole('button', { name: 'Close packet details', exact: true })).toBeVisible();
}
} finally { release(); }
});
}