feat(wails): move the e2e harness and headless launch onto v3

make e2e is green on chromium: 92 passed. The harness is rebuilt on
what v3 actually offers, and three of the four things it replaced turn
out to be better than what they replaced.

The headless launch is v3's own server mode. scripts/dev-headless.sh
ran a `-tags dev` binary whose app_dev.go parsed -devserver/-assetdir
out of os.Args; that file went with v2, so the harness had no server at
all. `-tags dev,server` is a first-class mode and needs no display, so
Xvfb is gone from the script and from CI.

The bridge hooks two places, neither of them EventsOn. Inbound is
window._wails.dispatchWailsEvent, wrapped by pre-creating the object
the runtime keeps and putting an accessor on the one property.
Outbound is fetch: v3 routes every runtime call through one POST, so
the bridge sees binding calls and event emits from any module, needs no
walk of an object graph, and cannot miss a call made before it looked.

__yjEvents.call posts to that endpoint by method name, so it depends on
nothing in the app's bundle and works on a page with no init script.
That is what lets seed-sandbox.sh drop playwright-cli entirely — it
drove AddLibrary through a browser only because window.go was v2's one
way in — and with it a global npm install and a second Chromium in CI.

measure.mjs and one spec lose their window.go walks and read the
bridge's log instead; e2e/support/method-ids.mjs derives id -> name
from frontend/bindings/ (phase 6b option 1, so it cannot go stale
silently). Plain .mjs because measure.mjs runs under bare node and one
derivation beats two that can disagree.

Four bugs surfaced, and the migration is how.

The cross-service wiring never ran headless. It hung off
Common.ApplicationStarted, which server mode never emits —
setupCommonEvents is an explicit no-op there — so the queue had no
TrackLoader and playing a track changed the queue and then silently did
nothing. It is a service registered last now (backend/startup.go):
services start in registration order, which is the ordering the wiring
needs, in every mode.

Six specs called SetQueue with 3 of its 4 arguments. v2 accepted that
and filled the gap; v3 answers "expects 4 arguments, got 3".

requested-badge's cleanup read window.go and returned early on
`if (!svc)` — the silent cleanup its own comment was written to
prevent, one migration later. It posts to the runtime endpoint now,
which any page can do.

SearchIndex.Search trusted a startup latch, so rows a spec staged
afterwards were unsearchable and three specs passed only when an
earlier one happened to flip it. shelves.go fixed exactly this and left
hasCatalogRows behind; the search path now uses it as the fallback,
with the latch still the fast path.

Two spec edits are deletions of assertions about v2. harness.spec
checked Object.keys(window.go) and that a bad call *hung*; it now
checks the real runtime is loaded and that the backend rejects with a
TypeError naming the argument. album-actions asserted a tracklist
legend that dcc40b1 deleted on main — that spec has been failing since,
and what replaced it is covered in frontend/test/components.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UDCbcCZQepnpSQYJ6SxxZm
This commit is contained in:
2026-08-14 20:58:20 -04:00
co-authored by Claude Opus 5
parent 60779c41c3
commit deb3f3da7e
22 changed files with 728 additions and 328 deletions
+74 -62
View File
@@ -56,6 +56,8 @@ import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from '@playwright/test';
import { methodIDs } from '../support/method-ids.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = resolve(HERE, '../..');
const OUT_DIR = resolve(REPO, '.dev/perf');
@@ -63,6 +65,16 @@ const BRIDGE = resolve(REPO, '.playwright/init-events.js');
const BASE_URL = process.env.YJ_URL ?? 'http://localhost:34115';
/**
* methodID -> 'pkg.Type.Method', derived from frontend/bindings/.
*
* A binding call carries only the id, so this is what turns a
* measurement's "which bindings did that provoke" back into names. It
* is derived rather than written down for the reason plan 009 phase 6b
* gives: a hand-maintained list goes stale silently.
*/
const METHOD_NAMES = Object.fromEntries(methodIDs());
// The browse script visited for the heap measurement. Deliberately the
// views the audit named as retaining: explore (two unbounded caches),
// artists and genres (per-frame work), settings (the 3 s ticker).
@@ -123,64 +135,41 @@ function parseArgs(argv) {
/* -------------------------------------------------------------------- */
/**
* Wrap every bound Go method so a measurement can say which bindings a
* user action provoked and how much they returned.
* Say which bindings a user action provoked, and how much they
* returned.
*
* Post-hoc wrapping is safe because `frontend/wailsjs` looks its target
* up at call time (`window['go']['library']['Library']['GetAllTracks']()`),
* so a store holding an imported wrapper still lands here.
* This used to walk `window.go` and wrap every bound method in place,
* which worked because v2's generated stubs looked their target up at
* call time. v3 has no such object — the bindings are bundled modules
* — so `.playwright/init-events.js` records every call off the single
* POST v3 routes them all through, and this reads that log. It is
* strictly better: it needs no walk, sees calls from any module, and
* cannot miss one made before a wrapper was installed, which is what
* the old "runs twice" dance was working around.
*
* `bytes` is the response size, so `measureBytes` is turned on here —
* only a measurement wants to pay for a clone-and-read of every body.
*/
const INSTRUMENT = `() => {
// Runs twice: once as an initScript (before window.go exists, which
// is the only moment early enough to catch the long-task observer's
// first entries) and once after the bridge reports ready. So the
// state is created at most once and the *walk* happens every time —
// getting that backwards silently measures zero binding calls.
const first = !window.__yjPerf;
const INSTRUMENT = `(names) => {
if (window.__yjPerf) return;
if (first) {
const calls = [];
window.__yjPerf = {
calls,
reset: () => { calls.length = 0; },
since: (t) => calls.filter((c) => c.start >= t),
longtasks: [],
};
}
window.__yjEvents.measureBytes = true;
const calls = window.__yjPerf.calls;
const wrap = (obj, key, path) => {
const fn = obj[key];
if (typeof fn !== 'function' || fn.__yjPerfWrapped) return;
const wrapped = function (...args) {
const start = performance.now();
let out;
try { out = fn.apply(this, args); } catch (e) { throw e; }
return Promise.resolve(out).then((v) => {
let bytes = 0;
try { bytes = JSON.stringify(v ?? null).length; } catch { bytes = -1; }
calls.push({ path, start, ms: performance.now() - start, bytes });
return v;
});
};
wrapped.__yjPerfWrapped = true;
obj[key] = wrapped;
window.__yjPerf = {
get calls() {
return window.__yjEvents.bindings.map((c) => ({
path: names[c.methodID] || ('#' + c.methodID),
methodID: c.methodID,
start: c.start,
ms: c.ms,
bytes: c.bytes,
}));
},
reset: () => { window.__yjEvents.reset(); },
since: (t) => window.__yjPerf.calls.filter((c) => c.start >= t),
longtasks: [],
};
const walk = (obj, prefix, depth) => {
if (!obj || depth > 4) return;
for (const key of Object.keys(obj)) {
const v = obj[key];
if (typeof v === 'function') wrap(obj, key, prefix + key);
else if (v && typeof v === 'object') walk(v, prefix + key + '.', depth + 1);
}
};
walk(window.go, '', 0);
if (!first) return;
// Long tasks are the honest form of "the app stalls": a 25 MB JSON
// parse on the main thread shows up here and nowhere else.
try {
@@ -352,7 +341,15 @@ async function measureTrackChange(page) {
const paths = (tracks ?? []).slice(0, 4).map((t) => t.FilePath);
if (paths.length < 2) return { error: 'library too small to measure' };
await ev.call('queue.Queue.SetQueue', [paths, 0, false], 15000);
await ev.call(
'queue.Queue.SetQueue',
// The fourth argument is the queue's source; these are
// ad-hoc tracks, so it is the empty one. v3 rejects a
// call with the wrong argument count where v2 filled the
// gap with a zero value.
[paths, 0, false, { type: '', id: 0, label: '' }],
15000,
);
await ev.call('queue.Queue.PlayIndex', [0], 15000);
// Settle mid-track before starting to record. Starting playback
@@ -1046,14 +1043,15 @@ const SCROLL_SETTLE_MS = 260;
async function measureScroll(page) {
// -- M3: the track list, with the Art column staged on. --
const priorColumns = await page.evaluate(async () => {
const prior = await window.go.config.Config.GetTrackListColumns();
const ev = window.__yjEvents;
const prior = await ev.call('config.Config.GetTrackListColumns', [], 15000);
await window.go.config.Config.SetTrackListColumns(
await ev.call('config.Config.SetTrackListColumns', [
[{ id: 'albumArt' }, { id: 'trackName' },
{ id: 'artistName' }, { id: 'trackLength' }],
);
], 15000);
return prior.map((c) => ({ id: c.id }));
return (prior ?? []).map((c) => ({ id: c.id }));
});
const scrollView = async (view, tag) => {
@@ -1141,7 +1139,9 @@ async function measureScroll(page) {
const artists = await scrollView('artists', 'artists-view');
await page.evaluate(
(cols) => window.go.config.Config.SetTrackListColumns(cols),
(cols) => window.__yjEvents.call(
'config.Config.SetTrackListColumns', [cols], 15000,
),
priorColumns,
);
@@ -1605,7 +1605,15 @@ async function measurePlayerBarPass(page) {
if (paths.length < 2) return { error: 'library too small to measure' };
await ev.call('queue.Queue.SetQueue', [paths, 0, false], 15000);
await ev.call(
'queue.Queue.SetQueue',
// The fourth argument is the queue's source; these are
// ad-hoc tracks, so it is the empty one. v3 rejects a
// call with the wrong argument count where v2 filled the
// gap with a zero value.
[paths, 0, false, { type: '', id: 0, label: '' }],
15000,
);
await ev.call('queue.Queue.PlayIndex', [0], 15000);
await ev.call('player.Player.Pause', [], 5000).catch(() => {});
await new Promise((r) => setTimeout(r, 600));
@@ -1804,7 +1812,9 @@ async function run(label) {
const browser = await chromium.launch();
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
await context.addInitScript({ path: BRIDGE });
await context.addInitScript(`(${INSTRUMENT})()`);
await context.addInitScript(
`(${INSTRUMENT})(${JSON.stringify(METHOD_NAMES)})`,
);
const page = await context.newPage();
const client = await context.newCDPSession(page);
@@ -1813,8 +1823,10 @@ async function run(label) {
const t0 = Date.now();
await page.goto(BASE_URL, { waitUntil: 'load' });
await page.evaluate(() => window.__yjEvents.ready(30000));
// Wrapping runs before `window.go` exists; re-run now that it does.
await page.evaluate(`(${INSTRUMENT})()`);
// No second instrumentation pass. The old one existed because
// wrapping had to happen after `window.go` appeared, yet the long
// task observer had to start before it; the bridge now records every
// binding call from the initScript onward, so one pass does both.
const report = {
label,
+2 -2
View File
@@ -1,8 +1,8 @@
import { defineConfig, devices } from '@playwright/test';
/**
* These specs drive the *real* application: the Wails dev server on
* :34115 serves the real frontend with real bindings on `window.go`,
* These specs drive the *real* application: Wails v3's server mode on
* :34115 serves the real frontend with the real generated bindings,
* bridged to the same Go backend a desktop window would use. Nothing
* here is mocked.
*
+8 -10
View File
@@ -16,6 +16,14 @@ import type { Page } from '@playwright/test';
* none, so Play was wired, labelled correctly, clicked cleanly and
* queued **nothing**. Every component test still passed.
*/
// There is no test for the tracklist legend, and there should not be:
// `dcc40b1` inverted the mark — rows *not* in the library are dimmed in
// place and nothing marks the ones that are — and deleted
// `.tracklist-legend` with it. The spec asserting it survived that
// commit and has been failing on main ever since. What replaced it
// (the dimming, and the `aria-disabled` that carries it to anyone not
// seeing the page) is covered at the component tier, in
// frontend/test/components/album-actions.test.ts.
test.describe('playing an album from its page', () => {
test.beforeEach(async ({ app }) => {
await openFirstAlbum(app);
@@ -55,16 +63,6 @@ test.describe('playing an album from its page', () => {
await expect.poll(() => queueLength(app)).toBe(before * 2);
});
test('the ticks against the tracks have a legend', async ({ app }) => {
// `H-13` calls them unexplained. They were never *unlabelled* — the
// indicator has carried a title and an aria-label reading
// "Track “X” is in your library" all along — but a sighted user
// scanning the page got a column of green circles and no key.
await expect(
app.locator('explore-album-details').locator('.tracklist-legend'),
).toContainText('in your library');
});
test('the ticks are badges, not keyboard stops', async ({ app }) => {
// Every one of them was a <button> whose click handler was a
// stopPropagation() and a comment saying to wire up the download
+25 -10
View File
@@ -15,12 +15,18 @@ import {
*/
test.describe('harness', () => {
test('the app is the real app, not a mock', async ({ app }) => {
// All 11 bound services land on window.go through the dev server.
const services = await app.evaluate(() => Object.keys(window.go));
// v2 landed every bound service on `window.go`, so "is this real"
// could be asked of an object. v3 has no such global — the
// bindings are ordinary bundled modules — so the question is asked
// of the runtime instead, which is a better question anyway: the
// real runtime is loaded, and it answers for real methods and
// refuses invented ones.
const runtime = await app.evaluate(() => ({
dispatch: typeof window._wails?.dispatchWailsEvent,
client: typeof window._wails?.clientId,
}));
expect(services).toEqual(
expect.arrayContaining(['queue', 'player', 'library', 'explore']),
);
expect(runtime).toEqual({ dispatch: 'function', client: 'string' });
const state = await callBinding<{ tracks: unknown[] }>(
app,
@@ -28,6 +34,12 @@ test.describe('harness', () => {
);
expect(state).toHaveProperty('tracks');
const unknown = await app
.evaluate(() => window.__yjEvents.call('queue.Queue.Nope', [], 2_000))
.catch((err: Error) => err.message);
expect(unknown).toContain('unknown bound method');
});
test('backend events are recorded, in order, with payloads', async ({
@@ -58,10 +70,12 @@ test.describe('harness', () => {
});
test('a binding called with wrong types fails fast', async ({ app }) => {
// player.UserVolume is an int. Passing a float makes the backend
// log "error parsing arguments" and never fire the callback; without
// a timeout the promise never settles and the spec hangs until the
// suite gives up.
// player.UserVolume is an int. Under v2 a float made the backend
// log "error parsing arguments" and never fire the callback, so
// this asserted that the harness's own timeout fired — the failure
// was visible only because the harness invented a deadline. v3
// answers 422 with a TypeError naming the argument, so the
// assertion is now on the backend's own words.
const failure = await app.evaluate(async () => {
try {
await window.__yjEvents.call(
@@ -76,7 +90,8 @@ test.describe('harness', () => {
}
});
expect(failure).toContain('did not settle');
expect(failure).toContain('TypeError');
expect(failure).toContain('player.UserVolume');
});
test('the control surface is mounted and seeded', async ({ testctl }) => {
+25 -25
View File
@@ -1,4 +1,13 @@
import { test, expect, resetEvents, callBinding } from '../support/fixtures.js';
import type { Page } from '@playwright/test';
import {
test,
expect,
resetEvents,
callBinding,
bindingCalls,
NO_QUEUE_SOURCE,
} from '../support/fixtures.js';
/**
* Finishing a track is cheap, and does not disturb the user.
@@ -19,23 +28,17 @@ import { test, expect, resetEvents, callBinding } from '../support/fixtures.js';
/** Long enough for a fixture track (26 s) to finish by itself. */
const FINISH_TIMEOUT = 60_000;
/** Instrument the library bindings so "was anything refetched" is a fact. */
const COUNT_LIBRARY_CALLS = `(() => {
const w = window;
if (w.__yjCalls) { w.__yjCalls.length = 0; return; }
w.__yjCalls = [];
const lib = w.go.library.Library;
for (const key of Object.keys(lib)) {
const fn = lib[key];
if (typeof fn !== 'function' || fn.__counted) continue;
const wrapped = function (...args) {
w.__yjCalls.push(key);
return fn.apply(this, args);
};
wrapped.__counted = true;
lib[key] = wrapped;
}
})()`;
/**
* "Was anything refetched" is a fact, not an inference.
*
* This used to wrap every method on `window.go.library.Library` in
* place. v3 has no such object, and does not need one: the harness
* bridge records every binding call off the single POST they all go
* through, so the question is answered by reading that log rather than
* by instrumenting a target first. `resetEvents` clears it.
*/
const libraryCalls = async (app: Page): Promise<string[]> =>
(await bindingCalls(app)).filter((c) => c.startsWith('library.Library.'));
/**
* Select rows by dispatching on the row rather than clicking it.
@@ -82,8 +85,7 @@ test.describe('a finished track', () => {
expect(paths.length).toBeGreaterThanOrEqual(2);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false]);
await app.evaluate(COUNT_LIBRARY_CALLS);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false, NO_QUEUE_SOURCE]);
await resetEvents(app);
await callBinding(app, 'queue.Queue.PlayIndex', [0]);
@@ -111,12 +113,10 @@ test.describe('a finished track', () => {
'a play emitted the retag event, which invalidates every cache',
).toBe(0);
const refetched = await app.evaluate(
() => (window as unknown as { __yjCalls: string[] }).__yjCalls,
);
const refetched = await libraryCalls(app);
expect(
refetched.filter((c) => c.startsWith('GetAll')),
refetched.filter((c) => c.startsWith('library.Library.GetAll')),
'a play refetched a collection',
).toEqual([]);
@@ -136,7 +136,7 @@ test.describe('a finished track', () => {
const paths = await app.evaluate(firstPaths, 2);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false]);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false, NO_QUEUE_SOURCE]);
await resetEvents(app);
await callBinding(app, 'queue.Queue.PlayIndex', [0]);
+3 -1
View File
@@ -7,6 +7,7 @@ import {
resetEvents,
waitForEvent,
LONG_TRACK,
NO_QUEUE_SOURCE,
} from '../support/fixtures.js';
import type { Page } from '@playwright/test';
@@ -161,6 +162,7 @@ test.describe('a finished queue keeps its context', () => {
[rows[0].file_path],
0,
false,
NO_QUEUE_SOURCE,
]);
await waitForEvent(app, 'QueueChanged');
await callBinding(app, 'queue.Queue.Play');
@@ -199,7 +201,7 @@ test.describe('a track that will not play says so', () => {
try {
await callBinding(app, 'queue.Queue.Clear');
await resetEvents(app);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false]);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false, NO_QUEUE_SOURCE]);
await waitForEvent(app, 'QueueChanged');
await callBinding(app, 'queue.Queue.Play');
+7 -2
View File
@@ -1,4 +1,9 @@
import { test, expect, callBinding } from '../support/fixtures.js';
import {
test,
expect,
callBinding,
NO_QUEUE_SOURCE,
} from '../support/fixtures.js';
import type { Page } from '@playwright/test';
/**
@@ -35,7 +40,7 @@ async function queueFourAndOpen(app: Page): Promise<string[]> {
return (tracks as { FilePath: string }[]).slice(0, 4).map((t) => t.FilePath);
});
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false]);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false, NO_QUEUE_SOURCE]);
// A closed panel renders no list at all, so there is no row to focus.
await app.locator('#queue-button').click();
+8 -2
View File
@@ -1,4 +1,10 @@
import { test, expect, callBinding, waitForEvent } from '../support/fixtures.js';
import {
test,
expect,
callBinding,
waitForEvent,
NO_QUEUE_SOURCE,
} from '../support/fixtures.js';
import type { Page } from '@playwright/test';
/**
@@ -64,7 +70,7 @@ async function playTheLongOne(app: Page): Promise<void> {
expect(paths.length).toBeGreaterThan(0);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false]);
await callBinding(app, 'queue.Queue.SetQueue', [paths, 0, false, NO_QUEUE_SOURCE]);
await waitForEvent(app, 'TrackChanged');
// The scroll cycle is armed 1500 ms after the geometry is measured,
+33 -23
View File
@@ -199,39 +199,49 @@ function addRequest(
}
/**
* Drop any request for this album, through the raw binding.
* Drop any request for this album, over the runtime endpoint.
*
* Deliberately not `callBinding`: that goes through `window.__yjEvents`,
* which only exists on a page the `app` fixture created — a bare
* `browser.newPage()` has no init script, so the bridge is undefined and
* the cleanup throws where nobody is looking. The first version of this
* did exactly that and left the request behind, which failed the *next*
* run of this same spec.
* Deliberately not `callBinding`: that goes through
* `window.__yjEvents`, which only exists on a page the `app` fixture
* created — a bare `browser.newPage()` has no init script, so the
* bridge is undefined and the cleanup throws where nobody is looking.
* The first version of this did exactly that and left the request
* behind, which failed the *next* run of this same spec.
*
* v2's answer was `window.go`, which every page had. v3 has no such
* global, and the version of this that kept reading it did not throw —
* it returned early on `if (!svc)`, which is the same silent cleanup
* with a different cause. A POST to `/wails/runtime` needs neither:
* it is the same request the bundle makes, and any page can make it.
*/
async function clearRequest(page: import('@playwright/test').Page) {
await page.evaluate(async (mbid) => {
const go = (
window as unknown as {
go?: {
download?: {
Service?: {
ListRequests(): Promise<{ id: number; mbid: string }[]>;
RemoveRequest(id: number): Promise<void>;
};
};
};
}
).go;
const call = async (method: string, args: unknown[]) => {
const res = await fetch('/wails/runtime', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
object: 0,
method: 0,
args: {
'call-id': `clear-${method}`,
methodName: `yellowjacket/backend/${method}`,
args,
},
}),
});
const svc = go?.download?.Service;
if (!res.ok) throw new Error(`${method}: ${await res.text()}`);
if (!svc) return;
return res.json();
};
const rows = (await svc.ListRequests()) ?? [];
const rows: { id: number; mbid: string }[] =
(await call('download.Service.ListRequests', [])) ?? [];
for (const row of rows) {
if (row.mbid?.toLowerCase() === mbid.toLowerCase()) {
await svc.RemoveRequest(row.id);
await call('download.Service.RemoveRequest', [row.id]);
}
}
}, MBID);
+49 -6
View File
@@ -3,12 +3,26 @@ import { dirname, resolve } from 'node:path';
import { test as base, expect, type Page } from '@playwright/test';
import { nameOf } from './method-ids.mjs';
const here = dirname(fileURLToPath(import.meta.url));
/** The same bridge `playwright-cli` loads, so an exploratory session and
* a committed spec see an identical page. */
const INIT_SCRIPT = resolve(here, '../../.playwright/init-events.js');
/**
* The fourth argument to `queue.Queue.SetQueue`, for a queue with no
* single source — the whole library, or a handful of ad-hoc tracks,
* which is what every spec here builds.
*
* It is passed explicitly because v3 rejects a call with the wrong
* argument count (`expects 4 arguments, got 3`) where v2 accepted one
* and filled the gap with a zero value. The specs had been three-arg
* since the parameter was added; nothing said so.
*/
export const NO_QUEUE_SOURCE = { type: '', id: 0, label: '' };
/**
* The 90-second fixture track (`cmd/gentestdata`, case `edge-lengths`).
*
@@ -61,12 +75,13 @@ export async function eventNames(
}
/**
* Call a bound Go method with a timeout.
* Call a bound Go method by name, over the runtime's own endpoint.
*
* Wrong argument types make the backend log "error parsing arguments"
* and never fire the callback, so an unguarded call hangs until the
* whole spec times out with no clue why. This fails in seconds and
* says where to look.
* v3 rejects a bad call rather than never firing its callback the way
* v2 did: a wrong argument type comes back as a TypeError naming the
* argument, a wrong count as `expects 4 arguments, got 3`, an unknown
* method as a ReferenceError. The timeout is a backstop for a hung
* request, not the mechanism that makes a mistake visible.
*/
export async function callBinding<T = unknown>(
page: Page,
@@ -81,6 +96,21 @@ export async function callBinding<T = unknown>(
) as Promise<T>;
}
/**
* The binding calls the *app* made, newest last, as `pkg.Type.Method`.
*
* This is what replaces v2's trick of wrapping `window.go` in place:
* `.playwright/init-events.js` records every call off the one POST v3
* routes them all through, and `method-ids.ts` names them from the
* generated tree. It sees calls from any module and cannot miss one
* made before a wrapper was installed.
*/
export async function bindingCalls(page: Page): Promise<string[]> {
const calls = await page.evaluate(() => window.__yjEvents.bindings);
return calls.map(nameOf);
}
/** Thin client for the dev-only /__test/ surface (backend/testctl). */
export class TestCtl {
constructor(private readonly baseURL: string) {}
@@ -166,7 +196,20 @@ declare global {
): Promise<YjEvent>;
ready(timeoutMs?: number): Promise<boolean>;
call(path: string, args?: unknown[], timeoutMs?: number): Promise<any>;
/** Every binding call the app itself made; see init-events.js. */
bindings: {
methodID: number | null;
methodName: string | null;
start: number;
ms: number;
bytes: number;
}[];
measureBytes: boolean;
};
/** The v3 runtime's own namespace, installed by @wailsio/runtime. */
_wails?: {
dispatchWailsEvent?: (event: unknown) => void;
clientId?: string;
};
go: Record<string, Record<string, Record<string, (...a: any[]) => any>>>;
}
}
+110
View File
@@ -0,0 +1,110 @@
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
/**
* Turns the method ids a binding call carries back into the names a
* spec (or a measurement) wants to read.
*
* Plain JavaScript, not TypeScript, because `e2e/perf/measure.mjs` runs
* under bare `node` and both it and the specs need exactly this map —
* and one derivation with a `.mjs` extension is better than two that
* can disagree.
*
* v2 put every bound method on `window.go`, so a harness could walk
* that object to wrap or enumerate them. v3 has no such surface: the
* generated bindings are ordinary bundled modules calling
* `$Call.ByID(<fnv hash of the fully-qualified name>)`, and what
* reaches the wire — and therefore what `.playwright/init-events.js`
* can record — is the number.
*
* Plan 009 phase 6b named two ways to get the list back. This is the
* preferred one: derive it from `frontend/bindings/`, which is a real
* generated tree and is already gated by `make bindings-check`. The
* alternative — a hand-maintained list — goes stale silently, which is
* the failure mode that check exists to prevent.
*
* Nothing here hashes anything. The generated source carries the id as
* a literal beside the function that sends it, so this reads the two
* together rather than recomputing one from the other and hoping the
* hash still matches.
*/
const here = dirname(fileURLToPath(import.meta.url));
const BINDINGS_ROOT = resolve(here, '../../frontend/bindings/yellowjacket');
/** `export function Name(…) { return $Call.ByID(123, …) }` */
const BOUND_METHOD = /export function (\w+)\([\s\S]*?\$Call\.ByID\((\d+)/g;
/** `import * as Library from "./library.js";` — the only place the Go
* type's casing survives; the file is `library.ts`, and
* `frontendutil.ts` cannot tell you it is `FrontendUtil`. */
const SERVICE_EXPORT = /import \* as (\w+) from "\.\/([\w.]+)\.js"/g;
function* walk(dir) {
for (const entry of readdirSync(dir)) {
const path = join(dir, entry);
if (statSync(path).isDirectory()) yield* walk(path);
else if (entry.endsWith('.ts')) yield path;
}
}
let cached;
/**
* methodIDs maps a binding's method id to `pkg.Type.Method` — the same
* short path `callBinding` takes, so a spec never has to know that the
* backend calls it `yellowjacket/backend/queue.Queue.GetState`.
*/
export function methodIDs() {
if (cached) return cached;
const byID = new Map();
for (const file of walk(BINDINGS_ROOT)) {
if (!file.endsWith('index.ts')) continue;
const dir = dirname(file);
const pkg = dir.split('/').pop() ?? '';
const index = readFileSync(file, 'utf8');
for (const [, typeName, base] of index.matchAll(SERVICE_EXPORT)) {
let source;
try {
source = readFileSync(join(dir, `${base}.ts`), 'utf8');
} catch {
continue; // a models-only re-export, which binds nothing
}
for (const [, method, id] of source.matchAll(BOUND_METHOD)) {
byID.set(Number(id), `${pkg}.${typeName}.${method}`);
}
}
}
if (byID.size === 0) {
throw new Error(
`method-ids: no bound methods under ${BINDINGS_ROOT}; ` +
`run 'make bindings'`,
);
}
cached = byID;
return byID;
}
/** Names one recorded binding call, or `#<id>` if the map has no entry
* — which fails the assertion naming it rather than passing quietly. */
export function nameOf(call) {
if (call.methodName) {
return call.methodName.replace(/^yellowjacket\/backend\//, '');
}
return call.methodID === null
? '#unknown'
: (methodIDs().get(call.methodID) ?? `#${call.methodID}`);
}
+8 -2
View File
@@ -8,7 +8,13 @@
"noEmit": true,
"skipLibCheck": true,
"types": ["node"],
"allowImportingTsExtensions": true
"allowImportingTsExtensions": true,
"allowJs": true
},
"include": ["specs/**/*.ts", "support/**/*.ts", "playwright.config.ts"]
"include": [
"specs/**/*.ts",
"support/**/*.ts",
"support/**/*.mjs",
"playwright.config.ts"
]
}