diff --git a/.github/workflows/update-visual-baselines.yml b/.github/workflows/update-visual-baselines.yml index e459cf93..6410f95e 100644 --- a/.github/workflows/update-visual-baselines.yml +++ b/.github/workflows/update-visual-baselines.yml @@ -50,6 +50,21 @@ jobs: - name: Install Chromium system dependencies if: runner.os == 'Linux' run: pnpm exec playwright install-deps chromium + - name: Match the CI browser mode + shell: bash + run: | + # The visual baselines are compared against the pixels the CI + # produces, so the refresh has to render in the same mode. macOS + # runs windowed Chromium in the CI, and the two modes do not draw + # the same glyph edges. + # + # The flag goes into the environment file from a step of its own: + # a step cannot read back what it writes, so writing it here + # would have left the refresh below in headless mode while the CI + # compared windowed pixels. + if [ "$RUNNER_OS" = "macOS" ]; then + echo "WEBUI_BROWSER_HEADED=1" >> "$GITHUB_ENV" + fi - name: Refresh the visual baselines shell: bash env: @@ -57,9 +72,6 @@ jobs: WEBUI_BROWSER_FONT_CACHE_DIR: ${{ runner.temp }}/webui-browser-font-cache SPECS: ${{ inputs.spec }} run: | - if [ "$RUNNER_OS" = "macOS" ]; then - echo "WEBUI_BROWSER_HEADED=1" >> "$GITHUB_ENV" - fi # The specs come from a manual dispatch, so they are read from the # environment and split here rather than interpolated into the # command line: an unquoted interpolation would let the input diff --git a/.plan/browser-use/complete/isolated-chromium.acceptance.json b/.plan/browser-use/complete/isolated-chromium.acceptance.json index b272403b..df006c32 100644 --- a/.plan/browser-use/complete/isolated-chromium.acceptance.json +++ b/.plan/browser-use/complete/isolated-chromium.acceptance.json @@ -16,7 +16,7 @@ }, "observed": "a pointer click and a text input both arrived in the page the provider was driving", "result": "pass", - "at": "2026-11-19T14:22:27.432Z", + "at": "2026-11-19T19:02:49.954Z", "os": "linux 7.0.0-43-generic", "suite": "isolated-chromium" }, @@ -37,7 +37,7 @@ }, "observed": "the stale identity was refused with browser_target_stale and the page that replaced it received nothing", "result": "pass", - "at": "2026-11-19T14:22:28.946Z", + "at": "2026-11-19T19:02:51.467Z", "os": "linux 7.0.0-43-generic", "suite": "isolated-chromium" } diff --git a/.plan/browser-use/complete/real-browser.acceptance.json b/.plan/browser-use/complete/real-browser.acceptance.json index 229da76a..36b90777 100644 --- a/.plan/browser-use/complete/real-browser.acceptance.json +++ b/.plan/browser-use/complete/real-browser.acceptance.json @@ -18,7 +18,7 @@ }, "observed": "the handshake completed and the host reported the surface connected", "result": "pass", - "at": "2026-11-19T14:25:04.290Z", + "at": "2026-11-19T19:06:51.990Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" }, @@ -41,7 +41,7 @@ }, "observed": "the host refused the extension and reported no connected surface", "result": "pass", - "at": "2026-11-19T14:25:04.627Z", + "at": "2026-11-19T19:06:52.310Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" }, @@ -64,7 +64,7 @@ }, "observed": "the extension completed the handshake with no configured identity, and the host reported the surface connected", "result": "pass", - "at": "2026-11-19T14:25:04.946Z", + "at": "2026-11-19T19:06:52.607Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" }, @@ -87,7 +87,7 @@ }, "observed": "the handshake completed and the host reported the surface connected", "result": "pass", - "at": "2026-11-19T14:25:05.693Z", + "at": "2026-11-19T19:06:53.516Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" }, @@ -110,7 +110,7 @@ }, "observed": "the host refused the extension and reported no connected surface", "result": "pass", - "at": "2026-11-19T14:25:06.091Z", + "at": "2026-11-19T19:06:53.906Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" }, @@ -133,7 +133,7 @@ }, "observed": "the extension completed the handshake with no configured identity, and the host reported the surface connected", "result": "pass", - "at": "2026-11-19T14:25:06.723Z", + "at": "2026-11-19T19:06:54.256Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" }, @@ -156,7 +156,7 @@ }, "observed": "both browsers were connected, each on its own surface, and each surface's provider belonged to that surface", "result": "pass", - "at": "2026-11-19T14:25:07.404Z", + "at": "2026-11-19T19:06:54.857Z", "os": "linux 7.0.0-43-generic", "suite": "real-browser" } diff --git a/.plan/browser-use/complete/real-external.acceptance.json b/.plan/browser-use/complete/real-external.acceptance.json index ab45694f..73686042 100644 --- a/.plan/browser-use/complete/real-external.acceptance.json +++ b/.plan/browser-use/complete/real-external.acceptance.json @@ -18,7 +18,7 @@ }, "observed": "the host noticed the terminated worker, the surface went down and came back, and a command against the live tab answered again", "result": "pass", - "at": "2026-11-19T14:25:09.060Z", + "at": "2026-11-19T19:06:56.460Z", "os": "linux 7.0.0-43-generic", "suite": "real-external" }, @@ -41,7 +41,7 @@ }, "observed": "the text the host sent appeared in the page's field, and a non-empty image frame for that page arrived at the host", "result": "pass", - "at": "2026-11-19T14:25:10.044Z", + "at": "2026-11-19T19:06:57.041Z", "os": "linux 7.0.0-43-generic", "suite": "real-external" }, @@ -64,7 +64,7 @@ }, "observed": "the command in the allowed subset answered with the page's title, and a command outside it was refused as unsupported", "result": "pass", - "at": "2026-11-19T14:25:10.375Z", + "at": "2026-11-19T19:06:57.385Z", "os": "linux 7.0.0-43-generic", "suite": "real-external" }, @@ -87,7 +87,7 @@ }, "observed": "the host noticed the terminated worker, the surface went down and came back, and a command against the live tab answered again", "result": "pass", - "at": "2026-11-19T14:25:11.411Z", + "at": "2026-11-19T19:06:58.363Z", "os": "linux 7.0.0-43-generic", "suite": "real-external" }, @@ -110,7 +110,7 @@ }, "observed": "the text the host sent appeared in the page's field, and a non-empty image frame for that page arrived at the host", "result": "pass", - "at": "2026-11-19T14:25:12.488Z", + "at": "2026-11-19T19:06:59.000Z", "os": "linux 7.0.0-43-generic", "suite": "real-external" }, @@ -133,7 +133,7 @@ }, "observed": "the command in the allowed subset answered with the page's title, and a command outside it was refused as unsupported", "result": "pass", - "at": "2026-11-19T14:25:12.992Z", + "at": "2026-11-19T19:06:59.402Z", "os": "linux 7.0.0-43-generic", "suite": "real-external" } diff --git a/.plan/browser-use/complete/real-packaged.acceptance.json b/.plan/browser-use/complete/real-packaged.acceptance.json index 878da3de..2a3d5ba8 100644 --- a/.plan/browser-use/complete/real-packaged.acceptance.json +++ b/.plan/browser-use/complete/real-packaged.acceptance.json @@ -9,12 +9,12 @@ "surface": "chrome", "build": "store", "allowlist": "store", - "extensionId": "heblokdedihpakpohjnbpdbdfefjonkp", + "extensionId": "ljbbjnefopohpfbhglimgkcanacelkhe", "installationKeyProved": true }, - "observed": "the browser assigned the extension the id the public key determines (heblokdedihpakpohjnbpdbdfefjonkp)", + "observed": "the browser assigned the extension the id the public key determines (ljbbjnefopohpfbhglimgkcanacelkhe)", "result": "pass", - "at": "2026-11-19T14:25:13.464Z", + "at": "2026-11-19T19:06:59.830Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -28,12 +28,12 @@ "surface": "chrome", "build": "store", "allowlist": "store", - "extensionId": "heblokdedihpakpohjnbpdbdfefjonkp", + "extensionId": "ljbbjnefopohpfbhglimgkcanacelkhe", "installationKeyProved": true }, "observed": "the packaged manifest carries the store's public key and differs from the development manifest in nothing else", "result": "pass", - "at": "2026-11-19T14:25:13.465Z", + "at": "2026-11-19T19:06:59.831Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -51,12 +51,12 @@ "fullCdp": "enforced in the runtime service, not in the bridge", "allowlist": "store", "build": "store", - "extensionId": "heblokdedihpakpohjnbpdbdfefjonkp", + "extensionId": "ljbbjnefopohpfbhglimgkcanacelkhe", "installationKeyProved": true }, "observed": "the packaged host completed the handshake and reported the surface connected", "result": "pass", - "at": "2026-11-19T14:25:13.552Z", + "at": "2026-11-19T19:06:59.911Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -74,12 +74,12 @@ "fullCdp": "enforced in the runtime service, not in the bridge", "allowlist": "development", "build": "store", - "extensionId": "heblokdedihpakpohjnbpdbdfefjonkp", + "extensionId": "ljbbjnefopohpfbhglimgkcanacelkhe", "installationKeyProved": true }, "observed": "the packaged host refused the extension and reported no connected surface", "result": "pass", - "at": "2026-11-19T14:25:13.611Z", + "at": "2026-11-19T19:06:59.954Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -93,12 +93,12 @@ "surface": "edge", "build": "store", "allowlist": "store", - "extensionId": "ckkgchfoceajkkiipmbjemlafekjmeen", + "extensionId": "ebhenfblcbngiamibfhlochmighaampe", "installationKeyProved": true }, - "observed": "the browser assigned the extension the id the public key determines (ckkgchfoceajkkiipmbjemlafekjmeen)", + "observed": "the browser assigned the extension the id the public key determines (ebhenfblcbngiamibfhlochmighaampe)", "result": "pass", - "at": "2026-11-19T14:25:13.995Z", + "at": "2026-11-19T19:07:00.320Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -112,12 +112,12 @@ "surface": "edge", "build": "store", "allowlist": "store", - "extensionId": "ckkgchfoceajkkiipmbjemlafekjmeen", + "extensionId": "ebhenfblcbngiamibfhlochmighaampe", "installationKeyProved": true }, "observed": "the packaged manifest carries the store's public key and differs from the development manifest in nothing else", "result": "pass", - "at": "2026-11-19T14:25:13.997Z", + "at": "2026-11-19T19:07:00.324Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -135,12 +135,12 @@ "fullCdp": "enforced in the runtime service, not in the bridge", "allowlist": "store", "build": "store", - "extensionId": "ckkgchfoceajkkiipmbjemlafekjmeen", + "extensionId": "ebhenfblcbngiamibfhlochmighaampe", "installationKeyProved": true }, "observed": "the packaged host completed the handshake and reported the surface connected", "result": "pass", - "at": "2026-11-19T14:25:14.098Z", + "at": "2026-11-19T19:07:00.411Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" }, @@ -158,12 +158,12 @@ "fullCdp": "enforced in the runtime service, not in the bridge", "allowlist": "development", "build": "store", - "extensionId": "ckkgchfoceajkkiipmbjemlafekjmeen", + "extensionId": "ebhenfblcbngiamibfhlochmighaampe", "installationKeyProved": true }, "observed": "the packaged host refused the extension and reported no connected surface", "result": "pass", - "at": "2026-11-19T14:25:14.185Z", + "at": "2026-11-19T19:07:00.475Z", "os": "linux 7.0.0-43-generic", "suite": "real-packaged" } diff --git a/.plan/workspace-browser-tab/complete/workspace-browser-tab.acceptance.json b/.plan/workspace-browser-tab/complete/workspace-browser-tab.acceptance.json index 96c006cd..ffc4910d 100644 --- a/.plan/workspace-browser-tab/complete/workspace-browser-tab.acceptance.json +++ b/.plan/workspace-browser-tab/complete/workspace-browser-tab.acceptance.json @@ -14,7 +14,7 @@ }, "observed": "the run's selection points at the page the Agent opened, the runtime publishes it, and the strip's reconciliation makes it the active panel tab", "result": "pass", - "at": "2026-11-19T14:20:53.857Z", + "at": "2026-11-19T19:01:27.103Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -33,7 +33,7 @@ }, "observed": "the page is at the requested url and the frame stream follows the page it opened", "result": "pass", - "at": "2026-11-19T14:20:55.044Z", + "at": "2026-11-19T19:01:28.284Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -52,7 +52,7 @@ }, "observed": "the action runs on the run's selection, and a reference recorded before the page moved is refused", "result": "pass", - "at": "2026-11-19T14:20:55.957Z", + "at": "2026-11-19T19:01:29.148Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -71,7 +71,7 @@ }, "observed": "the Agent's page and the person's page are different, and each shows its own picture", "result": "pass", - "at": "2026-11-19T14:20:56.009Z", + "at": "2026-11-19T19:01:29.200Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -90,7 +90,7 @@ }, "observed": "the run's selection becomes the person's page, so the Agent can act on it", "result": "pass", - "at": "2026-11-19T14:20:56.902Z", + "at": "2026-11-19T19:01:30.093Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -109,7 +109,7 @@ }, "observed": "the input reaches the person's page, not the Agent's", "result": "pass", - "at": "2026-11-19T14:20:57.714Z", + "at": "2026-11-19T19:01:30.899Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -128,7 +128,7 @@ }, "observed": "the tab becomes that page, and the url is shown read-only in the toolbar", "result": "pass", - "at": "2026-11-19T14:20:57.739Z", + "at": "2026-11-19T19:01:30.925Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -147,7 +147,7 @@ }, "observed": "the page is released, and the runtime's page set follows the strip", "result": "pass", - "at": "2026-11-19T14:20:58.522Z", + "at": "2026-11-19T19:01:31.707Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -166,7 +166,7 @@ }, "observed": "the page moves through its own history, and the generation follows", "result": "pass", - "at": "2026-11-19T14:21:01.173Z", + "at": "2026-11-19T19:01:34.332Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -185,7 +185,7 @@ }, "observed": "the Agent's open_tab and the person's launcher path are both refused with browser_surface_not_authorized", "result": "pass", - "at": "2026-11-19T14:21:01.175Z", + "at": "2026-11-19T19:01:34.333Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -204,7 +204,7 @@ }, "observed": "every action except open_tab is refused with browser_target_unknown", "result": "pass", - "at": "2026-11-19T14:21:01.196Z", + "at": "2026-11-19T19:01:34.352Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -223,7 +223,7 @@ }, "observed": "its pages are released and no page is left behind", "result": "pass", - "at": "2026-11-19T14:21:01.975Z", + "at": "2026-11-19T19:01:35.127Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -242,7 +242,7 @@ }, "observed": "both are addressable, and the strip shows both", "result": "pass", - "at": "2026-11-19T14:21:02.895Z", + "at": "2026-11-19T19:01:36.054Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" }, @@ -261,7 +261,7 @@ }, "observed": "its generation advances, and a reference recorded against the old generation is refused — on every tab, not only the first", "result": "pass", - "at": "2026-11-19T14:21:03.821Z", + "at": "2026-11-19T19:01:36.962Z", "os": "linux 7.0.0-43-generic", "suite": "workspace-browser-tab" } diff --git a/docs/webui-ci.md b/docs/webui-ci.md index c1c7fa52..41518095 100644 --- a/docs/webui-ci.md +++ b/docs/webui-ci.md @@ -49,7 +49,13 @@ after building the client and installing Chromium. ## Active and archived workflows -Only `webui-ci.yml` remains in `.github/workflows/`. The following inherited +Two workflows are active in `.github/workflows/`: `webui-ci.yml`, the gate above, +and `update-visual-baselines.yml`, a manual dispatch that re-records the +per-platform screenshot baselines. The refresh runs the same specs on the same +three runners and commits what each of them produced, because a baseline can +only be regenerated on the platform that compares against it. It renders in +the browser mode the CI compares with — windowed Chromium on macOS — and it +cannot publish anything. The following inherited workflows are archived under `.github/legacy-workflows/`: Source verification, CLI release, Node compatibility, Performance, Release audit, Source candidate, Label issue product, Sync GitHub issues to diff --git a/packages/webui/docs/client/design.md b/packages/webui/docs/client/design.md index 7eb97316..bfe4d5af 100644 --- a/packages/webui/docs/client/design.md +++ b/packages/webui/docs/client/design.md @@ -35,7 +35,7 @@ Drag any non-control part of a card to move the selected cards, and use its resi The capability panel separates two questions that the old page answered as one. Local media work — browser upload/crop/grid and local FFmpeg — is reported from this machine's own status. Cloud provider tools come from the account's connected connectors, discovered through the existing Connector gateway under the native-client identity, not from a Mini App installation grant. Discovery keeps its real outcome: ready, partially available with named provider failures, no connected account, expired login, failed discovery, or an account that simply does not offer a tool. Only a successful discovery that omits a tool means "the account does not provide it"; a failed discovery is never rendered as "not granted", and the tool list is never replaced by an empty all-or-nothing inventory. -Templates, assets, capabilities and tools are managed anchored panels. Destructive confirmations alone are modal. Templates keep their original groups, own-template deletion confirmation, inline save-name flow, direct local-file application and local path export. Importing a file does not implicitly add it to the owned template directory. The path panel offers Downloads/Desktop/Documents/Home shortcuts; the runtime writes only existing Design content to the explicitly chosen path, with a separate overwrite choice. The library shows native reference status, sizes and names, supports centered insertion and local export, and delegates deletion and unreferenced cleanup to the runtime. +Templates, assets, capabilities and tools are managed anchored panels. Destructive confirmations alone are modal. Templates keep their original groups, own-template deletion confirmation, inline save-name flow, direct local-file application and local path export. Importing a file does not implicitly add it to the owned template directory. The path panel offers Downloads/Desktop/Documents/Home shortcuts; the runtime writes only existing Design content to the explicitly chosen path, with a separate overwrite choice. The library shows native reference status, sizes and names, supports centered insertion and local export, and delegates deletion and unreferenced cleanup to the runtime. A centered insertion keeps the centre of the pane: the card the person inserted stays there, and a product grid that is laid out again gives way to it. Image crop operates over the source card with constrained move/resize handles; grid split uses the original geometry plans. Both execute in the browser and publish reusable, arranged result nodes through the runtime. Video/audio trim retains the frame strip or waveform, range handles, playhead keyboard/pointer control and bounded preview loop; closing the panel stops its preview. Card and toolbar tools share the original eligibility and disabled-reason policy. Tool inputs are the node's material followed by unique connected upstream material. FFmpeg tools report missing local dependencies, while model and connector tools use the runtime's execution capabilities. Portable templates retain the original versioned action format. Copied graph references receive new node identities; products remain reusable while execution and session identities are cleared. @@ -45,7 +45,7 @@ Prompt, category-field and expansion-template editors register their real dirty Upload, browser-produced media, video poster bytes and bounded lifecycle drafts use the authenticated native HTTP action endpoint, rather than the bounded WebSocket envelope. Other Design actions retain the standard operation wire. Both paths enter the same runtime validator, document locks and persistence owner; HTTP errors preserve their structured code and message. The client reads the HTTP body as text before deciding: a structured JSON refusal keeps its code, while a plain-text 405 is reported as a page/host version mismatch ("restart or upgrade the WebUI host") instead of surfacing a JSON parse error, a plain-text 401 as an authentication failure, and a non-JSON success as an invalid response. The host that does not yet serve the route has to be activated with the new build; the installed Mini App data is untouched. -Each materialized tool response identifies exactly its own new result nodes. The owner lays out those IDs from its latest queued document, preserving content and unrelated concurrent products. Grid tiles retain the original 240-pixel card width and requested column count; other batches use the original square-root column plan. The retained collision rule moves obstructing cards aside, and measured media dimensions trigger a new placement. The created results become selected. The material menu keeps per-file removal and the original append behavior of “换个素材”; cancellation or a failed upload leaves existing references intact. +Each materialized tool response identifies exactly its own new result nodes. The owner lays out those IDs from its latest queued document, preserving content and unrelated concurrent products. Grid tiles retain the original 240-pixel card width and requested column count; other batches use the original square-root column plan. The retained collision rule moves obstructing cards aside, and measured media dimensions trigger a new placement. A placement that is laid out again leaves the cards the person placed after it where they are — the card in the way steps aside instead — and a product of a run is not such a card: the runtime placed it, and the placement may still move it. The created results become selected. The material menu keeps per-file removal and the original append behavior of “换个素材”; cancellation or a failed upload leaves existing references intact. Runtime questionnaires retain their original step and option identities. Other is exclusive in a single-choice question and can accompany choices in a multiple-choice question. Unselected Other text does not answer a required question. Only explicit user actions answer permission requests. A generated node's conversation action opens its actual runtime session in the shell or a separate authenticated tab. diff --git a/packages/webui/docs/verification/browser-suite.md b/packages/webui/docs/verification/browser-suite.md index 5b33cd4d..1c74bc62 100644 --- a/packages/webui/docs/verification/browser-suite.md +++ b/packages/webui/docs/verification/browser-suite.md @@ -247,7 +247,13 @@ To deliberately regenerate only these baselines, use `pnpm exec playwright test packages/webui/test/browser/visual-baselines.spec.mjs --update-snapshots` on Linux CI Chromium, inspect every resulting image, then run the same command without `--update-snapshots` to compare. The font environment is part of the gate, so no extra setup is -needed to regenerate the baselines — the same files produce the same bytes anywhere. A passing +needed to regenerate the baselines — the same files produce the same bytes anywhere. +“The same bytes” holds for the committed typeface, not for the browser mode: macOS compares +windowed Chromium, and windowed and headless Chromium do not draw the same glyph edges. A macOS +baseline recorded headless therefore differs from the one the CI compares against, by a handful of +antialiased pixels per glyph — far more than the eight-pixel budget, and spread over the whole +capture. Record the macOS baselines in windowed mode, or dispatch +`.github/workflows/update-visual-baselines.yml`, which selects the mode the CI uses. A passing fixture screenshot proves the built client's rendered state under the in-page deterministic transport; it does not prove the production service or runtime diff --git a/packages/webui/package.json b/packages/webui/package.json index 831519b7..0966c11b 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -40,6 +40,7 @@ "lottie-web": "^5.13.0", "marked": "18.0.12", "mermaid": "12.3.0", + "node-abi": "3.96.0", "node-pty": "1.1.0", "qrcode.react": "4.2.0", "react": "18.3.1", diff --git a/packages/webui/src/client/features/design/projection/design-view.ts b/packages/webui/src/client/features/design/projection/design-view.ts index d40c0546..74f4f607 100644 --- a/packages/webui/src/client/features/design/projection/design-view.ts +++ b/packages/webui/src/client/features/design/projection/design-view.ts @@ -33,6 +33,16 @@ export interface DesignProductPlacement { readonly tile?: boolean; readonly measured?: boolean; readonly origin?: { readonly x: number; readonly y: number }; + /** + * The cards the board held when this placement was made. + * + * A card that is not among them is one the person placed after the + * placement: it is theirs, and a placement that is laid out again gives + * way to it — the card in the way steps aside instead. The rule reads the + * board it is given, so the cards it keeps are the ones that are on the + * board when the placement is saved. + */ + readonly known?: readonly string[]; } export const designCreatedNodeIds = ( state: DesignState | undefined, @@ -82,6 +92,21 @@ export function designPlaceProducts( }, ]), ); + // The cards the person placed after this placement are theirs: the + // placement gives way to them, and the card in the way steps aside. A + // product of a run is not theirs — the runtime placed it, and the + // placement may still move it. + const known = new Set(input.known ?? []); + const keep = input.known + ? document.nodes + .filter( + (node) => + !known.has(node.id) && + node.type !== "result" && + !products.some((product) => product.id === node.id), + ) + .map((node) => node.id) + : []; // The retained collision rule mutates positions, so give it fresh geometry. return pushAside( { @@ -93,6 +118,7 @@ export function designPlaceProducts( })), }, products.map((node) => node.id), + { keepIds: keep }, ); } export const designAddedNodeId = ( diff --git a/packages/webui/src/client/features/design/ui/DesignDialogs.tsx b/packages/webui/src/client/features/design/ui/DesignDialogs.tsx index b4ba6c21..beb68cc4 100644 --- a/packages/webui/src/client/features/design/ui/DesignDialogs.tsx +++ b/packages/webui/src/client/features/design/ui/DesignDialogs.tsx @@ -72,7 +72,7 @@ export function DesignDialogs({ readonly onAction: (action: DesignAction) => Promise; readonly assetUrl: (url: string) => string; readonly selectedNodeId?: string; - readonly viewportSize: { readonly width: number; readonly height: number }; + readonly viewportSize: () => { readonly width: number; readonly height: number }; readonly viewport: DesignDocument["viewport"]; readonly onInserted: (id: string) => void; readonly onTool: ( @@ -359,9 +359,15 @@ export function DesignDialogs({ variant="plain" size="inline-tiny" onClick={async () => { + // The pane is measured here, at the insert, and + // not when this dialog rendered: the pane can be + // re-laid-out in between, and a size read at render + // time is a size the pane no longer has. A node + // placed from a stale size lands off the pane's + // centre, which is where the insert put it. const position = designLibraryPosition( viewport, - viewportSize, + viewportSize(), ); const created = await onAction({ type: "add_node", diff --git a/packages/webui/src/client/features/design/ui/DesignSurface.public.tsx b/packages/webui/src/client/features/design/ui/DesignSurface.public.tsx index 8156a560..eb0a9cf3 100644 --- a/packages/webui/src/client/features/design/ui/DesignSurface.public.tsx +++ b/packages/webui/src/client/features/design/ui/DesignSurface.public.tsx @@ -126,7 +126,16 @@ export function DesignSurface({ new Set(), ); const productGroups = useRef( - new Map(), + new Map< + string, + { + input: DesignProductPlacement; + sizes: string; + // The cards the board held when this placement was made. A card that + // appears later is the person's own, and it keeps its place. + known: Set; + } + >(), ); const reportPending = (nodeId: string, pending: boolean): void => setPendingEditors((current) => { @@ -177,6 +186,10 @@ export function DesignSurface({ const gesture = useRef(); const stage = useRef(null); const [stageSize, setStageSize] = useState({ width: 800, height: 600 }); + /** Whether the library is open over the pane. */ + const libraryOpen = useRef(false); + /** The pane as it is drawn while the library is open over it. */ + const libraryPaneSize = useRef<{ readonly width: number; readonly height: number }>(); const clipboard = useRef<{ readonly nodes: readonly DesignNode[]; readonly connections: DesignDocument["connections"]; @@ -187,14 +200,26 @@ export function DesignSurface({ useEffect(() => { const element = stage.current; if (!element) return; - const measure = () => - setStageSize({ + const measure = () => { + const size = { width: element.clientWidth, height: element.clientHeight, - }); + }; + setStageSize(size); + // The pane an asset is inserted into is the pane the person was + // looking at while they chose it: the library is shown over the + // pane, and the pane is measured again while the library closes. + // The size the pane is drawn at while the library is open is the + // one the insert is placed against. + if (libraryOpen.current) libraryPaneSize.current = size; + }; measure(); return dom.observeSize(element, measure); }, [dom, snapshot.status]); + useEffect(() => { + libraryOpen.current = dialog === "library"; + if (libraryOpen.current) libraryPaneSize.current = undefined; + }, [dialog]); useEffect(() => { if (rename !== undefined && !renaming.current) { renaming.current = true; @@ -246,6 +271,7 @@ export function DesignSurface({ productGroups.current.set(input.ids.join(","), { input: placement, sizes: "", + known: new Set(latest.nodes.map((node) => node.id)), }); const result = await owner.placeProducts(placement); if (!result) @@ -263,7 +289,11 @@ export function DesignSurface({ .join(";"); if (sizes === group.sizes) continue; group.sizes = sizes; - const input = { ...group.input, measured: true }; + // The cards the person placed after this placement are theirs: the + // grid gives way to them, and the card in the way steps aside. The + // board that is saved may hold cards the board of the placement did + // not, so the rule reads the board it is given. + const input = { ...group.input, measured: true, known: [...group.known] }; const placed = designPlaceProducts(document, input); if ( placed.nodes.some( @@ -1559,10 +1589,18 @@ export function DesignSurface({ data={data} document={document} selectedNodeId={selected[0]} - viewportSize={{ - width: stage.current?.clientWidth ?? 800, - height: stage.current?.clientHeight ?? 600, - }} + // The pane is the one the person was looking at while the + // library was open: the library is shown over the pane, and the + // pane is measured again while the library closes, so a size + // read at the insert is the size of a layout in between. The + // size the pane is drawn at while the library is open is the one + // the insert is placed against. + viewportSize={() => + libraryPaneSize.current ?? { + width: stage.current?.clientWidth ?? 800, + height: stage.current?.clientHeight ?? 600, + } + } onTool={openTool} onClose={() => setDialog(undefined)} onAction={act} diff --git a/packages/webui/src/runtime/design/agent-runner.mjs b/packages/webui/src/runtime/design/agent-runner.mjs index 5d980fba..159cd508 100644 --- a/packages/webui/src/runtime/design/agent-runner.mjs +++ b/packages/webui/src/runtime/design/agent-runner.mjs @@ -15,9 +15,11 @@ // surfaced to the page and is only answered after the user decides, with // `allowOnce` — never automatically. import { randomUUID } from 'node:crypto'; -import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdir, readFile, stat } from 'node:fs/promises'; import { dirname, join } from 'node:path'; +import { writeFileAtomically } from './atomic-file.mjs'; + import { CAPABILITIES, CONNECTOR_TOOLS, @@ -747,9 +749,7 @@ export function createAgentRunner(context) { async function writePending(list) { if (!pendingFile) return; await mkdir(dirname(pendingFile), { recursive: true }); - const temp = `${pendingFile}.${randomUUID()}.tmp`; - try { await writeFile(temp, JSON.stringify(list, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 }); await rename(temp, pendingFile); } - finally { await rm(temp, { force: true }); } + await writeFileAtomically(pendingFile, JSON.stringify(list, null, 2)); } // The pending book is written through one queue. Two writes that overlap diff --git a/packages/webui/src/runtime/design/atomic-file.d.mts b/packages/webui/src/runtime/design/atomic-file.d.mts new file mode 100644 index 00000000..6aef7b11 --- /dev/null +++ b/packages/webui/src/runtime/design/atomic-file.d.mts @@ -0,0 +1,11 @@ +export interface DesignFileWriteOptions { + platform?: NodeJS.Platform; + wait?(delayMs: number): Promise; + move?(from: string, to: string): Promise; +} + +/** Replace one file with another, retrying the transient refusal Windows hands out. */ +export function replaceFile(from: string, to: string, options?: DesignFileWriteOptions): Promise; + +/** Write a file atomically: the bytes go to a temporary file that is renamed over the target. */ +export function writeFileAtomically(file: string, text: string | Uint8Array, options?: DesignFileWriteOptions): Promise; diff --git a/packages/webui/src/runtime/design/atomic-file.mjs b/packages/webui/src/runtime/design/atomic-file.mjs new file mode 100644 index 00000000..930dc964 --- /dev/null +++ b/packages/webui/src/runtime/design/atomic-file.mjs @@ -0,0 +1,56 @@ +// The Design runtime keeps its state in files: the canvas documents, the +// drafts, the run journal and the pending book. Every one of them is +// written atomically, so a crash mid-write cannot leave a half-written file +// behind: the new bytes go to a sibling temporary file and are renamed over +// the old one. +// +// Windows refuses that rename while another process holds the file open for +// a moment — an indexer, a scanner, a concurrent reader — and the refusal +// is transient. The refusal used to fail the whole operation: the canvas +// document was not written, the run that belonged to it never started, and +// the node it belonged to stayed idle for ever. The rename is retried the +// way the SSH store retries the same rename. +import { randomUUID } from "node:crypto"; +import { rename, rm, writeFile } from "node:fs/promises"; + +import { retryWindowsFileSystemOperationAsync } from "@mavis/shared"; + +/** + * Replace one file with another. + * + * The rename is retried when Windows refuses it: that refusal means the + * target is held open for a moment, not that the replacement is refused. + * + * @param {string} from the file that is moved + * @param {string} to the file it replaces + * @param {{ platform?: NodeJS.Platform, wait?: (delayMs: number) => Promise, move?: (from: string, to: string) => Promise }} [options] + */ +export async function replaceFile(from, to, options = {}) { + // The rename itself and the platform are given so the retry can be + // exercised on a machine that does not hand out the refusal itself. + const move = options.move ?? rename; + await retryWindowsFileSystemOperationAsync(() => move(from, to), { + platform: options.platform ?? process.platform, + wait: options.wait, + }); +} + +/** + * Write a file atomically. + * + * The bytes go to a sibling temporary file first and are renamed over the + * target, so a reader never sees a half-written file. + * + * @param {string} file the file that is written + * @param {string | Uint8Array} text the bytes it is given + * @param {{ platform?: NodeJS.Platform, wait?: (delayMs: number) => Promise, move?: (from: string, to: string) => Promise }} [options] + */ +export async function writeFileAtomically(file, text, options = {}) { + const temporary = `${file}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, text, { encoding: "utf8", flag: "wx", mode: 0o600 }); + await replaceFile(temporary, file, options); + } finally { + await rm(temporary, { force: true }); + } +} diff --git a/packages/webui/src/runtime/design/design-service.ts b/packages/webui/src/runtime/design/design-service.ts index 075f010b..3168e243 100644 --- a/packages/webui/src/runtime/design/design-service.ts +++ b/packages/webui/src/runtime/design/design-service.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import { lstat, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { lstat, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { acquireWebuiStorageLock, withWebuiStorageTransaction } from "../storage-transaction.js"; import type { NativeDesignExecution, NativeDesignToolAdapter } from "@mavis/local-runtime-v2/process-local"; @@ -9,6 +9,7 @@ import { CAPABILITIES, NODE_SIZE, PROMPT_TEMPLATES, findTool, palette } from ".. import { createAgentRunner, type DesignExecutionContext } from "./agent-runner.mjs"; import { createMediaRunner } from "./media-runner.mjs"; import { createCanvasStore } from "./store.mjs"; +import { replaceFile } from "./atomic-file.mjs"; import { createDesignEvents } from "./events.js"; import { readDesignTemplates, removeDesignTemplate, saveDesignTemplate } from "./templates.js"; import { prepareWebuiDesignPaths } from "../webui-paths.js"; @@ -114,7 +115,7 @@ export async function createWebuiDesignService(dataDir: string): Promise /^thumb_[a-f0-9]{64}\.jpg$/.test(name) || name.startsWith(".thumb-"); @@ -22,7 +23,7 @@ export async function publishDesignPoster(root: string, content: ReturnType [node.id, node])); - const kept = (placedIds ?? []).map((id) => byId.get(id)).filter(Boolean); - if (!kept.length) return { ...doc, nodes }; + const placedCards = (placedIds ?? []).map((id) => byId.get(id)).filter(Boolean); + if (!placedCards.length) return { ...doc, nodes }; const overlaps = (a, b) => { const ax = Number(a.position?.x) || 0; @@ -120,7 +127,8 @@ export function pushAside(doc, placedIds, { gap = NODE_GAP } = {}) { // The card in the way steps aside. The new card never does; of two old // cards, the one that is further right steps aside, so the board keeps its - // order. + // order. A card the person placed is newer than the placement that meets + // it, so it is the card in the way that steps aside. for (let round = 0; round < 64; round += 1) { let changed = false; for (const node of nodes) { @@ -128,14 +136,24 @@ export function pushAside(doc, placedIds, { gap = NODE_GAP } = {}) { for (const other of nodes) { if (other.id === node.id) continue; if (!overlaps(node, other)) continue; - if (placed.has(other.id)) { + if (keep.has(node.id) && keep.has(other.id)) { + // Two of the person's own cards: the rule leaves them alone. + } else if (keep.has(node.id)) { + other.position.x = (Number(node.position?.x) || 0) + (Number(node.width) || 0) + gap; + changed = true; + } else if (keep.has(other.id)) { + node.position.x = (Number(other.position?.x) || 0) + (Number(other.width) || 0) + gap; + changed = true; + } else if (placed.has(other.id)) { node.position.x = (Number(other.position?.x) || 0) + (Number(other.width) || 0) + gap; + changed = true; } else if ((Number(node.position?.x) || 0) <= (Number(other.position?.x) || 0)) { other.position.x = (Number(node.position?.x) || 0) + (Number(node.width) || 0) + gap; + changed = true; } else { node.position.x = (Number(other.position?.x) || 0) + (Number(other.width) || 0) + gap; + changed = true; } - changed = true; break; } } diff --git a/packages/webui/test/browser/account-login.spec.mjs b/packages/webui/test/browser/account-login.spec.mjs index 514da59f..c3be247f 100644 --- a/packages/webui/test/browser/account-login.spec.mjs +++ b/packages/webui/test/browser/account-login.spec.mjs @@ -47,6 +47,16 @@ test(`usage hover keeps the subscription label stable during refresh (${theme})` window.__railLabelChanges = []; new MutationObserver(() => window.__railLabelChanges.push(element.querySelector("small")?.textContent ?? null)).observe(element, { childList: true, subtree: true, characterData: true }); }); + // The first hover asks for the quota, and the answer is counted only + // once it has arrived: a count read while that request is still on its + // way reports one request too few, and the case blames the hover loop + // for a request the hover itself made. + await expect + .poll( + () => page.evaluate(() => window.__fixture.requests.filter((r) => r.operation === "getUsageQuota").length), + { timeout: 10_000 }, + ) + .toBeGreaterThan(0); const requestsBefore = await page.evaluate(() => window.__fixture.requests.filter((r) => r.operation === "getUsageQuota").length); const points = await page.evaluate(() => { const center = (testId) => { diff --git a/packages/webui/test/browser/browser-bridge-real-browser.spec.ts b/packages/webui/test/browser/browser-bridge-real-browser.spec.ts index 7c27b33c..886f96d1 100644 --- a/packages/webui/test/browser/browser-bridge-real-browser.spec.ts +++ b/packages/webui/test/browser/browser-bridge-real-browser.spec.ts @@ -63,7 +63,7 @@ test.describe("the browser bridge, against a real browser", () => { for (const { channel, surface } of BROWSERS) { test(`the extension completes the handshake on the ${surface} surface in ${channel} once it can prove the installation key`, async () => { - test.setTimeout(180_000); + test.setTimeout(300_000); // The installed Edge is not on every machine. A case that cannot run // says so instead of failing on a browser that was never there. test.skip( @@ -115,7 +115,7 @@ test.describe("the browser bridge, against a real browser", () => { }); test(`an extension that cannot prove the installation key is refused on the ${surface} surface in ${channel}`, async () => { - test.setTimeout(180_000); + test.setTimeout(300_000); // The installed Edge is not on every machine. A case that cannot run // says so instead of failing on a browser that was never there. test.skip( @@ -160,7 +160,7 @@ test.describe("the browser bridge, against a real browser", () => { }); test(`the extension pairs with a ${surface} host that was told nothing about it`, async () => { - test.setTimeout(180_000); + test.setTimeout(300_000); test.skip( !(await isBrowserInstalled(channel)), `the ${channel} browser is not installed on this machine`, @@ -219,7 +219,7 @@ test.describe("the browser bridge, against a real browser", () => { // Taking the first match instead would put the Chrome browser on the Edge // pairing: the Edge surface would report connected while the person is // looking at Chrome, and the Chrome surface would never come up at all. - test.setTimeout(240_000); + test.setTimeout(420_000); // This case needs both browsers, not one: it loads the same unpacked build // in Edge and Chrome and checks that each lands on its own surface. A // machine without Edge cannot run it at all, and the convention the two diff --git a/packages/webui/test/browser/native-design-tasks.spec.mjs b/packages/webui/test/browser/native-design-tasks.spec.mjs index cd166a6f..06f2b0b6 100644 --- a/packages/webui/test/browser/native-design-tasks.spec.mjs +++ b/packages/webui/test/browser/native-design-tasks.spec.mjs @@ -30,6 +30,40 @@ async function ipc(input) { }); host.send({ requestId, ...input }); return response; } +/** + * Wait for a node run to finish, and say where it stopped when it does not. + * + * The provider's media understanding runs in the runtime, behind the connector: + * the upload, the description and the run that consumes it are three steps + * that report separately. A run that never finishes is therefore reported + * with the evidence of the steps behind it, so the failure says which step + * stopped instead of only that the node stayed idle. + */ +async function expectNodeRunSucceeds(read, nodeId, label) { + try { + await expect + .poll(async () => { + const output = (await read()).document.nodes.find((node) => node.id === nodeId).metadata.output; + if (output.status === "error") throw new Error(`node run failed: ${JSON.stringify(output.error)}`); + return output.status; + }, { timeout: 60_000 }) + .toBe("success"); + } catch (error) { + const uploads = await ipc({ readUploadEvidence: true }).catch(() => undefined); + const understanding = await ipc({ readUnderstandingState: true }).catch(() => undefined); + throw new Error( + `${label} never finished: ${error instanceof Error ? error.message : String(error)}\n` + + `upload evidence: ${JSON.stringify(uploads)}\n` + + `understanding: ${JSON.stringify(understanding)}\n` + + // The host's own log is the runtime's account of the run: which + // stage it reached and what it was waiting for. A run that never + // finishes is reported with that account, so the failure says where + // the run stopped and not only that the node stayed idle. + `host log:\n${logs.slice(-4000)}`, + ); + } +} + async function rpc(page, operation, body) { return page.evaluate(({ operation, body }) => new Promise((resolve, reject) => { const config = window.__WEBUI_CONFIG__, url = new URL(config.websocketUrl); url.searchParams.set("token", config.token); @@ -198,13 +232,7 @@ test("native Design sends an uploaded image's understood content to a connected await card.click({ position: { x: 80, y: 80 } }); await expect(card.getByRole("button", { name: "生成", exact: true })).toBeEnabled(); await card.getByRole("button", { name: "生成", exact: true }).click(); - await expect - .poll(async () => { - const output = (await read()).document.nodes.find((node) => node.id === textId).metadata.output; - if (output.status === "error") throw new Error(`node run failed: ${JSON.stringify(output.error)}`); - return output.status; - }, { timeout: 20_000 }) - .toBe("success"); + await expectNodeRunSucceeds(read, textId, "the connected text node's run"); const prompt = await ipc({ readModelPrompt: true }); expect(prompt).toContain("合成理解:一只橘猫坐在窗台上"); expect(prompt).toContain(`节点 ${imageId}`); @@ -302,14 +330,7 @@ test("native Design image-mimic template keeps describe mode and sends the image await reloadedCard.click({ position: { x: 80, y: 80 } }); await expect(reloadedCard.getByRole("button", { name: "生成", exact: true })).toBeEnabled(); await reloadedCard.getByRole("button", { name: "生成", exact: true }).click(); - await expect - .poll(async () => { - const current = await read(); - const output = current.document.nodes.find((node) => node.id === reverseNode.id).metadata.output; - if (output.status === "error") throw new Error(`node run failed: ${JSON.stringify(output.error)}`); - return output.status; - }, { timeout: 20_000 }) - .toBe("success"); + await expectNodeRunSucceeds(read, reverseNode.id, "the template's reverse-prompt node run"); const prompt = await ipc({ readModelPrompt: true }); expect(prompt).toContain("合成理解:一只橘猫坐在窗台上"); expect(prompt).toContain(`节点 ${imageNode.id}`); @@ -321,14 +342,7 @@ test("native Design image-mimic template keeps describe mode and sends the image const renderCard = page.locator(`[data-design-node="${renderNode.id}"]`); await renderCard.click({ position: { x: 80, y: 80 } }); await renderCard.getByRole("button", { name: "生成", exact: true }).click(); - await expect - .poll(async () => { - const current = await read(); - const output = current.document.nodes.find((node) => node.id === renderNode.id).metadata.output; - if (output.status === "error") throw new Error(`render node failed: ${JSON.stringify(output.error)}`); - return output.status; - }, { timeout: 20_000 }) - .toBe("success"); + await expectNodeRunSucceeds(read, renderNode.id, "the template's render node run"); const rendered = (await read()).document.nodes.find((node) => node.id === renderNode.id).metadata.output; expect(rendered.media).toHaveLength(1); expect(rendered.media[0].kind).toBe("image"); diff --git a/packages/webui/test/browser/native-design.spec.mjs b/packages/webui/test/browser/native-design.spec.mjs index 8c283953..ae8e6442 100644 --- a/packages/webui/test/browser/native-design.spec.mjs +++ b/packages/webui/test/browser/native-design.spec.mjs @@ -117,7 +117,12 @@ async function read(page) { }); } async function saved(page, predicate) { - await expect.poll(async () => predicate(await read(page))).toBe(true); + // A design write crosses the runtime and comes back, and a loaded runner + // can take longer than the default poll allows. The wait is for the write + // to land, not for it to be quick. + await expect + .poll(async () => predicate(await read(page)), { timeout: 30_000 }) + .toBe(true); return read(page); } async function choose(page, name, label) { @@ -421,7 +426,10 @@ test("native Design preserves original menus, selected operations, graph gesture .locator(".webui-design-node-error") .getByRole("button", { name: "上报", exact: true }) .click(); - expect(await design.evaluate(() => navigator.clipboard.readText())).toBe( + // The report itself is written with LF. The Windows clipboard answers + // with CRLF, so the two are compared as the same text. + const reported = await design.evaluate(() => navigator.clipboard.readText()); + expect(reported.replace(/\r\n/g, "\n")).toBe( `节点:图片\nID:${imageId}\n错误:Synthetic error for real recovery controls`, ); await photograph(design, "design-error-controls-dark"); @@ -696,8 +704,9 @@ test("native Design processes real local media through in-card crop, grid, clip page.getByText("画布在用", { exact: false }).first(), ).toBeVisible(); await photograph(page, "design-library-dark"); - const beforeInsert = await read(page), - priorIds = new Set(beforeInsert.document.nodes.map((node) => node.id)); + // The pane's own transform says where the pane's centre is, and the + // pane places an inserted node there. The rounding is the pane's own + // rounding, so the two agree on the pixel and not on its neighbourhood. const insertPosition = await page .getByTestId("design-viewport") .evaluate((element) => { @@ -706,16 +715,41 @@ test("native Design processes real local media through in-card crop, grid, clip .transform, ); return { - x: (element.clientWidth / 2 - matrix.e) / matrix.a - 150, - y: (element.clientHeight / 2 - matrix.f) / matrix.a - 90, + x: Math.round((element.clientWidth / 2 - matrix.e) / matrix.a) - 150, + y: Math.round((element.clientHeight / 2 - matrix.f) / matrix.a) - 90, }; }); - await page.getByRole("button", { name: "插入", exact: true }).first().click(); + const libraryItem = page + .locator(".webui-design-library-item") + .filter({ has: page.locator("img") }) + .first(); + const assetSource = await libraryItem.locator("img").getAttribute("src"); + const assetName = + new URL(assetSource ?? "/", "http://library.invalid").pathname.split("/").pop() ?? ""; + await libraryItem.getByRole("button", { name: "插入", exact: true }).click(); + // The inserted node is the one the insert selected. "The node that is + // new" is not the same node: the media tool's tiles keep arriving after + // the split, and a tile that lands after this point is new too, and it + // carries the very file the library item names. + let insertedId = ""; + await expect + .poll( + async () => { + const selected = page.locator('[data-design-node][data-selected="true"]'); + if ((await selected.count()) !== 1) return ""; + insertedId = (await selected.getAttribute("data-design-node")) ?? ""; + return insertedId; + }, + { timeout: 30_000 }, + ) + .toBeTruthy(); state = await saved( page, - (value) => value.document.nodes.length === priorIds.size + 1, + (value) => value.document.nodes.some((node) => node.id === insertedId), ); - const inserted = state.document.nodes.find((node) => !priorIds.has(node.id)); + const inserted = state.document.nodes.find((node) => node.id === insertedId); + expect(inserted.metadata.output.media ?? []).toHaveLength(1); + expect(String(inserted.metadata.output.media[0].url ?? "")).toContain(assetName); expect(inserted.position.x).toBeCloseTo(insertPosition.x, 0); expect(inserted.position.y).toBeCloseTo(insertPosition.y, 0); await expect( diff --git a/packages/webui/test/browser/real-browser-bridge.ts b/packages/webui/test/browser/real-browser-bridge.ts index 3b151888..69c3489d 100644 --- a/packages/webui/test/browser/real-browser-bridge.ts +++ b/packages/webui/test/browser/real-browser-bridge.ts @@ -36,6 +36,17 @@ export const INSTALLATION_KEY_STORAGE_KEY = "webui.browserBridge.installationKey /** How long to wait for the extension to connect before calling it a failure. */ export const CONNECT_TIMEOUT_MS = 20_000; +/** + * How long a browser launch may take before it counts as a failure. + * + * The bound is about the machine, not the browser: the first Edge launch on + * a cold runner has to build its profile before the extension answers, and a + * loaded runner can spend past a minute on that alone. A launch bound that + * reports a slow machine as a broken bridge is a bound that fails for the + * wrong reason. + */ +export const BROWSER_LAUNCH_BOUND_MS = 120_000; + /** * The slice of the extension API the harness uses. * @@ -112,7 +123,9 @@ function extensionIdOf(worker: Worker): string { * * So every wait in this file that can outlive its case is bounded here, and * the message names the step that stopped. The bound is generous enough for a - * slow machine: the Edge handshake takes 22.6 s on a CI runner. + * slow machine: the Edge handshake takes 22.6 s on a CI runner, and the first + * Edge launch on a cold runner builds its profile before it answers — 28.1 s + * on an idle runner, and past a minute on a loaded one. */ async function bounded(what: string, ms: number, work: Promise): Promise { let timer: ReturnType | undefined; @@ -159,7 +172,7 @@ export async function launchWithExtension( const dist = options.dist ?? extensionDist; const context = await bounded( `the ${channel} browser did not start`, - 60_000, + BROWSER_LAUNCH_BOUND_MS, chromium.launchPersistentContext(profileDir, { headless: true, // "chromium" is the bundled browser and "msedge" is the installed Edge. @@ -178,7 +191,7 @@ export async function launchWithExtension( if (!worker) { worker = await bounded( `the ${channel} browser did not start the extension's service worker`, - 60_000, + BROWSER_LAUNCH_BOUND_MS, context.waitForEvent("serviceworker", { timeout: 30_000 }), ); } diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png index f32cdde5..aa0f1077 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png index c8357eaf..0fcee151 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png index 6a680653..c32a069c 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png differ diff --git a/packages/webui/test/browser/support/native-design-browser-host.ts b/packages/webui/test/browser/support/native-design-browser-host.ts index b58acf0b..279dcb7f 100644 --- a/packages/webui/test/browser/support/native-design-browser-host.ts +++ b/packages/webui/test/browser/support/native-design-browser-host.ts @@ -175,31 +175,60 @@ const uploadServer = createServer(async (request, response) => { return; } const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); try { - const form = await new Request("http://127.0.0.1/upload", { - method: "POST", - headers: { "content-type": String(request.headers["content-type"] ?? "") }, - body: Buffer.concat(chunks), - }).formData(); - const file = form.get("file"); - if (file && typeof file !== "string") { - const bytes = Buffer.from(await file.arrayBuffer()); - uploads.push({ - mime: file.type, - filename: file.name, - bytes: bytes.length, - magic: bytes.subarray(0, 8).toString("hex"), - }); - } else { - uploadError = "multipart did not carry a file field"; - } + for await (const chunk of request) chunks.push(Buffer.from(chunk)); } catch (error) { uploadError = error instanceof Error ? error.message : String(error); } + // The multipart body is read here rather than through a `Request` whose + // `formData()` parses it: that parser is the one dependency in this path + // that behaves differently across platforms, and the provider waits for an + // answer it never gets when it does. The body is a small, known shape, so + // it is read directly. + const file = parseMultipartFile( + Buffer.concat(chunks), + String(request.headers["content-type"] ?? ""), + ); + if (file) uploads.push(file); + else if (!uploadError) uploadError = "multipart did not carry a file field"; response.writeHead(200); response.end(); }); + +/** + * Read the one file part out of a multipart body. + * + * The bytes are kept as they arrived: the evidence the acceptance checks is + * the part's own type, name and leading bytes, so the parser reads the + * headers and leaves the content alone. + */ +function parseMultipartFile( + body: Buffer, + contentType: string, +): { readonly mime: string; readonly filename: string; readonly bytes: number; readonly magic: string } | undefined { + const boundary = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType); + const delimiter = boundary ? `--${(boundary[1] ?? boundary[2] ?? "").trim()}` : ""; + if (!delimiter) return undefined; + const raw = body.toString("latin1"); + for (const part of raw.split(delimiter)) { + const separator = part.indexOf("\r\n\r\n"); + if (separator < 0) continue; + const headers = part.slice(0, separator); + const disposition = /content-disposition:([^\r\n]*)/i.exec(headers)?.[1] ?? ""; + const name = /name="([^"]*)"/i.exec(disposition)?.[1] ?? ""; + if (name !== "file") continue; + const filename = /filename="([^"]*)"/i.exec(disposition)?.[1] ?? ""; + const mime = /content-type:\s*([^\r\n;]+)/i.exec(headers)?.[1]?.trim() ?? ""; + const content = Buffer.from(part.slice(separator + 4).replace(/\r\n$/, ""), "latin1"); + return { + mime, + filename, + bytes: content.length, + magic: content.subarray(0, 8).toString("hex"), + }; + } + return undefined; +} await new Promise((resolve) => uploadServer.listen(0, "127.0.0.1", resolve)); const uploadAddress = uploadServer.address(); if (!uploadAddress || typeof uploadAddress === "string") throw new Error("Synthetic provider upload did not bind"); diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png index 8e12a3cf..a74ae968 100644 Binary files a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png differ diff --git a/packages/webui/test/integration/isolated-chromium-screencast.test.ts b/packages/webui/test/integration/isolated-chromium-screencast.test.ts index eb557bcc..e3daafab 100644 --- a/packages/webui/test/integration/isolated-chromium-screencast.test.ts +++ b/packages/webui/test/integration/isolated-chromium-screencast.test.ts @@ -82,12 +82,54 @@ describe.skipIf(!available)("the isolated Chromium's screencast", () => { const selected = (await provider.listTargets()).find((entry) => entry.selected); if (!selected) throw new Error("the provider reported no selected target"); await provider.sendCommand(selected.id, "Page.navigate", { url }); - await new Promise((resolve) => setTimeout(resolve, 500)); - const current = (await provider.listTargets()).find( - (entry) => entry.id.targetId === selected.id.targetId, - ); - if (!current) throw new Error("the navigated page is not in the target list"); - return { targetId: current.id.targetId, id: current.id }; + const id = await waitForLoadedPage(selected.id.targetId, selected.id); + return { targetId: id.targetId, id }; + } + + /** + * Wait for the page to finish loading, and say the page that is there now. + * + * The navigation is answered before the page has loaded, so a fixed wait + * hands the next action to a page that is not there yet: the click is lost + * and the case reports that the click did not land, when the page was + * simply not ready for it. A loaded machine and a loaded runner differ by + * exactly that much time. + */ + async function waitForLoadedPage( + targetId: string, + before: WebuiBrowserTargetId, + ): Promise { + const deadline = Date.now() + 15_000; + for (;;) { + const current = (await provider.listTargets()).find( + (entry) => entry.id.targetId === targetId, + ); + if (!current) throw new Error("the navigated page is not in the target list"); + // A page that navigated is a different page: it carries a new + // generation, and an input aimed at the previous one is refused. The + // new generation is therefore part of what "the page is there now" + // means, and waiting for it is what keeps the click deliverable. + if (current.id.generation === before.generation) { + await new Promise((resolve) => setTimeout(resolve, 50)); + if (Date.now() >= deadline) { + throw new Error("the navigated page did not become the page that is there now"); + } + continue; + } + try { + const ready = (await provider.sendCommand(current.id, "Runtime.evaluate", { + expression: "document.readyState", + returnByValue: true, + })) as { result?: { value?: unknown } } | undefined; + if (ready?.result?.value === "complete") return current.id; + } catch { + // The page is navigating: there is no context to answer in yet. + } + if (Date.now() >= deadline) { + throw new Error("the navigated page did not finish loading"); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } } it("keeps delivering frames while the page changes", async () => { @@ -154,13 +196,23 @@ describe.skipIf(!available)("the isolated Chromium's screencast", () => { y: onSurface.y, button: "left", }); - await new Promise((resolve) => setTimeout(resolve, 300)); - - const clicked = (await provider.sendCommand(id, "Runtime.evaluate", { - expression: "document.getElementById('log').textContent", - returnByValue: true, - })) as { result?: { value?: unknown } } | undefined; - expect(clicked?.result?.value).toBe("clicked"); + // The page is polled for the click, not slept through: the click is + // delivered to the browser and the page answers in its own time, and a + // fixed wait reports a click that has not been handled yet as a click + // that never landed. + const deadline = Date.now() + 15_000; + let clicked: unknown; + for (;;) { + const read = (await provider.sendCommand(id, "Runtime.evaluate", { + expression: "document.getElementById('log').textContent", + returnByValue: true, + })) as { result?: { value?: unknown } } | undefined; + clicked = read?.result?.value; + if (clicked === "clicked") break; + if (Date.now() >= deadline) break; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + expect(clicked).toBe("clicked"); expect(targetId).toBeTruthy(); }); }); diff --git a/packages/webui/test/integration/real-host-loopback.test.ts b/packages/webui/test/integration/real-host-loopback.test.ts index 4160613f..7d4528a2 100644 --- a/packages/webui/test/integration/real-host-loopback.test.ts +++ b/packages/webui/test/integration/real-host-loopback.test.ts @@ -25,7 +25,7 @@ import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { chromium, expect as browserExpect } from "@playwright/test"; import { WebSocket } from "ws"; import type { RawData } from "ws"; @@ -66,6 +66,26 @@ interface Booted { const booted: Booted[] = []; const previousDataDir = process.env.MINIMAX_DATA_DIR; +/** + * Every case in this file runs offline. + * + * The real host fetches the official MiniMax model catalog on demand, and + * that request is asynchronous: the host it was booted for can still be + * waiting on it when the next case has already booted its own host in a + * different data directory. The catalog is then persisted through + * `replaceLocalManagedMinimaxProvider`, which resolves the config path at + * write time — so the late write lands in whichever directory the process + * points at by then, and a case finds its own fixture file replaced by the + * previous case's model catalog. + * + * Nothing in this file is about the network, so the network is cut at the + * door: a case that cannot reach a remote catalog cannot have one written + * into its directory, whatever the runner's network happens to allow. + */ +beforeEach(() => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline catalog"))); +}); + afterEach(async () => { for (const entry of booted.splice(0)) await entry.close(); if (previousDataDir === undefined) delete process.env.MINIMAX_DATA_DIR; @@ -244,11 +264,21 @@ describe("real host over the loopback service", () => { } }, 120_000); - it("lists builtin models on first boot without runtime environment or a remote catalog", async () => { - for (const key of ["MAVIS_REGION", "MAVIS_BUILD_ENV", "__MAVIS_RUNTIME_MANAGED"]) { - vi.stubEnv(key, undefined); - } - vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline catalog"))); + it("lists builtin models on first boot without a reachable model catalog", async () => { + // The scope is pinned to a test preset instead of being left unset. The + // WebUI assembly resolves an unset scope to cn/prod, whose managed base + // URL is the real production endpoint + // (`https://agent.minimax.cn/mavis/api/v1/llm/v1`, + // `packages/config/src/config.ts`), and the managed runtime fetches the + // official model catalog from it on demand. A runner with internet would + // therefore fetch that catalog and persist it into this data directory — + // the one write the fixture below forbids — while a machine without it + // would not. The test preset's endpoint does not resolve, so the first + // boot has no remote catalog either way, and the case stops depending on + // the machine's network. + vi.stubEnv("MAVIS_REGION", "cn"); + vi.stubEnv("MAVIS_BUILD_ENV", "test"); + vi.stubEnv("__MAVIS_RUNTIME_MANAGED", undefined); let client: Client | undefined; try { const host = await bootRealHost(); diff --git a/packages/webui/test/unit/design-atomic-file.test.ts b/packages/webui/test/unit/design-atomic-file.test.ts new file mode 100644 index 00000000..fe36a18b --- /dev/null +++ b/packages/webui/test/unit/design-atomic-file.test.ts @@ -0,0 +1,103 @@ +/** + * The Design runtime's atomic file write. + * + * Windows refuses a rename that replaces a file while another process holds + * that file open for a moment, and the refusal is transient. Every state + * file of the Design runtime is written that way, so the refusal used to + * fail a whole Design operation: the canvas document was not written, the + * run that belonged to it never started, and the node stayed idle for ever. + */ +import { mkdtemp, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { writeFileAtomically } from "../../src/runtime/design/atomic-file.mjs"; + +function refusal(): Error & { code: string } { + return Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM" }); +} + +async function scratch(): Promise { + return await mkdtemp(path.join(tmpdir(), "webui-design-atomic-")); +} + +describe("the Design runtime's atomic file write", () => { + it("retries the rename when Windows refuses it", async () => { + const directory = await scratch(); + try { + const file = path.join(directory, "design_document.json"); + await writeFile(file, "old", "utf8"); + let attempts = 0; + await writeFileAtomically(file, "new", { + platform: "win32", + wait: async () => undefined, + move: async (from, to) => { + attempts += 1; + if (attempts === 1) throw refusal(); + await rename(from, to); + }, + }); + expect(attempts).toBe(2); + expect(await readFile(file, "utf8")).toBe("new"); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it("does not retry the refusal away from Windows", async () => { + const directory = await scratch(); + try { + const file = path.join(directory, "design_document.json"); + await writeFile(file, "old", "utf8"); + let attempts = 0; + await expect( + writeFileAtomically(file, "new", { + platform: "linux", + move: async () => { + attempts += 1; + throw refusal(); + }, + }), + ).rejects.toThrow("EPERM"); + expect(attempts).toBe(1); + expect(await readFile(file, "utf8")).toBe("old"); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it("leaves the old file and no temporary file behind when the write fails", async () => { + const directory = await scratch(); + try { + const file = path.join(directory, "design_document.json"); + await writeFile(file, "old", "utf8"); + await expect( + writeFileAtomically(file, "new", { + platform: "win32", + wait: async () => undefined, + move: async () => { + throw refusal(); + }, + }), + ).rejects.toThrow("EPERM"); + expect(await readdir(directory)).toEqual(["design_document.json"]); + expect(await readFile(file, "utf8")).toBe("old"); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it("replaces the file with the bytes it is given and leaves no temporary file", async () => { + const directory = await scratch(); + try { + const file = path.join(directory, "design_document.json"); + await writeFile(file, "old", "utf8"); + await writeFileAtomically(file, "new"); + expect(await readFile(file, "utf8")).toBe("new"); + expect(await readdir(directory)).toEqual(["design_document.json"]); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/webui/test/unit/design-owner.test.ts b/packages/webui/test/unit/design-owner.test.ts index 6c2eca6a..634bf587 100644 --- a/packages/webui/test/unit/design-owner.test.ts +++ b/packages/webui/test/unit/design-owner.test.ts @@ -137,6 +137,24 @@ describe("native Design owner", () => { const measured = designPlaceProducts({ ...placed, nodes: placed.nodes.map((node) => node.id === ids[0] ? { ...node, height: 500 } : node) }, { ids, sourceNodeId: source.id, columns, tile: true, measured: true }); expect(measured.nodes.find((node) => node.id === ids[columns])!.position.y).toBe(80 + 500 + 80); }); + it("leaves the card the person placed where it is when the products are laid out again", () => { + // The card the person just inserted is theirs: a grid that is laid out + // again gives way to it, and the card in the way steps aside instead. + // The board held the source and the two products when the placement was + // made; the card of the person is not among them. + const source = { ...node("source"), position: { x: 20, y: 40 } }, + mine = { ...node("mine"), position: { x: 450, y: 90 } }, + before = { ...document("A"), nodes: [source, mine, node("t1"), node("t2")] }; + const kept = designPlaceProducts(before, { ids: ["t1", "t2"], sourceNodeId: source.id, known: ["source", "t1", "t2"] }); + expect(kept.nodes.find((item) => item.id === "mine")!.position).toEqual({ x: 450, y: 90 }); + expect(kept.nodes.find((item) => item.id === "t1")!.position.x).toBeGreaterThan(450); + // Without the card of the person in the way, the rule is the one it was: + // the card that was just placed keeps its place, and the card in the way + // steps aside. + const pushed = designPlaceProducts(before, { ids: ["t1", "t2"], sourceNodeId: source.id }); + expect(pushed.nodes.find((item) => item.id === "mine")!.position.x).toBeGreaterThan(450); + expect(pushed.nodes.find((item) => item.id === "t1")!.position.x).toBe(420); + }); it("resolves a queued batch placement against the newest product snapshot", async () => { let current = { ...document("A"), nodes: [node("source"), node("tile")] }; const writing = deferred(), requests: ApplyDesignActionRequest[] = []; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7aeb00c8..438c1998 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -981,6 +981,9 @@ importers: mermaid: specifier: 12.3.0 version: 12.3.0 + node-abi: + specifier: 3.96.0 + version: 3.96.0 node-pty: specifier: 1.1.0 version: 1.1.0 diff --git a/release/public-source.json b/release/public-source.json index d470ba39..3d33a097 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -4520,6 +4520,8 @@ "packages/webui/src/runtime/design/LICENSE", "packages/webui/src/runtime/design/agent-runner.d.mts", "packages/webui/src/runtime/design/agent-runner.mjs", + "packages/webui/src/runtime/design/atomic-file.d.mts", + "packages/webui/src/runtime/design/atomic-file.mjs", "packages/webui/src/runtime/design/connector-runner.d.mts", "packages/webui/src/runtime/design/connector-runner.mjs", "packages/webui/src/runtime/design/design-service.ts", @@ -5041,6 +5043,7 @@ "packages/webui/test/unit/conversation-usage-notice.test.ts", "packages/webui/test/unit/cron-harness-adapter.test.ts", "packages/webui/test/unit/delivery-disposers.test.ts", + "packages/webui/test/unit/design-atomic-file.test.ts", "packages/webui/test/unit/design-capability-discovery.test.ts", "packages/webui/test/unit/design-media-kind-preparation.test.ts", "packages/webui/test/unit/design-media-runtime.test.ts", diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index 4b324116..46d858bb 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -29,7 +29,9 @@ import { acceptanceRecordFiles, restoreAcceptanceRecords } from '../scripts/lib/ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => { const activeWorkflows = readdirSync(new URL('../.github/workflows/', import.meta.url)) .filter(name => /\.ya?ml$/.test(name)).sort(); - assert.deepEqual(activeWorkflows, ['webui-ci.yml']); + // The manual baseline refresh is a second active workflow: it records the + // pixels the CI compares against, and it cannot publish anything. + assert.deepEqual(activeWorkflows, ['update-visual-baselines.yml', 'webui-ci.yml']); const workflow = parseYaml(readFileSync(new URL('../.github/workflows/webui-ci.yml', import.meta.url), 'utf8')); assert.deepEqual(workflow.on.push.branches, ['main']); assert.ok(Object.hasOwn(workflow.on, 'pull_request')); @@ -58,9 +60,17 @@ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => assert.match(browserConfig, /process\.env\.WEBUI_PLAYWRIGHT_OUTPUT_DIR/); assert.match(browserConfig, /cacheDirectory: process\.env\.WEBUI_BROWSER_FONT_CACHE_DIR/); assert.doesNotMatch(browserConfig, /process\.env\.WEBUI_BROWSER_OUTPUT_DIR/); + // The steps that prepare the machine are not WebUI checks: they install the + // dependencies, the browser and the media binary the Design paths run for + // real. Every other step has to be a WebUI command from this repository. + const ffmpeg = job.steps.find(step => step.name === 'Install FFmpeg'); + assert.ok(ffmpeg, 'the native Design media paths run FFmpeg for real'); + assert.match(ffmpeg.run, /ffmpeg/); + assert.doesNotMatch(ffmpeg.run, /npm publish|curl |wget /); const commands = job.steps.filter(step => step.run && step !== directories).map(step => step.run); + const provisioning = ['pnpm install --frozen-lockfile', 'pnpm exec playwright install-deps chromium', ffmpeg.run]; for (const command of commands) { - if (command === 'pnpm install --frozen-lockfile' || command === 'pnpm exec playwright install-deps chromium') continue; + if (provisioning.includes(command)) continue; assert.match(command, /^pnpm (?:typecheck|check|build|install|test):webui(?:-[a-z]+)?$/); assert.ok(Object.hasOwn(manifest.scripts, command.slice('pnpm '.length)), command); } @@ -89,6 +99,33 @@ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => '${{ runner.temp }}/webui-playwright-results/', ]); }); +test('the manual baseline refresh renders in the mode the WebUI CI compares against', () => { + const refresh = parseYaml(readFileSync(new URL('../.github/workflows/update-visual-baselines.yml', import.meta.url), 'utf8')); + assert.deepEqual(Object.keys(refresh.on), ['workflow_dispatch']); + assert.ok(!Object.hasOwn(refresh.on, 'push')); + assert.ok(!Object.hasOwn(refresh.on, 'pull_request')); + const job = refresh.jobs.update; + assert.deepEqual(job.strategy.matrix.os, ['ubuntu-latest', 'macos-latest', 'windows-latest']); + const steps = job.steps; + const modeStep = steps.findIndex(step => typeof step.run === 'string' && step.run.includes('WEBUI_BROWSER_HEADED=')); + const refreshStep = steps.findIndex(step => typeof step.run === 'string' && step.run.includes('playwright test')); + assert.ok(modeStep >= 0, 'the refresh must select the browser mode the CI compares against'); + assert.ok(refreshStep >= 0, 'the refresh must render the baselines'); + assert.ok(modeStep < refreshStep, 'the browser mode must be selected before the baselines are rendered'); + assert.ok( + !steps[refreshStep].run.includes('WEBUI_BROWSER_HEADED'), + 'a step cannot read back the environment file it writes, so the mode has to be set by an earlier step', + ); + assert.match(steps[refreshStep].env.WEBUI_BROWSER_FONT_CACHE_DIR, /webui-browser-font-cache/); + const ci = parseYaml(readFileSync(new URL('../.github/workflows/webui-ci.yml', import.meta.url), 'utf8')); + const ciSteps = ci.jobs.webui.steps; + const ciModeStep = ciSteps.findIndex(step => typeof step.run === 'string' && step.run.includes('WEBUI_BROWSER_HEADED=')); + const ciBrowserStep = ciSteps.findIndex(step => step.run === 'pnpm test:webui-browser'); + assert.ok(ciModeStep >= 0 && ciModeStep < ciBrowserStep, 'the CI must select the browser mode before the browser suite runs'); + for (const step of steps) { + assert.doesNotMatch(String(step.run ?? ''), /npm publish|npm-release|release-cli/); + } +}); test('coverage review distinguishes declared browser scenarios from executed evidence', () => { const output = execFileSync(process.execPath, ['scripts/coverage-review.mjs', '--check'], { encoding: 'utf8' }); diff --git a/test/vitest-suites.json b/test/vitest-suites.json index b984a413..53fb3305 100644 --- a/test/vitest-suites.json +++ b/test/vitest-suites.json @@ -522,6 +522,7 @@ "packages/webui/test/unit/webui-workspace-canvas.test.tsx", "packages/webui/test/unit/design-owner.test.ts", "packages/webui/test/unit/design-runtime.test.ts", + "packages/webui/test/unit/design-atomic-file.test.ts", "packages/webui/test/unit/design-media-runtime.test.ts", "packages/webui/test/unit/design-capability-discovery.test.ts", "packages/webui/test/unit/design-text-material.test.ts",