Skip to content

Render the AI builder preview in the sandboxed frame - #1427

Open
vytisbulkevicius wants to merge 16 commits into
developmentfrom
bugfix/pro/658
Open

vytisbulkevicius wants to merge 16 commits into
developmentfrom
bugfix/pro/658

Conversation

@vytisbulkevicius

@vytisbulkevicius vytisbulkevicius commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

The AI Chart Builder drew its preview directly in the admin page, while the front end and the block editor draw D3 charts in a sandboxed frame. The builder now uses the same frame for the preview and for its code check.

What changed

  • Builder preview — chart code runs in the sandboxed D3 frame (sandbox="allow-scripts"), not in the admin page. The builder no longer bundles its own copy of D3 and TopoJSON.

  • Code check — the check that runs before a chart is shown or saved uses a hidden sandboxed frame and waits for its result. A chart that gives no result in 10 seconds counts as failed.

  • Builder settings — the builder gets the address of the frame script in its own settings (vizAIBuilder.iframeJsUrl), on the library page and in the block editor. The preview does not depend on a D3 chart in the library.

  • Frame script address — every page that loads the frame script gets its address from Visualizer_Module::d3_iframe_js_url(), which adds the plugin version (?ver=). A browser does not answer with the script of an older version, which never reports its render result.

  • Older check results — a check result is ignored when it no longer applies:

    • A code save check is dropped when newer data arrives, the draft code changes or the code editor closes.
    • A data check is dropped when the chart code is replaced: a manual save, a generated chart or a fixed chart.
    • The data that a generated chart brings goes to the preview with the generated code. The preview reports a chart that fails with it, and the builder repairs that chart.
    • Data that arrives during a repair goes to the preview with the repaired code, also when its check with the old code failed first. An error of the repaired code stays visible with the Fix control.
    • Data that a generated chart brings is shown with any column headers. The header warning is for data that the user brings.
  • D3 frame — after each render it reports the result to its parent as { type: 'render-result', error }.

Note

Tracked in Codeinwp/visualizer-pro#658.

Tests

New Playwright cases in tests/e2e/specs/ai-builder.spec.js:

  • the builder opened from the block editor renders in the sandbox;
  • code that throws shows Chart error: <message>;
  • a code save check is dropped when newer data arrives during it;
  • a data check is dropped when code saved with the newer data, or a generated chart, replaces the chart code;
  • the data a generated chart brings is shown with the generated code;
  • a generated chart that fails with the data it brings is repaired and shown with that data;
  • data that arrives during a repair is shown with the repaired code, and an error of that code stays visible;
  • data whose check failed before the repair finished is shown with the repaired code;
  • data that arrives during a generation is shown with the generated chart, also when the data of that chart cannot be read;
  • data with other column headers that a generated chart brings is shown without the header warning;
  • the frame script address carries the plugin version, on the library page and in the block editor.

Each case fails with its fix reverted.

QA

  1. On a site with no AI chart in the library, go to WP Admin → Visualizer → Chart Library. Click Add New Chart, select the AI builder, add data and generate a chart.

    Expect: the preview shows the chart, and the chart saves.

  2. In the library, click the edit control of that chart.

    Expect: the builder opens and the preview shows the saved chart.

  3. In the builder, ask for a change to the chart (for example, another colour).

    Expect: the preview updates, and a chart with broken code shows an error message, not an empty preview.

  4. In a post, add a Visualizer block with that chart and click its edit control.

    Expect: the builder opens and the preview shows the chart. In Edit code, change the code and click Save: the preview shows the change.

Review responses

Answers to the points of the review of a941148 that have no inline thread:

  • Pro hooks that receive chart code (Module/Chart.php) — this PR does not change what reaches those hooks. Whether a Pro consumer runs chart code is a question for the Pro plugin, so it is out of scope here.
  • PHPUnit and Jest suites not run — CI runs PHPUnit on this branch. This round changes no Jest-covered file.
  • Block Edit control not clicked — the new block editor case calls window.vizOpenAIBuilderEdit, the function the control calls, as the review run did. The case covers the missing setting, which is what broke the block editor.

The builder preview and its code check now use the same sandboxed
frame as the front end and the block editor.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
@pirate-bot

pirate-bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Plugin build for ca37631 is ready 🛎️!

vytisbulkevicius and others added 2 commits November 27, 2026 17:15
Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
… checks

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

@pirate-bot pirate-bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes requested

The sandboxed preview works on the library page, but the block editor builder cannot render, and a save check can restore old data.

Validation details
  • Files reviewed: 4/4 changed files.
  • The new Playwright case passed at HEAD cd /workspace/head && sandbox-doctor.sh --plugin visualizer 2>&1 | grep -vE '^\s*$' | tail -8; export WP_BASE_URL=http:/… (run R9, exit 0) and failed with pr-base code cd /var/www/html && ln -sfn /workspace/base wp-content/plugins/visualizer && wp plugin deactivate visualizer >/dev/null … (run R10, exit 0).
  • Block editor vizAIBuilder lacks iframeJsUrl, and the builder showed the renderer error cat > /workspace/checks/C12/open.js <<'EOF' const { chromium } = require( 'playwright' ); const fs = require( 'fs' ); co… (run R13, exit 0).
  • Every other place that runs saved D3 code uses the sandboxed renderer frame.
  • The source check, the #chart container and the ready message of the frame match the builder.
Untested areas
  • Pro plugin hooks that receive chart code were not checked. Their source is not available.
  • The PHPUnit and Jest suites were not run.
  • The block Edit control was not clicked. The run called the function the control calls.
  • The variant pass did not settle these places, where the fixed cause may still reach:
    • classes/Visualizer/Module/Chart.php:82-92,426-437,876-884,978-982,1541-1567 — unverified: Whole chart records containing code reach Pro sidebar/resource hooks and the legacy Pro resource loader. Pro implementation and version are unavailable; whether those consumers exe…

🤖 Automated review · run code-review-agent_6b0b41f36e9e62.82123300.


🤖 Review agent — review posted ✅ on a9411487 · changes requested · 3 findings · 21 min

Run code-review-agent_6b0b41f36e9e62.82123300 · trail

Comment thread classes/Visualizer/Module/Admin.php Resolved
Comment thread tests/e2e/specs/ai-builder.spec.js Resolved
vytisbulkevicius and others added 6 commits December 1, 2026 12:12
…rseded code checks

The block editor localized vizAIBuilder without iframeJsUrl, so the builder
opened from a Visualizer block could not render or save code. New data now
drops a pending code save check, and a saved code drops a pending data check.

Adds E2E cases for the block editor preview, the error the chart code throws
and both superseded checks.
…ript

A generated or fixed chart now drops a pending data check of the code it
replaces, and the data a generated chart brings is checked with the generated
code. The address of the sandboxed frame script carries the plugin version, so
a browser does not answer the builder with the script of an older version that
never reports its render result.
…a with repaired code

Data that comes with a generated chart goes to the preview without a hidden
check, so a generated chart that fails is reported there and repaired.
When a repair replaces the chart code, data whose check was pending is
checked again with the repaired code.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
…epaired code

The preview reports a failure of the repaired code with that data, so the
error and the Fix control stay. The repair test waits for both jobs.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

@pirate-bot pirate-bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes requested

The three earlier findings are fixed, but data that reaches the builder during a repair or a generation can still miss the preview.

Validation details
  • Files reviewed: 8/8 changed files.
  • The repair order where the data check fails first was reproduced in the sandbox at 068cfa1: cd /workspace/checks/C7 && python3 - <<'EOF' import re p='specs/c7-order.spec.js' s=open(p).read() old="if ( body.includ… printed C7-A RESULT: preview=rows: 1 warning_shown=true (run R9).
  • The block editor case passed at HEAD cd /workspace/checks/C7 && export WP_BASE_URL=http://localhost:8080 WP_USERNAME=admin WP_PASSWORD=admin STORAGE_STATE_PA… (run R14, exit 0).
  • Every page that loads the frame script uses the versioned address. No builder path runs chart code outside the sandbox.
Untested areas
  • The new cases were not run with each fix reverted. At pr-base they fail because the sandbox preview is missing.
  • The output of the external chart generator was not captured.
  • The block Edit control was not clicked. The PHPUnit suite was not run.
  • Pro plugin hooks that receive chart code remain unchecked. Their source is not available.

🤖 Automated review · run code-review-agent_6b0f1e508a4217.85342430.


🤖 Review agent — review posted ✅ on 068cfa11 · changes requested · 3 findings · 30 min

Run code-review-agent_6b0f1e508a4217.85342430 · trail

Comment thread tests/e2e/specs/ai-builder.spec.js Resolved
vytisbulkevicius and others added 3 commits December 1, 2026 22:24
…code

Data whose check failed, or whose column headers changed, goes to the
preview when a repair or a generation replaces the chart code. Data that a
generated chart brings is shown with any column headers. The spec opens a
saved chart through one helper.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
…at arrives during a generation

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>

@pirate-bot pirate-bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes requested

The three earlier findings are fixed, but data that arrives during a generation can still miss the preview, and a late preview error can overwrite a generated chart.

  • classes/Visualizer/ChartBuilder/src/AIBuilder/DataSource.js:216-238 — note Not blocking: another place of the cause this PR fixes, in a file the PR does not change. Overlapping uploads apply in the order their responses arrive. When the user edits the CSV again while the first upload runs, two uploads are in flight. Nothing ties a response to the newest request before onDataReady(). When the older response arrives last, handleDataReady() gives it the newest check token, and it replaces the newer data. Invalidate a running upload whenever the input changes, also when the input returns to the last uploaded CSV. Apply only a response that matches the current input. Add a case to ai-builder.spec.js that holds two uploads, releases them in reverse order, and expects the newer rows.
Validation details
  • Files reviewed: 2/2 files changed since the prior review, and 8/8 files of the PR.
  • The passed-check order during a generation was run in the sandbox at 91884d5: cd /workspace/checks/C2 && ln -sfn /workspace/head/node_modules node_modules && export WP_BASE_URL=http://localhost:8080… printed C2 RESULT preview=rows: 1 (run R9).
  • The existing case for data that arrives during a generation passed cd /workspace/checks/C2 && export WP_BASE_URL=http://localhost:8080 WP_USERNAME=admin WP_PASSWORD=admin STORAGE_STATE_PA… (run R10, exit 0).
  • A late preview error during a generation started a repair that replaced the generated code cd /workspace/checks/C5 && python3 - <<'EOF' p='specs/ai-builder-c5.spec.js' s=open(p).read() s=s.replace("const BUSY_CO… (run R20, exit 0).
Untested areas
  • The new cases were not run with each fix reverted.
  • The late-error case ran only with the generation finishing first.
  • The output of the external chart generator was mocked. The PHPUnit suite was not run.
  • Pro plugin hooks that receive chart code remain unchecked. Their source is not available.
  • The variant pass did not settle these places, where the fixed cause may still reach:
    • classes/Visualizer/Module/Chart.php:82-92,426-437,876-884,978-982,1541-1571 — unverified: Whole records containing D3 code reach Pro sidebar/resource hooks. Pro implementation source is unavailable, so whether those consumers execute code or asynchronously apply stale c…

🤖 Automated review · run code-review-agent_6b0fb36b2fb680.63507608.


🤖 Review agent — review posted ✅ on 91884d51 · changes requested · 3 findings · 25 min

Run code-review-agent_6b0fb36b2fb680.63507608 · trail

Comment on lines +451 to +467
// Without data of its own, the new chart shows the newest data, also when that arrived during the generation.
const current = replaceCode( newCode, 'agent' ) || { series, data };
if ( dataCsv && uploadNonce ) {
try {
const trimmedCsv = String( dataCsv ).trim();
const parsed = await uploadCsvString( chartId, uploadNonce, trimmedCsv );
setInitialCsvText( trimmedCsv );
handleDataReady( parsed.series, parsed.data );
handleDataReady( parsed.series, parsed.data, true );
} catch ( e ) {
setPreviewSeries( series );
setPreviewData( data );
setPreviewSeries( current.series );
setPreviewData( current.data );
setDataIncompatible( null );
setGenError( __( 'Chart generated, but the extracted data could not be parsed. Please verify the data or regenerate.', 'visualizer' ) );
}
} else {
setPreviewSeries( series );
setPreviewData( data );
setPreviewSeries( current.series );
setPreviewData( current.data );

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correctness ✓ Verified in the sandbox Data that arrives during a generation is lost when its data check passes. The passed check clears pendingDataRef and shows the new rows. A generation without data_csv then gets null from replaceCode(). The fallback { series, data } holds the values of the render where Generate was clicked. The preview reverts to the older rows. The catch branch does the same. Keep the latest data in a ref that handleDataReady() sets. Read that ref when each fallback runs, also after a failed CSV upload, not before the await. Add a case to ai-builder.spec.js where the saved code accepts the two rows, the check passes during the generation, and the preview shows rows: 2.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cd1c360. handleDataReady() keeps the newest data in latestDataRef, and both fallbacks of the generation read it when they run, also after a failed CSV upload. Test: 'keeps data whose check passed during a generation'.

Comment on lines +299 to +309
renderD3( activeCode, previewRef.current, previewSeries, previewData ).then( ( err ) => {
if ( stale ) return;
if ( editOpen ) {
setEditorError( err || null );
return;
}
} else {
setRenderError( null );
}
if ( err ) {
setRenderError( err );
if ( codeOriginRef.current === 'agent' && ! fixing && ! fixAttemptedRef.current ) {
fixAttemptedRef.current = true;
autoFix( err );

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correctness ✓ Verified in the sandbox A late preview error starts a repair while a generation runs, and the repair then overwrites the generated chart. Clicking Generate changes no dependency of the preview effect, so stale stays false. Line 307 checks fixing and fixAttemptedRef, but not a running generation. Both jobs end in replaceCode(), and the last one wins. This assumes a slow or failed frame-script load overlaps a generation. Start an automatic repair only when no generation or repair runs, read from a ref, because the effect holds an old generating value. Add a case to ai-builder.spec.js where the preview answers after Generate is clicked, and expect no repair request and the generated code in the preview.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cd1c360. busyRef is true while a generation or a repair runs, and the preview effect starts an automatic repair only when it is false. Test: 'does not repair the replaced code when its preview fails during a generation'.

Comment on lines +380 to +383
} else if ( code && ! generated ) {
pendingDataRef.current = { series: newSeries, data: newData };
testD3( code, newSeries, newData ).then( ( err ) => {
if ( check !== dataCheckRef.current ) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correctness Data that arrives after a generation or repair replaced the code is checked with the replaced code. A file or URL import calls the onDataReady callback of the render where it started. That handleDataReady() reads the code of the same render, so testD3() at line 382 runs the old code. When the old code fails with the data, the mismatch warning shows. The preview keeps the old rows, although the new code accepts them. Run the data check with the current code, read from a ref that replaceCode() sets. Add a case to ai-builder.spec.js where the upload finishes after a repair, the old code fails with it, and the repaired code shows the rows.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cd1c360. replaceCode() sets codeRef, and handleDataReady() checks the data with that code. Test: 'checks data that arrives after a repair with the repaired code'.

…its render

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
@vytisbulkevicius

Copy link
Copy Markdown
Contributor Author

Review note F10 (overlapping uploads in DataSource.js) is not changed here. That file is outside this PR, and the order of two uploads is a separate behaviour from the code and data checks that this PR changes. It needs its own change.

@pirate-bot

pirate-bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

🤖 Review agent — running 🔄 on ca376315 · a push that changes the diff stops this run and reviews the new head

Run code-review-agent_6b0fe471644f18.81741555 · trail

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants