Skip to content
Merged
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
23 changes: 23 additions & 0 deletions agent-notes/fix-browser-session-ci-log.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Browser-session CI progress log

## Goal

Make the Chromium browser-session check show which operation it reached when a CI job stalls.

## State

The first master run after PR #293 passed the lighting test and reached the job timeout without any progress from the browser-session script. The script now prints progress before its waits and cleanup. [Timed-out job](https://github.com/MongooseMoo/react-client/actions/runs/46232557133/job/141251384840).

`node --check`, `npm run build`, and the existing native Chromium session journey passed locally. The production journey ran through the private desktop launcher and printed the IndexedDB, per-tab service worker, push, editor, visitor, reload, and cleanup progress to stdout.

## Decisions and why

Log before work starts so a canceled job still shows the last operation reached. Forward only explicitly labeled fixture logs from Chromium to stdout. Keep the original assertions, waits, and order.

## Surprises

The old script's only explicit log was its final success message. The GitHub cancellation record identifies the script that had no completion output and gives no evidence about the underlying wait.

## Next step

The logging change is local on `fix/browser-session-ci-log`. If the original stall recurs after the logging change is published, its last labeled operation will narrow the diagnosis.
64 changes: 49 additions & 15 deletions scripts/check-browser-sessions.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { chromium, expect } from '@playwright/test';
// The socket and API are controlled protocol fixtures, never live accounts.
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const dist = resolve(root, 'dist');
const progressPrefix = '[browser sessions]';
const progress = message => console.log(`${progressPrefix} ${message}`);
const server = createServer(async (req, res) => {
const pathname = new URL(req.url, 'http://localhost').pathname;
const file = resolve(dist, `.${pathname === '/' || pathname === '/editor' ? '/index.html' : pathname}`);
Expand All @@ -19,11 +21,18 @@ const server = createServer(async (req, res) => {
file.endsWith('.css') ? 'text/css' : file.endsWith('.html') ? 'text/html' : 'application/octet-stream' }).end(bytes);
} catch { res.writeHead(404).end(); }
});
progress('Starting the production fixture server');
await new Promise(done => server.listen(0, '127.0.0.1', done));
const origin = `http://127.0.0.1:${server.address().port}`;
progress('Launching native Chromium');
const browser = await chromium.launch({ channel: 'chromium', headless: true });
try {
const context = await browser.newContext();
// Forward fixture progress from inside page.evaluate without echoing app logs.
context.on('console', message => {
const text = message.text();
if (text.startsWith(`${progressPrefix} `)) console.log(text);
});
await context.route('**/*', route => route.request().url().startsWith(origin) ? route.continue() : route.abort());
await context.route('https://cdn.jsdelivr.net/npm/monaco-editor@*/min/vs/**', async route => {
const suffix = new URL(route.request().url()).pathname.split('/min/')[1];
Expand Down Expand Up @@ -51,11 +60,15 @@ try {
});
setTimeout(() => socket.send(gmcp('Char.Name', who)), 150);
});
progress('Opening the first game tab');
const a = await context.newPage();
await a.goto(origin);
progress('Waiting for the session grant in the first tab');
await expect.poll(() => a.evaluate(() => window.mudClient?.gmcp.require('Auth.Autologin').currentGrant?.playerUuid)).toBe('native-owner-a');
progress('Opening the second game tab');
const b = await context.newPage();
await b.goto(origin);
progress('Waiting for the session grant in the second tab');
await expect.poll(() => b.evaluate(() => window.mudClient?.gmcp.require('Auth.Autologin').currentGrant?.playerUuid)).toBe('native-owner-b');
const owners = await Promise.all([a, b].map(page => page.evaluate(() => window.mudClient.gmcp.require('Auth.Autologin').currentGrant)));
assert.equal(owners[0].installationId, owners[1].installationId);
Expand All @@ -66,13 +79,16 @@ try {
const profile = { id: owners[0].installationId, revision: 1, quiet: 0,
bindings: recipients.map((recipient, index) => ({ ...recipient, label: `Owner ${index}`, primary: index === 0,
mode: index === 0 ? 'primary' : 'retained', enabled: 1, stoppedKinds: [] })) };
await a.evaluate(async ({ owners, recipients, profile }) => {
progress('Writing the browser storage fixtures');
await a.evaluate(async ({ owners, recipients, profile, progressPrefix }) => {
const open = (name, version, stores) => new Promise((resolve, reject) => {
console.info(`${progressPrefix} Opening IndexedDB ${name}`);
const request = indexedDB.open(name, version);
request.onupgradeneeded = () => { for (const store of stores) if (!request.result.objectStoreNames.contains(store)) request.result.createObjectStore(store); };
request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error);
});
const commit = (db, stores, work) => new Promise((resolve, reject) => {
console.info(`${progressPrefix} Committing fixtures to ${db.name}`);
const tx = db.transaction(stores, 'readwrite'); work(tx); tx.oncomplete = () => { db.close(); resolve(); }; tx.onerror = () => reject(tx.error);
});
const browser = await open('mongoose-browser', 1, ['installation']);
Expand All @@ -86,20 +102,28 @@ try {
tx.objectStore('credentials').put({ ...recipient, version: 2, sessionId: owners[index].sessionId,
token: `synthetic-away-${index}`, expires_at: owners[index].expires_at }, [...key, owners[index].sessionId]);
}));
}, { owners, recipients, profile });
for (let i = 0; i < 2; i++) await [a, b][i].evaluate(async ({ recipient, owner, profile }) => {
await navigator.serviceWorker.register('/sw.js');
const registration = await navigator.serviceWorker.ready;
await new Promise(resolve => {
if (navigator.serviceWorker.controller) resolve(); else navigator.serviceWorker.addEventListener('controllerchange', resolve, { once: true });
});
window.mudClient.setBrowserNotificationContext({ recipient,
grant: { ...recipient, version: 2, token: 'synthetic-away', sessionId: owner.sessionId, expires_at: owner.expires_at },
sessionId: owner.sessionId, profile });
navigator.serviceWorker.controller.postMessage({ type: 'browser-owner', recipient, sessionId: owner.sessionId, connected: true });
window.nativeOwnerMessages = [];
navigator.serviceWorker.addEventListener('message', event => window.nativeOwnerMessages.push(event.data));
}, { recipient: recipients[i], owner: owners[i], profile });
}, { owners, recipients, profile, progressPrefix });
for (const [index, page] of [a, b].entries()) {
const tab = index + 1;
progress(`Configuring the service worker in tab ${tab}`);
await page.evaluate(async ({ recipient, owner, profile, progressPrefix, tab }) => {
console.info(`${progressPrefix} Tab ${tab} registering the service worker`);
await navigator.serviceWorker.register('/sw.js');
console.info(`${progressPrefix} Tab ${tab} waiting for serviceWorker.ready`);
await navigator.serviceWorker.ready;
console.info(`${progressPrefix} Tab ${tab} waiting for a service worker controller`);
await new Promise(resolve => {
if (navigator.serviceWorker.controller) resolve(); else navigator.serviceWorker.addEventListener('controllerchange', resolve, { once: true });
});
window.mudClient.setBrowserNotificationContext({ recipient,
grant: { ...recipient, version: 2, token: 'synthetic-away', sessionId: owner.sessionId, expires_at: owner.expires_at },
sessionId: owner.sessionId, profile });
navigator.serviceWorker.controller.postMessage({ type: 'browser-owner', recipient, sessionId: owner.sessionId, connected: true });
window.nativeOwnerMessages = [];
navigator.serviceWorker.addEventListener('message', event => window.nativeOwnerMessages.push(event.data));
}, { recipient: recipients[index], owner: owners[index], profile, progressPrefix, tab });
}
progress('Waiting for the DevTools service worker registration');
await context.grantPermissions(['notifications'], { origin });
const cdp = await context.newCDPSession(a);
let registrationId;
Expand All @@ -110,16 +134,20 @@ try {
await expect.poll(() => registrationId).toBeTruthy();
const data = { ...recipients[0], version: 2, streamId: 'native-stream-a', streamOrder: 1,
firstAvailable: 1, from: 1, to: 1, lines: [[1, 'Native A private backlog']] };
progress('Delivering the push message to the service worker');
await cdp.send('ServiceWorker.deliverPushMessage', { origin, registrationId, data: JSON.stringify({ title: 'Native A', kind: 'room', data }) });
progress('Checking which tabs received the push message');
await expect.poll(() => a.evaluate(() => window.nativeOwnerMessages.filter(message => message.type === 'browser-away').length)).toBe(1);
assert.equal(await b.evaluate(() => window.nativeOwnerMessages.filter(message => message.type === 'browser-away').length), 0);
progress('Reading the browser notifications');
const notifications = await a.evaluate(async () => (await (await navigator.serviceWorker.ready).getNotifications()).map(notification =>
({ title: notification.title, tag: notification.tag, data: notification.data })));
assert.equal(notifications.length, 1);
assert.equal(notifications[0].data.recipient.playerUuid, owners[0].playerUuid);
assert(!JSON.stringify(notifications).includes('synthetic-away'));
assert(!JSON.stringify(notifications).includes('Native A private backlog'));

progress('Opening the owned editor');
const popup = a.waitForEvent('popup');
await a.evaluate(() => window.mudClient.editors.openEditorWindow({ reference: 'native-edit-ref', type: 'string', name: 'Native owner draft', contents: ['Owner-only draft'] }));
const editor = await popup;
Expand All @@ -132,6 +160,7 @@ try {

// Change the canonical policy through IndexedDB; the actual cross-window
// channel must mask both owners without assigning either window to the visitor.
progress('Writing the visitor policy to IndexedDB');
await a.evaluate(async () => {
const db = await new Promise(resolve => { const request = indexedDB.open('mongoose-browser', 1); request.onsuccess = () => resolve(request.result); });
await new Promise(resolve => {
Expand All @@ -141,16 +170,21 @@ try {
});
new BroadcastChannel('mongoose:browser-policy:v1').postMessage({ revision: 1 });
});
progress('Checking that the visitor policy pauses both game tabs and the editor');
await expect(a.getByRole('textbox', { name: 'Command', exact: true })).toBeHidden();
await expect(b.getByRole('textbox', { name: 'Command', exact: true })).toBeHidden();
await expect(editor.getByRole('button', { name: 'Download', exact: true })).toBeHidden();
await expect(editor.getByText('This editor is paused during the temporary visit. Your work is kept for the owner.')).toBeVisible();
await a.locator('details.browser-sessions summary').click();
await expect(a.getByText('A temporary visit is active in another tab. Saved data stays paused.')).toBeVisible();
progress('Reloading the second game tab during the visit');
await b.reload();
await expect(b.getByRole('textbox', { name: 'Command', exact: true })).toBeHidden();
console.log('Native Chromium browser-session journey passed: independent tab grants, canonical installation, actual worker push ownership, private notification metadata, cross-tab visitor pause and reload.');
} finally {
progress('Closing Chromium');
await browser.close();
progress('Closing the production fixture server');
await new Promise(done => server.close(done));
progress('Finished cleanup');
}