An open source design system that's fully customizable and agent ready
TypeScript
fix(docsite): surface preview startup failures (#6634)
Cindy Zhang82fb22c3c14b
diff --git a/apps/docsite/e2e/playground-preview-isolation.spec.ts b/apps/docsite/e2e/playground-preview-isolation.spec.tsindex 2c0891b5b5..1c589c457c 100644--- a/apps/docsite/e2e/playground-preview-isolation.spec.ts+++ b/apps/docsite/e2e/playground-preview-isolation.spec.ts@@ -153,6 +153,66 @@ function exampleRendering(text: string) {}test.describe('playground preview isolation', () => {+ test('reports a compiler bootstrap failure instead of building forever', async ({+ page,+ }) => {+ await page.route('**/vendor/typescript.js', route => route.abort());++ await page.goto('/playground');++ await expect(page.getByText('Build error', {exact: true})).toBeVisible();+ await expect(page.getByText('Building…', {exact: true})).not.toBeVisible();++ // An edit updates the pending code but preserves the actionable error. It+ // must not re-enter Building without restarting the failed document.+ await setEditorCode(page, exampleRendering('Pending retry'));+ await page.waitForTimeout(600);+ await expect(page.getByText('Build error', {exact: true})).toBeVisible();+ await expect(page.getByText('Building…', {exact: true})).not.toBeVisible();+ });++ test('allows an attested preview time to load its compiler', async ({+ page,+ }) => {+ let releaseCompiler!: () => void;+ let markCompilerRequested!: () => void;+ const compilerRequested = new Promise<void>(resolve => {+ markCompilerRequested = resolve;+ });+ const compilerGate = new Promise<void>(resolve => {+ releaseCompiler = resolve;+ });+ await page.route('**/vendor/typescript.js', async route => {+ markCompilerRequested();+ await compilerGate;+ await route.continue();+ });++ await page.goto('/playground', {waitUntil: 'domcontentloaded'});+ await compilerRequested;+ await page.waitForTimeout(12_000);+ await expect(+ page.getByText('Build error', {exact: true}),+ ).not.toBeVisible();++ releaseCompiler();+ await expectPreviewToRender(page, 'Welcome');+ });++ test('times out a preview document that never starts', async ({page}) => {+ await page.route(+ /\/_next\/static\/chunks\/app\/playground\/preview\/page-[^/]+\.js/,+ route => route.abort(),+ );++ await page.goto('/playground');++ await expect(page.getByText('Build error', {exact: true})).toBeVisible({+ timeout: 40_000,+ });+ await expect(page.getByText('Building…', {exact: true})).not.toBeVisible();+ });+test('recovers from a reloaded preview document with the current code, theme and mode', async ({page,}) => {diff --git a/apps/docsite/src/__tests__/playground-preview-channel.test.ts b/apps/docsite/src/__tests__/playground-preview-channel.test.tsindex bdd94674e5..5417c86809 100644--- a/apps/docsite/src/__tests__/playground-preview-channel.test.ts+++ b/apps/docsite/src/__tests__/playground-preview-channel.test.ts@@ -187,9 +187,11 @@ function connectorHarness() {const nonces: string[] = [];let counter = 0;const received: Array<{type?: string}> = [];+ const onAttested = vi.fn();const onReplaced = vi.fn();const connector = createPreviewConnector({onMessage: event => received.push(event.data as {type?: string}),+ onAttested,onReplaced,nonce: () => {const next = `nonce-${(counter += 1)}`;@@ -201,6 +203,7 @@ function connectorHarness() {connector,nonces,received,+ onAttested,onReplaced,get doc() {return current;@@ -244,14 +247,17 @@ describe('createPreviewConnector', () => {expect(doc.port).toBe(null);expect(stranger.port).toBe(null);expect(h.connector.isAttested()).toBe(false);+ expect(h.onAttested).not.toHaveBeenCalled();// The right hello from the right window earns exactly one port.h.connector.handleWindowMessage(doc.hello(nonce));expect(doc.port).toBeInstanceOf(MessagePort);expect(h.connector.isAttested()).toBe(true);+ expect(h.onAttested).toHaveBeenCalledTimes(1);const firstPort = doc.port;h.connector.handleWindowMessage(doc.hello(nonce));expect(doc.port).toBe(firstPort);+ expect(h.onAttested).toHaveBeenCalledTimes(1);});it('flows traffic over the adopted pair in both directions', async () => {diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsxindex 5f474c3173..bec49a1118 100644--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx@@ -4,7 +4,8 @@* @file PlaygroundClient.tsx* @input URL hash or template query, user edits, and knob edits* @output Full-page two-panel playground (editor + live preview), with a- * production-only notice explaining the ephemeral preview's restrictions+ * production-only notice explaining the ephemeral preview's restrictions and+ * a retryable terminal error when the isolated preview cannot start* @position app/playground — the interactive Astryx code playground.** AppShell: side-nav-only shell; desktop nav is controlled collapsed to@@ -168,6 +169,12 @@ type LeftView = 'code' | 'theme';type MobileTopTab = 'preview' | 'code' | 'theme';type BuildStatus = 'idle' | 'building' | 'finished' | 'error';const MOBILE_BREAKPOINT_QUERY = '(max-width: 768px)';+// A preview that never boots cannot report its own failure. End the indefinite+// "Building…" state and let Rebuild mount a fresh isolated document. Once the+// document attests, restart the deadline for the self-hosted compiler's 9 MB+// download.+const PREVIEW_DOCUMENT_STARTUP_TIMEOUT_MS = 30_000;+const PREVIEW_COMPILER_STARTUP_TIMEOUT_MS = 30_000;const BUILD_STATUS_META: Record<Exclude<BuildStatus, 'idle'>,@@ -321,6 +328,10 @@ export function PlaygroundClient() {const readyRef = useRef(false);const pendingRef = useRef<string | null>(null);+ const previewStartupTimerRef = useRef<ReturnType<typeof setTimeout> | null>(+ null,+ );+ const restartPreviewRef = useRef<() => void>(() => {});// The preview frame generation: a fresh iframe element (key) navigated to// the preview URL with a fresh nonce (src). Issued on the client only, and// re-issued whenever the attested preview document is replaced — see@@ -449,6 +460,10 @@ export function PlaygroundClient() {const handler = (e: MessageEvent) => {if (e.data?.type === 'preview-ready') {readyRef.current = true;+ if (previewStartupTimerRef.current != null) {+ clearTimeout(previewStartupTimerRef.current);+ previewStartupTimerRef.current = null;+ }setPreviewReady(true);if (pendingRef.current != null) {postCode(pendingRef.current);@@ -490,33 +505,52 @@ export function PlaygroundClient() {// The window listener goes up BEFORE the frame is issued so the hello cannot// arrive unheard.useEffect(() => {+ const clearStartupTimer = () => {+ if (previewStartupTimerRef.current != null) {+ clearTimeout(previewStartupTimerRef.current);+ previewStartupTimerRef.current = null;+ }+ };+ const armStartupTimer = (timeout: number) => {+ clearStartupTimer();+ previewStartupTimerRef.current = setTimeout(() => {+ if (!readyRef.current) {+ setBuildStatus('error');+ }+ }, timeout);+ };const issueFrame = () => {frameGenerationRef.current += 1;setFrame({key: frameGenerationRef.current,src: previewSrc(connector.issue()),});+ armStartupTimer(PREVIEW_DOCUMENT_STARTUP_TIMEOUT_MS);};const connector = createPreviewConnector({onMessage: e => portHandlerRef.current?.(e),+ onAttested: () => armStartupTimer(PREVIEW_COMPILER_STARTUP_TIMEOUT_MS),// The attested preview document is gone (previewed code navigated or// reloaded its frame). Its port and nonce are already discarded; start// a new generation and queue the current code so the fresh document// picks up exactly where the old one was — the preview-ready handler// flushes it and the theme effect re-sends on the previewReady flip.- onReplaced: () => {- readyRef.current = false;- setPreviewReady(false);- pendingRef.current = codeRef.current;- issueFrame();- },+ onReplaced: () => restartPreviewRef.current(),});+ restartPreviewRef.current = () => {+ readyRef.current = false;+ setPreviewReady(false);+ pendingRef.current = codeRef.current;+ issueFrame();+ };connectorRef.current = connector;const onWindowMessage = (e: MessageEvent) =>connector.handleWindowMessage(e);window.addEventListener('message', onWindowMessage);issueFrame();return () => {+ clearStartupTimer();+ restartPreviewRef.current = () => {};window.removeEventListener('message', onWindowMessage);connector.stop();connectorRef.current = null;@@ -546,7 +580,9 @@ export function PlaygroundClient() {}debounceRef.current = setTimeout(() => {if (code) {- setBuildStatus('building');+ setBuildStatus(status =>+ status === 'error' && !readyRef.current ? status : 'building',+ );}if (!readyRef.current) {pendingRef.current = code;@@ -622,6 +658,7 @@ export function PlaygroundClient() {postCode(code);} else {pendingRef.current = code;+ restartPreviewRef.current();}}, [postCode, code]);diff --git a/apps/docsite/src/app/playground/preview/page.tsx b/apps/docsite/src/app/playground/preview/page.tsxindex a79c89b340..c5346938dd 100644--- a/apps/docsite/src/app/playground/preview/page.tsx+++ b/apps/docsite/src/app/playground/preview/page.tsx@@ -3,7 +3,8 @@/*** @file page.tsx* @input Attested preview channel, editor code, and active theme- * @output Isolated live preview with native navigation in production+ * @output Isolated live preview with native navigation in production, or a+ * compile error sent to the playground when the compiler bootstrap fails* @position Playground runner; platform restrictions never grant parent privileges.*/@@ -117,6 +118,7 @@ export default function PreviewPage() {const [customTheme, setCustomTheme] = useState<DefinedTheme | null>(null);const [resetKey, setResetKey] = useState(0);const [tsReady, setTsReady] = useState(false);+ const [compilerError, setCompilerError] = useState<string | null>(null);// Whether this document's own `load` event has fired (or the wait for it// ran out); readiness is announced only after it.const [documentLoaded, setDocumentLoaded] = useState(false);@@ -137,14 +139,19 @@ export default function PreviewPage() {useEffect(() => {const script = document.createElement('script');script.src = '/vendor/typescript.js';+ const fail = () => setCompilerError('TypeScript compiler failed to load');script.onload = () => {const w = window as unknown as {ts?: typeof TS};if (w.ts) {setTypeScript(w.ts);setTsReady(true);+ } else {+ fail();}};+ script.onerror = fail;document.head.appendChild(script);+ return () => script.remove();}, []);const theme = customTheme ?? themeByValue[themeName] ?? FALLBACK_THEME;@@ -278,7 +285,20 @@ export default function PreviewPage() {}, [tsReady, documentLoaded]);useEffect(() => {- if (!tsReady || !documentLoaded || port == null) {+ if (+ !documentLoaded ||+ port == null ||+ (!tsReady && compilerError == null)+ ) {+ return;+ }++ if (compilerError != null) {+ postToParent({+ type: 'preview-error',+ error: compilerError,+ phase: 'compile',+ });return;}@@ -327,6 +347,7 @@ export default function PreviewPage() {};}, [tsReady,+ compilerError,documentLoaded,port,postToParent,diff --git a/apps/docsite/src/app/playground/previewChannel.ts b/apps/docsite/src/app/playground/previewChannel.tsindex 63945c1d29..94cbf4282c 100644--- a/apps/docsite/src/app/playground/previewChannel.ts+++ b/apps/docsite/src/app/playground/previewChannel.ts@@ -6,7 +6,8 @@* page's `message` events. Preview side: the document's own URL and the* incoming `message` events.* @output A dedicated MessagePort pair that only the playground and a preview- * document the playground itself navigated to can hold.+ * document the playground itself navigated to can hold, plus lifecycle+ * callbacks for attestation and replacement.* @position Playground <-> preview iframe — the postMessage trust boundary.** ## Why there is a boundary at all@@ -187,11 +188,14 @@ export interface PreviewConnector {*/export function createPreviewConnector({onMessage,+ onAttested,onReplaced,nonce = createPreviewNonce,}: {/** Receives every message that arrives on the adopted port. */onMessage: (event: MessageEvent) => void;+ /** The current frame proved it loaded the issued preview URL. */+ onAttested?: () => void;/*** The attested document is gone. The caller must `issue()` a new* generation and mount a fresh iframe for it.@@ -245,6 +249,7 @@ export function createPreviewConnector({attested = true;port = connectToPreview(frame as Pick<Window, 'postMessage'>);port.onmessage = onMessage;+ onAttested?.();},handleFrameLoad() {