Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

test: measure synthetic collection traffic and idle transfers (#8250)

[._.]/ Adam Eivy8a29dafa3690
diff --git a/scripts/perf/README.md b/scripts/perf/README.md
index 8eb899048d..8c568a9852 100644
--- a/scripts/perf/README.md
+++ b/scripts/perf/README.md
@@ -73,3 +73,67 @@ npm run test:db -- ../scripts/perf/collectionFixture.db.test.js
The first covers pre-import isolation rejection. The second covers actual HTTP
pagination, projections, unavailable actions, and success/failure cleanup against
portos_test.
+
+## Browser and CDP audit
+
+With Google Chrome installed, run from the repository root:
+
+~~~sh
+npm run build
+PGDATABASE=portos_test node scripts/perf/browserCollectionAudit.mjs /tmp/collection-audit.json
+~~~
+
+`COLLECTION_AUDIT_BROWSER` optionally selects a Chromium executable. The audit
+uses the existing server `playwright-core`, a fresh context for each cold route,
+no browser profile, no dev proxy, and no live-instance URL option. It owns and
+closes the fixture and browser, including on SIGINT/SIGTERM. An output filename
+must not already exist; omit it to print aggregate JSON. Exit 0 means all gates
+passed; exit 1 means the report contains findings or measurement failed. A failed
+gate is evidence to fix, never a reason to raise the limit until the run passes.
+
+The report records:
+
+- Time from navigation start until the first visible synthetic collection row,
+ then a two-second observation tail for eager fetches; 60 media cards / 50 inbox
+ rows maximum, checked against response counts before client rendering.
+- CDP requests, completion/failure/cancellation counts, encoded HTTP transfer
+ bytes and decoded body bytes by endpoint and phase. Redirect hops count as
+ requests; partial failed transfers retain observed bytes. Headers count toward
+ encoded transfer; decoded counts use `dataReceived.dataLength`. Terminal totals
+ reconcile observed encoded bytes rather than adding them twice. Cached contexts
+ and service workers are disabled. In-flight requests are reported explicitly.
+- WebSocket sent/received frame counts and payload bytes (UTF-8 text, decoded
+ base64 binary). These exclude frame/TCP/TLS overhead and are separate from HTTP
+ bytes; do not add a WebSocket handshake or frame twice. This is CDP accounting,
+ not a packet capture.
+- Detail reads after opening a row, then the real Contacts tab click and a full
+ measured 60-second idle window. Idle bytes/minute use actual elapsed time,
+ with HTTP encoded/decoded and socket payload bytes separate. Requests count in
+ the phase they start; bytes count in the phase CDP observes them.
+
+Only aggregates and fixed failure codes are retained. Query strings, hostnames,
+record IDs, response bodies, headers, screenshots, HARs, and frames are not saved.
+Response payloads are inspected transiently for pagination, totals, hidden media,
+and compact projections (at most 2 KiB per permitted list row; prompt previews
+at most 512 characters, no inbox bodies or evaluation reasoning). Unrelated
+fixture 503s are counted separately as unavailable, not production failures.
+The fixture's unavailable password-check dialog is dismissed through the UI in
+the disposable browser; this does not accept risk or change any live install.
+Contacts APIs remain unavailable: its route/idle traffic is measured, not contact
+loading performance. Timing is diagnostic, with no machine-specific threshold.
+
+Run deterministic accounting and regression-gate tests from `server/`:
+
+~~~sh
+npm test -- ../scripts/perf/collectionTraffic.test.js
+~~~
+
+### Initial findings
+
+The initial synthetic run identified media contract failures tracked in #8292:
+full prompt fields in the first 60-row response (511,086 decoded bytes), totals
+including hidden records, and no lazy media detail read. These remain hard
+failures, not an accepted baseline. Inbox summary/detail and Contacts idle gates
+passed, including a full idle minute with zero HTTP transfer and four bytes of
+socket heartbeat payload. Completing #8292 is necessary before this audit can
+report an overall pass. This runner does not claim all #8232 contracts are met.
diff --git a/scripts/perf/browserCollectionAudit.mjs b/scripts/perf/browserCollectionAudit.mjs
new file mode 100644
index 0000000000..f1140b7272
--- /dev/null
+++ b/scripts/perf/browserCollectionAudit.mjs
@@ -0,0 +1,158 @@
+#!/usr/bin/env node
+import { createRequire } from 'node:module';
+import { writeFile } from 'node:fs/promises';
+import { setTimeout as delay } from 'node:timers/promises';
+import { performance } from 'node:perf_hooks';
+import { startCollectionFixture } from './collectionFixture.js';
+import { createTrafficAccumulator, endpointFor, inspectCollection, trafficFailures } from './collectionTraffic.js';
+
+const { chromium } = createRequire(new URL('../../server/package.json', import.meta.url))('playwright-core');
+const events = ['requestWillBeSent', 'responseReceived', 'dataReceived', 'loadingFinished', 'loadingFailed',
+ 'webSocketCreated', 'webSocketClosed', 'webSocketFrameSent', 'webSocketFrameReceived'];
+const output = process.argv[2];
+let browser;
+let fixture;
+const abort = new AbortController();
+const stop = () => { abort.abort(); browser?.close().catch(() => {}); };
+process.once('SIGINT', stop);
+process.once('SIGTERM', stop);
+const report = { version: 1, synthetic: true, idleTargetMs: 60000, scenarios: [], failures: [] };
+
+async function scenario(route) {
+ const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, serviceWorkers: 'block' });
+ const page = await context.newPage();
+ page.setDefaultTimeout(15000);
+ const cdp = await context.newCDPSession(page);
+ const traffic = createTrafficAccumulator();
+ const inspections = new Set();
+ const failures = [];
+ let listResponses = 0;
+ let returnedRows = 0;
+ let details = 0;
+ let phase = 'cold';
+ const advance = name => { phase = name; traffic.setPhase(name); };
+ const media = route === '/media/history';
+ const listEndpoint = media ? '/api/image-gen/gallery' : '/api/messages/inbox';
+ const rows = media ? page.locator('button[aria-label^="synthetic-"]') : page.getByRole('button', { name: /Example Sender.*Synthetic message/ });
+ const result = { route, usefulContentMs: null, renderedRows: 0, listResponses: 0, returnedRows: 0, details: 0, phases: {} };
+ try {
+ for (const name of events) cdp.on('Network.' + name, event => traffic.event(name, event));
+ await cdp.send('Network.enable');
+ await cdp.send('Network.setCacheDisabled', { cacheDisabled: true });
+ page.on('response', response => {
+ const url = new URL(response.url());
+ if (url.origin !== fixture.url) return;
+ const endpoint = endpointFor(response.url());
+ const responsePhase = phase;
+ if (endpoint !== listEndpoint && !['/api/messages/:account/:message', '/api/video-gen/history/:record', '/api/image-gen/gallery/lookup'].includes(endpoint)) return;
+ const inspect = (async () => {
+ if (response.status() !== 200) {
+ failures.push({ endpoint, reason: 'collection-http-status', count: response.status(), bytes: 0 }); return;
+ }
+ let timer;
+ const body = await Promise.race([response.body(), new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Response inspection timed out')), 15000);
+ })]).finally(() => clearTimeout(timer));
+ const payload = JSON.parse(body.toString('utf8'));
+ if (endpoint === listEndpoint) {
+ listResponses++;
+ const inspected = inspectCollection(endpoint, url.searchParams, payload, body.length, fixture.cardinalities);
+ returnedRows += inspected.count;
+ failures.push(...inspected.failures);
+ } else {
+ details++;
+ if (responsePhase !== 'detail' || (media ? !((Array.isArray(payload) ? payload[0]?.prompt : payload.prompt)?.length >= fixture.cardinalities.detailCharacters) : payload.bodyText?.length !== fixture.cardinalities.detailCharacters)) {
+ failures.push({ endpoint, reason: 'lazy-detail-contract', bytes: body.length });
+ }
+ }
+ })().catch(() => failures.push({ endpoint, reason: 'response-inspection-failed', bytes: 0 }));
+ inspections.add(inspect);
+ inspect.finally(() => inspections.delete(inspect));
+ });
+ const started = performance.now();
+ await page.goto(fixture.url + route, { waitUntil: 'domcontentloaded' });
+ await rows.first().waitFor({ state: 'visible' });
+ result.usefulContentMs = Math.round(performance.now() - started);
+ // A fixed observation tail catches eager hydration after first paint; do
+ // not use networkidle, which can hide recurring fetches behind a timeout.
+ await delay(2000, undefined, { signal: abort.signal });
+ await Promise.all([...inspections]);
+ result.renderedRows = await rows.count();
+ if (!listResponses || result.renderedRows < 1 || result.renderedRows > (media ? 60 : 50)
+ || returnedRows > (media ? 60 : 50)) {
+ failures.push({ endpoint: listEndpoint, reason: 'cold-page-bound', count: returnedRows, bytes: 0 });
+ }
+ // The fixture deliberately leaves unrelated security-status APIs unavailable.
+ // Dismiss that check through the UI in this disposable browser only.
+ const dismiss = page.getByRole('button', { name: 'Dismiss and don’t show again', exact: true });
+ if (await dismiss.isVisible()) await dismiss.click();
+ if (media) {
+ advance('detail');
+ await rows.first().click();
+ await delay(1000, undefined, { signal: abort.signal });
+ await Promise.all([...inspections]);
+ if (details !== 1) failures.push({ endpoint: listEndpoint, reason: 'missing-lazy-media-detail', count: details, bytes: 0 });
+ } else {
+ advance('detail');
+ await rows.first().click();
+ await page.getByRole('button', { name: 'Back', exact: true }).waitFor({ state: 'visible' });
+ await delay(500, undefined, { signal: abort.signal });
+ await Promise.all([...inspections]);
+ if (details !== 1) failures.push({ endpoint: '/api/messages/:account/:message', reason: 'detail-request-count', count: details, bytes: 0 });
+ await page.getByRole('button', { name: 'Back', exact: true }).click();
+ advance('sibling');
+ await page.getByRole('tab', { name: 'Contacts', exact: true }).click();
+ await page.waitForURL('**/messages/contacts');
+ await delay(2000, undefined, { signal: abort.signal });
+ advance('idle');
+ const idleStart = performance.now();
+ await delay(60000, undefined, { signal: abort.signal });
+ result.idleMs = Math.round(performance.now() - idleStart);
+ }
+ } catch {
+ // Playwright errors include DOM text, URLs and filesystem paths. Only a
+ // fixed stage identifier and aggregates may cross the report boundary.
+ failures.push({ endpoint: listEndpoint, reason: 'browser-stage-' + phase, bytes: 0 });
+ } finally {
+ await Promise.all([...inspections]);
+ result.phases = traffic.snapshot();
+ result.pendingRequests = traffic.pending();
+ result.listResponses = listResponses;
+ result.returnedRows = returnedRows;
+ result.details = details;
+ if (result.idleMs) {
+ const entries = Object.values(result.phases.idle || {});
+ const total = key => entries.reduce((sum, value) => sum + value[key], 0);
+ result.idleBytesPerMinute = {
+ encoded: Math.round(total('encodedBytes') * 60000 / result.idleMs),
+ decoded: Math.round(total('decodedBytes') * 60000 / result.idleMs),
+ socketPayload: Math.round((total('socketSentBytes') + total('socketReceivedBytes')) * 60000 / result.idleMs),
+ };
+ }
+ failures.push(...trafficFailures(result.phases));
+ report.failures.push(...failures);
+ report.scenarios.push(result);
+ await context.close();
+ }
+}
+
+try {
+ fixture = await startCollectionFixture();
+ report.cardinalities = fixture.cardinalities;
+ browser = await chromium.launch({ headless: true, ...(process.env.COLLECTION_AUDIT_BROWSER
+ ? { executablePath: process.env.COLLECTION_AUDIT_BROWSER } : { channel: 'chrome' }) });
+ await scenario('/media/history');
+ await scenario('/messages/inbox');
+} catch {
+ report.failures.push({ endpoint: 'fixture', reason: 'audit-startup-or-shutdown', bytes: 0 });
+} finally {
+ await browser?.close().catch(() => report.failures.push({ endpoint: 'browser', reason: 'cleanup', bytes: 0 }));
+ await fixture?.close().catch(() => report.failures.push({ endpoint: 'fixture', reason: 'cleanup', bytes: 0 }));
+ process.removeListener('SIGINT', stop);
+ process.removeListener('SIGTERM', stop);
+}
+report.passed = report.failures.length === 0;
+const serialized = JSON.stringify(report, null, 2) + '\n';
+if (output) await writeFile(output, serialized, { flag: 'wx' });
+else process.stdout.write(serialized);
+process.exitCode = report.passed ? 0 : 1;
diff --git a/scripts/perf/collectionTraffic.js b/scripts/perf/collectionTraffic.js
new file mode 100644
index 0000000000..b83cf26c35
--- /dev/null
+++ b/scripts/perf/collectionTraffic.js
@@ -0,0 +1,128 @@
+/** CDP accounting for the synthetic audit. Never retains URLs, headers or bodies. */
+export function endpointFor(rawUrl) {
+ const { pathname, protocol } = new URL(rawUrl);
+ if (!['http:', 'https:', 'ws:', 'wss:'].includes(protocol)) return '/non-http';
+ if (pathname.startsWith('/assets/')) return '/assets/:asset';
+ if (pathname.startsWith('/data/')) return '/data/:asset';
+ if (/^\/api\/video-gen\/history\/[^/]+$/.test(pathname)) return '/api/video-gen/history/:record';
+ if (/^\/api\/messages\/[^/]+\/[^/]+$/.test(pathname)) return '/api/messages/:account/:message';
+ // Collection endpoints and bootstrap paths contain no record identifiers.
+ return pathname.replace(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/gi, ':account')
+ .replace(/synthetic-[^/]+/g, ':record');
+}
+
+const empty = () => ({ requests: 0, completed: 0, failed: 0, canceled: 0,
+ encodedBytes: 0, decodedBytes: 0, unavailable: 0, socketSentFrames: 0,
+ socketReceivedFrames: 0, socketSentBytes: 0, socketReceivedBytes: 0 });
+
+export function createTrafficAccumulator() {
+ const phases = new Map();
+ const requests = new Map();
+ const sockets = new Map();
+ let phase = 'cold';
+ const bucket = (endpoint, target = phase) => {
+ if (!phases.has(target)) phases.set(target, new Map());
+ const entries = phases.get(target);
+ if (!entries.has(endpoint)) entries.set(endpoint, empty());
+ return entries.get(endpoint);
+ };
+ const finish = (id, encoded, failed, canceled) => {
+ const request = requests.get(id);
+ if (!request) return;
+ const row = bucket(request.endpoint);
+ // dataReceived encoded lengths are provisional. loadingFinished is the
+ // authoritative total (including headers); add only the uncounted remainder.
+ row.encodedBytes += Math.max(0, (encoded || 0) - request.encoded);
+ row[failed ? 'failed' : 'completed']++;
+ if (canceled) row.canceled++;
+ requests.delete(id);
+ };
+ return {
+ setPhase(name) { phase = name; },
+ event(name, event) {
+ const id = event.requestId;
+ if (name === 'requestWillBeSent') {
+ if (event.redirectResponse) finish(id, event.redirectResponse.encodedDataLength, false, false);
+ const endpoint = endpointFor(event.request.url);
+ requests.set(id, { endpoint, encoded: 0 });
+ bucket(endpoint).requests++;
+ } else if (name === 'responseReceived') {
+ const request = requests.get(id);
+ if (request) {
+ const row = bucket(request.endpoint);
+ if (event.response.status === 503) row.unavailable++;
+ const headers = Math.max(0, event.response.encodedDataLength || 0);
+ row.encodedBytes += headers;
+ request.encoded += headers;
+ }
+ } else if (name === 'dataReceived') {
+ const request = requests.get(id);
+ if (!request) return;
+ const encoded = Math.max(0, event.encodedDataLength || 0);
+ const row = bucket(request.endpoint);
+ row.decodedBytes += Math.max(0, event.dataLength || 0);
+ row.encodedBytes += encoded;
+ request.encoded += encoded;
+ } else if (name === 'loadingFinished') finish(id, event.encodedDataLength, false, false);
+ else if (name === 'loadingFailed') finish(id, 0, true, event.canceled);
+ else if (name === 'webSocketCreated') sockets.set(id, endpointFor(event.url));
+ else if (name === 'webSocketClosed') sockets.delete(id);
+ else if (name === 'webSocketFrameSent' || name === 'webSocketFrameReceived') {
+ const row = bucket(sockets.get(id) || '/socket.io/');
+ const direction = name === 'webSocketFrameSent' ? 'Sent' : 'Received';
+ const { opcode, payloadData } = event.response;
+ row['socket' + direction + 'Frames']++;
+ row['socket' + direction + 'Bytes'] += opcode === 1
+ ? Buffer.byteLength(payloadData, 'utf8') : Buffer.from(payloadData, 'base64').length;
+ }
+ },
+ snapshot() {
+ return Object.fromEntries([...phases].map(([name, endpoints]) => [name,
+ Object.fromEntries([...endpoints].sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, { ...value }]))]));
+ },
+ pending() { return requests.size; },
+ };
+}
+
+/** Transient payload inspection returns only counts and contract failures. */
+export function inspectCollection(endpoint, query, payload, bytes, cardinalities) {
+ const failures = [];
+ const fail = reason => failures.push({ endpoint, reason, bytes });
+ const media = endpoint === '/api/image-gen/gallery';
+ const rows = media ? payload?.items : payload?.messages;
+ const pageLimit = media ? 60 : 50;
+ const total = media ? cardinalities.images + cardinalities.videos - cardinalities.hiddenImages - cardinalities.hiddenVideos : cardinalities.messages;
+ if (!Array.isArray(rows)) { fail('unpaged-response'); return { count: 0, failures }; }
+ if (query.get('summary') !== 'true') fail('missing-summary-projection');
+ if (rows.length > pageLimit || payload.total !== total) fail('page-limit-or-total');
+ if (bytes > pageLimit * 2048) fail('list-byte-budget');
+ if (media && payload.hiddenTotal !== cardinalities.hiddenImages + cardinalities.hiddenVideos) fail('hidden-total');
+ for (const item of rows) {
+ const row = media ? item.data : item;
+ if (!row || (media && !['image', 'video'].includes(item.kind))) { fail('invalid-row'); break; }
+ if (media && (row.hidden || /synthetic-(image|video)-\d*0(?:\.|$)/.test(row.filename || ''))) { fail('hidden-row'); break; }
+ if ((media && (row.prompt?.length > 512 || row.negativePrompt?.length > 512))
+ || (!media && ('bodyText' in row || 'bodyHtml' in row || row.evaluation?.reasoning))) {
+ fail('eager-detail-fields'); break;
+ }
+ }
+ return { count: rows.length, failures };
+}
+
+export function trafficFailures(phases) {
+ const failures = [];
+ for (const [phase, endpoints] of Object.entries(phases)) {
+ for (const [endpoint, row] of Object.entries(endpoints)) {
+ if (['sibling', 'idle'].includes(phase) && endpoint === '/api/messages/inbox' && row.requests) {
+ failures.push({ endpoint, reason: 'sibling-inbox-fetch', count: row.requests, bytes: row.encodedBytes });
+ }
+ if (phase === 'cold' && ['/api/messages/:account/:message', '/api/video-gen/history/:record', '/api/image-gen/gallery/lookup'].includes(endpoint) && row.requests) {
+ failures.push({ endpoint, reason: 'eager-detail-request', count: row.requests, bytes: row.encodedBytes });
+ }
+ if (['/api/video-gen/history', '/api/image-gen/history'].includes(endpoint) && row.requests) {
+ failures.push({ endpoint, reason: 'full-history-fetch', count: row.requests, bytes: row.encodedBytes });
+ }
+ }
+ }
+ return failures;
+}
diff --git a/scripts/perf/collectionTraffic.test.js b/scripts/perf/collectionTraffic.test.js
new file mode 100644
index 0000000000..52fa0388d4
--- /dev/null
+++ b/scripts/perf/collectionTraffic.test.js
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+import { createTrafficAccumulator, endpointFor, inspectCollection, trafficFailures } from './collectionTraffic.js';
+import { CARDINALITIES, messageFixture, mediaFixture } from './collectionFixtureData.js';
+const start = (t, id = 'one', path = '/api/messages/inbox?secret=never-retain') => t.event('requestWillBeSent', { requestId: id, request: { url: 'http://example.com' + path } });
+
+describe('synthetic CDP traffic accounting', () => {
+ it('redacts thread accounts and non-HTTP payload URLs', () => {
+ expect(endpointFor('http://example.com/api/messages/thread/00000000-0000-4000-8000-000000000002/synthetic-thread-1')).toBe('/api/messages/thread/:account/:record');
+ expect(endpointFor('data:text/plain,payload')).toBe('/non-http');
+ });
+ it('counts compressed transfer once and decoded data separately without retaining URLs', () => {
+ const t = createTrafficAccumulator(); start(t);
+ t.event('responseReceived', { requestId: 'one', response: { status: 200, encodedDataLength: 20 } });
+ t.event('dataReceived', { requestId: 'one', dataLength: 1000, encodedDataLength: 100 });
+ t.event('loadingFinished', { requestId: 'one', encodedDataLength: 120 });
+ expect(t.snapshot().cold['/api/messages/inbox']).toMatchObject({ requests: 1, completed: 1, encodedBytes: 120, decodedBytes: 1000 });
+ expect(JSON.stringify(t.snapshot())).not.toMatch(/secret|example.com|never-retain/);
+ expect(t.pending()).toBe(0);
+ });
+ it('accounts redirects, partial cancellations, fixture failures, and phase-crossing bytes', () => {
+ const t = createTrafficAccumulator(); start(t);
+ t.event('requestWillBeSent', { requestId: 'one', redirectResponse: { encodedDataLength: 30 }, request: { url: 'http://example.com/api/messages/inbox' } });
+ t.event('responseReceived', { requestId: 'one', response: { status: 503, encodedDataLength: 20 } });
+ t.setPhase('idle');
+ t.event('dataReceived', { requestId: 'one', dataLength: 80, encodedDataLength: 40 });
+ t.event('loadingFailed', { requestId: 'one', canceled: true });
+ t.event('loadingFailed', { requestId: 'one', canceled: true });
+ expect(t.snapshot().cold['/api/messages/inbox']).toMatchObject({ requests: 2, completed: 1, encodedBytes: 50, unavailable: 1 });
+ expect(t.snapshot().idle['/api/messages/inbox']).toMatchObject({ requests: 0, failed: 1, canceled: 1, encodedBytes: 40, decodedBytes: 80 });
+ });
+ it('counts UTF-8 and base64 socket payloads without retaining frames or double counting HTTP', () => {
+ const t = createTrafficAccumulator();
+ t.event('webSocketCreated', { requestId: 'socket', url: 'ws://example.com/socket.io/?token=private' });
+ t.setPhase('idle');
+ t.event('webSocketFrameSent', { requestId: 'socket', response: { opcode: 1, payloadData: 'é' } });
+ t.event('webSocketFrameReceived', { requestId: 'socket', response: { opcode: 2, payloadData: 'AAECAw==' } });
+ expect(t.snapshot().idle['/socket.io/']).toMatchObject({ socketSentFrames: 1, socketSentBytes: 2, socketReceivedFrames: 1, socketReceivedBytes: 4, encodedBytes: 0 });
+ expect(JSON.stringify(t.snapshot())).not.toMatch(/private|AAECAw/);
+ });
+});
+
+describe('collection regression gates', () => {
+ const q = new URLSearchParams('summary=true');
+ it('accepts compact pages but rejects full hydration before client slicing', () => {
+ const messages = Array.from({ length: 50 }, (_, i) => ({ id: String(i), preview: 'summary' }));
+ expect(inspectCollection('/api/messages/inbox', q, { messages, total: 4000 }, 12000, CARDINALITIES).failures).toEqual([]);
+ const full = Array.from({ length: 4000 }, (_, i) => messageFixture('synthetic-account', i));
+ const result = inspectCollection('/api/messages/inbox', q, { messages: full, total: 4000 }, 1000000, CARDINALITIES);
+ expect(result.failures.map(f => f.reason)).toEqual(['page-limit-or-total', 'list-byte-budget', 'eager-detail-fields']);
+ expect(JSON.stringify(result)).not.toContain('bodyText');
+ expect(inspectCollection('/api/messages/inbox', q, full, 1000000, CARDINALITIES).failures[0].reason).toBe('unpaged-response');
+ });
+ it('catches hidden media, full prompts, and lost query-wide totals', () => {
+ const payload = { items: [{ kind: 'image', data: { ...mediaFixture('image', 1), prompt: 'summary' } }], total: 3240, hiddenTotal: 360 };
+ expect(inspectCollection('/api/image-gen/gallery', q, payload, 1000, CARDINALITIES).failures).toEqual([]);
+ payload.items[0].data = mediaFixture('image', 1);
+ expect(inspectCollection('/api/image-gen/gallery', q, payload, 9000, CARDINALITIES).failures[0].reason).toBe('eager-detail-fields');
+ payload.items[0].data = mediaFixture('image', 0);
+ expect(inspectCollection('/api/image-gen/gallery', q, payload, 9000, CARDINALITIES).failures[0].reason).toBe('hidden-row');
+ payload.total = 3600;
+ expect(inspectCollection('/api/image-gen/gallery', q, payload, 9000, CARDINALITIES).failures[0].reason).toBe('page-limit-or-total');
+ });
+ it('rejects sibling list reads, eager details and full history without rejecting heartbeats', () => {
+ const t = createTrafficAccumulator(); t.setPhase('sibling'); start(t);
+ t.setPhase('idle'); t.event('webSocketFrameReceived', { requestId: 's', response: { opcode: 1, payloadData: '2' } });
+ t.setPhase('cold'); start(t, 'detail', '/api/messages/account/record'); start(t, 'history', '/api/video-gen/history');
+ expect(trafficFailures(t.snapshot()).map(f => f.reason)).toEqual(['sibling-inbox-fetch', 'eager-detail-request', 'full-history-fetch']);
+ });
+});