@buffcore/cli 0.8.44 → 0.8.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/commands/prototype/browser.d.ts +4 -24
  3. package/dist/commands/prototype/browser.js +13 -76
  4. package/dist/commands/prototype/loaded-garbage.d.ts +10 -0
  5. package/dist/commands/prototype/loaded-garbage.js +20 -0
  6. package/dist/commands/prototype/mark-shot.d.ts +31 -0
  7. package/dist/commands/prototype/mark-shot.js +149 -0
  8. package/dist/commands/prototype/media-ready.d.ts +9 -3
  9. package/dist/commands/prototype/media-ready.js +9 -4
  10. package/dist/commands/prototype/messages.en.d.ts +1 -0
  11. package/dist/commands/prototype/messages.en.js +1 -0
  12. package/dist/commands/prototype/messages.js +1 -0
  13. package/dist/commands/prototype/scene-check.d.ts +37 -0
  14. package/dist/commands/prototype/scene-check.js +68 -0
  15. package/dist/commands/prototype/scene-look.d.ts +14 -0
  16. package/dist/commands/prototype/scene-look.js +89 -0
  17. package/dist/commands/prototype/scene-ready.d.ts +46 -0
  18. package/dist/commands/prototype/scene-ready.js +116 -0
  19. package/dist/commands/prototype/scene.d.ts +22 -1
  20. package/dist/commands/prototype/scene.js +60 -5
  21. package/dist/commands/prototype/snapshot-command.js +20 -10
  22. package/dist/commands/prototype/snapshot-inputs.js +7 -0
  23. package/dist/commands/prototype/snapshot-requests.d.ts +1 -1
  24. package/dist/commands/prototype/snapshot-requests.js +1 -1
  25. package/dist/commands/prototype/snapshot-servers.js +4 -2
  26. package/dist/commands/prototype/snapshot.d.ts +1 -0
  27. package/dist/commands/prototype/snapshot.js +1 -0
  28. package/dist/commands/ui/commands.en.d.ts +3 -0
  29. package/dist/commands/ui/commands.en.js +3 -0
  30. package/dist/commands/ui/commands.es.d.ts +3 -0
  31. package/dist/commands/ui/commands.es.js +3 -0
  32. package/dist/commands/ui/plan-brief.d.ts +13 -0
  33. package/dist/commands/ui/plan-brief.js +91 -0
  34. package/dist/commands/ui/plan-files.d.ts +1 -11
  35. package/dist/commands/ui/plan-files.js +2 -48
  36. package/dist/commands/ui/prototype-main.d.ts +5 -0
  37. package/dist/commands/ui/prototype-shot-route.d.ts +16 -0
  38. package/dist/commands/ui/prototype-shot-route.js +98 -0
  39. package/dist/commands/ui/server-core.js +2 -0
  40. package/dist/commands/ui/server.js +13 -1
  41. package/dist/commands/ui/studio-state.d.ts +5 -0
  42. package/dist/ui/page.js +109 -99
  43. package/docs/PROTOTYPE.md +3 -2
  44. package/docs/WORKBENCH.md +1 -1
  45. package/package.json +11 -11
  46. package/skills/ape-plan-change/SKILL.md +8 -0
  47. package/templates/product/apps/app/app.json +3 -0
  48. package/templates/product/plan/brief.md +29 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,26 @@ One section per release (a git tag). **Upgrade notes** list anything that breaks
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## v0.8.46 (2026-12-03)
8
+
9
+ - Prototype snapshots draw a scene's later looks in place, on the same page. Each scene starts in a fresh browser context and then checks its last look against a fresh load; when the picture or findings differ, the scene is drawn again with full loads. The terminal counts full-page fallbacks of looks and scenes. Every load now blurs a field that autofocuses late before the picture, so a scene's focus ring no longer depends on timing; this changes earlier pictures only where that ring came and went. A view that takes the focus back after the blur keeps it, as a plain load shows it. Limits: code above the scene page that reads the look or storage once at boot is not rechecked per look, and scenes whose pictures vary between loads always redraw fresh.
10
+ - On Linux (and likely macOS), the app's first page after its Metro server starts (in `ape dev` and in a prototype snapshot's warm-up) no longer fails with HTTP 500 "Failed to collapse": a new product's `apps/app/app.json` turns off Expo's tsconfig `paths` resolver (`"experiments": { "tsconfigPaths": false }`), which tripped on the app's tsconfig extending the root one. No product tsconfig declares `paths`.
11
+
12
+ **Upgrade notes** (every product): on Linux (and likely macOS), add `"experiments": { "tsconfigPaths": false }` under `expo` in `apps/app/app.json`. Leave it out if your app relies on tsconfig `paths`.
13
+
14
+ ## v0.8.45 (2026-12-03)
15
+
16
+ - The studio's Prototype is a workspace: along the top, the change and its version (Compare, Approve), **Customer app | Console**, **Mobile | Tablet | Desktop** (Rotate for a tablet) and the tools **Select | Comment | Draw | Area**; on the left, **Journeys** (from `plan/journeys.md`, by who does them and in which app, joined to the journeys the running app plays; the open one lists its steps to jump to) and **Screens**, with the sample data at the foot; in the middle, the app in its device, zoomed to fit, with a line saying what you see and the step bar (Back, the step, Play, Next) under it. The console is a second frame at the stack's admin address: switching keeps each one's step and never reloads the other. The rail folds to its icons on this page. At phone width a phone's app takes the page (a tablet or a desktop is drawn in its bezel, zoomed to fit), the device choice shows as icons, and a bar sits at the app's foot (Journeys, Back, the step, Next, Changes); on a touch screen the Comment hint says tap. The preview's Try a journey and Preview options menus, the canvas's Full screen button and the drawn-only full-screen scenes are gone.
17
+
18
+ **Upgrade notes** (hosts that build on `@buffcore/admin-shell/workbench`): the drawn-only full screen is removed from the public types: `LOOP_MOMENTS` (and so `LoopMoment`) no longer has `fs-tablet`, `fs-overview` or `fs-change`, `LoopSample` no longer has `fs`, and `FsSample` and `FsMark` are gone; delete them from your own sample data. The studio catalog's `studio.loop.proto.fullScreen` and `studio.loop.fs.*` messages are gone too, so drop any override of them. `ProtoSample` gains an optional `consoleOthers` (the console's scenes for the workspace's Screens).
19
+ - Marking in the Prototype workspace, with the bar's tools (or the keys V, C, P and R; Escape for Select) and their hint in the line above the device: Comment pins a numbered note on the part clicked (the running app names it, "Comment on Price", by its accessible label or test id, else "this spot"), Area drags a dashed box and Draw marks freehand. The marks are kept per change and version until sent and listed above the chat's box, each with its number, kind, screen and device (a mark records the app, the device, a turned tablet, and the journey step or sample data shown; a click shows them again), its note and Remove, with Clear all and a box for anything else. One **Send N changes** sends one message with every mark, its note and its place, and a picture of each marked screen, shot by the snapshot's browser at that device with the marks drawn (`POST /api/prototype/shot`); while the agent works it waits in the chat as one card (Edit, Back to the box) and goes when the turn ends. The bridge's new `ape:prototype:part` ask goes only on the private port of the current hello and its answer is read strictly: only a name and a box, never the app's data. At phone width the foot bar's Changes counts the marks. `TextArea` gains `labelHidden`; the icon set gains `tablet`. Known limits: marks go on the customer app only, so on the Console the marking tools are off and the line above the device says why (a picture of the console would need a signed-in browser); and the picture's browser refuses requests and WebSockets to other hosts and a page that ends on another address, but a redirect the app's own server answers is followed before that check (the app's server could fetch that address anyway).
20
+
21
+ **Upgrade notes** (every product): keep `@buffcore/app-shell` and `@buffcore/admin-shell` on the same release (`ape upgrade` does); an older prototype home does not answer the part ask, so a comment is on "this spot".
22
+ - The Brief reads short first: What it is; Who uses it as a table (role, where, what we know); Kind; How it earns with the money seal; Must have and Not now side by side, the first few of each with "N more"; Not this project, each line with Edit and Add a line (both a message to the agent, as adding was); the agent's questions. Each section's Read more opens its whole text from `plan/brief.md` in a reading sheet (headings, real lists, about 68 characters a line, the product's Markdown shown as text only), and the brief's other sections open from one Read the whole brief. The short form is the `> Summary:` line the agent writes under each heading (one per role in Who it is for, one per item in Must do and Later); a section without one shows its first sentence, and a section the brief does not have is not shown. The studio state's brief gains `parts` (each section's summaries and Markdown); `Markdown` reads numbered lists and takes `size="read"`, and `Sheet` takes `size="read"` and a `sub` line.
23
+
24
+ **Upgrade notes** (every product): the brief template and the `ape-plan-change` skill now ask for a `> Summary:` line under each heading of `plan/brief.md`; `ape upgrade` refreshes the skill. An existing brief works as it is (each section shows its first sentence); to read it short, ask the agent to add the summary lines.
25
+ - The studio's scroll bars are a little easier to find: the thumb is a little stronger than a border.
26
+
7
27
  ## v0.8.44 (2026-12-02)
8
28
 
9
29
  - A host whose own trusted launcher starts the agent's turns can say so: `createUiServer({ hostLaunched: true })`, or `APE_HOST_LAUNCHED=1` in the environment of `ape ui` (exactly `1`). Every Claude Code turn (coding, Build, design, validation, tests, fixes, planning on Autopilot) then launches exactly as a 0.8.41 turn did: no per-turn `--settings` file with the limits hook, no `--mcp-config` with the permission tool, no `--permission-prompt-tool` and no per-turn socket; `acceptEdits`, or `dontAsk` with hooks off for planning, at every level (never `auto` or `bypassPermissions`, Autopilot and Never ask included), with 0.8.41's allow and deny lists. Fresh turns (the review before Save and the critique) follow it: hooks off through the inline `--settings` JSON, no settings file and no `--setting-sources=`. Settings says once that the host starts the agents and applies their limits (English and Spanish), and the studio state gains an optional `hostLaunched`. Off by default: nothing changes for a host that passes nothing.
@@ -1,5 +1,7 @@
1
- import { type Browser, type BrowserContextOptions, type Frame, type Page } from 'playwright-core';
1
+ import { type Browser, type BrowserContextOptions, type Page } from 'playwright-core';
2
2
  import type { Size } from './checks.ts';
3
+ import type { MediaState } from './media-ready.ts';
4
+ export { animationsDone, sceneFrames, waitForScene } from './scene-ready.ts';
3
5
  /**
4
6
  * The one command that installs the browser, anywhere (a product has no playwright-core of its
5
7
  * own): the version this CLI runs, since each version drives its own Chromium build.
@@ -30,32 +32,10 @@ export declare const pageGone: (error: unknown) => boolean;
30
32
  export declare function pageOptions(frame: Size): BrowserContextOptions;
31
33
  /** A page for one scene, opened as `pageOptions` says. */
32
34
  export declare function openPage(browser: Browser, frame: Size, timeout?: number): Promise<Page>;
33
- /**
34
- * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
35
- * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
36
- * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
37
- * page from another origin while it is off screen, so the wait for a paint ends after a second.
38
- */
39
- export declare function animationsDone(timeout: number): Promise<void>;
40
- /** The console can show an app scene in an iframe of its own. */
41
- export declare function sceneFrames(page: Page, locale: string): Promise<{
42
- frame: Frame;
43
- index: number;
44
- locale: string;
45
- }[]>;
46
- /**
47
- * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
48
- * was still loading as its allowance ran out: the page is shot as it is.
49
- */
50
- export declare function waitForScene(page: Page, locale: string, { live, animationWait, mediaWait, }?: {
51
- live?: () => boolean;
52
- animationWait?: number;
53
- mediaWait?: number;
54
- }): Promise<boolean>;
55
35
  /**
56
36
  * Show a scene page and wait until it has drawn. A scene that frames a scene page (a console
57
37
  * scene with the app's `/_scene` inside, e.g. a `DeviceFrame`) waits for that page too. A page
58
38
  * whose module fails to load (a busy dev server drops requests under load) is loaded again once.
59
39
  * True when a font or picture was still loading after `mediaWait` (`MEDIA_WAIT` unset).
60
40
  */
61
- export declare function openScene(page: Page, url: string, locale: string, mediaWait?: number): Promise<boolean>;
41
+ export declare function openScene(page: Page, url: string, locale: string, mediaWait?: number, onMedia?: (media: MediaState) => void): Promise<boolean>;
@@ -5,8 +5,10 @@
5
5
  import { createRequire } from 'node:module';
6
6
  import { chromium, } from 'playwright-core';
7
7
  import { accessDenied } from './access-denied.js';
8
- import { MEDIA_WAIT, mediaReady } from './media-ready.js';
8
+ import { collectLoadedGarbage } from './loaded-garbage.js';
9
+ import { waitForScene } from './scene-ready.js';
9
10
  import { SnapshotAccessRefused } from './snapshot-refused.js';
11
+ export { animationsDone, sceneFrames, waitForScene } from './scene-ready.js';
10
12
  /**
11
13
  * The one command that installs the browser, anywhere (a product has no playwright-core of its
12
14
  * own): the version this CLI runs, since each version drives its own Chromium build.
@@ -94,84 +96,14 @@ export async function openPage(browser, frame, timeout = 120_000) {
94
96
  throw new PageLoadError(String(error), { cause: error });
95
97
  }
96
98
  }
97
- /**
98
- * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
99
- * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
100
- * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
101
- * page from another origin while it is off screen, so the wait for a paint ends after a second.
102
- */
103
- export async function animationsDone(timeout) {
104
- const frames = () => new Promise((done) => {
105
- requestAnimationFrame(() => requestAnimationFrame(done));
106
- setTimeout(done, 1_000);
107
- });
108
- const end = performance.now() + timeout;
109
- await frames();
110
- while (performance.now() < end) {
111
- const running = document
112
- .getAnimations()
113
- .filter((a) => a.playState === 'running' && a.effect?.getComputedTiming().endTime !== Infinity);
114
- if (running.length === 0)
115
- return;
116
- const wait = Math.max(end - performance.now(), 0);
117
- await Promise.race([
118
- Promise.allSettled(running.map((a) => a.finished)),
119
- new Promise((done) => setTimeout(done, wait)),
120
- ]);
121
- await frames();
122
- }
123
- }
124
- /** The longest `openScene` waits for animations to finish. */
125
- const ANIMATION_WAIT = 2_000;
126
- /**
127
- * Wait until a scene page in this frame has drawn: the view rendered in the asked language, the
128
- * fonts and pictures loaded (`mediaReady`), two frames painted, and animations finished within
129
- * their allowance. The focused element is blurred first, so a field that autofocuses shows no
130
- * focus ring. True when fonts or pictures were still loading as their allowance ran out.
131
- */
132
- async function drawn(frame, locale, live, { animationWait, mediaWait }) {
133
- await frame.waitForFunction((lang) => document.documentElement.lang === lang &&
134
- (document.getElementById('root')?.childElementCount ?? 0) > 0, locale);
135
- // An attempt that lost its page (a module failed, the page loaded again) does nothing more.
136
- if (!live())
137
- return false;
138
- await frame.evaluate(() => document.activeElement?.blur());
139
- const ready = await frame.evaluate(mediaReady, mediaWait);
140
- await frame.evaluate(animationsDone, animationWait);
141
- return !ready;
142
- }
143
99
  /** A script or module of the page failed to load: a busy dev server dropping a request. */
144
100
  class ModuleLost extends Error {
145
101
  }
146
- /** The console can show an app scene in an iframe of its own. */
147
- export async function sceneFrames(page, locale) {
148
- const frames = await Promise.all((await page.$$('iframe')).map(async (iframe, index) => {
149
- const src = new URL((await iframe.getAttribute('src')) ?? '', page.url());
150
- if (src.pathname !== '/_scene')
151
- return;
152
- const frame = await iframe.contentFrame();
153
- if (frame)
154
- return { frame, index, locale: src.searchParams.get('locale') ?? locale };
155
- }));
156
- return frames.filter((entry) => entry !== undefined);
157
- }
158
- /**
159
- * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
160
- * was still loading as its allowance ran out: the page is shot as it is.
161
- */
162
- export async function waitForScene(page, locale, { live = () => true, animationWait = ANIMATION_WAIT, mediaWait = MEDIA_WAIT, } = {}) {
163
- const waits = { animationWait, mediaWait };
164
- let late = await drawn(page.mainFrame(), locale, live, waits);
165
- for (const entry of await sceneFrames(page, locale))
166
- if (await drawn(entry.frame, entry.locale, live, waits))
167
- late = true;
168
- return late;
169
- }
170
102
  /**
171
103
  * Open the page (or load it again) and wait until it has drawn. A page whose script or module
172
104
  * fails to load never draws, so that ends the wait at once, not at the timeout.
173
105
  */
174
- async function show(page, url, locale, again, mediaWait) {
106
+ async function show(page, url, locale, again, mediaWait, onMedia) {
175
107
  let lose = (_) => { };
176
108
  const lost = new Promise((_, reject) => {
177
109
  lose = reject;
@@ -191,6 +123,7 @@ async function show(page, url, locale, again, mediaWait) {
191
123
  page.on('requestfailed', watch);
192
124
  const drawing = (async () => {
193
125
  try {
126
+ await collectLoadedGarbage(page);
194
127
  await (again ? page.reload({ waitUntil: 'load' }) : page.goto(url, { waitUntil: 'load' }));
195
128
  }
196
129
  catch (error) {
@@ -199,7 +132,11 @@ async function show(page, url, locale, again, mediaWait) {
199
132
  throw new ConnectionRefused(url);
200
133
  throw error;
201
134
  }
202
- return waitForScene(page, locale, { live, ...(mediaWait === undefined ? {} : { mediaWait }) });
135
+ return waitForScene(page, locale, {
136
+ live,
137
+ onMedia,
138
+ ...(mediaWait === undefined ? {} : { mediaWait }),
139
+ });
203
140
  })();
204
141
  // Whichever loses the race must not end the run as an unhandled rejection.
205
142
  drawing.catch(() => { });
@@ -218,15 +155,15 @@ async function show(page, url, locale, again, mediaWait) {
218
155
  * whose module fails to load (a busy dev server drops requests under load) is loaded again once.
219
156
  * True when a font or picture was still loading after `mediaWait` (`MEDIA_WAIT` unset).
220
157
  */
221
- export async function openScene(page, url, locale, mediaWait) {
158
+ export async function openScene(page, url, locale, mediaWait, onMedia) {
222
159
  try {
223
160
  try {
224
- return await show(page, url, locale, false, mediaWait);
161
+ return await show(page, url, locale, false, mediaWait, onMedia);
225
162
  }
226
163
  catch (error) {
227
164
  if (!(error instanceof ModuleLost))
228
165
  throw error;
229
- return await show(page, url, locale, true, mediaWait);
166
+ return await show(page, url, locale, true, mediaWait, onMedia);
230
167
  }
231
168
  }
232
169
  catch (error) {
@@ -0,0 +1,10 @@
1
+ import type { Page } from 'playwright-core';
2
+ /**
3
+ * On Linux, Chromium keeps each loaded response in a shared-memory file of about 2 MB, which it
4
+ * reserves on disk (Playwright moves it from /dev/shm to /tmp), until the page's garbage is
5
+ * collected. Its scripts' heap stays small, so no collection comes: a console page served as
6
+ * about 1,250 separate modules held about 1.2 GB per full load, in the renderer that every
7
+ * context shares, until the disk was full and loads failed with net::ERR_INSUFFICIENT_RESOURCES.
8
+ * Collecting before each full load (about 60 ms) keeps that to the page being replaced.
9
+ */
10
+ export declare function collectLoadedGarbage(page: Page, platform?: NodeJS.Platform): Promise<void>;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * On Linux, Chromium keeps each loaded response in a shared-memory file of about 2 MB, which it
3
+ * reserves on disk (Playwright moves it from /dev/shm to /tmp), until the page's garbage is
4
+ * collected. Its scripts' heap stays small, so no collection comes: a console page served as
5
+ * about 1,250 separate modules held about 1.2 GB per full load, in the renderer that every
6
+ * context shares, until the disk was full and loads failed with net::ERR_INSUFFICIENT_RESOURCES.
7
+ * Collecting before each full load (about 60 ms) keeps that to the page being replaced.
8
+ */
9
+ export async function collectLoadedGarbage(page, platform = process.platform) {
10
+ if (platform !== 'linux')
11
+ return;
12
+ // Only an aid: a page that cannot collect still loads.
13
+ try {
14
+ const session = await page.context().newCDPSession(page);
15
+ await session
16
+ .send('HeapProfiler.collectGarbage')
17
+ .finally(() => session.detach().catch(() => { }));
18
+ }
19
+ catch { }
20
+ }
@@ -0,0 +1,31 @@
1
+ import type { MarkShotBody } from '@buffcore/contracts/workbench';
2
+ import type { Browser } from 'playwright-core';
3
+ /** The running app's prototype home at the marked step or data, as the studio frames it. */
4
+ export declare function shotAddress(app: string, body: MarkShotBody, navigation: string): URL;
5
+ /**
6
+ * Runs inside the page (Playwright sends its source): one layer over the screen with each mark,
7
+ * an area dashed, a drawing as its line, and every mark's number in a dot. Only numbers are drawn:
8
+ * a note never reaches the page. The colors are fixed, not the app's: they must read on any app.
9
+ */
10
+ export declare function drawMarks(marks: MarkShotBody['marks']): void;
11
+ /** The whole picture (load, fonts, marks and the shot itself) is done within this, or refused (ms). */
12
+ export declare const SHOT_LIMIT = 30000;
13
+ /** The shot took longer than its limit: its context was closed. */
14
+ export declare class ShotTimeout extends Error {
15
+ }
16
+ /** A WebSocket address on the app's own origin: ws for http, wss for https, the same host. */
17
+ export declare function sameHost(socket: URL, app: URL): boolean;
18
+ /** The page left the app's own address before the shot. */
19
+ export declare class ShotMoved extends Error {
20
+ }
21
+ /**
22
+ * Runs inside the page: scrolls the page, and its tallest scroller, as the app was scrolled when
23
+ * marked (the same rule finds the scroller as the app's own answer does).
24
+ */
25
+ export declare function scrollTo(scroll: NonNullable<MarkShotBody['scroll']>): void;
26
+ /**
27
+ * Opens `url` at the marked size in a fresh context, scrolled as marked, draws the marks and returns
28
+ * the PNG, all within `limit` ms. The context reaches only the app's own origin: any request to
29
+ * another host is refused, and a page that left the address (a redirect) is not shot.
30
+ */
31
+ export declare function shootMarks(browser: Browser, url: URL, body: MarkShotBody, limit?: number): Promise<Buffer>;
@@ -0,0 +1,149 @@
1
+ /** How long the page's own requests get to settle before the picture is taken (ms). */
2
+ const SETTLE = 5_000;
3
+ /** The running app's prototype home at the marked step or data, as the studio frames it. */
4
+ export function shotAddress(app, body, navigation) {
5
+ const url = new URL(app);
6
+ url.pathname = `${url.pathname.replace(/\/+$/, '')}/prototype`;
7
+ url.search = new URLSearchParams({
8
+ embed: '1',
9
+ apeNav: navigation,
10
+ studioPreview: '1',
11
+ locale: body.locale,
12
+ mode: body.mode,
13
+ ...(body.journey ? { journey: body.journey, step: String(body.step ?? 0) } : {}),
14
+ ...(body.data ? { data: body.data } : {}),
15
+ }).toString();
16
+ url.hash = '';
17
+ return url;
18
+ }
19
+ /**
20
+ * Runs inside the page (Playwright sends its source): one layer over the screen with each mark,
21
+ * an area dashed, a drawing as its line, and every mark's number in a dot. Only numbers are drawn:
22
+ * a note never reaches the page. The colors are fixed, not the app's: they must read on any app.
23
+ */
24
+ export function drawMarks(marks) {
25
+ const svg = 'http://www.w3.org/2000/svg';
26
+ const layer = document.createElementNS(svg, 'svg');
27
+ layer.setAttribute('width', String(window.innerWidth));
28
+ layer.setAttribute('height', String(window.innerHeight));
29
+ layer.setAttribute('style', 'position:fixed;inset:0;z-index:2147483647;pointer-events:none;overflow:visible');
30
+ const add = (name, attributes) => {
31
+ const node = document.createElementNS(svg, name);
32
+ for (const [key, value] of Object.entries(attributes))
33
+ node.setAttribute(key, String(value));
34
+ layer.appendChild(node);
35
+ return node;
36
+ };
37
+ const line = { fill: 'none', stroke: '#2563eb', 'stroke-linecap': 'round' };
38
+ for (const mark of marks) {
39
+ if (mark.kind === 'area' && mark.box)
40
+ add('rect', {
41
+ ...line,
42
+ x: mark.box.x,
43
+ y: mark.box.y,
44
+ width: mark.box.w,
45
+ height: mark.box.h,
46
+ rx: 4,
47
+ 'stroke-width': 2,
48
+ 'stroke-dasharray': '6 4',
49
+ });
50
+ if (mark.kind === 'draw' && mark.points)
51
+ add('polyline', {
52
+ ...line,
53
+ points: mark.points.map(([x, y]) => `${x},${y}`).join(' '),
54
+ 'stroke-width': 3,
55
+ 'stroke-linejoin': 'round',
56
+ });
57
+ const [x, y] = mark.box ? [mark.box.x, mark.box.y] : (mark.points?.[0] ?? [0, 0]);
58
+ add('circle', { cx: x, cy: y, r: 12, fill: '#2563eb', stroke: '#ffffff', 'stroke-width': 2 });
59
+ const label = add('text', {
60
+ x,
61
+ y,
62
+ fill: '#ffffff',
63
+ 'font-family': 'system-ui, sans-serif',
64
+ 'font-size': 12,
65
+ 'font-weight': 700,
66
+ 'text-anchor': 'middle',
67
+ 'dominant-baseline': 'central',
68
+ });
69
+ label.textContent = String(mark.n);
70
+ }
71
+ document.body.appendChild(layer);
72
+ }
73
+ /** The whole picture (load, fonts, marks and the shot itself) is done within this, or refused (ms). */
74
+ export const SHOT_LIMIT = 30_000;
75
+ /** The shot took longer than its limit: its context was closed. */
76
+ export class ShotTimeout extends Error {
77
+ }
78
+ /** A WebSocket address on the app's own origin: ws for http, wss for https, the same host. */
79
+ export function sameHost(socket, app) {
80
+ const scheme = { 'ws:': 'http:', 'wss:': 'https:' }[socket.protocol];
81
+ return scheme === app.protocol && socket.host === app.host;
82
+ }
83
+ /** The page left the app's own address before the shot. */
84
+ export class ShotMoved extends Error {
85
+ }
86
+ /**
87
+ * Runs inside the page: scrolls the page, and its tallest scroller, as the app was scrolled when
88
+ * marked (the same rule finds the scroller as the app's own answer does).
89
+ */
90
+ export function scrollTo(scroll) {
91
+ window.scrollTo(scroll.page.x, scroll.page.y);
92
+ let tallest;
93
+ let most = 0;
94
+ const all = document.body?.querySelectorAll('*') ?? [];
95
+ for (let i = 0; i < all.length && i < 20_000; i++) {
96
+ const el = all[i];
97
+ const room = el.scrollHeight - el.clientHeight;
98
+ if (room > most && /auto|scroll|overlay/.test(getComputedStyle(el).overflowY)) {
99
+ most = room;
100
+ tallest = el;
101
+ }
102
+ }
103
+ tallest?.scrollTo(scroll.inner.x, scroll.inner.y);
104
+ }
105
+ /**
106
+ * Opens `url` at the marked size in a fresh context, scrolled as marked, draws the marks and returns
107
+ * the PNG, all within `limit` ms. The context reaches only the app's own origin: any request to
108
+ * another host is refused, and a page that left the address (a redirect) is not shot.
109
+ */
110
+ export async function shootMarks(browser, url, body, limit = SHOT_LIMIT) {
111
+ const context = await browser.newContext({
112
+ viewport: body.view,
113
+ deviceScaleFactor: 1,
114
+ colorScheme: body.mode,
115
+ locale: body.locale,
116
+ serviceWorkers: 'block',
117
+ });
118
+ let timer;
119
+ const expired = new Promise((_, reject) => {
120
+ timer = setTimeout(() => reject(new ShotTimeout(`no picture within ${limit} ms`)), limit);
121
+ });
122
+ const shot = async () => {
123
+ // tsx names functions with `__name`; functions sent to the page need it there too.
124
+ await context.addInitScript({ content: 'globalThis.__name = (fn) => fn;' });
125
+ await context.route('**/*', (route) => new URL(route.request().url()).origin === url.origin ? route.continue() : route.abort());
126
+ // A WebSocket to another host is closed before it connects; the app's own goes through.
127
+ await context.routeWebSocket((socket) => !sameHost(socket, url), (socket) => socket.close());
128
+ const page = await context.newPage();
129
+ await page.goto(url.href, { waitUntil: 'load', timeout: limit });
130
+ await page.waitForLoadState('networkidle', { timeout: SETTLE }).catch(() => undefined);
131
+ await page.evaluate(() => document.fonts?.ready.then(() => true));
132
+ if (body.scroll)
133
+ await page.evaluate(scrollTo, body.scroll);
134
+ await page.evaluate(drawMarks, body.marks);
135
+ if (new URL(page.url()).origin !== url.origin)
136
+ throw new ShotMoved(`the page left ${url.origin}`);
137
+ return await page.screenshot({ animations: 'disabled', type: 'png' });
138
+ };
139
+ const running = shot();
140
+ running.catch(() => undefined);
141
+ try {
142
+ return await Promise.race([running, expired]);
143
+ }
144
+ finally {
145
+ clearTimeout(timer);
146
+ // Closing the context ends whatever the shot was still waiting for.
147
+ await context.close().catch(() => undefined);
148
+ }
149
+ }
@@ -1,8 +1,14 @@
1
1
  /** The longest a scene page waits for its fonts and pictures; then it is shot anyway, with a hint. */
2
2
  export declare const MEDIA_WAIT = 10000;
3
+ /** `ready`: all loaded in time. `failed`: a picture or font failed. `elapsed`: ms spent waiting. */
4
+ export interface MediaState {
5
+ ready: boolean;
6
+ failed: boolean;
7
+ elapsed: number;
8
+ }
3
9
  /**
4
10
  * Runs in the page: wait until its fonts are ready and every picture has finished, loaded or
5
- * failed (a lazy picture loads now: the shot is of the whole page). False when `timeout` ran out
6
- * first. Self-contained, since Playwright sends it to the page as text.
11
+ * failed (a lazy picture loads now: the shot is of the whole page). Also say whether any failed
12
+ * and how long the wait took. Self-contained, since Playwright sends it to the page as text.
7
13
  */
8
- export declare function mediaReady(timeout: number): Promise<boolean>;
14
+ export declare function mediaReady(timeout: number): Promise<MediaState>;
@@ -4,13 +4,15 @@
4
4
  export const MEDIA_WAIT = 10_000;
5
5
  /**
6
6
  * Runs in the page: wait until its fonts are ready and every picture has finished, loaded or
7
- * failed (a lazy picture loads now: the shot is of the whole page). False when `timeout` ran out
8
- * first. Self-contained, since Playwright sends it to the page as text.
7
+ * failed (a lazy picture loads now: the shot is of the whole page). Also say whether any failed
8
+ * and how long the wait took. Self-contained, since Playwright sends it to the page as text.
9
9
  */
10
10
  export async function mediaReady(timeout) {
11
11
  // Layout first, so the fonts the text needs have started loading before `fonts.ready` is read.
12
+ const start = performance.now();
12
13
  document.body?.getBoundingClientRect();
13
- const pictures = [...document.images].flatMap((image) => {
14
+ const images = [...document.images];
15
+ const pictures = images.flatMap((image) => {
14
16
  if (image.loading === 'lazy')
15
17
  image.loading = 'eager';
16
18
  if (image.complete)
@@ -28,7 +30,10 @@ export async function mediaReady(timeout) {
28
30
  });
29
31
  const ready = Promise.all([document.fonts.ready, ...pictures]).then(() => true);
30
32
  try {
31
- return await Promise.race([ready, late]);
33
+ const finished = await Promise.race([ready, late]);
34
+ const failed = images.some((image) => image.naturalWidth === 0) ||
35
+ [...document.fonts].some((font) => font.status === 'error');
36
+ return { ready: finished, failed, elapsed: performance.now() - start };
32
37
  }
33
38
  finally {
34
39
  clearTimeout(timer);
@@ -42,6 +42,7 @@ export declare const en: {
42
42
  'prototype.remade': string;
43
43
  'prototype.problems': string;
44
44
  'prototype.sceneResult': string;
45
+ 'prototype.drawFallbacks': string;
45
46
  'prototype.sceneFailed': string;
46
47
  'prototype.serverUnavailable': string;
47
48
  'prototype.serverExitCode': string;
@@ -43,6 +43,7 @@ export const en = {
43
43
  'prototype.remade': 'remade',
44
44
  'prototype.problems': '{count} problem(s)',
45
45
  'prototype.sceneResult': ' {title}: {result}{retry}',
46
+ 'prototype.drawFallbacks': 'Full-page fallbacks: {looks} looks, {scenes} scenes.',
46
47
  'prototype.sceneFailed': 'Scene "{scene}" failed{retry}: {detail}',
47
48
  'prototype.serverUnavailable': 'Server "{server}" is not answering for scene "{scene}". {status}.',
48
49
  'prototype.serverExitCode': 'Last exit code was {code}',
@@ -44,6 +44,7 @@ const es = {
44
44
  'prototype.remade': 'regenerada',
45
45
  'prototype.problems': '{count} problema(s)',
46
46
  'prototype.sceneResult': ' {title}: {result}{retry}',
47
+ 'prototype.drawFallbacks': 'Recargas completas: {looks} apariencias, {scenes} escenas.',
47
48
  'prototype.sceneFailed': 'La escena "{scene}" falló{retry}: {detail}',
48
49
  'prototype.serverUnavailable': 'El servidor "{server}" no responde para la escena "{scene}". {status}.',
49
50
  'prototype.serverExitCode': 'El último código de salida fue {code}',
@@ -0,0 +1,37 @@
1
+ import type { Scene } from '@buffcore/config';
2
+ import type { PrototypeProblem } from '@buffcore/contracts/prototype';
3
+ import type { Browser, Page } from 'playwright-core';
4
+ import type { checkLook, Run } from './scene.ts';
5
+ type Look = {
6
+ theme: string;
7
+ mode: string;
8
+ locale: string;
9
+ };
10
+ /** The scene's last look as drawn: where it is and whether its media was late. */
11
+ export interface LastLook {
12
+ look: Look;
13
+ url: string;
14
+ mediaWait: number | undefined;
15
+ late: boolean;
16
+ }
17
+ /** One look's picture and findings, from a found list of its own. */
18
+ export interface LookEvidence {
19
+ picture: Buffer;
20
+ problems: PrototypeProblem[];
21
+ late: boolean;
22
+ }
23
+ /** The page as it shows `last` now: its picture and the findings `check` gives on it. */
24
+ export declare function lookEvidence(page: Page, last: LastLook, run: Run, scene: Scene, check: typeof checkLook): Promise<LookEvidence>;
25
+ /** True when a fresh load of the last look, in a new context, matches the in-place evidence. */
26
+ export declare function freshLoadAgrees(browser: Browser, scene: Scene, run: Run, signal: AbortSignal, last: LastLook, inPlace: LookEvidence, check: typeof checkLook): Promise<boolean>;
27
+ /** A look drawn in place and its evidence, to be compared with a fresh load. */
28
+ export type SceneCheck = {
29
+ last: LastLook;
30
+ evidence: LookEvidence;
31
+ };
32
+ /**
33
+ * Every check agrees with its fresh load, within the time the draw left of the scene timeout.
34
+ * An error other than an abort (a timeout, a page that failed) counts as a disagreement.
35
+ */
36
+ export declare function freshLoadsAgree(browser: Browser, scene: Scene, run: Run, signal: AbortSignal, checks: readonly SceneCheck[], started: number, check: typeof checkLook): Promise<boolean>;
37
+ export {};
@@ -0,0 +1,68 @@
1
+ // The check a scene drawn with in-place looks must pass: its last look, which carries the most
2
+ // state left by earlier looks, drawn again by a fresh load in a new context must give the same
3
+ // picture and the same findings. Otherwise the scene is drawn again with full loads.
4
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { isDeepStrictEqual } from 'node:util';
8
+ import { openScene } from './browser.js';
9
+ import { dataWords } from './checks.js';
10
+ import { fullShot } from './full-shot.js';
11
+ import { renderScene, SCENE_TIMEOUT_MS } from './scene-render.js';
12
+ import { sceneRequests } from './snapshot-requests.js';
13
+ /** The page as it shows `last` now: its picture and the findings `check` gives on it. */
14
+ export async function lookEvidence(page, last, run, scene, check) {
15
+ const out = await mkdtemp(join(tmpdir(), 'ape-look-check-'));
16
+ try {
17
+ const found = {
18
+ scene,
19
+ data: dataWords(scene.props),
20
+ screenshots: {},
21
+ cut: [],
22
+ problems: [],
23
+ hints: [],
24
+ pairs: new Set(),
25
+ };
26
+ await check(page, last.look, { ...run, out }, found);
27
+ const path = join(out, 'look.png');
28
+ await fullShot(page, path);
29
+ return { picture: await readFile(path), problems: found.problems, late: last.late };
30
+ }
31
+ finally {
32
+ await rm(out, { recursive: true, force: true });
33
+ }
34
+ }
35
+ /** True when a fresh load of the last look, in a new context, matches the in-place evidence. */
36
+ export async function freshLoadAgrees(browser, scene, run, signal, last, inPlace, check) {
37
+ const fresh = await renderScene(browser, run.frames[scene.frame], scene.key, run.sceneTimeout, async (page) => {
38
+ // Requests this load makes count too: the scene's facts stay a union over every load.
39
+ sceneRequests(page, run, scene);
40
+ const late = await openScene(page, last.url, last.look.locale, last.mediaWait);
41
+ return lookEvidence(page, { ...last, late }, run, scene, check);
42
+ }, signal, run);
43
+ return (fresh.late === inPlace.late &&
44
+ fresh.picture.equals(inPlace.picture) &&
45
+ isDeepStrictEqual(fresh.problems, inPlace.problems));
46
+ }
47
+ /**
48
+ * Every check agrees with its fresh load, within the time the draw left of the scene timeout.
49
+ * An error other than an abort (a timeout, a page that failed) counts as a disagreement.
50
+ */
51
+ export async function freshLoadsAgree(browser, scene, run, signal, checks, started, check) {
52
+ const deadline = started + (run.sceneTimeout ?? SCENE_TIMEOUT_MS);
53
+ for (const { last, evidence } of checks) {
54
+ const left = deadline - performance.now();
55
+ if (left <= 0)
56
+ return false;
57
+ try {
58
+ const fresh = { ...run, sceneTimeout: left };
59
+ if (!(await freshLoadAgrees(browser, scene, fresh, signal, last, evidence, check)))
60
+ return false;
61
+ }
62
+ catch {
63
+ signal.throwIfAborted();
64
+ return false;
65
+ }
66
+ }
67
+ return true;
68
+ }
@@ -0,0 +1,14 @@
1
+ import type { Page } from 'playwright-core';
2
+ /** Counts a look drawn by a full load instead of in place, or a scene drawn again fresh. */
3
+ export type FallbackCounter = (kind: 'look' | 'scene') => void;
4
+ /** The attempt may have had side effects. Discard its context before replaying the scene. */
5
+ export declare class LookMoveFailed extends Error {
6
+ }
7
+ /**
8
+ * A fresh navigation starts the scene; its later looks move in place. A picture is shot only once
9
+ * `mediaReady` says all is ready, so warm media draws the same picture; only a media finding could
10
+ * differ. So a later look loads fresh when the first look got one (late or failed), or when its
11
+ * wait used more than half the later look's allowance (a cold load near the limit). A cold load
12
+ * well within the allowance means a warm one is too, so the findings are equal.
13
+ */
14
+ export declare function sceneLookLoader(page: Page, onFallback?: FallbackCounter, inPlace?: boolean, onMove?: () => void): (url: string, locale: string, mediaWait?: number) => Promise<boolean>;