Fix dashboard sandbox compile errors and switch smart model to Grok#1476
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughSwitch authenticated smart-quality backend model IDs to x-ai/grok-build-0.1 and refactor the dashboard iframe sandbox to embed the AI source as JSON, load Babel with crossorigin, install an early error bridge, compile with Babel.transform, and execute compiled code with scoped globals and a compile-failure UI. ChangesAI Model and Sandbox Execution
🎯 4 (Complex) | ⏱️ ~45 minutes sequenceDiagram
participant Iframe as Dashboard Iframe
participant Head as Iframe Head
participant Babel as window.Babel
participant Runtime as Bootstrap Runtime
participant Parent as Parent Window
Iframe->>Head: load Babel script (crossorigin="anonymous")
Head->>Iframe: embed `script#ai-dashboard-source` (JSON payload)
Iframe->>Iframe: install window.__postDashboardError (for error & unhandledrejection)
Runtime->>Runtime: JSON.parse(ai-dashboard-source)
Runtime->>Babel: Babel.transform(source, { presets: ['react'] })
alt Compilation Success
Babel-->>Runtime: compiledCode
Runtime->>Runtime: new Function(compiledCode)(React, ReactDOM, DashboardUI, Recharts, stackServerApp)
Runtime->>Iframe: render Dashboard export
else Compilation Failure
Babel-->>Runtime: throw error
Runtime->>Parent: window.__postDashboardError(postedError)
Runtime->>Iframe: render "Dashboard failed to compile" UI
end
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
e11c08f to
f2d62da
Compare
Greptile SummaryThis PR improves error visibility in the AI dashboard sandbox by forwarding Babel compile errors, runtime throws, and unhandled rejections to the parent composer via
Confidence Score: 5/5Safe to merge — the sandbox changes are a well-scoped improvement to error surfacing with no regressions to the happy path, and the model swap is a single config line. The two previously flagged issues (duplicate error listeners and </script> injection via text/plain) are both resolved cleanly. The new application/json + JSON-encoding approach is correct and safe. The Babel.transform + new Function execution path scopes variables explicitly and handles the compile-error branch without double-reporting. The model change is a trivial string swap with no surrounding logic touched. No files require special attention. Important Files Changed
Reviews (3): Last reviewed commit: "Enhance error handling in dashboard sand..." | Re-trigger Greptile |
There was a problem hiding this comment.
Pull request overview
This PR improves the AI dashboard sandbox preview experience by surfacing compilation/runtime failures from the sandboxed srcDoc iframe back to the dashboard composer, and updates the backend “smart” authenticated model routing to use Grok.
Changes:
- Add iframe → parent error forwarding for compile/runtime errors, and compile AI-generated JSX explicitly via
Babel.transformwith a try/catch to surface parse errors. - Adjust Babel loading to improve cross-origin error readability (
crossorigin="anonymous"). - Switch authenticated smart-tier model selection from
moonshotai/kimi-k2.6:nitrotox-ai/grok-build-0.1.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx | Enhances sandbox iframe error reporting and changes how AI code is compiled/executed. |
| apps/backend/src/lib/ai/models.ts | Updates smart-tier authenticated model ID selection. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx (1)
486-501:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDuplicate error/unhandledrejection listeners.
These event listeners are duplicates of the ones installed earlier at lines 362-369 in the IIFE block. Both register handlers for
'error'and'unhandledrejection'that post the same'dashboard-error-boundary'message to the parent. This causes each error to be reported twice.Remove these duplicate listeners since the early IIFE (lines 350-371) already covers this case and runs before any AI code.
Proposed fix
- // Forward uncaught runtime errors (async throws, unhandled rejections) that never - // reach the React boundary. React ErrorBoundary alone misses these, so without this - // the parent has no way to observe e.g. a fetch() that rejected inside useEffect. - window.addEventListener('error', (event) => { - const err = event?.error; - window.parent.postMessage({ - type: 'dashboard-error-boundary', - message: err?.message || event?.message || 'Unknown runtime error', - stack: err?.stack, - }, '*'); - }); - window.addEventListener('unhandledrejection', (event) => { - const reason = event?.reason; - window.parent.postMessage({ - type: 'dashboard-error-boundary', - message: (reason && (reason.message || String(reason))) || 'Unhandled promise rejection', - stack: reason?.stack, - }, '*'); - });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx` around lines 486 - 501, Remove the duplicate global error handlers that post 'dashboard-error-boundary' to the parent: delete the second pair of window.addEventListener calls for 'error' and 'unhandledrejection' in dashboard-sandbox-host.tsx (the handlers that extract event?.error / event?.reason and call window.parent.postMessage with type 'dashboard-error-boundary'); rely on the existing IIFE-installed listeners (the earlier IIFE block that already registers 'error' and 'unhandledrejection') so each runtime error or promise rejection is reported only once.
🧹 Nitpick comments (1)
apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx (1)
566-570: 💤 Low valueAdd defensive check for missing source element.
If
ai-dashboard-sourceelement is somehow missing,aiSourcebecomes an empty string, which would then fail during execution with a confusing "Dashboard component not found" error rather than a clear message about the missing source.Proposed improvement
const aiSourceEl = document.getElementById('ai-dashboard-source'); - const aiSource = aiSourceEl ? aiSourceEl.textContent : ''; + if (!aiSourceEl) { + throw new Error('AI dashboard source element not found'); + } + const aiSource = aiSourceEl.textContent || '';🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx` around lines 566 - 570, The code assumes document.getElementById('ai-dashboard-source') exists; add a defensive check after retrieving aiSourceEl (and before calling window.Babel.transform) to handle a missing element or empty source: if aiSourceEl is null or aiSource is empty, throw or log a clear error like "Missing ai-dashboard-source element or empty dashboard source" and bail early (so compiledSource isn't attempted); update the block that references aiSourceEl, aiSource and compiledSource and ensure any downstream logic that expects compiledSource handles this early-exit path.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In
`@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx`:
- Around line 486-501: Remove the duplicate global error handlers that post
'dashboard-error-boundary' to the parent: delete the second pair of
window.addEventListener calls for 'error' and 'unhandledrejection' in
dashboard-sandbox-host.tsx (the handlers that extract event?.error /
event?.reason and call window.parent.postMessage with type
'dashboard-error-boundary'); rely on the existing IIFE-installed listeners (the
earlier IIFE block that already registers 'error' and 'unhandledrejection') so
each runtime error or promise rejection is reported only once.
---
Nitpick comments:
In
`@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx`:
- Around line 566-570: The code assumes
document.getElementById('ai-dashboard-source') exists; add a defensive check
after retrieving aiSourceEl (and before calling window.Babel.transform) to
handle a missing element or empty source: if aiSourceEl is null or aiSource is
empty, throw or log a clear error like "Missing ai-dashboard-source element or
empty dashboard source" and bail early (so compiledSource isn't attempted);
update the block that references aiSourceEl, aiSource and compiledSource and
ensure any downstream logic that expects compiledSource handles this early-exit
path.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: a00205d3-1555-41e9-8755-7a696aa186dc
📒 Files selected for processing (2)
apps/backend/src/lib/ai/models.tsapps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx
Forward Babel/JSX parse failures from the AI dashboard iframe to the parent composer instead of showing a blank preview, and use x-ai/grok-build-0.1 for authenticated smart-tier requests.
f2d62da to
8685ca0
Compare
Updated the dashboard sandbox to replace script closing tags in the source code to prevent parsing issues. Removed redundant global error listeners, as uncaught runtime errors and unhandled rejections are now handled by an early listener installed before Babel loads.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx (1)
486-501:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDuplicate error listeners cause double error reporting.
These
errorandunhandledrejectionlisteners duplicate the ones installed earlier (lines 362-369). Both fire for the same event, soonRuntimeErroris invoked twice per error. Remove this block since the early listener already covers runtime errors.Proposed fix: remove duplicate listeners
- // Forward uncaught runtime errors (async throws, unhandled rejections) that never - // reach the React boundary. React ErrorBoundary alone misses these, so without this - // the parent has no way to observe e.g. a fetch() that rejected inside useEffect. - window.addEventListener('error', (event) => { - const err = event?.error; - window.parent.postMessage({ - type: 'dashboard-error-boundary', - message: err?.message || event?.message || 'Unknown runtime error', - stack: err?.stack, - }, '*'); - }); - window.addEventListener('unhandledrejection', (event) => { - const reason = event?.reason; - window.parent.postMessage({ - type: 'dashboard-error-boundary', - message: (reason && (reason.message || String(reason))) || 'Unhandled promise rejection', - stack: reason?.stack, - }, '*'); - });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx` around lines 486 - 501, Remove the duplicate runtime error handlers: delete the window.addEventListener('error', ...) and window.addEventListener('unhandledrejection', ...) blocks that post messages with type 'dashboard-error-boundary' (the block that constructs message/stack and posts to window.parent). Those listeners duplicate the earlier installed handlers (which call onRuntimeError), so removing this block will stop double-reporting; ensure no other code depends on these specific registrations.
🧹 Nitpick comments (1)
apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx (1)
566-570: ⚡ Quick winAdd defensive check for
Babel.transformresult.
window.Babel.transform(...)returns an object with acodeproperty, but if Babel fails to load or the transform returns unexpectedly, accessing.codecould throw. A defensive check aligns with the coding guidelines.Proposed fix
let compiledSource; try { - compiledSource = window.Babel.transform(aiSource, { presets: ['react'] }).code; + const transformResult = window.Babel.transform(aiSource, { presets: ['react'] }); + if (!transformResult || typeof transformResult.code !== 'string') { + throw new Error('Babel transform returned invalid result'); + } + compiledSource = transformResult.code; } catch (err) {Based on coding guidelines: "Use defensive coding with
?? throwErr(...)over non-null assertions and fallback values".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx` around lines 566 - 570, The code directly accesses window.Babel.transform(...).code which can throw if Babel is missing or transform returns unexpectedly; change the block to first capture the transform result (e.g., const transformResult = window.Babel.transform(aiSource, { presets: ['react'] })) and then set compiledSource = transformResult.code ?? throwErr('Babel transform returned no code') (or throw a descriptive error) so you defensively handle a missing transform result; update references to compiledSource and the window.Babel.transform call in dashboard-sandbox-host.tsx accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In
`@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx`:
- Around line 486-501: Remove the duplicate runtime error handlers: delete the
window.addEventListener('error', ...) and
window.addEventListener('unhandledrejection', ...) blocks that post messages
with type 'dashboard-error-boundary' (the block that constructs message/stack
and posts to window.parent). Those listeners duplicate the earlier installed
handlers (which call onRuntimeError), so removing this block will stop
double-reporting; ensure no other code depends on these specific registrations.
---
Nitpick comments:
In
`@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx`:
- Around line 566-570: The code directly accesses
window.Babel.transform(...).code which can throw if Babel is missing or
transform returns unexpectedly; change the block to first capture the transform
result (e.g., const transformResult = window.Babel.transform(aiSource, {
presets: ['react'] })) and then set compiledSource = transformResult.code ??
throwErr('Babel transform returned no code') (or throw a descriptive error) so
you defensively handle a missing transform result; update references to
compiledSource and the window.Babel.transform call in dashboard-sandbox-host.tsx
accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 75da2d4b-f29a-40b2-abfc-9567320469ad
📒 Files selected for processing (2)
apps/backend/src/lib/ai/models.tsapps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx
✅ Files skipped from review due to trivial changes (1)
- apps/backend/src/lib/ai/models.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx`:
- Around line 541-546: The current JSON.parse swallow hides parse errors for
aiSource causing misleading downstream failures; update the parsing around
aiSource/aiSourceEl so that instead of setting aiSource = '' on parse failure
you throw a descriptive error (or rethrow the original) that includes the
invalid aiSourceEl.textContent and the parse exception; locate the block that
declares aiSource and uses JSON.parse and replace the silent catch with code
that constructs and throws a new Error (or rethrows) containing both context
("Failed to parse aiSource from aiSourceEl") and the original exception/message
so callers fail fast with a clear diagnostic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 512b93af-2c05-448c-b146-f7e3d1e5261b
📒 Files selected for processing (1)
apps/dashboard/src/components/commands/create-dashboard/dashboard-sandbox-host.tsx
…xtraction and improving JSON parsing feedback.
There was a problem hiding this comment.
1 issue found across 4 files
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
…nce by conditionally retrieving user data based on the source of truth configuration.
Summary
postMessage, so users see actionable errors instead of a blank previewBabel.transform+ try/catch (stored intext/plainto avoid Babel's auto-handler swallowing parse errors) and addcrossorigin="anonymous"on the Babel script for readable cross-origin error messagesmoonshotai/kimi-k2.6:nitrotox-ai/grok-build-0.1Test plan
x-ai/grok-build-0.1Made with Cursor
Summary by CodeRabbit
Bug Fixes
Updates