A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Fix mobile plan phone preview rendering (#725)
Priyanshu Agrawal83e2c4463762
diff --git a/plugins/mobile-apps/assets/run-plan.html b/plugins/mobile-apps/assets/run-plan.htmlindex 9313c295c..0e1b1aa70 100644--- a/plugins/mobile-apps/assets/run-plan.html+++ b/plugins/mobile-apps/assets/run-plan.html@@ -19,6 +19,7 @@- `img-src data:` only - the brand mark and the QR are both inlined, so no image is everfetched, and an injected `<img src=...>` cannot call out.- No `connect-src`, `frame-src` or `object-src`: the plan never talks to the network.+ The phone uses an inline `srcdoc` document, not a fetched frame.--><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-__ATTR_CSP_NONCE__'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'"/><title>__PLAN_TITLE__ - __APP_NAME__</title>@@ -76,7 +77,7 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14.device{width:300px;height:620px;border-radius:40px;background:#1f1f1f;border:9px solid #2e2e2e;box-shadow:var(--shadow-4),0 18px 46px rgba(0,0,0,0.22);position:relative;overflow:hidden;flex-shrink:0;}.device-notch{position:absolute;top:0;left:50%;transform:translateX(-50%);width:118px;height:22px;background:#2e2e2e;border-radius:0 0 14px 14px;z-index:5;}.device-screen{position:absolute;inset:0;background:#faf9f8;overflow:hidden;}-.device-screen iframe{width:100%;height:100%;border:0;}+.device-screen iframe{border:0;}/* Stage 1 - building */.bld{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:22px;background:#faf9f8;padding:0 28px;text-align:center;}.bld-orbit{position:relative;width:132px;height:132px;display:grid;place-items:center;}@@ -96,18 +97,17 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14@keyframes railFade{to{opacity:1;}}/* Stage 2 - carousel */.car{position:absolute;inset:0;background:#fff;}-.car-frame{position:absolute;inset:0;overflow:auto;contain:layout paint;}-/* `contain: paint` makes this a containing block for absolutely AND fixed positioned- descendants, so an injected `style="position:fixed;inset:0"` in a mockup is trapped in the- phone frame instead of covering the plan. Attribute styles survive sanitizing because they- are what makes a mockup look like the screen; this is what keeps them local.- https://developer.mozilla.org/en-US/docs/Web/CSS/contain */-.car-nav{position:absolute;bottom:0;left:0;right:0;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 12px;background:linear-gradient(to top,rgba(0,0,0,.55),transparent);z-index:4;}-.car-btn{width:30px;height:30px;border-radius:50%;border:0;background:rgba(255,255,255,.92);color:#201f1e;font-size:15px;cursor:pointer;display:grid;place-items:center;box-shadow:var(--shadow-4);}+.car-frame{position:absolute;inset:0;overflow:hidden;contain:layout paint;}+/* A 375 x 812 viewport is scaled, not reflowed into the smaller rail. Its sandboxed document+ keeps mockup selectors, media queries, and fixed tab bars independent of the plan.+ https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox */+.car-frame iframe{position:absolute;width:375px;height:812px;transform-origin:top left;}+.car-nav{width:300px;display:flex;align-items:center;justify-content:space-between;gap:8px;}+.car-btn{width:30px;height:30px;border-radius:50%;border:1px solid var(--border);background:var(--surface);color:var(--text-bright);font-size:15px;cursor:pointer;display:grid;place-items:center;box-shadow:var(--shadow-4);}.car-btn:disabled{opacity:.35;cursor:default;}.car-dots{display:flex;gap:5px;}-.car-dot{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.45);}-.car-dot.on{background:#fff;}+.car-dot{width:6px;height:6px;border-radius:50%;background:var(--border-light);}+.car-dot.on{background:var(--accent);}.rail-caption{font-size:12px;color:var(--text-dim);text-align:center;min-height:32px;padding:0 10px;}/* Stage 3 - QR */.qr{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;background:#fff;padding:0 26px;text-align:center;}@@ -492,6 +492,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi<div class="device-notch"></div><div class="device-screen" id="deviceScreen"></div></div>+ <div id="railControls" hidden></div><div class="rail-caption" id="railCaption"></div><div class="rail-note" id="railNote" hidden></div><div id="railPreviewLink"></div>@@ -791,12 +792,8 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi// Elements that execute, navigate, or reach the network. `link`/`meta`/`base` are included// because a mockup is a fragment of a document and must not redefine this one's head.- // `STYLE` is here for a different reason from the rest. The others execute or navigate; a- // stylesheet cannot, but its selectors are global, so a mockup carrying one could restyle the- // approval banner or the trust report - hiding or spoofing the very UI a reviewer is reading.- // The CSP cannot refuse it: `style-src 'unsafe-inline'` is required for this page's own- // stylesheet and for Mermaid's. Mockups keep their `style=` attributes, which only ever affect- // the element carrying them; see `.car-frame` for how those are kept inside the phone.+ // Styles are permitted only in isolated screen documents and Mermaid's scoped SVG.+ // Inserting a mockup stylesheet into the plan itself would let its selectors hide approvals.// `ANIMATE` and `SET` are SVG animation elements, which can rewrite another element's `href`// after this pass has checked it.var MOCKUP_BANNED_TAGS = ['SCRIPT', 'IFRAME', 'OBJECT', 'EMBED', 'LINK', 'META', 'BASE', 'FORM', 'STYLE',@@ -813,14 +810,21 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi* page's CSP already refuses unnonced scripts and inline handlers; this is the second line, so* a policy that is ever loosened does not immediately become an execution path.*- * Parsed into a `<template>`, whose content is an inert fragment: nothing executes and no- * resource is fetched while it is being cleaned.+ * Fragments use an inert `<template>`; complete screen documents use a detached DOMParser+ * document so html/body attributes survive. Neither is inserted into the live plan.*/function sanitizeMockup(markup, options) {var keepStyle = !!(options && options.keepStyle);- var holder = document.createElement('template');- holder.innerHTML = String(markup == null ? '' : markup);- var nodes = holder.content.querySelectorAll('*');+ var source = String(markup == null ? '' : markup);+ var content;+ if (options && options.asDocument) {+ content = new DOMParser().parseFromString(source, 'text/html');+ } else {+ var holder = document.createElement('template');+ holder.innerHTML = source;+ content = holder.content;+ }+ var nodes = content.querySelectorAll('*');for (var i = 0; i < nodes.length; i++) {var node = nodes[i];// `tagName` is upper case only for HTML elements. Inside inline SVG an element keeps its@@ -839,21 +843,82 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margivar value = attrs[j].value.replace(/[\u0000-\u0020]/g, '');// Every event handler, however it is spelled.if (/^on/i.test(name)) { node.removeAttribute(name); continue; }+ // Screens are static: even a safe link must not navigate the sandbox to a remote page.+ // Local SVG references such as href="#check" remain available for icon rendering.+ if (options && options.asDocument && /^(href|xlink:href)$/i.test(name) && value.charAt(0) !== '#') {+ node.removeAttribute(name);+ continue;+ }if (/^(href|src|xlink:href|action|formaction)$/i.test(name) && MOCKUP_BANNED_URL.test(value)) {node.removeAttribute(name);}}}- return holder.content;+ return content;+ }++ function previewScreens(markup) {+ var source = sanitizeMockup(markup, { keepStyle: true, asDocument: true });+ var tabs = Array.from(source.querySelectorAll('[data-screen]'));+ return Array.from(source.querySelectorAll('.screen')).map(function (entry) {+ var root = source.documentElement.cloneNode(false);+ var head = document.createElement('head');+ source.querySelectorAll('style').forEach(function (style) { head.appendChild(style.cloneNode(true)); });+ var body = source.body.cloneNode(false);+ var selected = entry.cloneNode(true);+ selected.classList.add('active');+ selected.removeAttribute('hidden');+ selected.style.setProperty('display', 'flex', 'important');+ // Preserve ancestor classes and inline tokens, but leave out the gallery's tabs, labels,+ // notch and home indicator: the plan already supplies its own phone shell.+ for (var ancestor = entry.parentElement; ancestor && ancestor !== source.body; ancestor = ancestor.parentElement) {+ var wrapper = ancestor.cloneNode(false);+ wrapper.appendChild(selected);+ selected = wrapper;+ }+ body.appendChild(selected);+ root.appendChild(head);+ root.appendChild(body);+ var reset = document.createElement('style');+ reset.textContent = 'html,body{width:100%;height:100%;margin:0!important;padding:0!important;min-height:0!important;overflow:hidden;}'+ + '.phone{width:100%!important;height:100%!important;margin:0!important;padding:0!important;border:0!important;border-radius:0!important;box-shadow:none!important;}'+ + '.screen-wrap{border-radius:0!important;}';+ head.appendChild(reset);+ var tab = tabs.find(function (button) { return button.getAttribute('data-screen') === entry.id; });+ return {+ name: (tab && tab.textContent.trim()) || entry.getAttribute('data-name') || entry.getAttribute('aria-label') || entry.id,+ html: '<!DOCTYPE html>' + root.outerHTML,+ };+ });+ }++ function mockupDocument(markup) {+ var source = sanitizeMockup(markup, { keepStyle: true, asDocument: true });+ var policy = source.createElement('meta');+ policy.setAttribute('http-equiv', 'Content-Security-Policy');+ policy.setAttribute('content', "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none'");+ source.head.prepend(policy);+ return '<!DOCTYPE html>' + source.documentElement.outerHTML;}function renderPhone() {+ if (phone.stage === 'screens' && phone.previewHtml) phone.screens = previewScreens(phone.previewHtml);railPreviewLink();var screen = document.getElementById('deviceScreen');var title = document.getElementById('railTitle');var caption = document.getElementById('railCaption');+ var controls = document.getElementById('railControls');screen.textContent = '';caption.textContent = '';+ controls.textContent = '';+ controls.hidden = true;++ if (phone.stage === 'screens' && phone.previewHtml && !phone.screens.length) {+ title.textContent = 'Screen preview unavailable';+ caption.textContent = 'The preview contains no .screen blocks. Regenerate _plan_preview.html.';+ console.error(caption.textContent);+ return;+ }if (phone.stage === 'qr' && phone.qrImage) {title.textContent = 'Open it on your phone';@@ -875,6 +940,10 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margivar index = 0;var car = el('div', 'car');var frame = el('div', 'car-frame');+ var viewport = document.createElement('iframe');+ viewport.setAttribute('sandbox', '');+ viewport.setAttribute('referrerpolicy', 'no-referrer');+ frame.appendChild(viewport);var nav = el('div', 'car-nav');var prev = el('button', 'car-btn', '\u2039');prev.setAttribute('aria-label', 'Previous screen');@@ -882,16 +951,28 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;marginext.setAttribute('aria-label', 'Next screen');var dots = el('div', 'car-dots');nav.appendChild(prev); nav.appendChild(dots); nav.appendChild(next);- car.appendChild(frame); car.appendChild(nav);+ car.appendChild(frame);screen.appendChild(car);+ controls.appendChild(nav);+ controls.hidden = false;++ var fit = function () {+ var scale = Math.min(frame.clientWidth / 375, frame.clientHeight / 812);+ viewport.style.transform = 'scale(' + scale + ')';+ viewport.style.left = (frame.clientWidth - 375 * scale) / 2 + 'px';+ viewport.style.top = (frame.clientHeight - 812 * scale) / 2 + 'px';+ };+ fit();+ window.addEventListener('resize', fit);+ if (typeof ResizeObserver !== 'undefined') new ResizeObserver(fit).observe(frame);var show = function (i) {index = Math.max(0, Math.min(phone.screens.length - 1, i));var current = phone.screens[index] || {};- // Replaced wholesale each time, then refilled from the sanitized fragment. Assigning- // innerHTML directly would put unexamined markup into the document.- frame.textContent = '';- frame.appendChild(sanitizeMockup(current.html));+ // No allow-scripts or allow-same-origin: the retained stylesheet belongs only to this+ // frame. The child CSP also blocks fetches, including CSS imports and external images.+ viewport.setAttribute('title', current.name || 'Screen preview');+ viewport.srcdoc = mockupDocument(current.html);caption.textContent = (current.name ? current.name + ' \u00b7 ' : '')+ (index + 1) + ' of ' + phone.screens.length;prev.disabled = index === 0;diff --git a/plugins/mobile-apps/scripts/app-docs.js b/plugins/mobile-apps/scripts/app-docs.jsindex 1408bc676..6011a13ce 100644--- a/plugins/mobile-apps/scripts/app-docs.js+++ b/plugins/mobile-apps/scripts/app-docs.js@@ -21,7 +21,7 @@* init --working-dir <d> --app-name <n> [--data-platform dataverse|connector-only]* step --working-dir <d> --id <phase-id> --status <pending|active|done|skipped|failed> [--note <t>]* set --working-dir <d> --section <name> --json <obj> | --json-file <path> [--state proposed|approved]- * phone --working-dir <d> --stage building|screens|qr [--screens-file <path>] [--qr-image <png>] [--qr-url <url>]+ * phone --working-dir <d> --stage building|screens|qr [--preview-file <html> | --screens-file <json>] [--qr-image <png>] [--qr-url <url>]* show --working-dir <d>*/@@ -152,7 +152,14 @@ function setPhone(state, update) {}state.phone.stage = update.stage;}- if (update.screens !== undefined) state.phone.screens = update.screens;+ if (update.screens !== undefined) {+ state.phone.screens = update.screens;+ delete state.phone.previewHtml;+ }+ if (update.previewHtml !== undefined) {+ state.phone.previewHtml = update.previewHtml;+ state.phone.screens = [];+ }if (update.qrImage !== undefined) state.phone.qrImage = update.qrImage;if (update.qrHref !== undefined) state.phone.qrHref = update.qrHref;if (update.qrUrl !== undefined) state.phone.qrUrl = update.qrUrl;@@ -441,6 +448,12 @@ function parseArgs(argv) {else if (argument === '--state') options.state = argv[++index];else if (argument === '--stage') options.stage = argv[++index];else if (argument === '--screens-file') options.screensFile = argv[++index];+ else if (argument === '--preview-file') {+ options.previewFile = argv[++index];+ if (!options.previewFile || options.previewFile.startsWith('--')) {+ throw new Error('--preview-file requires an HTML file path.');+ }+ }else if (argument === '--qr-image') options.qrImage = argv[++index];else if (argument === '--qr-url') options.qrUrl = argv[++index];else if (!argument.startsWith('--') && !options.command) options.command = argument;@@ -476,7 +489,16 @@ if (require.main === module) {} else if (options.command === 'phone') {const state = loadState(root);if (!state) throw new Error('No run plan yet; run `init` first.');+ if (options.previewFile && options.screensFile) {+ throw new Error('Provide --preview-file or --screens-file, not both.');+ }const update = { stage: options.stage, qrUrl: options.qrUrl };+ if (options.previewFile) {+ // Retain the whole document: screen fragments alone lose shared CSS, root tokens,+ // and ancestor selectors. The page extracts each .screen inside an isolated viewport.+ update.previewHtml = fs.readFileSync(options.previewFile, 'utf8');+ if (!update.previewHtml.trim()) throw new Error('The screen preview HTML is empty.');+ }if (options.screensFile) {update.screens = JSON.parse(fs.readFileSync(options.screensFile, 'utf8'));}diff --git a/plugins/mobile-apps/scripts/tests/app-docs.test.js b/plugins/mobile-apps/scripts/tests/app-docs.test.jsindex 135a28ad8..76de2d22c 100644--- a/plugins/mobile-apps/scripts/tests/app-docs.test.js+++ b/plugins/mobile-apps/scripts/tests/app-docs.test.js@@ -205,6 +205,61 @@ test('the CLI refuses a step before init and reports the reason', () => {assert.equal(JSON.parse(set.stdout.trim()).section, 'auth');});+test('the phone CLI carries the full preview, including shared CSS, without rewriting screens', (t) => {+ const root = project('docs-phone-preview');+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ seeded(root);+ const preview = '<!doctype html><html><head><style>:root{--brand:#0078d4}.card{display:flex}</style>'+ + '</head><body><div class="screen" id="products">Products</div>'+ + '<div class="screen" id="detail">Detail</div></body></html>';+ const previewPath = path.join(root, '_plan_preview.html');+ fs.writeFileSync(previewPath, preview);+ const result = spawnSync(process.execPath, [+ scriptPath, '--working-dir', root, 'phone', '--stage', 'screens', '--preview-file', previewPath,+ ], { encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ assert.equal(loadState(root).phone.previewHtml, preview);+ const html = fs.readFileSync(outputPath(root), 'utf8');+ const phone = JSON.parse(html.match(/<script id="phoneData" type="application\/json">([\s\S]*?)<\/script>/)[1]);+ assert.equal(phone.previewHtml, preview);+});++test('replacing a full preview with legacy screens cannot leave stale markup selected', (t) => {+ const root = project('docs-phone-source');+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const state = initState(root, { appName: 'Screens' });+ const screens = [{ name: 'Products', html: '<div>Products</div>' }];+ setPhone(state, { stage: 'screens', previewHtml: '<div class="screen">Old</div>' });+ setPhone(state, { screens });+ assert.equal(state.phone.previewHtml, undefined);+ assert.deepEqual(state.phone.screens, screens);+ setPhone(state, { previewHtml: '<div class="screen">New</div>' });+ assert.deepEqual(state.phone.screens, []);+ assert.match(state.phone.previewHtml, /New/);+});++test('the phone CLI rejects conflicting or empty preview inputs without changing the plan', (t) => {+ const root = project('docs-phone-input');+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ seeded(root);+ const previewPath = path.join(root, '_plan_preview.html');+ fs.writeFileSync(previewPath, ' \n');+ const previous = loadState(root);+ const run = (...args) => spawnSync(process.execPath, [+ scriptPath, '--working-dir', root, 'phone', '--stage', 'screens', ...args,+ ], { encoding: 'utf8' });+ const empty = run('--preview-file', previewPath);+ assert.equal(empty.status, 1);+ assert.match(empty.stderr, /preview HTML is empty/);+ const conflicting = run('--preview-file', previewPath, '--screens-file', 'unused.json');+ assert.equal(conflicting.status, 1);+ assert.match(conflicting.stderr, /not both/);+ const missing = run('--preview-file');+ assert.equal(missing.status, 1);+ assert.match(missing.stderr, /requires an HTML file path/);+ assert.deepEqual(loadState(root), previous);+});+test('the data model tab carries the power-pages colour vocabulary', () => {const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',diff --git a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js b/plugins/mobile-apps/scripts/tests/run-plan-page.test.jsindex 2f65fa5c3..68ff0ee1e 100644--- a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js+++ b/plugins/mobile-apps/scripts/tests/run-plan-page.test.js@@ -41,13 +41,14 @@ function node(id, attributes = {}) {set innerHTML(value) { this._html = String(value); },appendChild(child) { this.children.push(child); return child; },append(...kids) { this.children.push(...kids); },- setAttribute() {},+ setAttribute(name, value) { attributes[name] = String(value); },getAttribute(name) { return Object.hasOwn(attributes, name) ? attributes[name] : null; },removeAttribute() {},addEventListener() {}, removeEventListener() {}, remove() {},querySelector() { return null; }, querySelectorAll() { return []; },closest() { return null; }, focus() {}, scrollIntoView() {},getBoundingClientRect() { return { top: 0, left: 0, width: 0, height: 0 }; },+ clientWidth: 282, clientHeight: 602,};}@@ -144,6 +145,26 @@ async function runPage(htmlPath, { session = {} } = {}) {},},navigator: { userAgent: 'node' },+ // Parsing/sanitizing decisions have separate node-level tests below. The page harness+ // retains the source only to exercise the srcdoc handoff, not to emulate an HTML parser.+ DOMParser: class {+ parseFromString(source) {+ const head = node('head');+ head.prepend = (child) => head.children.unshift(child);+ return {+ head,+ createElement: document.createElement,+ querySelectorAll: () => [],+ documentElement: {+ get outerHTML() {+ const policies = head.children.map((child) =>+ `<meta http-equiv="${child.getAttribute('http-equiv')}" content="${child.getAttribute('content')}">`).join('');+ return `<html><head>${policies}</head><body>${source}</body></html>`;+ },+ },+ };+ }+ },console: { log() {}, warn() {}, error(message) { errors.push(String(message)); } },setTimeout() { return 0; }, clearTimeout() {},setInterval() { return 0; }, clearInterval() {},@@ -673,6 +694,7 @@ function sanitize(nodes, options) {nodes.forEach((n) => { n.parentNode = parent; });const context = vm.createContext({document: { createElement: () => ({ innerHTML: '', content: { querySelectorAll: () => nodes } }) },+ DOMParser: class { parseFromString() { return { querySelectorAll: () => nodes }; } },options,});vm.runInContext(`${source}\nsanitizeMockup('', options);`, context);@@ -712,7 +734,7 @@ test('the sanitizer removes SVG-cased elements and disguised script URLs', () =>assert.deepEqual(image.attrs, { src: 'data:image/png;base64,AAAA' }, 'images stay; handlers go');});-test('Mermaid output keeps its own stylesheet, and nothing else does', () => {+test('styles survive only in Mermaid output or isolated screen documents', () => {// Mermaid scopes its rules to the SVG's id, and the diagram is unstyled without them.const kept = element('style');const script = element('script');@@ -722,8 +744,96 @@ test('Mermaid output keeps its own stylesheet, and nothing else does', () => {const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');const calls = [...template.matchAll(/sanitizeMockup\(([^)]*)\)/g)].map((m) => m[1]);- assert.deepEqual(calls.filter((c) => /keepStyle/.test(c)), ['result.svg, { keepStyle: true }'],- 'only the Mermaid render may keep a stylesheet; mockups must not');+ const styled = calls.filter((c) => /keepStyle/.test(c));+ assert.ok(styled.includes('result.svg, { keepStyle: true }'));+ assert.ok(styled.filter((c) => !c.startsWith('result.svg')).every((c) => /asDocument: true/.test(c)),+ 'mockup styles must stay in a separate document');+});++test('isolated screen documents retain CSS but refuse handlers, scripts, and remote navigation', () => {+ const style = element('style');+ const script = element('SCRIPT');+ const link = element('a', { href: 'https://contoso.com/', onclick: 'void(0)' });+ const icon = element('use', { href: '#check' });+ const refresh = element('META', { 'http-equiv': 'refresh', content: '0;url=https://contoso.com/' });+ sanitize([style, script, link, icon, refresh], { keepStyle: true, asDocument: true });+ assert.equal(style.removed, false);+ assert.equal(script.removed, true);+ assert.deepEqual(link.attrs, {});+ assert.equal(icon.attrs.href, '#check');+ assert.equal(refresh.removed, true);+});++test('preview extraction keeps shared styles, theme attributes, and ancestors without gallery chrome', () => {+ function markup(tag, attributes = {}, children = [], text = '') {+ const attrs = { ...attributes };+ const created = {+ children: [],+ textContent: text,+ get id() { return attrs.id; },+ getAttribute(name) { return attrs[name] || null; },+ removeAttribute(name) { delete attrs[name]; },+ classList: { add(name) { attrs.class = `${attrs.class || ''} ${name}`.trim(); } },+ style: { setProperty(name, value, priority) { attrs.style = `${name}:${value}!${priority}`; } },+ appendChild(child) { this.children.push(child); child.parentElement = this; },+ cloneNode(deep) {+ return markup(tag, attrs, deep ? this.children.map((child) => child.cloneNode(true)) : [], this.textContent);+ },+ get outerHTML() {+ const encodedAttrs = Object.entries(attrs).map(([name, value]) => ` ${name}="${value}"`).join('');+ return `<${tag}${encodedAttrs}>${this.textContent}${this.children.map((child) => child.outerHTML).join('')}</${tag}>`;+ },+ };+ children.forEach((child) => created.appendChild(child));+ return created;+ }++ const products = markup('div', { id: 'products', class: 'screen', hidden: '' }, [], 'Products');+ const detail = markup('div', { id: 'detail', class: 'screen' }, [], 'Details');+ const area = markup('div', { class: 'screen-area', style: '--spacing:12px' }, [products, detail]);+ const wrap = markup('div', { class: 'screen-wrap' }, [markup('div', { class: 'notch' }), area]);+ const body = markup('body', { class: 'brand', style: '--brand:#0078d4' }, [+ markup('div', { class: 'page-title' }, [], 'Gallery'),+ markup('div', { class: 'phone' }, [wrap]),+ ]);+ const style = markup('style', {}, [], ':root{--brand:#0078d4}.card{display:flex;gap:12px}');+ const source = {+ documentElement: markup('html', { lang: 'en', class: 'dark' }),+ body,+ querySelectorAll(selector) {+ return {+ '[data-screen]': [+ markup('button', { 'data-screen': 'products' }, [], 'Products'),+ markup('button', { 'data-screen': 'detail' }, [], 'Product details'),+ ],+ '.screen': [products, detail],+ style: [style],+ }[selector];+ },+ };+ const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');+ const extract = template.slice(template.indexOf(' function previewScreens('), template.indexOf(' function mockupDocument('));+ const context = vm.createContext({+ document: { createElement: (tag) => markup(tag) },+ sanitizeMockup(input, options) {+ assert.equal(input, 'complete preview');+ assert.equal(options.keepStyle, true);+ assert.equal(options.asDocument, true);+ return source;+ },+ });+ const screens = vm.runInContext(`${extract}\npreviewScreens('complete preview')`, context);+ assert.deepEqual(Array.from(screens, (screen) => screen.name), ['Products', 'Product details']);+ for (const screen of screens) {+ assert.match(screen.html, /<html lang="en" class="dark">/);+ assert.match(screen.html, /<body class="brand" style="--brand:#0078d4">/);+ assert.match(screen.html, /\.card\{display:flex;gap:12px\}/);+ assert.match(screen.html, /class="screen-area" style="--spacing:12px"/);+ assert.match(screen.html, /class="screen active" style="display:flex!important"/);+ assert.doesNotMatch(screen.html, /class="page-title"|class="notch"| hidden=/);+ }+ assert.doesNotMatch(screens[0].html, /id="detail"/);+ assert.doesNotMatch(screens[1].html, /id="products"/);});test('the topbar pills say what their numbers mean', async () => {@@ -814,13 +924,16 @@ test('the create skill renders the screen preview but never opens it', () => {// opening mid-run interrupts a user who is already watching the plan.for (const block of skill.matchAll(/```(?:bash|sh)\n([\s\S]*?)```/g)) {assert.ok(- !/_plan_preview\.html/.test(block[1]),- `a runnable command still touches the screen preview: ${block[1].trim().slice(0, 80)}`,+ !/_plan_preview\.html/.test(block[1])+ || /app-docs\.js"[^\n]*phone --stage screens --preview-file/.test(block[1]),+ `a command opens the preview instead of embedding it: ${block[1].trim().slice(0, 80)}`,);}// It must still be rendered - the carousel takes its markup from those blocks - and it is// written into docs/ with every other artifact the user is asked to look at.assert.match(skill, /Render `_plan_preview\.html`/);+ assert.match(skill, /phone --stage screens --preview-file '<working_dir>\/_plan_preview\.html'/);+ assert.doesNotMatch(skill, /screens-preview\.json/);});test('the QR is drawn in the phone and linked for scanning full size', async () => {@@ -961,6 +1074,44 @@ test('the carousel says the mockups are not the built app, and only while they aassert.equal((await await runPage(outputPath(root))).elements.get('railNote').hidden, true);});+test('screen documents are sandboxed and scaled, with carousel controls outside the device', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-frame-'));+ const state = initState(root, { appName: 'Screens' });+ setPhone(state, { stage: 'screens', screens: [+ { name: 'Products', html: '<style>.card{display:flex;gap:12px}</style><div class="card">Products</div>' },+ ] });+ save(root, state);+ const { elements, thrown } = await runPage(outputPath(root));+ assert.deepEqual(thrown.map((error) => error.message), []);+ const device = elements.get('deviceScreen');+ const frame = device.children[0].children[0];+ const viewport = frame.children[0];+ assert.equal(viewport.tagName, 'IFRAME');+ assert.equal(viewport.getAttribute('sandbox'), '');+ assert.equal(viewport.getAttribute('referrerpolicy'), 'no-referrer');+ assert.equal(viewport.getAttribute('title'), 'Products');+ assert.match(viewport.srcdoc, /script-src 'none'/);+ assert.match(viewport.srcdoc, /default-src 'none'/);+ assert.match(viewport.srcdoc, /\.card\{display:flex;gap:12px\}/);+ const scale = Number(viewport.style.transform.match(/scale\(([^)]+)\)/)[1]);+ assert.equal(scale, Math.min(282 / 375, 602 / 812));+ assert.equal(elements.get('railControls').hidden, false);+ assert.equal(elements.get('railControls').children[0].className, 'car-nav');+});++test('a preview without screen blocks reports the problem instead of silently showing an animation', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'run-plan-invalid-preview-'));+ const state = initState(root, { appName: 'Invalid preview' });+ setPhone(state, { stage: 'screens', previewHtml: '<html><body>No screens</body></html>' });+ save(root, state);+ const { elements, errors, thrown } = await runPage(outputPath(root));+ assert.deepEqual(thrown.map((error) => error.message), []);+ assert.equal(elements.get('railTitle').textContent, 'Screen preview unavailable');+ assert.match(elements.get('railCaption').textContent, /no \.screen blocks/);+ assert.equal(errors.length, 1);+ assert.equal(elements.get('railControls').hidden, true);+});+test('the page carries a policy that makes injected mockup markup inert', () => {const template = fs.readFileSync(path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8');@@ -989,16 +1140,18 @@ test('generated markup is cleaned before it reaches the document', () => {// Parsed into a <template>, whose content is inert: nothing runs and no resource is fetched// while it is being cleaned.- assert.match(template, /holder\.content\.querySelectorAll\('\*'\)/);+ assert.match(template, /content\.querySelectorAll\('\*'\)/);for (const tag of ['SCRIPT', 'IFRAME', 'OBJECT', 'EMBED', 'FORM']) {assert.ok(template.includes(`'${tag}'`), `${tag} must be stripped from mockups`);}assert.match(template, /\/\^on\/i\.test\(name\)/, 'every on* handler must be removed');assert.match(template, /javascript:\|data:text\\\/html/, 'executing and navigating URLs must be refused');- // The two places that take generated markup both go through it.+ // Mermaid inserts a cleaned fragment; screens serialize a cleaned, sandboxed document.const sanitized = [...template.matchAll(/appendChild\(sanitizeMockup\(/g)];- assert.equal(sanitized.length, 2, 'mockups and mermaid output both need cleaning');+ assert.equal(sanitized.length, 1, 'Mermaid output must be cleaned');+ assert.match(template, /viewport\.srcdoc = mockupDocument\(current\.html\)/);+ assert.match(template, /function mockupDocument\(markup\) \{\s+var source = sanitizeMockup/);// And neither assigns it straight in.assert.doesNotMatch(template, /frame\.innerHTML/);assert.doesNotMatch(template, /panel\.innerHTML = result\.svg/);@@ -1117,6 +1270,8 @@ test('mockup CSS cannot reach past the phone frame', () => {// against the viewport. `contain: paint` makes the frame a containing block for fixed and// absolute descendants, so an injected overlay stays inside the phone.assert.match(template, /\.car-frame\{[^}]*contain:layout paint/);+ assert.match(template, /viewport\.setAttribute\('sandbox', ''\)/);+ assert.doesNotMatch(template, /sandbox', 'allow-/);});test('a table status tints the whole entity box, not just its header', () => {diff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.mdindex bfe93e301..b6e77823d 100644--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md@@ -1821,23 +1821,23 @@ Offline profile setup is intentionally deferred until after the approvedDataverse model has been materialized. Follow the shared connectivity-intentownership contract during this phase.-**Switch the plan's phone to the screen carousel.** `/design-system` has just rendered-`_plan_preview.html` — plan-time mockups built from the locked brand tokens, before a single line-of TSX exists. Those same per-screen blocks become the carousel:+**Switch the plan's phone to the screen carousel.**+`/design-system` has just rendered `_plan_preview.html`, with plan-time mockups built from the locked brand tokens before any TSX exists.+Pass that complete file to the carousel:```bash-node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' phone --stage screens --screens-file <tmp>/screens-preview.json+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' phone --stage screens --preview-file '<working_dir>/_plan_preview.html'```-`screens-preview.json` is `[{ "name": "Today's route", "html": "<the screen's markup>" }, …]`, in-navigation order.+The page extracts every `.screen` block in document order and takes its label from the matching `data-screen` tab.+It preserves shared styles, root tokens, and ancestor selectors inside a sandboxed 375 × 812 viewport, scaled to fit the phone.+The gallery's outer phone shell and controls stay outside the carousel.+Pass the file unchanged; copying only a screen's markup loses its stylesheet.+The legacy `--screens-file` JSON input remains supported for self-contained screen documents.-**Carry over exactly the screens `_plan_preview.html` contains — no more, no fewer.** How many-that is depends on what the user chose at `/design-system` Sub-step 6.5: option (a) renders every-screen, and the default (b) renders only the List, Form and Detail archetypes. Take the markup-from those blocks rather than re-authoring any of it: a hand-written block would drift from-`_plan_preview.html` and from the screen the builder later generates, which is the one thing the-carousel exists to rule out. A three-screen carousel is the expected shape, not a failure.+**Carry over exactly the screens `_plan_preview.html` contains - no more, no fewer.**+Option (a) at `/design-system` Sub-step 6.5 renders every screen; the default (b) renders only the List, Form and Detail archetypes.+A three-screen carousel is the expected shape, not a failure.**When there is no preview to carry over, leave the phone on the building animation.** That is`--no-design`, or Sub-step 6.5 option (c) "Skip preview" — in both cases `_plan_preview.html` was