/** * Static-source regression guards for live-browser.js. * * `skill/scripts/live-browser.js` is a self-contained * IIFE served directly to user pages by live-server.mjs (no bundle step, * no module exports). That makes its internal helpers untestable via * normal import — but a few behaviors have failed in real-world live * sessions in ways that are easy to express as "this exact code shape * MUST NOT come back." This file pins those down. * * Add a guard whenever a bug we fix has a one-line "anti-pattern" cause * that's easy to reintroduce on an unrelated edit. */ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const LIVE_BROWSER = path.resolve( __dirname, '..', 'skill/scripts/live-browser.js', ); const SOURCE = fs.readFileSync(LIVE_BROWSER, 'utf-8'); describe('live-browser.js regression guards', () => { it('resolveCanvasBackground does not fall back to `getComputedStyle(...).backgroundColor || ...`', () => { // The browser returns the literal string `"rgba(0, 0, 0, 0)"` for an // unset body/html background. That string is non-empty and truthy, so a // `||` chain short-circuits to transparent-black, which modern-screenshot // hands to its WebGL shader as the canvas color and the screenshot // overlay flashes solid black during loading on any page that doesn't // explicitly set its own background. Forbid the pattern outright; the // correct fallback is a literal `'#ffffff'` (the browser's default // canvas color). const buggy = /getComputedStyle\(document\.(?:body|documentElement)\)\.backgroundColor\s*\|\|/; assert.ok( !buggy.test(SOURCE), 'live-browser.js must not chain `getComputedStyle(...).backgroundColor || ...` — that returns transparent-black for default-bg pages and renders the screenshot overlay as solid black during loading. Use a literal fallback (`#ffffff`) instead.', ); }); it('detectPageTheme honors alpha when reading body / html backgroundColor', () => { // Equivalent trap: `rgba(0, 0, 0, 0)` parsed naively as `(0,0,0)` makes // a perfectly white default page register as "dark," which flips the // chrome to the wrong palette. The fix introduced an alpha guard // (function readOpaque) — keep that signature in source. assert.match( SOURCE, /function detectPageTheme\b[\s\S]{0,1500}?function readOpaque\b/, 'detectPageTheme must keep its readOpaque helper that filters out fully-transparent backgrounds before computing luminance', ); }); it('shader bitmap decode failure keeps a visible fallback overlay', () => { assert.match( SOURCE, /function showShaderBitmapFallback\(canvas, blob\)[\s\S]{0,900}?fallback\.style\.backgroundImage = 'url\("' \+ objectUrl \+ '"\)';[\s\S]{0,300}?shaderState = \{ canvas: fallback,[\s\S]{0,180}?objectUrl \};/, 'shader fallback should render the captured bitmap via a background-image div and keep its object URL revocable', ); assert.match( SOURCE, /catch \(err\) \{[\s\S]{0,220}?shader bitmap decode failed[\s\S]{0,220}?showShaderBitmapFallback\(canvas, blob\);[\s\S]{0,80}?return;/, 'createImageBitmap failures should fall back to a visible captured-bitmap overlay', ); assert.doesNotMatch( SOURCE, /new Image\(/, 'shader fallback should not use an image element fallback', ); }); it('uses a framework-component-gated painted-ancestor crop proxy for shader capture', () => { assert.match( SOURCE, /function findShaderProxyCaptureRoot\(el\) \{[\s\S]{0,500}?let node = el\.parentElement;[\s\S]{0,700}?containsElement && paintsShaderProxySurface\(node\)[\s\S]{0,120}?return null;/, 'shader proxy should choose the nearest painted ancestor, not the document root', ); assert.match( SOURCE, /async function captureElementFromRenderedAncestor\(ms, el, opts\) \{[\s\S]{0,360}?const captureRoot = findShaderProxyCaptureRoot\(el\);[\s\S]{0,220}?ms\.domToCanvas\(captureRoot, opts\)[\s\S]{0,900}?cctx\.drawImage\(rootCanvas, sx, sy, sw, sh, 0, 0, crop\.width, crop\.height\);/, 'shader capture should render the minimal painted ancestor and crop the selected element rect', ); assert.match( SOURCE, /function shouldUseAncestorCropShaderProxy\(el\) \{[\s\S]{0,260}?window\.__IMPECCABLE_LIVE_ADAPTER__[\s\S]{0,280}?isFrameworkComponentPreviewMode\(currentPreviewMode\) \|\| svelteComponentSession[\s\S]{0,260}?isFrameworkComponentPreviewMode\(wrapper\?\.dataset\?\.impeccablePreview\);/, 'ancestor crop proxy must be gated to Svelte/Vue component previews', ); assert.match( SOURCE, /if \(shouldUseAncestorCropShaderProxy\(el\)\) \{[\s\S]{0,240}?return await hideCaptureChromeForShaderProxy\(\(\) => captureElementFromRenderedAncestor\(ms, el, opts\)\);[\s\S]{0,280}?Svelte ancestor crop capture failed, falling back to element capture/, 'Svelte ancestor crop must run before the legacy capture path and hide live chrome while doing so', ); assert.match( SOURCE, /const paper = dominantRgb01\(cctx, crop\.width, crop\.height\) \|\| averageRgb01\(cctx, crop\.width, crop\.height\);/, 'shader paper should come from the cropped pixels so framework/backdrop composition is preserved', ); assert.match( SOURCE, /const radius = getComputedStyle\(el\)\.borderRadius;[\s\S]{0,420}?borderRadius: radius,[\s\S]{0,80}?overflow: 'hidden'/, 'the shader canvas should clip to the selected element radius when using a rectangular ancestor crop', ); assert.doesNotMatch( SOURCE, /isSemiTransparentOwnBackground|findCompositedBackdropAncestor|compositeRgbOver|cssColorToRgba01/, 'the shader fix should not depend on semi-transparent CSS special cases', ); }); it('locks every global bar mode toggle while manual Apply is in flight', () => { assert.match( SOURCE, /const controlsLocked = pendingApplyInFlight === true;[\s\S]{0,120}?\[pickToggle, insertToggle, detectToggle, designToggle\]\.forEach/, 'pending manual Apply must visually disable Pick, Insert, Detect, and Design together', ); assert.match( SOURCE, /function toggleInsert\(\) \{[\s\S]{0,120}?if \(pendingApplyInFlight\) \{ showManualApplyBusyToast\(\); return; \}/, 'Insert must have the same in-flight Apply guard as the other mode toggles', ); }); it('exits inline editing directly on outside click', () => { assert.match( SOURCE, /function cancelEditingToPicking\(\) \{[\s\S]{0,600}?setLiveState\('PICKING'\);/, 'outside-click editing cancel should avoid rebuilding configure UI before hiding it', ); assert.match( SOURCE, /state === 'EDITING'[\s\S]{0,180}?cancelEditingToPicking\(\);[\s\S]{0,40}?return;/, 'outside-click handler should leave EDITING directly', ); }); it('restores unsaved inline edit drafts before hideBar tears editing down', () => { assert.match( SOURCE, /function hideBar\(\) \{[\s\S]{0,620}?if \(state === 'EDITING'\) restoreInlineEditDrafts\(\);[\s\S]{0,80}?disableInlineEdit\(\);/, 'hideBar should not leave unsaved contenteditable drafts in the DOM when an external event hides the bar', ); }); it('does not autofocus the steering chat while inline editing', () => { assert.match( SOURCE, /function shouldFocusSteerChat\(\) \{\s*return state !== 'CONFIGURING'\s*&& state !== 'EDITING'\s*&& !steerLocked;\s*\}/, 'edit-mode contenteditable focus must not be stolen by the global steering chat focus recovery', ); }); it('keeps the Steer pill from clipping its label or the global bar exit control', () => { assert.match( SOURCE, /const PAGE_CHAT_COLLAPSED_W = '104px';/, 'collapsed Steer pill should reserve enough room for icon, "Steer", and voice button', ); assert.match( SOURCE, /function pageChatExpandedWidth\(\)[\s\S]{0,520}?window\.innerWidth - 16 - nonChatWidth[\s\S]{0,220}?Math\.max\(pageChatCollapsedWidthPx\(\), Math\.min\(PAGE_CHAT_EXPANDED_MAX_W, available\)\)/, 'expanded Steer width should reserve viewport room for the rest of the global bar', ); assert.match( SOURCE, /syncGlobalBarExpandedLabels\(false\);[\s\S]{0,80}?pageChatEl\.style\.width = pageChatExpandedWidth\(\);/, 'opening Steer should collapse inactive mode labels before measuring input width', ); assert.match( SOURCE, /maxWidth: 'calc\(100vw - 16px\)'[\s\S]{0,80}?boxSizing: 'border-box'/, 'global bar should be constrained to the viewport instead of clipping the exit control offscreen', ); assert.match( SOURCE, /globalBarEl = el\('div', \{[\s\S]{0,360}?width: 'max-content'/, 'fixed-position global bar must use max-content sizing before maxWidth clamps it, or narrow panes clip the exit button', ); assert.match( SOURCE, /const inner = el\('div', \{[\s\S]{0,220}?flex: '0 0 auto'/, 'global bar inner controls must not flex-shrink and crop hover labels', ); assert.match( SOURCE, /function makeIconBtn[\s\S]{0,360}?flex: '0 0 auto'[\s\S]{0,80}?minWidth: '30px'/, 'global bar icon buttons must keep stable hitboxes when Steer expands', ); assert.match( SOURCE, /applyGlobalBarLabelState\(expandInactive, pageChatExpanded\)/, 'expanded Steer should force labels closed without shrinking the icons', ); }); it('does not autofocus the steering chat while a page editable is focused', () => { assert.match( SOURCE, /function isPageEditableElement\(el\) \{[\s\S]{0,160}?own\(el\)[\s\S]{0,160}?\^\(INPUT\|TEXTAREA\|SELECT\)\$[\s\S]{0,80}?el\.isContentEditable/, 'page-owned inputs, textareas, selects, and contenteditables must be recognized before steer focus recovery runs', ); assert.match( SOURCE, /function isPageEditableActive\(\) \{[\s\S]{0,120}?activeElementDeep\(\)[\s\S]{0,120}?isPageEditableElement\(active\) && !isInlineEditActive\(active\)/, 'auto-focus recovery must check the deep active element instead of only host text selection', ); assert.match( SOURCE, /function shouldSteerAutoFocus\(\) \{[\s\S]{0,160}?&& !isPageEditableActive\(\)/, 'steer chat auto-focus must back off while the page owns an editable caret', ); }); it('pins edit badge button metrics instead of inheriting host button chrome', () => { const start = SOURCE.indexOf('const calloutStyle = (color, borderColor) => ({'); const end = SOURCE.indexOf(' });', start); const calloutStyle = SOURCE.slice(start, end); assert.match( calloutStyle, /fontSize: '10px'/, 'edit badge controls should not scale from host rem settings', ); assert.match( calloutStyle, /lineHeight: '16px'/, 'edit badge controls need the same 22px button height on pages with or without button resets', ); assert.match( calloutStyle, /boxSizing: 'border-box'/, 'edit badge controls should include padding and border in their rendered dimensions', ); assert.doesNotMatch( calloutStyle, /fontSize: '0\.625rem'/, 'edit badge controls should not depend on the host root font-size', ); }); it('does not shadow the global live state when storing Apply state', () => { assert.doesNotMatch( SOURCE, /function readStoredManualApplyState\(\)[\s\S]{0,240}?const state = JSON\.parse\(raw\);/, 'stored manual Apply JSON should not shadow the outer UI state variable', ); assert.doesNotMatch( SOURCE, /function writeManualApplyState\(state\)/, 'stored manual Apply object should not shadow the outer UI state variable', ); }); it('handleServerLost preserves the current recoverable phase', () => { assert.doesNotMatch( SOURCE, /state\s*=\s*currentSessionId\s*\?\s*['"]GENERATING['"]\s*:\s*['"]IDLE['"]/, 'event=live_browser.server_lost_phase actor=browser operation=sse_disconnect risk=cycling_or_saving_session_saved_as_generating expected=preserve current phase actual=forced generating', ); assert.match( SOURCE, /function handleServerLost\(\)[\s\S]{0,300}?const recoveryState = currentSessionId \? state : 'IDLE';[\s\S]{0,1200}?setLiveState\(recoveryState\);[\s\S]{0,120}?if \(currentSessionId\) saveSession\(\);/, 'server-lost cleanup should keep the current session phase in local recovery state instead of rewriting it to GENERATING', ); }); it('source reinjection preserves the visible variant after cycling', () => { assert.doesNotMatch( SOURCE, /Replace the live element[\s\S]{0,900}?visibleVariant\s*=\s*1;\s*showVariantInDOM\(sessionId,\s*1\);/, 'event=live_browser.visible_variant_reset actor=browser operation=hmr_source_reinject risk=late_hmr_accepts_variant_1_after_user_cycles expected=preserve visible variant actual=reset_to_first', ); assert.match( SOURCE, /previousVisibleVariant[\s\S]{0,900}?savedVisibleVariant[\s\S]{0,500}?showVariantInDOM\(sessionId, visibleVariant\);/, 'source reinjection should preserve the in-memory or saved visible variant instead of always showing variant 1', ); }); it('suppresses scroll anchoring via a stylesheet rule, not inline html/body style', () => { // The scroll lock disables the browser's scroll-anchoring on the scroll // root so it can't fight our manual scroll correction. Doing that by // mutating `document.documentElement.style` / `document.body.style` // inline makes React 19 report a hydration mismatch on the next // Fast-Refresh re-render: / are server-rendered by frameworks // like Next.js App Router, so a client-only inline `style` the server HTML // never emitted trips "a tree hydrated but some attributes ... didn't // match." That surfaced as a console.error and failed the // nextjs-app-router live-e2e fixture's expectConsoleClean probe. The fix // injects a