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
mobile-apps 0.6.0: a watchable edit run and an app plan that stays current (#730)
Priyanshu Agrawal8a10052386a5
diff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.jsonindex ebfcd23e6..0dd0621b5 100644--- a/plugins/mobile-apps/.claude-plugin/plugin.json+++ b/plugins/mobile-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.5.4",+ "version": "0.6.0","description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors","author": {"name": "Microsoft",diff --git a/plugins/mobile-apps/.plugin/plugin.json b/plugins/mobile-apps/.plugin/plugin.jsonindex ebfcd23e6..0dd0621b5 100644--- a/plugins/mobile-apps/.plugin/plugin.json+++ b/plugins/mobile-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.5.4",+ "version": "0.6.0","description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors","author": {"name": "Microsoft",diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.mdindex 0d2499607..e0f19702a 100644--- a/plugins/mobile-apps/AGENTS.md+++ b/plugins/mobile-apps/AGENTS.md@@ -158,7 +158,7 @@ Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-ro## Decisions made-- ✅ Markdown plan with Mermaid (no HTML rendering)+- ✅ Markdown plan with Mermaid as the durable source, plus a living HTML plan and edit-progress page for user-visible status- ✅ **Architecture-first approval gates** in the planner (data platform + native APIs + connectors → conditional Dataverse model → screen plan)- ✅ `/edit-app` skill for post-generation app iteration: updates the approved plan delta, applies Dataverse/native/design/screen mutations, verifies, and refreshes preview output. `--plan-only` is the explicit docs-only escape hatch.- ✅ Single `/deploy` skill — `npm run build` + `pa app push`; no local native compile, no OTA in v0diff --git a/plugins/mobile-apps/assets/run-plan.html b/plugins/mobile-apps/assets/run-plan.htmlindex 0e1b1aa70..d638ccf38 100644--- a/plugins/mobile-apps/assets/run-plan.html+++ b/plugins/mobile-apps/assets/run-plan.html@@ -52,6 +52,7 @@--purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820;--warn:#ca5010; --warn-bg:#ca50100a; --warn-border:#ca501020;--footer-h:38px;+ --topbar-h:72px;--fail:#a4262c; --fail-bg:#a4262c0a; --fail-border:#a4262c20;--mono:'Cascadia Code','Consolas',monospace; --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;--radius:8px; --radius-sm:4px; --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);@@ -71,12 +72,18 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14.pill-progress{background:var(--purple-bg);color:var(--purple);border-color:var(--purple-border);}.pill-live{background:var(--pass-bg);color:var(--pass);border-color:var(--pass-border);}.shell{display:flex;align-items:flex-start;}-.layout{display:flex;min-height:calc(100vh - 65px);flex:1;min-width:0;}-.rail{width:430px;flex-shrink:0;position:sticky;top:65px;height:calc(100vh - 65px - var(--footer-h));display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px 20px;border-left:1px solid var(--border);background:var(--surface);}+.layout{display:flex;min-height:calc(100vh - var(--topbar-h));flex:1;min-width:0;}+.rail{width:430px;flex-shrink:0;position:sticky;top:var(--topbar-h);height:calc(100vh - var(--topbar-h) - var(--footer-h));display:flex;flex-direction:column;align-items:center;justify-content:safe center;gap:14px;padding:24px 20px;overflow-y:auto;border-left:1px solid var(--border);background:var(--surface);}.rail-title{font-size:11px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;}-.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;}+/* The sticky rail is shorter than the viewport because the topbar and footer remain visible.+ The phone is the only rail item that can give up height, so it flex-shrinks into whatever the+ label, caption, preview link and store buttons leave. A fixed budget cannot work here: the QR+ stage adds the link and store row, so a budget sized for the building stage pushes the label+ under the topbar and the store row behind the footer on a 720px-tall window. Below 360px the+ phone stops shrinking and the rail scrolls, because a smaller phone cannot show the QR copy. */+.device{flex:0 1 620px;min-height:360px;max-height:620px;width:auto;max-width:calc(100vw - 44px);aspect-ratio:300/620;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;}.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{position:absolute;inset:0;background:#faf9f8;overflow:hidden;container-type:size;}.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;}@@ -110,12 +117,16 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14.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;}-.qr img{width:196px;height:196px;}+/* On a short window the phone shrinks (see .device), so the QR screen must fit a smaller frame:+ the code gives up height first, the content clears the notch, and the copy tightens when the+ phone is short. Without this the code slides under the notch and the Metro URL is cut off. */+.qr{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:safe center;gap:16px;background:#fff;padding:30px 22px 18px;text-align:center;}+.qr img{flex:0 1 196px;min-height:84px;max-height:196px;width:auto;max-width:100%;aspect-ratio:1/1;object-fit:contain;}.qr-title{font-size:16px;font-weight:700;color:#201f1e;}.qr-sub{font-size:12.5px;color:#605e5c;line-height:1.55;}.qr-url{font-family:var(--mono);font-size:11px;color:#0078d4;word-break:break-all;}-@media(max-width:1180px){.shell{flex-direction:column;}.rail{width:100%;position:static;height:auto;border-left:none;border-top:1px solid var(--border);}}+@container (max-height:520px){.qr{gap:8px;padding:28px 12px 14px;}.qr-title{font-size:14px;}.qr-sub{font-size:11px;line-height:1.4;}.qr-url{font-size:10px;}}+@media(max-width:1180px){.shell{flex-direction:column;}.rail{width:100%;position:static;height:auto;border-left:none;border-top:1px solid var(--border);}.device{flex:none;height:auto;width:min(300px,calc(100vw - 44px));}}.sidebar{width:240px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}.nav-group-label{font-size:10px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;padding:16px 22px 6px;}.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;}@@ -760,7 +771,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margicontainer.appendChild(link);}- add(summary.screenPreviewHref, 'Open screens full size \u2197');+ add(phone.previewHref || summary.screenPreviewHref, 'Open screens full size \u2197');// The QR is already drawn in the phone; this is for scanning it larger, and it links the// PNG rather than the inlined data URI because browsers block top-level navigation to a// data: URL. It drops away once `.expo/` is cleaned, leaving the inlined copy.@@ -1805,6 +1816,17 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi{ year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });}+ // The sticky rail is offset by the topbar, whose height grows when its pills wrap on a narrow+ // window. Mirror the real height into --topbar-h so the rail neither slides under the topbar+ // nor runs behind the fixed footer; the CSS default covers the single-row topbar.+ var topbarEl = document.querySelector ? document.querySelector('.topbar') : null;+ var rootStyle = document.documentElement && document.documentElement.style;+ if (topbarEl && rootStyle && rootStyle.setProperty) {+ var syncTopbar = function () { rootStyle.setProperty('--topbar-h', topbarEl.offsetHeight + 'px'); };+ syncTopbar();+ window.addEventListener('resize', syncTopbar);+ }+renderPhone();renderOverview();renderRequirements();diff --git a/plugins/mobile-apps/scripts/app-docs.js b/plugins/mobile-apps/scripts/app-docs.jsindex 6011a13ce..899fad439 100644--- a/plugins/mobile-apps/scripts/app-docs.js+++ b/plugins/mobile-apps/scripts/app-docs.js@@ -22,13 +22,19 @@* 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 [--preview-file <html> | --screens-file <json>] [--qr-image <png>] [--qr-url <url>]+ * progress --working-dir <d> --json-file <path>+ * sync --working-dir <d> --json-file <path>+ * temp --working-dir <d>* show --working-dir <d>*/'use strict';const fs = require('node:fs');+const crypto = require('node:crypto');+const os = require('node:os');const path = require('node:path');+const { pathToFileURL } = require('node:url');const { publishAtomic, renderTemplate } = require('./lib/render-template');@@ -57,6 +63,8 @@ const OUTPUT_FILE = 'create-app-plan.html';const TEMPLATE_PATH = path.join(__dirname, '..', 'assets', 'run-plan.html');const STATUSES = new Set(['pending', 'active', 'done', 'skipped', 'failed']);+const EDIT_ITEM_STATUSES = new Set(['pending', 'active', 'waiting', 'done', 'skipped', 'failed']);+const EDIT_PROGRESS_STATUSES = new Set(['active', 'waiting', 'done', 'failed']);/*** Sections the skill records as it learns them. Each is written once by the step that owns@@ -112,6 +120,48 @@ function outputPath(projectRoot) {return path.join(docsDir(projectRoot), OUTPUT_FILE);}+function editTempDir(projectRoot) {+ const projectHash = crypto.createHash('sha256')+ .update(path.resolve(projectRoot))+ .digest('hex')+ .slice(0, 16);+ const userNamespace = typeof process.getuid === 'function' ? `uid-${process.getuid()}` : 'user';+ return path.join(os.tmpdir(), `power-platform-mobile-app-${userNamespace}`, projectHash);+}++function ensurePrivateDirectory(directory) {+ try {+ fs.mkdirSync(directory, { mode: 0o700 });+ } catch (error) {+ if (error.code !== 'EEXIST') throw error;+ }++ const stat = fs.lstatSync(directory);+ if (stat.isSymbolicLink() || !stat.isDirectory()) {+ throw new Error(`Refusing unsafe temporary directory: ${directory}`);+ }+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {+ throw new Error(`Temporary directory is owned by another user: ${directory}`);+ }++ // POSIX temp roots such as /tmp are shared between users. Restrict both the stable parent and+ // project namespace so separate CLI invocations can reuse them without exposing payloads.+ // Windows temp directories are already user-scoped, and its chmod mode bits are not POSIX ACLs.+ if (process.platform !== 'win32') {+ fs.chmodSync(directory, 0o700);+ if ((fs.lstatSync(directory).mode & 0o077) !== 0) {+ throw new Error(`Temporary directory permissions are not private: ${directory}`);+ }+ }+}++function prepareEditTempDir(projectRoot) {+ const directory = editTempDir(projectRoot);+ ensurePrivateDirectory(path.dirname(directory));+ ensurePrivateDirectory(directory);+ return directory;+}+function loadState(projectRoot) {return readJson(statePath(projectRoot));}@@ -160,6 +210,7 @@ function setPhone(state, update) {state.phone.previewHtml = update.previewHtml;state.phone.screens = [];}+ if (update.previewHref !== undefined) state.phone.previewHref = update.previewHref;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;@@ -408,6 +459,1035 @@ function render(projectRoot, state) {});}+function escapeHtml(value) {+ return String(value ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');+}++function inlineJson(value) {+ return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (character) => ({+ '<': '\\u003c',+ '>': '\\u003e',+ '&': '\\u0026',+ '\u2028': '\\u2028',+ '\u2029': '\\u2029',+ })[character]);+}++function normalizeEditItems(options) {+ const supplied = Array.isArray(options.items) ? options.items : null;+ const legacy = Array.isArray(options.checklist)+ ? options.checklist.map((label, index) => ({+ id: `item-${index + 1}`,+ label,+ status: index === 0 ? 'active' : 'pending',+ }))+ : null;+ const items = supplied || legacy || [+ { id: 'inspect', label: 'Inspect the current app', status: 'active' },+ { id: 'plan', label: 'Plan the requested changes', status: 'pending' },+ { id: 'apply', label: 'Apply the approved changes', status: 'pending' },+ { id: 'verify', label: 'Verify the edited app', status: 'pending' },+ { id: 'preview', label: 'Refresh the preview and app plan', status: 'pending' },+ ];+ const ids = new Set();++ return items.map((item, index) => {+ if (!item || typeof item !== 'object' || Array.isArray(item)) {+ throw new Error(`Progress item ${index + 1} must be an object.`);+ }+ const id = String(item.id || '').trim();+ const label = String(item.label || '').trim();+ const status = String(item.status || 'pending');+ if (!id || !label) throw new Error(`Progress item ${index + 1} requires id and label.`);+ if (ids.has(id)) throw new Error(`Duplicate progress item id '${id}'.`);+ if (!EDIT_ITEM_STATUSES.has(status)) {+ throw new Error(+ `Unknown progress item status '${status}'. Known: ${[...EDIT_ITEM_STATUSES].join(', ')}`,+ );+ }+ ids.add(id);+ return { id, label, status, note: item.note ? String(item.note) : '' };+ });+}++function reconcileCoarseEditItems(items, phase, status, waiting, supplied) {+ const coarseIds = ['inspect', 'plan', 'apply', 'verify', 'preview'];+ if (items.length !== coarseIds.length+ || items.some((item, index) => item.id !== coarseIds[index])) {+ return items;+ }++ // An explicit snapshot is authoritative, including skipped and failed rows. Phase inference is+ // only for the five-row fallback generated when the caller omits operation details.+ if (supplied) return items;++ // The five-row fallback combines finer workflow gates such as impact and approval into+ // "Plan". Agents may publish only the new top-level phase and omit a fresh items array; without+ // this reconciliation the fallback restarts at "Inspect" even though planning is already done.+ const phaseToItem = new Map([+ ['review', 'inspect'],+ ['inspect', 'inspect'],+ ['impact', 'plan'],+ ['planning', 'plan'],+ ['plan', 'plan'],+ ['approval', 'plan'],+ ['save-plan', 'apply'],+ ['implementation', 'apply'],+ ['apply', 'apply'],+ ['data', 'apply'],+ ['native', 'apply'],+ ['design', 'apply'],+ ['screens', 'apply'],+ ['verification', 'verify'],+ ['verify', 'verify'],+ ['preview', 'preview'],+ ['device', 'preview'],+ ['sync', 'preview'],+ ['sync-plan', 'preview'],+ ]);+ const currentId = phaseToItem.get(String(phase).toLowerCase());+ if (status === 'done') {+ return items.map((item) => ({ ...item, status: 'done' }));+ }+ if (!currentId) return items;++ const currentIndex = coarseIds.indexOf(currentId);+ if (status === 'failed') {+ return items.map((item, index) => ({+ ...item,+ status: index < currentIndex ? 'done'+ : index === currentIndex ? 'failed'+ : 'skipped',+ }));+ }+ return items.map((item, index) => ({+ ...item,+ status: index < currentIndex ? 'done'+ : index === currentIndex ? (waiting ? 'waiting' : 'active')+ : 'pending',+ }));+}++function normalizeEditChanges(options) {+ const changes = Array.isArray(options.changes) ? options.changes : [];+ return changes.map((change, index) => {+ if (!change || typeof change !== 'object' || Array.isArray(change)) {+ throw new Error(`Edit change ${index + 1} must be an object.`);+ }+ const diagramInputs = [change, change.dataModel, change.screenGraph]+ .filter((value) => value && typeof value === 'object' && !Array.isArray(value));+ if (diagramInputs.some(+ (value) => Object.hasOwn(value, 'diagram') || Object.hasOwn(value, 'mermaid'),+ )) {+ throw new Error(+ `Edit change ${index + 1} cannot carry raw diagram or Mermaid source; use structured data.`,+ );+ }+ const title = String(change.title || change.label || '').trim();+ if (!title) throw new Error(`Edit change ${index + 1} requires a title.`);+ const detail = change.detail ? String(change.detail) : '';+ const rationale = change.rationale ? String(change.rationale)+ : change.reason ? String(change.reason) : '';+ if (!rationale.trim()) throw new Error(`Edit change ${index + 1} requires a rationale.`);+ const kind = String(change.kind || '').trim().toLowerCase();+ if (!['general', 'data-model', 'screen'].includes(kind)) {+ throw new Error(+ `Edit change ${index + 1} requires kind general, data-model, or screen.`,+ );+ }+ const diagram = buildEditChangeDiagram(change, kind, index);+ return {+ title,+ detail,+ rationale: rationale.trim(),+ kind,+ diagram,+ };+ });+}++function safeMermaidName(value, fallback) {+ const source = value === undefined || value === null ? fallback : String(value);+ return source.replace(/[^A-Za-z0-9_]/g, '_') || fallback;+}++function uniqueMermaidName(value, fallback, usedNames) {+ const base = safeMermaidName(value, fallback);+ let candidate = base;+ let suffix = 2;+ // Mermaid merges nodes that share an ID, while normalization can map distinct routes or table+ // names to the same token. Preserve the original-value lookup and disambiguate only the ID.+ while (usedNames.has(candidate)) {+ candidate = `${base}_${suffix}`;+ suffix += 1;+ }+ usedNames.add(candidate);+ return candidate;+}++// Mermaid labels are always emitted inside a quoted string here (`["..."]`,+// `|"..."|`, `: "..."`), so the characters below are escaped with Mermaid's+// decimal entity codes rather than dropped. Stripping them silently rewrote the+// text the user reads: Expo dynamic routes are the common case in this plugin,+// and `/inspections/[id]` came out as `/inspections/ id`.+// `#` is escaped too, and in the same pass, so a literal `#` already in the+// source cannot combine with a code emitted after it.+// See: https://mermaid.js.org/syntax/flowchart.html#entity-codes-to-escape-characters+const MERMAID_LABEL_ESCAPES = {+ '#': '#35;',+ '"': '#quot;',+ '[': '#91;',+ ']': '#93;',+ '{': '#123;',+ '}': '#125;',+ '<': '#60;',+ '>': '#62;',+ '|': '#124;',+};++function safeMermaidLabel(value, fallback = '') {+ const source = value === undefined || value === null ? fallback : String(value);+ const escaped = source+ .replace(/[#"[\]{}<>|]/g, (character) => MERMAID_LABEL_ESCAPES[character])+ .replace(/\s+/g, ' ')+ .trim();+ return escaped || fallback;+}++function relationshipConnector(cardinality) {+ const normalized = String(cardinality || 'one-to-many').toLowerCase();+ const connectors = {+ 'one-to-many': '||--o{',+ 'many-to-one': '}o--||',+ 'one-to-one': '||--||',+ 'many-to-many': '}o--o{',+ 'optional-to-many': 'o|--o{',+ };+ if (!Object.hasOwn(connectors, normalized)) {+ throw new Error(`Unknown data-model relationship cardinality '${cardinality}'.`);+ }+ return connectors[normalized];+}++function buildDataModelDiagram(change, index) {+ const model = change.dataModel && typeof change.dataModel === 'object'+ ? change.dataModel+ : change;+ const tables = Array.isArray(model.tables) ? model.tables : [];+ if (!tables.length) {+ throw new Error(`Data-model edit change ${index + 1} requires tables.`);+ }+ const ids = new Map();+ const usedNames = new Set();+ const tableLines = tables.map((table, tableIndex) => {+ if (!table || typeof table !== 'object' || Array.isArray(table)) {+ throw new Error(`Data-model table ${tableIndex + 1} must be an object.`);+ }+ const name = String(table.name || table.logicalName || '').trim();+ if (!name) throw new Error(`Data-model table ${tableIndex + 1} requires a name.`);+ const id = uniqueMermaidName(name, `Entity${tableIndex + 1}`, usedNames);+ [name, table.logicalName, table.id].filter(Boolean).forEach((key) => ids.set(String(key), id));+ const columns = Array.isArray(table.columns) ? table.columns+ : Array.isArray(table.fields) ? table.fields : [];+ const columnLines = columns.map((column, columnIndex) => {+ const value = column && typeof column === 'object' ? column : { name: column };+ const columnName = safeMermaidName(+ value.name || value.logicalName,+ `field${columnIndex + 1}`,+ );+ const type = safeMermaidName(value.type || value.dataType || 'string', 'string');+ const key = value.primaryKey ? ' PK' : value.foreignKey ? ' FK' : '';+ return ` ${type} ${columnName}${key}`;+ });+ return ` ${id} {\n${columnLines.join('\n')}\n }`;+ });+ const relationships = Array.isArray(model.relationships) ? model.relationships : [];+ const relationshipLines = relationships.map((relationship, relationshipIndex) => {+ if (!relationship || typeof relationship !== 'object' || Array.isArray(relationship)) {+ throw new Error(`Data-model relationship ${relationshipIndex + 1} must be an object.`);+ }+ const from = ids.get(String(relationship.from || relationship.parent || ''));+ const to = ids.get(String(relationship.to || relationship.child || ''));+ if (!from || !to) {+ throw new Error(+ `Data-model relationship ${relationshipIndex + 1} must reference declared tables.`,+ );+ }+ const label = safeMermaidLabel(+ relationship.label || relationship.name || 'relates to',+ 'relates to',+ );+ return ` ${from} ${relationshipConnector(relationship.cardinality)} ${to} : "${label}"`;+ });+ return `erDiagram\n${tableLines.concat(relationshipLines).join('\n')}`;+}++function buildScreenDiagram(change, index) {+ const graph = change.screenGraph && typeof change.screenGraph === 'object'+ ? change.screenGraph+ : change;+ const screens = Array.isArray(graph.screens) ? graph.screens : [];+ if (!screens.length) throw new Error(`Screen edit change ${index + 1} requires screens.`);+ const ids = new Map();+ const usedNames = new Set();+ const nodes = screens.map((screen, screenIndex) => {+ const value = screen && typeof screen === 'object' ? screen : { name: screen };+ const name = String(value.name || value.title || value.route || '').trim();+ if (!name) throw new Error(`Screen ${screenIndex + 1} requires a name or route.`);+ const id = uniqueMermaidName(+ `S_${value.id || value.route || name}`,+ `S_${screenIndex + 1}`,+ usedNames,+ );+ [value.id, value.route, name].filter(Boolean).forEach((key) => ids.set(String(key), id));+ const route = value.route && value.route !== name+ ? ` · ${safeMermaidLabel(value.route)}`+ : '';+ return ` ${id}["${safeMermaidLabel(name)}${route}"]`;+ });+ const edges = Array.isArray(graph.edges) ? graph.edges+ : Array.isArray(graph.navigation) ? graph.navigation : [];+ if (screens.length > 1 && !edges.length) {+ throw new Error(+ `Screen edit change ${index + 1} requires navigation edges for multiple screens.`,+ );+ }+ const links = edges.map((edge, edgeIndex) => {+ if (!edge || typeof edge !== 'object' || Array.isArray(edge)) {+ throw new Error(`Screen navigation edge ${edgeIndex + 1} must be an object.`);+ }+ const from = ids.get(String(edge.from || ''));+ const to = ids.get(String(edge.to || ''));+ if (!from || !to) {+ throw new Error(`Screen navigation edge ${edgeIndex + 1} must reference declared screens.`);+ }+ const label = safeMermaidLabel(edge.label || edge.action || '');+ return label ? ` ${from} -->|"${label}"| ${to}` : ` ${from} --> ${to}`;+ });+ return `flowchart LR\n${nodes.concat(links).join('\n')}`;+}++function buildEditChangeDiagram(change, kind, index) {+ if (kind === 'data-model') return buildDataModelDiagram(change, index);+ if (kind === 'screen') return buildScreenDiagram(change, index);+ if (change.dataModel || change.screenGraph || change.tables || change.screens) {+ throw new Error(+ `General edit change ${index + 1} cannot carry data-model or screen graph data.`,+ );+ }+ return '';+}++function writeEditProgress(projectRoot, options = {}) {+ const phase = options.phase || 'review';+ const note = options.note || 'Working on the approved change';+ const waiting = Boolean(options.waiting);+ const status = options.status || (waiting ? 'waiting' : 'active');+ if (!EDIT_PROGRESS_STATUSES.has(status)) {+ throw new Error(+ `Unknown edit progress status '${status}'. Known: ${[...EDIT_PROGRESS_STATUSES].join(', ')}`,+ );+ }+ const suppliedItems = Array.isArray(options.items) || Array.isArray(options.checklist);+ const items = reconcileCoarseEditItems(+ normalizeEditItems(options), phase, status, waiting, suppliedItems,+ );+ const changes = normalizeEditChanges(options);+ const completed = items.filter((item) => ['done', 'skipped'].includes(item.status)).length;+ const failed = items.filter((item) => item.status === 'failed').length;+ const percent = items.length ? Math.round((completed / items.length) * 100) : 0;+ const settled = status === 'done' || status === 'failed';+ const activeItem = items.find((item) => ['active', 'waiting'].includes(item.status));+ const state = loadState(projectRoot);+ const appName = options.appName || (state && state.appName) || path.basename(path.resolve(projectRoot));+ const generatedAt = new Date().toISOString().replace('T', ' ').slice(0, 16);+ const displayPhase = String(phase).replace(/[-_]+/g, ' ');+ const phasePill = displayPhase.toLowerCase() === status.toLowerCase()+ ? ''+ : `<span class="pill pill-phase">${escapeHtml(displayPhase)}</span>`;+ const nonce = crypto.randomBytes(16).toString('base64');+ const phone = state && state.phone && typeof state.phone === 'object' ? state.phone : {};+ const qrImage = status === 'done'+ && options.devicePreviewReady === true+ && phone.stage === 'qr'+ && typeof phone.qrImage === 'string'+ && phone.qrImage.startsWith('data:image/png;base64,')+ ? phone.qrImage+ : '';+ const qrUrl = qrImage && typeof phone.qrUrl === 'string' ? phone.qrUrl : '';+ const previewHtml = !settled+ && phone.stage === 'screens'+ && typeof phone.previewHtml === 'string'+ ? phone.previewHtml+ : '';+ const previewPath = typeof phone.previewHref === 'string'+ ? path.resolve(docsDir(projectRoot), phone.previewHref)+ : path.resolve(projectRoot, 'preview.html');+ const previewHref = fs.existsSync(previewPath) ? pathToFileURL(previewPath).href : '';+ const qrHref = qrImage && typeof phone.qrHref === 'string'+ ? pathToFileURL(path.resolve(docsDir(projectRoot), phone.qrHref)).href+ : '';+ const activeId = activeItem && activeItem.id;+ const deviceProgress = activeId === 'preview'+ ? {+ title: 'Refreshing your preview',+ copy: 'The live preview and app plan are being updated.',+ }+ : activeId === 'verify'+ ? {+ title: 'Verifying your changes',+ copy: 'The edited app is being checked before the preview is refreshed.',+ }+ : ['apply', 'data', 'native', 'design', 'screens'].includes(activeId)+ ? {+ title: 'Applying your changes',+ copy: 'The approved edits are being written to the app.',+ }+ : ['plan', 'impact', 'approve'].includes(activeId)+ ? {+ title: waiting ? 'Waiting for approval' : 'Planning your changes',+ copy: waiting+ ? 'The preview will update after you approve the proposed edit.'+ : 'The requested edit is being turned into an implementation plan.',+ }+ : {+ title: 'Inspecting your app',+ copy: 'The current app is being inspected before changes are planned.',+ };+ const deviceContent = qrImage+ ? `<div class="device-qr"><img src="${escapeHtml(qrImage)}" alt="Metro QR code" />`+ + `<div class="device-title">Scan to test the changes</div>`+ + `<div class="device-copy">Open Power Apps Mobile Preview and scan this code. `+ + `Your phone and this machine need to be on the same network.</div>`+ + `${qrUrl ? `<div class="device-url">${escapeHtml(qrUrl)}</div>` : ''}</div>`+ : previewHtml+ ? `<div class="device-carousel"><div class="device-carousel-frame">`+ + `<iframe id="devicePreviewFrame" sandbox="" referrerpolicy="no-referrer" `+ + `title="Screen preview"></iframe></div></div>`+ : `<div class="device-building${status === 'failed' ? ' device-failed' : ''}">`+ + `<div class="device-orbit"><span></span><span></span>`+ + `<img src="${brandIconDataUri()}" alt="" /></div>`+ + `<div class="device-title">${status === 'failed' ? 'Edit stopped' : status === 'done'+ ? 'Device preview unavailable' : deviceProgress.title}</div>`+ + `<div class="device-copy">${status === 'failed'+ ? 'Resolve the failed step before testing this edit on a device.'+ : status === 'done'+ ? 'Metro did not provide a QR code. Run the app preview to test this edit on a device.'+ : deviceProgress.copy}</div>`+ + `<div class="device-progress"><span style="width:${percent}%"></span></div></div>`;+ const deviceCaption = qrImage+ ? 'Edits hot-reload onto the device while Metro is running.'+ : status === 'done'+ ? 'The edit is complete, but no active device preview was found.'+ : status === 'failed'+ ? 'No device preview was started.'+ : activeId === 'preview'+ ? 'The phone switches to the live QR code when the preview is ready.'+ : activeId === 'verify'+ ? 'The phone switches to the live QR code after verification.'+ : previewHtml+ ? 'Plan-time screen preview'+ : 'The phone preview follows the current edit step.';+ const previewLink = previewHref+ ? `<a class="rail-link" href="${escapeHtml(previewHref)}" target="_blank" rel="noopener">`+ + `Open screens full size ↗</a>`+ : '';+ const qrLink = qrHref+ ? `<a class="rail-link" href="${escapeHtml(qrHref)}" target="_blank" rel="noopener">`+ + `Open QR code full size ↗</a>`+ : '';+ const storeButtons = qrImage+ ? `<div class="store-row" aria-label="Download Power Apps Mobile Preview">`+ + `<a class="store-btn" href="https://apps.apple.com/app/id6753083462" target="_blank" `+ + `rel="noopener noreferrer"><span class="store-kicker">Download on the</span>`+ + `<strong>App Store</strong></a>`+ + `<a class="store-btn" href="https://play.google.com/store/apps/details?id=com.microsoft.PreviewApp" `+ + `target="_blank" rel="noopener noreferrer"><span class="store-kicker">GET IT ON</span>`+ + `<strong>Google Play</strong></a></div>`+ : '';++ const filePath = path.join(prepareEditTempDir(projectRoot), 'edit-app-progress.html');++ const rows = items.map((item) => {+ const itemNote = item.note ? `<span class="item-note">${escapeHtml(item.note)}</span>` : '';+ return ` <li class="item ${escapeHtml(item.status)}" data-item-id="${escapeHtml(item.id)}">`+ + `<span class="bullet"></span><span class="item-copy"><span>${escapeHtml(item.label)}</span>`+ + `${itemNote}</span><span class="item-status">${escapeHtml(item.status)}</span></li>`;+ }).join('\n');++ const changeCards = changes.length+ ? changes.map((change) => {+ const detail = change.detail+ ? `<div class="change-detail">${escapeHtml(change.detail)}</div>`+ : '';+ const rationale = change.rationale+ ? `<div class="change-rationale"><strong>Why this matters:</strong> ${escapeHtml(change.rationale)}</div>`+ : '';+ const diagram = change.diagram+ ? `<div class="diagram-block"><div class="diagram-title">`+ + `${change.kind === 'data-model' ? 'Proposed data model' : 'Proposed screen graph'}`+ + `</div><div class="diagram-canvas" role="img" aria-label="`+ + `${change.kind === 'data-model' ? 'Proposed data model diagram' : 'Proposed screen navigation graph'}"></div>`+ + `<div class="diagram-fallback-note">The interactive diagram could not be rendered.</div>`+ + `<details class="diagram-source"><summary>View diagram source</summary>`+ + `<pre>${escapeHtml(change.diagram)}</pre></details></div>`+ : '';+ const kindLabel = change.kind ? `<span class="change-kind">${escapeHtml(change.kind)}</span>` : '';+ return `<article class="change-card"><span class="change-mark"></span><div>`+ + `<div class="change-header"><div class="change-title">${escapeHtml(change.title)}</div>${kindLabel}</div>`+ + `${detail}${rationale}${diagram}</div></article>`;+ }).join('\n')+ : `<div class="empty">Planned changes will appear here after the current app has been inspected.</div>`;+ // Mirror the create-app plan: a small floating pill pinned to the top-right rather than a+ // full-width bar. The answer is wanted in the terminal, so the page only needs a persistent+ // marker that survives a tab switch, not a banner that displaces the content.+ const waitingPrompt = waiting ? (note || 'Review the proposed changes or provide the missing details.') : '';+ const waitingBanner = waiting+ ? `<div class="input-banner" id="inputBanner" role="status" data-prompt="${escapeHtml(waitingPrompt)}">`+ + `<span class="input-banner-icon">●</span>`+ + `<div class="input-banner-text"><b>Waiting for your input</b>`+ + `<small>${escapeHtml(waitingPrompt)}</small></div>`+ + `<button type="button" class="input-banner-close" id="inputBannerClose" aria-label="Dismiss">×</button>`+ + `</div>`+ : '';+ const autoRefresh = settled ? '' : `+ var RELOAD_MS = 2500;+ var QUIET_MS = 10000;+ var lastInteraction = 0;+ ['scroll', 'keydown', 'pointerdown'].forEach(function (event) {+ window.addEventListener(event, function () { lastInteraction = Date.now(); }, { passive: true });+ });+ setInterval(function () {+ if (document.hidden || Date.now() - lastInteraction < QUIET_MS) return;+ try { sessionStorage.setItem(STORE_SCROLL, String(window.scrollY)); } catch (error) { /* private mode */ }+ var fresh = location.href.split('#')[0].split('?')[0] + '?t=' + Date.now();+ location.replace(fresh);+ }, RELOAD_MS);`;++ const html = `<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; img-src data:; font-src data:; base-uri 'none'; form-action 'none';" />+ <title>Mobile app edit plan - ${escapeHtml(appName)}</title>+ <script nonce="${nonce}"+ src="https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"+ integrity="sha384-EOXBFmc3gx5mb+vn0vPvvGqACToJD24hhacX5Yx+8NUUQrHIle/Qi5Bg9o3zKwW2"+ crossorigin="anonymous"></script>+ <style>+ :root {+ --bg:#faf9f8; --surface:#fff; --surface2:#f3f2f1; --border:#e1dfdd;+ --border-light:#c8c6c4; --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020;+ --warn:#ca5010; --warn-bg:#ca50100a; --warn-border:#ca501020;+ --fail:#a4262c; --fail-bg:#a4262c0a; --fail-border:#a4262c20;+ --footer-h:38px; --radius:8px;+ --shadow:0 1.6px 3.6px rgba(0,0,0,.132),0 .3px .9px rgba(0,0,0,.108);+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ }+ *{box-sizing:border-box;}+ body{font-family:var(--sans);margin:0;background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;padding-bottom:var(--footer-h);}+ button{font:inherit;}+ .topbar{position:sticky;top:0;z-index:10;background:var(--surface);box-shadow:var(--shadow);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap;}+ .topbar-left{display:flex;align-items:center;gap:14px;min-width:0;}+ .logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}+ .topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}+ .topbar-sub{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11px;color:var(--text-dim);}+ .topbar-sep{opacity:.5;}+ .topbar-right{display:flex;align-items:center;gap:6px;flex-wrap:wrap;}+ .pill{font-size:11px;padding:4px 10px;border-radius:999px;font-weight:600;letter-spacing:.2px;border:1px solid var(--border);color:var(--text-dim);background:var(--surface2);}+ .pill-phase{background:var(--accent-bg);color:var(--accent);border-color:var(--accent-border);text-transform:capitalize;}+ .pill-done{background:var(--pass-bg);color:var(--pass);border-color:var(--pass-border);}+ .pill-failed{background:var(--fail-bg);color:var(--fail);border-color:var(--fail-border);}+ .shell{display:flex;align-items:flex-start;}+ .layout{display:flex;min-height:calc(100vh - var(--topbar-h, 65px) - var(--footer-h));flex:1;min-width:0;}+ .sidebar{width:240px;flex-shrink:0;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;}+ .nav-label{font-size:10px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;padding:16px 22px 6px;}+ .nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:0;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;text-align:left;}+ .nav-btn:hover{color:var(--text);background:var(--surface2);}+ .nav-btn:focus-visible{outline:2px solid var(--accent);outline-offset:-2px;}+ .nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+ .nav-icon{font-size:15px;opacity:.55;width:18px;text-align:center;}+ .content{flex:1;min-width:0;max-width:960px;padding:32px 40px 72px;}+ .section{display:none;}+ .section.active{display:block;}+ h1{font-size:26px;line-height:1.2;letter-spacing:-.3px;margin:0 0 6px;color:var(--text-bright);}+ .section-desc{font-size:13px;color:var(--text-dim);margin-bottom:22px;max-width:72ch;}+ .summary{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;box-shadow:var(--shadow);}+ .note{font-size:16px;line-height:1.55;color:var(--text-bright);}+ .status-line{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:12px;color:var(--text-dim);margin-top:16px;}+ .progress-track{height:6px;overflow:hidden;border-radius:999px;background:var(--surface2);border:1px solid var(--border);margin-top:9px;}+ .progress-bar{display:block;height:100%;background:var(--accent);width:${percent}%;}+ .input-banner{position:fixed;top:calc(var(--topbar-h, 65px) + 13px);right:24px;z-index:100;display:flex;align-items:center;gap:12px;background:#fff8f2;border:1px solid var(--warn-border);color:var(--warn);padding:12px 14px 12px 18px;border-radius:999px;font-size:13.5px;max-width:min(380px,calc(100vw - 48px));box-shadow:0 6px 20px rgba(0,0,0,.12);}+ .input-banner[hidden]{display:none;}+ .input-banner-icon{font-size:11px;flex-shrink:0;animation:bannerPulse 1.6s ease-in-out infinite;}+ .input-banner-text{line-height:1.35;flex:1;min-width:0;}+ .input-banner-text b{display:block;font-weight:650;}+ .input-banner-text small{display:block;font-size:12px;opacity:.85;margin-top:2px;color:var(--text-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}+ .input-banner-close{width:24px;height:24px;border:0;border-radius:50%;background:rgba(202,80,16,.12);color:var(--warn);cursor:pointer;font-size:17px;line-height:1;flex-shrink:0;}+ .input-banner-close:hover{background:rgba(202,80,16,.22);}+ @keyframes bannerPulse{0%,100%{opacity:1;}50%{opacity:.35;}}+ .change-card{display:grid;grid-template-columns:18px 1fr;gap:12px;align-items:start;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px;margin-bottom:10px;box-shadow:var(--shadow);}+ .change-mark{width:10px;height:10px;border-radius:50%;background:var(--accent);margin-top:6px;}+ .change-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:3px;flex-wrap:wrap;}+ .change-title{font-weight:650;color:var(--text-bright);}+ .change-kind{font-size:10px;text-transform:uppercase;letter-spacing:.12em;color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);padding:2px 6px;border-radius:999px;}+ .change-detail{font-size:12.5px;color:var(--text-dim);margin-top:3px;}+ .change-rationale{font-size:12.4px;color:var(--text);margin-top:8px;padding:9px 11px;border:1px solid var(--accent-border);background:var(--accent-bg);border-radius:4px;}+ .change-rationale strong{color:var(--text-bright);}+ .diagram-block{margin-top:14px;padding-top:13px;border-top:1px solid var(--border);}+ .diagram-title{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-dim);margin-bottom:8px;}+ .diagram-canvas{display:flex;justify-content:center;overflow:auto;min-height:90px;padding:12px;background:var(--surface2);border:1px solid var(--border);border-radius:6px;}+ .diagram-canvas svg{max-width:100%;height:auto;}+ .diagram-source{margin-top:8px;font-size:11px;color:var(--text-dim);}+ .diagram-source summary{cursor:pointer;color:var(--accent);}+ .diagram-source pre{font-size:11px;background:var(--surface2);border:1px solid var(--border);border-radius:6px;padding:10px;white-space:pre-wrap;word-break:break-word;overflow-x:auto;color:var(--text-bright);}+ .diagram-fallback-note{display:none;margin-top:8px;color:var(--warn);font-size:12px;}+ .diagram-unavailable .diagram-fallback-note{display:block;}+ .empty{color:var(--text-dim);font-size:13px;padding:18px 20px;background:var(--surface);border:1px dashed var(--border);border-radius:var(--radius);}+ ul{list-style:none;padding:0;margin:0;}+ .item{display:grid;grid-template-columns:18px minmax(0,1fr) auto;gap:12px;align-items:start;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:15px 18px;margin-bottom:10px;box-shadow:var(--shadow);}+ .bullet{width:16px;height:16px;border-radius:50%;border:2px solid var(--border-light);display:inline-block;margin-top:2px;}+ .item-copy { display: flex; flex: 1; flex-direction: column; gap: 2px; }+ .item-note{color:var(--text-dim);font-size:12px;}+ .item-status{color:var(--text-dim);font-size:11px;text-transform:uppercase;font-weight:600;letter-spacing:.3px;white-space:nowrap;}+ .item.active{border-color:var(--accent-border);background:var(--accent-bg);}+ .item.active .bullet{border-color:var(--accent);border-right-color:transparent;animation:spin 1s linear infinite;}+ .item.waiting{border-color:var(--warn-border);background:var(--warn-bg);}+ .item.waiting .bullet{border-color:var(--warn);background:var(--warn);}+ .item.done .bullet{border-color:var(--pass);background:var(--pass);}+ .item.failed{border-color:var(--fail-border);background:var(--fail-bg);}+ .item.failed .bullet{border-color:var(--fail);background:var(--fail);}+ .item.active .item-copy>span:first-child,.item.waiting .item-copy>span:first-child{color:var(--text-bright);font-weight:650;}+ .item.done .item-copy>span:first-child{color:var(--pass);}+ .item.skipped{opacity:.6;}+ @keyframes spin{to{transform:rotate(360deg);}}+ .device-rail{width:420px;flex-shrink:0;position:sticky;top:var(--topbar-h, 65px);height:calc(100vh - var(--topbar-h, 65px) - var(--footer-h));display:flex;flex-direction:column;align-items:center;justify-content:safe center;gap:14px;padding:24px 20px;overflow-y:auto;border-left:1px solid var(--border);background:var(--surface);}+ .device-rail-label{font-size:11px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;}+ /* The phone gives up height before the other rail items. Below 360px the rail scrolls instead,+ because a smaller frame cannot keep the QR handoff readable. */+ .device{flex:0 1 620px;min-height:360px;max-height:620px;width:auto;max-width:calc(100vw - 44px);aspect-ratio:300/620;border-radius:40px;background:#1f1f1f;border:9px solid #2e2e2e;box-shadow:var(--shadow),0 18px 46px rgba(0,0,0,.22);position:relative;overflow:hidden;}+ .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:2;}+ .device-screen{position:absolute;inset:0;background:#faf9f8;overflow:hidden;container-type:size;}+ .device-building,.device-qr{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:0 26px;}+ .device-carousel,.device-carousel-frame{position:absolute;inset:0;overflow:hidden;background:#fff;}+ .device-carousel-frame iframe{position:absolute;width:375px;height:812px;border:0;transform-origin:top left;}+ .device-controls{width:300px;display:flex;align-items:center;justify-content:space-between;gap:8px;}+ .device-controls[hidden]{display:none;}+ .carousel-btn{width:30px;height:30px;border-radius:50%;border:1px solid var(--border);background:var(--surface);color:var(--text-bright);font-size:18px;cursor:pointer;display:grid;place-items:center;box-shadow:var(--shadow);}+ .carousel-btn:disabled{opacity:.35;cursor:default;}+ .carousel-dots{display:flex;gap:5px;}+ .carousel-dot{width:6px;height:6px;border-radius:50%;background:var(--border-light);}+ .carousel-dot.on{background:var(--accent);}+ .device-building{gap:22px;}+ .device-orbit{position:relative;width:132px;height:132px;display:grid;place-items:center;}+ .device-orbit span{position:absolute;border:1px solid rgba(32,31,30,.14);border-radius:50%;animation:device-spin linear infinite;}+ .device-orbit span:first-child{width:96px;height:96px;animation-duration:9s;}+ .device-orbit span:nth-child(2){width:132px;height:132px;animation-duration:16s;animation-direction:reverse;border-style:dashed;}+ .device-orbit img{width:62px;height:62px;animation:device-float 4s ease-in-out infinite;}+ .device-failed .device-orbit span{border-color:var(--fail-border);animation-play-state:paused;}+ @keyframes device-spin{to{transform:rotate(360deg);}}+ @keyframes device-float{0%,100%{transform:translateY(0);}50%{transform:translateY(-6px);}}+ .device-title{font-size:16px;font-weight:700;color:var(--text-bright);}+ .device-copy{font-size:12.5px;color:var(--text-dim);line-height:1.55;}+ .device-progress{width:100%;height:4px;border-radius:4px;background:#eceaea;overflow:hidden;}+ .device-progress span{display:block;height:100%;background:var(--accent);}+ .device-qr{justify-content:safe center;gap:16px;background:#fff;padding:30px 22px 18px;}+ .device-qr img{flex:0 1 196px;min-height:84px;max-height:196px;width:auto;max-width:100%;aspect-ratio:1/1;object-fit:contain;}+ .device-url{font-family:'Cascadia Code','Consolas',monospace;font-size:11px;color:var(--accent);word-break:break-all;}+ .device-caption{font-size:12px;color:var(--text-dim);text-align:center;max-width:320px;min-height:38px;}+ .rail-actions{display:flex;flex-direction:column;align-items:center;gap:6px;max-width:100%;}+ .rail-link{display:inline-flex;align-items:center;font-size:12.5px;color:var(--accent);text-decoration:none;padding:6px 12px;border-radius:999px;border:1px solid transparent;}+ .rail-link:hover{border-color:var(--accent-border);background:var(--accent-bg);}+ .store-row{display:flex;gap:8px;justify-content:center;}+ .store-btn{display:flex;flex-direction:column;padding:7px 13px;border-radius:9px;background:#000;color:#fff;text-decoration:none;line-height:1.05;border:1px solid rgba(255,255,255,.22);min-width:122px;}+ .store-btn:hover{background:#141414;}+ .store-kicker{font-size:8.5px;letter-spacing:.03em;opacity:.9;}+ .store-btn strong{font-size:14px;font-weight:600;}+ @container (max-height:520px){.device-qr{gap:8px;padding:28px 12px 14px;}.device-qr .device-title{font-size:14px;}.device-qr .device-copy{font-size:11px;line-height:1.4;}.device-url{font-size:10px;}}+ .ai-footer{position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:var(--text-dim);border-top:1px solid var(--border);background:var(--surface);z-index:10;}+ @media(max-width:1180px){+ .shell{flex-direction:column;}+ .device-rail{width:100%;position:static;height:auto;border-left:0;border-top:1px solid var(--border);padding-bottom:72px;}+ .device{flex:none;height:auto;min-height:0;width:min(300px,calc(100vw - 44px));}+ }+ @media(max-width:720px){+ .topbar{padding:12px 16px;}+ .layout{flex-direction:column;}+ .sidebar{width:100%;display:flex;padding:8px;border-right:0;border-bottom:1px solid var(--border);position:sticky;top:64px;z-index:9;}+ .nav-label{display:none;}+ .nav-btn{width:auto;border-left:0;border-bottom:2px solid transparent;padding:10px 14px;}+ .nav-btn.active{border-left:0;border-bottom-color:var(--accent);}+ .content{padding:24px 18px 60px;}+ .topbar-right{width:100%;}+ }+ </style>+</head>+<body>+ <header class="topbar">+ <div class="topbar-left">+ <img class="logo" src="${brandIconDataUri()}" alt="Power Apps" />+ <div>+ <div class="topbar-title">Mobile app edit plan</div>+ <div class="topbar-sub">+ <span>${escapeHtml(appName)}</span><span class="topbar-sep">|</span>+ <span>Updated ${escapeHtml(generatedAt)} UTC</span>+ </div>+ </div>+ </div>+ <div class="topbar-right">+ ${phasePill}+ <span class="pill ${status === 'done' ? 'pill-done' : status === 'failed' ? 'pill-failed' : ''}">${escapeHtml(status)}</span>+ <span class="pill">${completed} of ${items.length} complete</span>+ </div>+ </header>+ ${waitingBanner}+ <div class="shell">+ <div class="layout">+ <nav class="sidebar" aria-label="Edit plan">+ <div class="nav-label">Edit plan</div>+ <button class="nav-btn active" type="button" role="tab" aria-selected="true" data-tab="changes"><span class="nav-icon">✎</span> Changes</button>+ <button class="nav-btn" type="button" role="tab" aria-selected="false" data-tab="steps"><span class="nav-icon">▦</span> Build steps</button>+ </nav>+ <main class="content">+ <section class="section active" id="tab-changes" role="tabpanel">+ <h1>Changes</h1>+ <div class="section-desc">The requested app updates and the activity currently in progress.</div>+ <div class="summary">+ <div class="note">${escapeHtml(note)}</div>+ <div class="status-line">+ <span>Current phase: <strong>${escapeHtml(displayPhase)}</strong></span>+ <span>${completed} of ${items.length} operations complete${failed ? `, ${failed} failed` : ''}</span>+ </div>+ <div class="progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${percent}">+ <span class="progress-bar"></span>+ </div>+ </div>+ ${changeCards}+ </section>+ <section class="section" id="tab-steps" role="tabpanel" hidden>+ <h1>Build steps</h1>+ <div class="section-desc">Live progress for each operation in the approved edit plan.</div>+ <ul>${rows}</ul>+ </section>+ </main>+ </div>+ <aside class="device-rail${previewLink || qrLink || storeButtons ? ' has-actions' : ''}" aria-label="Device preview">+ <div class="device-rail-label">${qrImage ? 'Test the edited app' : previewHtml ? 'Your screens' : 'Device preview'}</div>+ <div class="device">+ <div class="device-notch"></div>+ <div class="device-screen">${deviceContent}</div>+ </div>+ <div class="device-controls" id="deviceControls" ${previewHtml ? '' : 'hidden'}>+ <button class="carousel-btn" id="previousScreen" type="button" aria-label="Previous screen">‹</button>+ <div class="carousel-dots" id="screenDots"></div>+ <button class="carousel-btn" id="nextScreen" type="button" aria-label="Next screen">›</button>+ </div>+ <div class="device-caption" id="deviceCaption">${escapeHtml(deviceCaption)}</div>+ <div class="rail-actions">${previewLink}${qrLink}${storeButtons}</div>+ </aside>+ </div>+ <footer class="ai-footer">AI-generated content may be incorrect</footer>+ <script nonce="${nonce}">+ (function () {+ var phonePreviewHtml = ${inlineJson(previewHtml)};+ var STORE_TAB = 'mobile-edit-plan-tab';+ var STORE_SCROLL = 'mobile-edit-plan-scroll';+ // The page republishes itself every few seconds, so a dismissal held only in memory would+ // reappear on the next reload. Keying it to the prompt text means closing one gate's pill does+ // not suppress the next gate's.+ var STORE_DISMISSED = 'mobile-edit-plan-dismissed-prompt';+ var banner = document.getElementById('inputBanner');+ var bannerPrompt = banner ? banner.getAttribute('data-prompt') || '' : '';+ // The topbar wraps its pills onto a second row in a narrow window, so a fixed offset would+ // park the pill on top of them. Track the rendered height instead.+ function syncTopbarHeight() {+ var topbar = document.querySelector('.topbar');+ if (!topbar) return;+ document.documentElement.style.setProperty('--topbar-h', topbar.getBoundingClientRect().height + 'px');+ }+ syncTopbarHeight();+ window.addEventListener('resize', syncTopbarHeight, { passive: true });+ try {+ if (!bannerPrompt) {+ sessionStorage.removeItem(STORE_DISMISSED);+ } else if (banner && sessionStorage.getItem(STORE_DISMISSED) === bannerPrompt) {+ banner.hidden = true;+ }+ } catch (error) { /* private mode; the pill simply stays visible */ }+ if (banner) {+ document.getElementById('inputBannerClose').addEventListener('click', function () {+ banner.hidden = true;+ try { sessionStorage.setItem(STORE_DISMISSED, bannerPrompt); } catch (error) { /* private mode */ }+ });+ }+ var MOCKUP_BANNED_TAGS = ['SCRIPT', 'IFRAME', 'OBJECT', 'EMBED', 'LINK', 'META', 'BASE',+ 'FORM', 'STYLE', 'ANIMATE', 'SET'];+ var MOCKUP_BANNED_URL = /^(javascript:|data:text\\/html)/i;+ function sanitizeMockup(markup, options) {+ var source = new DOMParser().parseFromString(String(markup || ''), 'text/html');+ Array.from(source.querySelectorAll('*')).forEach(function (node) {+ var tag = String(node.tagName || '').toUpperCase();+ if (MOCKUP_BANNED_TAGS.indexOf(tag) >= 0 && !(options.keepStyle && tag === 'STYLE')) {+ node.remove();+ return;+ }+ Array.from(node.attributes).forEach(function (attribute) {+ var name = attribute.name;+ var value = attribute.value.replace(/[\\u0000-\\u0020]/g, '');+ if (/^on/i.test(name)+ || (/^(href|xlink:href)$/i.test(name) && value.charAt(0) !== '#')+ || (/^(href|src|xlink:href|action|formaction)$/i.test(name)+ && MOCKUP_BANNED_URL.test(value))) {+ node.removeAttribute(name);+ }+ });+ });+ return source;+ }+ function previewScreens(markup) {+ var source = sanitizeMockup(markup, { keepStyle: 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');+ 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 policy = document.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'");+ head.prepend(policy);+ 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 renderScreenCarousel() {+ if (!phonePreviewHtml) return;+ var screens = previewScreens(phonePreviewHtml);+ // Older preview files can include the untouched template home route before the generated+ // app screens. Keep it only when it is the sole screen, otherwise it misrepresents the app.+ var appScreens = screens.filter(function (screen) {+ return !(screen.html.includes('Power Apps Standalone')+ && screen.html.includes('Build your first screen by connecting data sources'));+ });+ if (appScreens.length) screens = appScreens;+ var frame = document.querySelector('.device-carousel-frame');+ var viewport = document.getElementById('devicePreviewFrame');+ var caption = document.getElementById('deviceCaption');+ var controls = document.getElementById('deviceControls');+ if (!frame || !viewport || !screens.length) {+ if (caption) caption.textContent = 'Screen preview unavailable. Regenerate preview.html.';+ if (controls) controls.hidden = true;+ return;+ }+ var index = 0;+ var previous = document.getElementById('previousScreen');+ var next = document.getElementById('nextScreen');+ var dots = document.getElementById('screenDots');+ function fit() {+ 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';+ }+ function show(nextIndex) {+ index = Math.max(0, Math.min(screens.length - 1, nextIndex));+ viewport.title = screens[index].name || 'Screen preview';+ viewport.srcdoc = screens[index].html;+ caption.textContent = (screens[index].name ? screens[index].name + ' · ' : '')+ + (index + 1) + ' of ' + screens.length;+ previous.disabled = index === 0;+ next.disabled = index === screens.length - 1;+ dots.textContent = '';+ screens.forEach(function (unused, screenIndex) {+ var dot = document.createElement('span');+ dot.className = 'carousel-dot' + (screenIndex === index ? ' on' : '');+ dots.appendChild(dot);+ });+ }+ previous.addEventListener('click', function () { show(index - 1); });+ next.addEventListener('click', function () { show(index + 1); });+ fit();+ window.addEventListener('resize', fit, { passive: true });+ if (typeof ResizeObserver !== 'undefined') new ResizeObserver(fit).observe(frame);+ show(0);+ }+ renderScreenCarousel();+ var diagramBlocks = Array.from(document.querySelectorAll('.diagram-block'));+ function markDiagramUnavailable(block) {+ block.classList.add('diagram-unavailable');+ }+ if (diagramBlocks.length) {+ if (window.mermaid) {+ window.mermaid.initialize({+ startOnLoad: false,+ securityLevel: 'strict',+ theme: 'base',+ themeVariables: {+ primaryColor: '#f3f2f1',+ primaryTextColor: '#201f1e',+ primaryBorderColor: '#c8c6c4',+ lineColor: '#605e5c',+ tertiaryColor: '#ffffff',+ fontFamily: 'Segoe UI, sans-serif'+ }+ });+ diagramBlocks.forEach(function (block, index) {+ var canvas = block.querySelector('.diagram-canvas');+ var source = block.querySelector('.diagram-source pre').textContent;+ window.mermaid.render('editDiagram' + index, source).then(function (result) {+ // The source is derived from allowlisted structured fields and Mermaid runs in strict+ // security mode, so its SVG output is the only HTML admitted into this local page.+ canvas.innerHTML = result.svg;+ }).catch(function () {+ markDiagramUnavailable(block);+ });+ });+ } else {+ diagramBlocks.forEach(markDiagramUnavailable);+ }+ }+ function showTab(tab) {+ document.querySelectorAll('.nav-btn').forEach(function (button) {+ var selected = button.dataset.tab === tab;+ button.classList.toggle('active', selected);+ button.setAttribute('aria-selected', String(selected));+ });+ document.querySelectorAll('.section').forEach(function (section) {+ var selected = section.id === 'tab-' + tab;+ section.classList.toggle('active', selected);+ section.hidden = !selected;+ });+ }+ document.querySelectorAll('.nav-btn').forEach(function (button) {+ button.addEventListener('click', function () {+ showTab(button.dataset.tab);+ try { sessionStorage.setItem(STORE_TAB, button.dataset.tab); } catch (error) { /* private mode */ }+ });+ });+ window.addEventListener('beforeunload', function () {+ try { sessionStorage.setItem(STORE_SCROLL, String(window.scrollY)); } catch (error) { /* private mode */ }+ });+ try {+ var savedTab = sessionStorage.getItem(STORE_TAB);+ if (savedTab) showTab(savedTab);+ var savedScroll = Number(sessionStorage.getItem(STORE_SCROLL) || 0);+ if (savedScroll > 0) window.scrollTo(0, savedScroll);+ } catch (error) { /* sessionStorage unavailable; Changes stays selected */ }+ ${autoRefresh}+ }());+ </script>+</body>+</html>`;++ publishAtomic(filePath, html);+ return filePath;+}++function syncPlanToCurrentApp(projectRoot, options = {}) {+ const root = path.resolve(projectRoot);+ const existing = loadState(root);+ const sections = options.sections || (+ options.section && options.value !== undefined ? { [options.section]: options.value } : {}+ );+ const sectionEntries = Object.entries(sections);+ const requestedAppName = options.appName || (sections.requirements || {}).appName;+ const requestedDataPlatform = options.dataPlatform || (sections.architecture || {}).dataPlatform+ || (sections.requirements || {}).dataPlatform;+ if (!existing && sectionEntries.length === 0) {+ throw new Error('A missing plan requires structured current-app sections; refusing a generic shell.');+ }++ const state = existing || initState(root, {+ appName: requestedAppName || 'Your app',+ dataPlatform: requestedDataPlatform || 'unknown',+ });+ if (requestedAppName) state.appName = String(requestedAppName);+ if (requestedDataPlatform) state.dataPlatform = String(requestedDataPlatform);+ state.sections = state.sections || {};+ state.sectionStates = state.sectionStates || {};++ // Each supplied section is a current-state snapshot, not a patch. Replacing it is what lets an+ // edit remove a screen, connector, capability, or table instead of leaving stale rows behind.+ for (const [name, value] of sectionEntries) {+ if (!SECTIONS.has(name)) {+ throw new Error(`Unknown section '${name}'. Known: ${[...SECTIONS].join(', ')}`);+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ throw new Error(`Section '${name}' must be a JSON object`);+ }+ state.sections[name] = value;+ const requestedState = (options.sectionStates || {})[name] || options.state || 'approved';+ if (!SECTION_STATES.has(requestedState)) {+ throw new Error(`Unknown state '${requestedState}'. Known: ${[...SECTION_STATES].join(', ')}`);+ }+ state.sectionStates[name] = requestedState;+ }++ if (!existing || options.inferred === true) {+ const requirements = state.sections.requirements || {};+ state.sections.requirements = {+ ...requirements,+ appName: requirements.appName || state.appName,+ dataPlatform: requirements.dataPlatform || state.dataPlatform,+ source: requirements.source || 'existing app state',+ inferred: true,+ summary: requirements.summary || options.summary+ || 'Plan inferred from existing app state because no prior create-run plan was present.',+ };+ state.sectionStates.requirements = 'approved';+ }++ if (!existing) {+ for (const phase of state.phases) {+ const notApplicable = state.dataPlatform === 'connector-only'+ && (phase.id === 'data-model' || phase.id === 'dataverse');+ phase.status = notApplicable ? 'skipped' : 'done';+ phase.note = notApplicable ? 'Not used by this app' : 'Inferred from the existing app';+ }+ }++ state.lastEdit = {+ summary: options.summary || '',+ syncedAt: new Date().toISOString(),+ sections: sectionEntries.map(([name]) => name),+ };+ state.updatedAt = new Date().toISOString();+ save(root, state);+ return outputPath(root);+}+/*** The brand mark as a `data:` URI.*@@ -442,7 +1522,12 @@ function parseArgs(argv) {else if (argument === '--id') options.id = argv[++index];else if (argument === '--status') options.status = argv[++index];else if (argument === '--note') options.note = argv[++index];+ else if (argument === '--phase') options.phase = argv[++index];+ else if (argument === '--summary') options.summary = argv[++index];+ else if (argument === '--waiting') options.waiting = true;+ else if (argument === '--checklist') options.checklist = JSON.parse(argv[++index]);else if (argument === '--section') options.section = argv[++index];+ else if (argument === '--value') options.value = JSON.parse(argv[++index]);else if (argument === '--json') options.json = argv[++index];else if (argument === '--json-file') options.jsonFile = argv[++index];else if (argument === '--state') options.state = argv[++index];@@ -461,7 +1546,7 @@ function parseArgs(argv) {}options.workingDir = options.workingDir || process.cwd();options.command = options.command || 'show';- if (!['init', 'step', 'show', 'set', 'phone'].includes(options.command)) {+ if (!['init', 'step', 'show', 'set', 'phone', 'progress', 'sync', 'temp'].includes(options.command)) {throw new Error(`Unknown command: ${options.command}`);}return options;@@ -475,6 +1560,14 @@ if (require.main === module) {if (options.command === 'show') {const state = loadState(root);process.stdout.write(`${JSON.stringify(state ? summarize(state) : { total: 0, done: 0 })}\n`);+ } else if (options.command === 'temp') {+ const directory = prepareEditTempDir(root);+ process.stdout.write(`${JSON.stringify({+ directory,+ progress: path.join(directory, 'edit-app-progress.json'),+ progressHtml: path.join(directory, 'edit-app-progress.html'),+ sync: path.join(directory, 'app-plan-sync.json'),+ })}\n`);} else if (options.command === 'init') {// `--app-name` is the display name the user typed, so it may contain a quote, a backtick// or `$(...)`. Passed as a shell argument those break out of the quoting before Node ever@@ -486,6 +1579,31 @@ if (require.main === module) {: options;const written = save(root, initState(root, seed));process.stdout.write(`${JSON.stringify({ status: 'ok', plan: written })}\n`);+ } else if (options.command === 'progress') {+ const payload = options.jsonFile+ ? JSON.parse(fs.readFileSync(options.jsonFile, 'utf8'))+ : {+ phase: options.phase,+ status: options.status,+ note: options.note,+ waiting: options.waiting,+ checklist: options.checklist,+ };+ const filePath = writeEditProgress(root, payload);+ process.stdout.write(`${JSON.stringify({ status: 'ok', file: filePath })}\n`);+ } else if (options.command === 'sync') {+ const payload = options.jsonFile+ ? JSON.parse(fs.readFileSync(options.jsonFile, 'utf8'))+ : {+ appName: options.appName,+ dataPlatform: options.dataPlatform,+ summary: options.summary,+ section: options.section,+ value: options.value,+ state: options.state,+ };+ const result = syncPlanToCurrentApp(root, payload);+ process.stdout.write(`${JSON.stringify({ status: 'ok', plan: result })}\n`);} else if (options.command === 'phone') {const state = loadState(root);if (!state) throw new Error('No run plan yet; run `init` first.');@@ -498,6 +1616,11 @@ if (require.main === module) {// 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.');+ const previewPath = path.resolve(options.previewFile);+ const relative = path.relative(docsDir(root), previewPath);+ // Keep the living plan portable with a relative link; the temp-hosted edit page converts+ // it back to a file URL because it does not share the project's directory.+ update.previewHref = relative.split(path.sep).join('/');}if (options.screensFile) {update.screens = JSON.parse(fs.readFileSync(options.screensFile, 'utf8'));@@ -545,6 +1668,8 @@ module.exports = {STATE_FILE,applyStep,docsDir,+ editTempDir,+ prepareEditTempDir,initState,loadState,outputPath,@@ -554,6 +1679,10 @@ module.exports = {setPhone,setSection,summarize,+ syncPlanToCurrentApp,+ writeEditProgress,+ EDIT_ITEM_STATUSES,+ EDIT_PROGRESS_STATUSES,PHONE_STAGES,SECTIONS,};diff --git a/plugins/mobile-apps/scripts/tests/app-docs.test.js b/plugins/mobile-apps/scripts/tests/app-docs.test.jsindex cec8d9304..52a95b2c0 100644--- a/plugins/mobile-apps/scripts/tests/app-docs.test.js+++ b/plugins/mobile-apps/scripts/tests/app-docs.test.js@@ -8,8 +8,9 @@ const path = require('node:path');const test = require('node:test');const {- PHASES, PHONE_STAGES, SECTIONS, applyStep, initState, loadState, outputPath, save, setPhone,- setSection, summarize,+ EDIT_ITEM_STATUSES, PHASES, PHONE_STAGES, SECTIONS, applyStep, initState, loadState, outputPath,+ save, setPhone, setSection, summarize, syncPlanToCurrentApp, writeEditProgress, editTempDir,+ prepareEditTempDir,} = require('../app-docs');const scriptPath = path.resolve(__dirname, '..', 'app-docs.js');@@ -205,6 +206,637 @@ test('the CLI refuses a step before init and reports the reason', () => {assert.equal(JSON.parse(set.stdout.trim()).section, 'auth');});+test('edit temp paths are stable, private, and reject redirected namespaces', (t) => {+ const root = project('docs-edit-temp');+ const directory = prepareEditTempDir(root);+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));++ assert.equal(prepareEditTempDir(root), directory, 'separate invocations must reuse the namespace');+ assert.equal(fs.lstatSync(directory).isSymbolicLink(), false);+ if (process.platform !== 'win32') {+ assert.equal(path.basename(path.dirname(directory)), `power-platform-mobile-app-uid-${process.getuid()}`,+ 'shared POSIX temp roots need one private parent per user');+ assert.equal(fs.statSync(directory).mode & 0o077, 0, 'project namespace must be owner-only');+ assert.equal(fs.statSync(path.dirname(directory)).mode & 0o077, 0,+ 'stable parent namespace must be owner-only');+ }++ const redirectedTarget = project('docs-edit-temp-target');+ fs.rmSync(directory, { recursive: true, force: true });+ fs.symlinkSync(redirectedTarget, directory, process.platform === 'win32' ? 'junction' : 'dir');+ assert.throws(() => prepareEditTempDir(root), /Refusing unsafe temporary directory/);+ fs.rmSync(directory, { force: true });+ fs.rmSync(redirectedTarget, { recursive: true, force: true });+});++test('edit progress renders each operation state and settles when work completes', (t) => {+ const root = project('docs-edit-progress');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));+ const progress = writeEditProgress(root, {+ phase: 'planning',+ note: 'Waiting for your approval',+ waiting: true,+ changes: [+ {+ kind: 'data-model',+ title: 'Add inspection evidence',+ detail: 'Introduce a child table for captured evidence.',+ rationale: 'Evidence needs its own lifecycle and can contain multiple files per inspection.',+ dataModel: {+ tables: [+ {+ name: 'Inspection',+ columns: [{ name: 'inspectionid', type: 'guid', primaryKey: true }],+ },+ {+ name: 'Evidence',+ columns: [+ { name: 'evidenceid', type: 'guid', primaryKey: true },+ { name: 'inspectionid', type: 'guid', foreignKey: true },+ ],+ },+ ],+ relationships: [+ {+ from: 'Inspection',+ to: 'Evidence',+ cardinality: 'one-to-many',+ label: 'contains',+ },+ ],+ },+ },+ {+ kind: 'screen',+ title: 'Add inspection detail',+ detail: 'Introduce a detail route for each inspection.',+ rationale: 'Inspectors need one place to review findings and open captured evidence.',+ screenGraph: {+ screens: [+ { id: 'list', name: 'Inspections', route: '/inspections' },+ { id: 'detail', name: 'Inspection detail', route: '/inspections/[id]' },+ ],+ edges: [{ from: 'list', to: 'detail', label: 'Select inspection' }],+ },+ },+ ],+ items: [+ { id: 'inspect', label: 'Inspect app', status: 'done' },+ { id: 'approve', label: 'Approve changes', status: 'waiting', note: 'Review the plan delta' },+ { id: 'screens', label: 'Update screens', status: 'pending' },+ ],+ });+ assert.ok(fs.existsSync(progress));+ const html = fs.readFileSync(progress, 'utf8');+ assert.match(html, /Mobile app edit plan/);+ assert.match(html, /data-tab="changes"/);+ assert.match(html, /data-tab="steps"/);+ assert.match(html, /Add inspection detail/);+ assert.match(html, /Why this matters:/);+ assert.match(html, /Evidence needs its own lifecycle/);+ assert.match(html, /class="diagram-canvas" role="img" aria-label="Proposed data model diagram"/);+ assert.match(html, /<pre>erDiagram/);+ assert.match(html, /Inspection \|\|--o\{ Evidence : "contains"/);+ assert.match(html, /aria-label="Proposed screen navigation graph"/);+ assert.match(html, /<pre>flowchart LR/);+ assert.match(html, /S_list -->\|"Select inspection"\| S_detail/);+ assert.match(html, /mermaid@11\.17\.2/);+ assert.match(html, /window\.mermaid\.render/);+ assert.doesNotMatch(html, /<pre class="change-diagram">/);+ assert.match(html, /AI-generated content may be incorrect/);+ assert.match(html, /class="device-rail"/);+ assert.match(html, /Waiting for approval/);+ assert.match(html, /The phone preview follows the current edit step/);+ assert.doesNotMatch(html, /Scan to test the changes/);+ assert.match(html, /Waiting for your input/);+ assert.ok(+ html.indexOf('class="input-banner"') < html.indexOf('<div class="shell">'),+ 'the pill must sit outside both tab panels so it stays visible on Build steps',+ );+ assert.match(html, /position:fixed;top:calc\(var\(--topbar-h, 65px\) \+ 13px\);right:24px/);+ assert.match(html, /id="inputBannerClose"/);+ assert.match(html, /class="item done" data-item-id="inspect"/);+ assert.match(html, /class="item waiting" data-item-id="approve"/);+ assert.match(html, /1 of 3 operations complete/);+ assert.match(html, /aria-valuenow="33"/);+ assert.match(html, /location\.replace\(fresh\)/);+ assert.match(html, /sessionStorage\.setItem\(STORE_SCROLL/);+ assert.match(html, /sessionStorage\.getItem\(STORE_SCROLL/);+ assert.match(html, /window\.scrollTo\(0, savedScroll\)/);+ assert.match(html, /Waiting for your approval/);++ seeded(root);+ const state = loadState(root);+ setPhone(state, {+ stage: 'qr',+ qrImage: 'data:image/png;base64,iVBORw0KGgo=',+ qrUrl: 'exp://192.168.1.4:8081',+ });+ save(root, state);+ writeEditProgress(root, {+ phase: 'done',+ status: 'done',+ note: 'Edit verified',+ devicePreviewReady: true,+ items: [+ { id: 'inspect', label: 'Inspect app', status: 'done' },+ { id: 'approve', label: 'Approve changes', status: 'done' },+ { id: 'screens', label: 'Update screens', status: 'done' },+ ],+ });+ const completedHtml = fs.readFileSync(progress, 'utf8');+ assert.doesNotMatch(completedHtml, /location\.replace\(fresh\)/);+ assert.match(completedHtml, /sessionStorage\.getItem\(STORE_SCROLL/);+ assert.match(completedHtml, /window\.scrollTo\(0, savedScroll\)/);+ assert.match(completedHtml, /Scan to test the changes/);+ assert.match(completedHtml, /data:image\/png;base64,iVBORw0KGgo=/);+ assert.match(completedHtml, /exp:\/\/192\.168\.1\.4:8081/);+ assert.match(completedHtml, /Edits hot-reload onto the device/);+ assert.doesNotMatch(completedHtml, /pill-phase">done</);++ writeEditProgress(root, {+ phase: 'done',+ status: 'done',+ note: 'Edit verified without a current device preview',+ devicePreviewReady: false,+ items: [+ { id: 'inspect', label: 'Inspect app', status: 'done' },+ { id: 'approve', label: 'Approve changes', status: 'done' },+ { id: 'screens', label: 'Update screens', status: 'done' },+ ],+ });+ const unavailableHtml = fs.readFileSync(progress, 'utf8');+ assert.match(unavailableHtml, /Device preview unavailable/);+ assert.doesNotMatch(unavailableHtml, /Scan to test the changes/);+ assert.doesNotMatch(unavailableHtml, /data:image\/png;base64,iVBORw0KGgo=/);++ assert.ok(EDIT_ITEM_STATUSES.has('waiting'));+ assert.throws(() => writeEditProgress(root, {+ items: [{ id: 'inspect', label: 'Inspect app', status: 'unknown' }],+ }), /Unknown progress item status/);+ assert.throws(() => writeEditProgress(root, {+ status: 'pending',+ items: [{ id: 'inspect', label: 'Inspect app', status: 'pending' }],+ }), /Unknown edit progress status/);+ assert.throws(() => writeEditProgress(root, {+ changes: [{ detail: 'Missing title' }],+ }), /requires a title/);+ assert.throws(() => writeEditProgress(root, {+ changes: [{ title: 'Missing rationale', kind: 'general' }],+ }), /requires a rationale/);+ assert.throws(() => writeEditProgress(root, {+ changes: [{+ title: 'Disconnected screens',+ rationale: 'Add a detail route.',+ kind: 'screen',+ screenGraph: {+ screens: [{ id: 'list', name: 'List' }, { id: 'detail', name: 'Detail' }],+ edges: [],+ },+ }],+ }), /requires navigation edges/);+ assert.throws(() => writeEditProgress(root, {+ changes: [{+ title: 'Raw diagram',+ rationale: 'Structured data must remain the source of truth.',+ kind: 'screen',+ mermaid: 'flowchart LR\nA --> B',+ screenGraph: {+ screens: [{ id: 'a', name: 'A' }],+ },+ }],+ }), /cannot carry raw diagram or Mermaid source/);+ for (const cardinality of ['constructor', '__proto__']) {+ assert.throws(() => writeEditProgress(root, {+ changes: [{+ title: 'Invalid relationship',+ rationale: 'Only allowlisted relationship shapes can render.',+ kind: 'data-model',+ dataModel: {+ tables: [{ name: 'A' }, { name: 'B' }],+ relationships: [{ from: 'A', to: 'B', cardinality }],+ },+ }],+ }), /Unknown data-model relationship cardinality/);+ }+ assert.throws(() => writeEditProgress(root, {+ changes: [{+ title: 'Nested raw diagram',+ rationale: 'Structured data must remain the source of truth.',+ kind: 'data-model',+ dataModel: {+ mermaid: 'erDiagram\nA ||--o{ B : contains',+ tables: [{ name: 'A' }],+ },+ }],+ }), /cannot carry raw diagram or Mermaid source/);+});++test('coarse progress follows the top-level phase when rows are omitted', (t) => {+ const root = project('docs-coarse-phase');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));++ const progress = writeEditProgress(root, {+ phase: 'approval',+ status: 'waiting',+ waiting: true,+ note: 'Waiting for approval of the proposed changes.',+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /class="item done" data-item-id="inspect"/);+ assert.match(html, /class="item waiting" data-item-id="plan"/);+ assert.doesNotMatch(html, /class="item active" data-item-id="inspect"/);+ assert.match(html, /1 of 5 operations complete/);+});++test('failed fallback progress marks the failed phase and skips later phases', (t) => {+ const root = project('docs-coarse-failed');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));++ const progress = writeEditProgress(root, {+ phase: 'verification',+ status: 'failed',+ note: 'Verification failed.',+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /class="item done" data-item-id="inspect"/);+ assert.match(html, /class="item done" data-item-id="plan"/);+ assert.match(html, /class="item done" data-item-id="apply"/);+ assert.match(html, /class="item failed" data-item-id="verify"/);+ assert.match(html, /class="item skipped" data-item-id="preview"/);+ assert.doesNotMatch(html, /class="item active" data-item-id="inspect"/);+});++test('explicit coarse progress preserves skipped operations', (t) => {+ const root = project('docs-explicit-coarse');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));+ const progress = writeEditProgress(root, {+ phase: 'verification',+ status: 'active',+ items: [+ { id: 'inspect', label: 'Inspect', status: 'done' },+ { id: 'plan', label: 'Plan', status: 'done' },+ { id: 'apply', label: 'Apply', status: 'skipped' },+ { id: 'verify', label: 'Verify', status: 'active' },+ { id: 'preview', label: 'Preview', status: 'skipped' },+ ],+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /class="item skipped" data-item-id="apply"/);+ assert.match(html, /class="item active" data-item-id="verify"/);+ assert.match(html, /class="item skipped" data-item-id="preview"/);+ assert.doesNotMatch(html, /class="item done" data-item-id="apply"/);+});++test('the device preview follows the active checklist operation', (t) => {+ const root = project('docs-device-phase');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));++ const progress = writeEditProgress(root, {+ phase: 'preview',+ status: 'active',+ items: [+ { id: 'inspect', label: 'Inspect the current app', status: 'done' },+ { id: 'plan', label: 'Plan the requested changes', status: 'done' },+ { id: 'apply', label: 'Apply the approved changes', status: 'done' },+ { id: 'verify', label: 'Verify the edited app', status: 'done' },+ { id: 'preview', label: 'Refresh the preview and app plan', status: 'active' },+ ],+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /Refreshing your preview/);+ assert.match(html, /The live preview and app plan are being updated/);+ assert.doesNotMatch(html, /Applying your changes/);+});++test('edit progress embeds preview screens and links to the full HTML', (t) => {+ const root = project('docs-device-screens');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));+ const preview = '<!doctype html><html><head><style>.screen{display:none}</style></head>'+ + '<body><button data-screen="screen-home">Home</button>'+ + '<div class="phone"><div class="screen" id="screen-home">Home screen</div></div></body></html>';+ fs.writeFileSync(path.join(root, 'preview.html'), preview);+ const state = initState(root, { appName: 'Field Readings' });+ save(root, setPhone(state, {+ stage: 'screens',+ previewHtml: preview,+ previewHref: '../preview.html',+ }));++ const progress = writeEditProgress(root, {+ phase: 'preview',+ status: 'active',+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /id="devicePreviewFrame"/);+ assert.match(html, /var phonePreviewHtml = /);+ assert.match(html, /Home screen/);+ assert.match(html, /Open screens full size/);+ assert.match(html, /file:\/\/.*preview\.html/);+ assert.match(html, /id="previousScreen"/);+ assert.doesNotMatch(html, /Scan to test the changes/);+});++test('embedded preview skips the untouched starter home when real screens exist', (t) => {+ const root = project('docs-preview-starter-home');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));+ seeded(root);+ const state = loadState(root);+ setPhone(state, {+ stage: 'screens',+ previewHtml: '<div class="screen" id="screen-home">'+ + '<h1>Power Apps Standalone</h1>'+ + '<p>Build your first screen by connecting data sources</p></div>'+ + '<div class="screen" id="screen-readings"><h1>Field Readings</h1></div>',+ });+ save(root, state);++ const progress = writeEditProgress(root, {+ phase: 'preview',+ status: 'active',+ items: [+ { id: 'inspect', label: 'Inspect', status: 'done' },+ { id: 'plan', label: 'Plan', status: 'done' },+ { id: 'apply', label: 'Apply', status: 'done' },+ { id: 'verify', label: 'Verify', status: 'done' },+ { id: 'preview', label: 'Preview', status: 'active' },+ ],+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /var appScreens = screens\.filter/);+ assert.match(html, /Build your first screen by connecting data sources/);+ assert.match(html, /if \(appScreens\.length\) screens = appScreens/);+});++test('the final QR replaces embedded screens and adds mobile app downloads', (t) => {+ const root = project('docs-device-qr');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, '.expo'), { recursive: true });+ fs.writeFileSync(path.join(root, 'preview.html'), '<div class="screen">Preview</div>');+ fs.writeFileSync(path.join(root, '.expo', 'metro-qr.png'), 'qr');+ const state = initState(root, { appName: 'Field Readings' });+ setPhone(state, {+ stage: 'screens',+ previewHtml: '<div class="screen">Preview</div>',+ previewHref: '../preview.html',+ });+ setPhone(state, {+ stage: 'qr',+ qrImage: 'data:image/png;base64,aW1hZ2U=',+ qrHref: '../.expo/metro-qr.png',+ qrUrl: 'exp://192.0.2.1:8081',+ });+ save(root, state);++ const progress = writeEditProgress(root, {+ phase: 'done',+ status: 'done',+ devicePreviewReady: true,+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /Scan to test the changes/);+ assert.doesNotMatch(html, /id="devicePreviewFrame"/);+ assert.match(html, /Open screens full size/);+ assert.match(html, /Open QR code full size/);+ assert.match(html, /Download Power Apps Mobile Preview/);+ assert.match(html, /App Store/);+ assert.match(html, /Google Play/);+ assert.match(html, /5 of 5 operations complete/);+});++test('screen diagram labels keep Expo dynamic route segments', () => {+ // Expo file-based routing names dynamic segments `[id]`, so these brackets are the+ // common case in a screen graph rather than an edge case. Dropping them rewrote the+ // route the maker reads (`/inspections/[id]` became `/inspections/ id`), so the+ // characters are escaped with Mermaid entity codes and must survive to the source.+ const root = project('docs-edit-routes');+ const progress = writeEditProgress(root, {+ changes: [{+ title: 'Add the inspection detail route',+ rationale: 'Inspectors open one record before capturing evidence against it.',+ kind: 'screen',+ screenGraph: {+ screens: [+ { id: 'list', name: 'Inspections', route: '/inspections' },+ { id: 'detail', name: 'Inspection detail', route: '/inspections/[id]' },+ ],+ edges: [{ from: 'list', to: 'detail', label: 'select {row}' }],+ },+ }],+ });+ const html = fs.readFileSync(progress, 'utf8');+ assert.match(html, /\/inspections\/#91;id#93;/);+ assert.match(html, /select #123;row#125;/);+ assert.doesNotMatch(html, /\/inspections\/ id/);+});++test('data-model diagrams do not invent columns when schema details are unknown', () => {+ const root = project('docs-data-model-unknown-columns');+ const progress = writeEditProgress(root, {+ changes: [{+ kind: 'data-model',+ title: 'Reuse account data',+ rationale: 'Use the existing account table.',+ dataModel: {+ tables: [{ logicalName: 'account' }],+ },+ }],+ });+ const html = fs.readFileSync(progress, 'utf8');++ assert.match(html, /account \{\n\n \}/);+ assert.doesNotMatch(html, /string id PK/);+});++test('diagram node IDs remain distinct when normalized names collide', () => {+ const root = project('docs-edit-id-collisions');+ const progress = writeEditProgress(root, {+ changes: [+ {+ title: 'Connect colliding routes',+ rationale: 'Both routes must remain visible as separate screens.',+ kind: 'screen',+ screenGraph: {+ screens: [+ { name: 'Hyphen route', route: '/a-b' },+ { name: 'Slash route', route: '/a/b' },+ ],+ edges: [{ from: '/a-b', to: '/a/b' }],+ },+ },+ {+ title: 'Relate colliding table names',+ rationale: 'Both tables must remain visible as separate entities.',+ kind: 'data-model',+ dataModel: {+ tables: [{ name: 'a-b' }, { name: 'a/b' }],+ relationships: [{ from: 'a-b', to: 'a/b', cardinality: 'one-to-many' }],+ },+ },+ ],+ });+ const html = fs.readFileSync(progress, 'utf8');+ assert.match(html, /S__a_b\["Hyphen route · \/a-b"\]/);+ assert.match(html, /S__a_b_2\["Slash route · \/a\/b"\]/);+ assert.match(html, /S__a_b --> S__a_b_2/);+ assert.match(html, /a_b \{/);+ assert.match(html, /a_b_2 \{/);+ assert.match(html, /a_b \|\|--o\{ a_b_2/);+});++test('edit progress is published atomically for the auto-refreshing browser', () => {+ const source = fs.readFileSync(scriptPath, 'utf8');+ assert.match(source, /publishAtomic\(filePath, html\);/);+ assert.doesNotMatch(source, /fs\.writeFileSync\(filePath, html/);+});++test('plan sync creates an inferred full snapshot and replaces changed sections', () => {+ const root = project('docs-edit-sync');+ const inferred = syncPlanToCurrentApp(root, {+ appName: 'Survey app',+ dataPlatform: 'dataverse',+ summary: 'Plan inferred from existing app state because no prior create-run plan was present.',+ sections: {+ architecture: {+ dataPlatform: 'dataverse',+ nativeCapabilities: [{ name: 'camera', reason: 'Capture evidence' }],+ connectors: [{ name: 'Office 365 Users', reason: 'Resolve inspectors' }],+ },+ dataModel: { tables: [{ logicalName: 'contoso_survey', status: 'reuse' }] },+ screens: { navigation: 'tabs', list: [{ name: 'Surveys', route: '/surveys' }] },+ design: { direction: 'Field utility', palette: [] },+ },+ });+ assert.equal(inferred, outputPath(root));+ const state = loadState(root);+ assert.equal(state.sections.requirements.source, 'existing app state');+ assert.equal(state.sectionStates.requirements, 'approved');+ assert.equal(state.sections.architecture.connectors[0].name, 'Office 365 Users');+ assert.equal(state.sections.dataModel.tables[0].logicalName, 'contoso_survey');+ assert.equal(state.sections.screens.list[0].route, '/surveys');+ assert.equal(summarize(state).percent, 100, 'an imported existing app must not look unbuilt');++ syncPlanToCurrentApp(root, {+ summary: 'Replaced the surveys screen with survey detail.',+ sections: {+ screens: { navigation: 'stack', list: [{ name: 'Survey detail', route: '/surveys/[id]' }] },+ },+ });+ const updated = loadState(root);+ assert.deepEqual(updated.sections.screens.list, [+ { name: 'Survey detail', route: '/surveys/[id]' },+ ]);+ assert.equal(updated.sections.architecture.connectors[0].name, 'Office 365 Users',+ 'unsupplied sections must remain intact');+ assert.deepEqual(updated.lastEdit.sections, ['screens']);++ const empty = project('docs-edit-sync-empty');+ assert.throws(() => syncPlanToCurrentApp(empty, { summary: 'Generic shell' }),+ /requires structured current-app sections/);+});++test('edit progress and plan sync CLI commands consume JSON files', (t) => {+ const root = project('docs-edit-cli');+ t.after(() => fs.rmSync(editTempDir(root), { recursive: true, force: true }));+ const progressPayload = path.join(root, 'progress.json');+ fs.writeFileSync(progressPayload, JSON.stringify({+ phase: 'verifying',+ status: 'active',+ note: 'Running TypeScript',+ items: [{ id: 'verify', label: 'Verify app', status: 'active' }],+ }));+ const progress = spawnSync(process.execPath, [+ scriptPath, '--working-dir', root, 'progress', '--json-file', progressPayload,+ ], { encoding: 'utf8' });+ assert.equal(progress.status, 0, progress.stderr);+ assert.match(fs.readFileSync(path.join(editTempDir(root), 'edit-app-progress.html'), 'utf8'),+ /Running TypeScript/);++ const syncPayload = path.join(root, 'sync.json');+ fs.writeFileSync(syncPayload, JSON.stringify({+ appName: 'Imported app',+ dataPlatform: 'connector-only',+ sections: {+ architecture: {+ dataPlatform: 'connector-only',+ nativeCapabilities: [],+ connectors: [{ name: 'SharePoint', reason: 'Existing list data' }],+ },+ screens: { navigation: 'tabs', list: [{ name: 'Home', route: '/' }] },+ },+ }));+ const sync = spawnSync(process.execPath, [+ scriptPath, '--working-dir', root, 'sync', '--json-file', syncPayload,+ ], { encoding: 'utf8' });+ assert.equal(sync.status, 0, sync.stderr);+ assert.equal(loadState(root).sections.architecture.connectors[0].name, 'SharePoint');+});++test('edit-app wires progress, imported-app inference, and final plan sync into the workflow', () => {+ const skill = fs.readFileSync(+ path.resolve(__dirname, '..', '..', 'skills', 'edit-app', 'SKILL.md'), 'utf8',+ ).replace(/\r\n/g, '\n');+ const previewSkill = fs.readFileSync(+ path.resolve(__dirname, '..', '..', 'skills', 'preview-screens', 'SKILL.md'), 'utf8',+ ).replace(/\r\n/g, '\n');+ assert.match(skill, /progress \\\n\s+--json-file '<edit-temp-dir>\/edit-app-progress\.json'/);+ assert.match(skill, /--working-dir '<working_dir>' temp/);+ assert.match(skill, /user's OS temp directory/);+ assert.match(skill, /top-level `changes` array/);+ assert.match(skill, /every entry requires `kind`, `title`, `rationale`/);+ assert.match(skill, /"dataModel": \{/);+ assert.match(skill, /"screenGraph": \{/);+ assert.match(skill, /Do not hand-author Mermaid source/);+ assert.match(skill, /validated normalized contract[\s\S]*updated screen graph/);+ assert.match(skill, /Do not open or focus it during `\/edit-app`/);+ assert.match(skill, /Claim the plan was updated only when the final sync succeeded/);+ assert.match(skill, /living plan refresh failed and include that concern/);+ assert.match(skill, /set `approve: waiting`/i);+ assert.match(skill, /set `verify: active`/i);+ assert.match(skill, /`sync-plan: active`/);+ assert.match(skill, /Inferred current-state baseline/);+ assert.match(skill, /routes\/layouts[\s\S]*generated[\s\S]*src\/native\/[\s\S]*brand\/token/);+ const step4 = skill.slice(skill.indexOf('### Step 4'), skill.indexOf('### Step 5'));+ assert.doesNotMatch(step4, /app-docs\.js sync --json-file/);+ assert.match(step4, /keep `docs\/create-app-plan\.html` unchanged until Step 8 verifies/);+ assert.match(skill, /Step 8[\s\S]*scripts\/app-docs\.js" --working-dir '<working_dir>' sync/);+ assert.match(skill, /\/create-mobile-app` Step 12/);+ assert.match(skill, /MOBILE_APP_ORCHESTRATING=1/);+ assert.match(skill, /MOBILE_APP_EMBED_PREVIEW=1/);+ assert.match(previewSkill, /\| `MOBILE_APP_EMBED_PREVIEW=1` \| Print the link and stop/);+ assert.doesNotMatch(previewSkill, /\| `MOBILE_APP_ORCHESTRATING=1` \|/);+ assert.match(previewSkill, /untouched template `app\/\(app\)\/home\.tsx`/);+ assert.match(previewSkill, /Keep it when it is the only visible screen/);+ assert.match(skill, /phone --stage screens[\s\S]*--preview-file '<working_dir>\/preview\.html'/);+ assert.match(skill, /without opening a separate browser page/);+ assert.match(skill, /phone --stage qr/);+ assert.match(skill, /replaces the screen carousel with the same QR code/);+ assert.match(skill, /App Store and Google Play/);+ assert.match(skill, /Run the final\s+`progress` write with `devicePreviewReady: true` after this command succeeds/);+ assert.doesNotMatch(skill, /If `native-app-plan\.md` is missing → STOP/);+ assert.match(skill, /devicePreviewReady: false[\s\S]*earlier run/);+ assert.match(skill, /`--plan-only`[\s\S]*mark `save-plan: done`[\s\S]*publish one final progress/);+ assert.match(skill, /Keep `docs\/create-app-plan\.html` unchanged because it describes the current app/);+ assert.match(skill, /Every branch that ends the workflow must publish a terminal progress write/);+ assert.match(skill, /configuration-only request[\s\S]*`configure-insights` checklist row/);+ assert.match(skill, /planning-phase handoff[\s\S]*validated proposal was returned to the owning workflow/);+ assert.match(skill, /When exactly one session is live, reuse it/);+ assert.match(skill, /do not run `npm run dev`/);+ assert.match(skill, /When several sessions are live[\s\S]*Do not start another server/);+ const tempAllocation = skill.indexOf('Immediately run the edit documentation protocol');+ const inferredPlanSync = skill.indexOf('Create `<edit-temp-dir>/app-plan-sync.json`');+ assert.ok(tempAllocation > -1 && tempAllocation < inferredPlanSync);+ assert.ok(step4.indexOf('If this is `--plan-only`') < step4.indexOf('For an implementation run'),+ 'plan-only must return before implementation work begins');+});+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 }));@@ -212,16 +844,18 @@ test('the phone CLI carries the full preview, including shared CSS, without rewrconst 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');+ const previewPath = path.join(root, '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);+ assert.equal(loadState(root).phone.previewHref, '../preview.html');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);+ assert.equal(phone.previewHref, '../preview.html');});test('replacing a full preview with legacy screens cannot leave stale markup selected', (t) => {@@ -932,8 +1566,22 @@ test('every renderer the page defines is also invoked', () => {});test('the device rail moves through building, screens and QR', () => {+ const template = fs.readFileSync(+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',+ );+ assert.match(template, /\.device\{flex:0 1 620px;min-height:360px;max-height:620px;[^}]*aspect-ratio:300\/620;/);+ assert.match(template, /@media\(max-width:1180px\)[\s\S]*\.device\{flex:none;height:auto;width:min\(300px/);+ assert.match(template, /\.qr img\{flex:0 1 196px;min-height:84px;max-height:196px;[^}]*aspect-ratio:1\/1;/);+const root = project('docs-rail');const state = initState(root, { appName: 'App' });+ const progress = writeEditProgress(root, { phase: 'preview', status: 'active' });+ const html = fs.readFileSync(progress, 'utf8');+ assert.match(html, /\.device-rail\{[^}]*justify-content:safe center;[^}]*overflow-y:auto;/);+ assert.match(html, /\.device\{flex:0 1 620px;min-height:360px;max-height:620px;/);+ assert.match(html, /\.device-screen\{[^}]*container-type:size;/);+ assert.match(html, /\.device-qr img\{flex:0 1 196px;min-height:84px;max-height:196px;/);+ assert.match(html, /@container \(max-height:520px\)\{\.device-qr/);assert.equal(state.phone.stage, 'building', 'a new plan starts on the animation');setPhone(state, { stage: 'screens', screens: [{ name: 'Home', html: '<div>Home</div>' }] });diff --git a/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js b/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.jsindex c498f87a5..cb2b3272d 100644--- a/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js+++ b/plugins/mobile-apps/scripts/tests/app-edit-routing-contract.test.js@@ -229,7 +229,9 @@ test('fresh starters do not enter the existing-app edit workflow', () => {assert.match(state, /standalone prerequisites and approval gates/);assert.match(state, /Do not\s+silently widen it to full app creation/);assert.match(state, /missing\s+plan does not make the app fresh/);- assert.match(state, /ask to restore the plan or approve bounded/);+ assert.match(state, /After full-integration consent, invoke\s+`edit-app`/);+ assert.match(state, /read-only inspection infers the current-state baseline/);+ assert.match(state, /impact and mutation approval gates/);assert.match(state, /Unclear state or intent[\s\S]*ask before choosing/);const direct = section(routing, '## Direct requests', '## Orchestrated calls');assert.match(direct, /confirmed fresh starter stays with `\/add-native`/);diff --git a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js b/plugins/mobile-apps/scripts/tests/run-plan-page.test.jsindex 68ff0ee1e..dec3b2b51 100644--- a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js+++ b/plugins/mobile-apps/scripts/tests/run-plan-page.test.js@@ -1050,7 +1050,17 @@ test('the plan carries the same AI disclaimer as every other plan page', () => {// It is fixed to the viewport, so the page and the sticky device rail must both stop short of// it; otherwise their last line sits underneath it.assert.match(template, /body\{[^}]*padding-bottom:var\(--footer-h\)/);- assert.match(template, /\.rail\{[^}]*calc\(100vh - 65px - var\(--footer-h\)\)/);+ assert.match(template, /\.rail\{[^}]*top:var\(--topbar-h\);height:calc\(100vh - var\(--topbar-h\) - var\(--footer-h\)\)/);+});++test('the short-phone container query overrides the default QR copy sizes', () => {+ const template = fs.readFileSync(+ path.resolve(__dirname, '..', '..', 'assets', 'run-plan.html'), 'utf8',+ );+ const compact = template.indexOf('@container (max-height:520px)');+ assert.ok(compact > template.indexOf('.qr-title{font-size:16px'));+ assert.ok(compact > template.indexOf('.qr-sub{font-size:12.5px'));+ assert.ok(compact > template.indexOf('.qr-url{font-family:var(--mono);font-size:11px'));});test('the carousel says the mockups are not the built app, and only while they are shown', async () => {diff --git a/plugins/mobile-apps/shared/references/app-edit-routing.md b/plugins/mobile-apps/shared/references/app-edit-routing.mdindex f50899b5d..b272b8c29 100644--- a/plugins/mobile-apps/shared/references/app-edit-routing.md+++ b/plugins/mobile-apps/shared/references/app-edit-routing.md@@ -70,10 +70,14 @@ memory-bank update. Do not ask the user to run a second command themselves.The entry choice approves entering that workflow, not its mutations: preserveits impact/plan approval and explicit approval for data-source removals.-If full integration was selected but the app's plan is missing, report that-prerequisite and ask whether to restore it or choose a limited implementation-only-operation. Implementation-only work does not require a complete app plan.-Do not re-scaffold over the app or fabricate a complete plan from one request.+If full integration was selected for a confirmed existing or customized app whose+plan is missing, invoke `/edit-app`.+Its read-only inspection creates an inferred current-state baseline before proposing+the requested delta.+The entry choice authorizes delegation only; retain `/edit-app`'s impact and mutation+approval gates.+Implementation-only work does not require a complete app plan.+Do not re-scaffold over the app or infer an existing app when its state is unclear.Outside an existing app, retain the skill's project prerequisites and standaloneplanning behavior; brand-only design generation need not create an app.diff --git a/plugins/mobile-apps/skills/edit-app/SKILL.md b/plugins/mobile-apps/skills/edit-app/SKILL.mdindex 0c94e5ecd..da997bbf0 100644--- a/plugins/mobile-apps/skills/edit-app/SKILL.md+++ b/plugins/mobile-apps/skills/edit-app/SKILL.md@@ -16,6 +16,172 @@ Post-generation editor for an existing mobile app. `native-app-plan.md` remainsUse `--plan-only` only when the user explicitly asks to update planning docs without changing app code. Normal follow-up prompts in Copilot Chat Agent mode should apply the app change end to end.+## Edit documentation protocol++Keep two HTML files current during every edit:++- `<edit-temp-dir>/edit-app-progress.html` shows the live operation checklist.+- `docs/create-app-plan.html` remains the living description of the app.++Both are best-effort documentation. A rendering failure does not authorize a mutation, cancel an+approval gate, or turn a failed verification into success.++### Progress page++As soon as Step 0 resolves `working_dir`, before inferred-plan sync or the first progress write, ask+`app-docs.js` for a namespaced directory inside the user's OS temp directory:++```bash+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' temp+```++Use the returned `directory`, `progress`, `progressHtml`, and `sync` paths for the rest of the+run. Do not create progress files inside the project. Create `<edit-temp-dir>/edit-app-progress.json`+with one row per operation this edit will run.+Use stable IDs such as `inspect`, `impact`, `plan`, `approve`, `save-plan`, `data`, `native`,+`design`, `screens`, `verify`, `preview`, and `sync-plan`. Omit operations that do not apply.+Each row has `id`, `label`, `status` (`pending`, `active`, `waiting`, `done`, `skipped`, or+`failed`), and an optional `note`.+Add a top-level `changes` array for the Changes tab.+Keep it empty during initial inspection.+After Step 2, every entry requires `kind`, `title`, `rationale`, and optional `detail`.+Use `kind: general` for text-only changes.+Use structured diagram data for data-model and screen changes:++```json+{+ "changes": [+ {+ "kind": "data-model",+ "title": "Add inspection evidence",+ "detail": "Create a child table for photos and signatures.",+ "rationale": "One inspection can have several evidence records with independent metadata.",+ "dataModel": {+ "tables": [+ {+ "name": "Inspection",+ "columns": [{ "name": "inspectionid", "type": "guid", "primaryKey": true }]+ },+ {+ "name": "Evidence",+ "columns": [+ { "name": "evidenceid", "type": "guid", "primaryKey": true },+ { "name": "inspectionid", "type": "guid", "foreignKey": true }+ ]+ }+ ],+ "relationships": [+ {+ "from": "Inspection",+ "to": "Evidence",+ "cardinality": "one-to-many",+ "label": "contains"+ }+ ]+ }+ },+ {+ "kind": "screen",+ "title": "Add inspection detail",+ "detail": "Add a route that shows findings and evidence.",+ "rationale": "Inspectors need a focused review surface before updating a record.",+ "screenGraph": {+ "screens": [+ { "id": "list", "name": "Inspections", "route": "/inspections" },+ { "id": "detail", "name": "Inspection detail", "route": "/inspections/[id]" }+ ],+ "edges": [+ { "from": "list", "to": "detail", "label": "Select inspection" }+ ]+ }+ }+ ]+}+```++Derive data-model tables, columns, and relationships from the validated schema proposal.+Derive screen nodes and edges from the updated Screen Map and Navigation Contracts.+When multiple screens are shown, include every navigation edge needed to explain how the user moves+between them.+Do not hand-author Mermaid source in the payload.+`app-docs.js` derives and renders the ER diagram or screen graph from the structured data.+Retain the approved wording, rationale, and graph data through implementation and verification.++Rewrite that JSON at every numbered step boundary and run:++```bash+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' progress \+ --json-file '<edit-temp-dir>/edit-app-progress.json'+```++Every progress payload is a complete snapshot, not a patch.+Carry every operation row forward and update all rows whose state changed before publishing.+When the top-level phase advances, no row from an earlier phase may remain `active` or `waiting`.+In particular, an approval wait must show inspection and planning as complete and the approval row+as `waiting`.++The top-level object also carries `phase`, `status`, `note`, `waiting`, and+`devicePreviewReady`. Set the current row to `waiting` and `waiting: true` before every user+question. Set completed rows to `done`; do not leave the first row active for the whole run. On+failure, mark the failed row and top-level status `failed`. The page keeps a phone preview on the+right while work is active. Keep `devicePreviewReady: false` until this edit's Step 8 phone command+succeeds. Then set it to `true` in the final progress write, mark every applicable row settled, and+set top-level status `done`. A QR left by an earlier run is never current-run preview evidence.+Every branch that ends the workflow must publish a terminal progress write. Preserve the operation's+actual result, mark completed rows `done` or `failed`, mark rows that will not run `skipped`, clear+`waiting`, and set the top-level status to `done` or `failed`.++Open `<edit-temp-dir>/edit-app-progress.html` once after the first write using the host's file+opener. If no opener is available, print the absolute path. The page refreshes itself while work+is active.++### Living app plan++`app-docs.js sync` accepts a structured snapshot, not a prose summary:++```json+{+ "appName": "Field inspections",+ "dataPlatform": "dataverse",+ "inferred": false,+ "summary": "Added inspection detail and evidence capture.",+ "sections": {+ "requirements": {},+ "architecture": { "dataPlatform": "dataverse", "nativeCapabilities": [], "connectors": [] },+ "dataModel": { "tables": [] },+ "screens": { "navigation": "", "list": [] },+ "design": {},+ "offline": {},+ "trust": {}+ },+ "sectionStates": { "screens": "approved" }+}+```++For an existing plan, include every section this edit changed and omit unchanged sections. Serialize+the complete current section after implementation; the sync command replaces that section so+removed screens, connectors, capabilities, and tables do not survive as stale rows. Build values+from the verified app and its durable plan, not from the pre-approval proposal.++Write the payload to `<edit-temp-dir>/app-plan-sync.json`, then run:++```bash+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' sync \+ --json-file '<edit-temp-dir>/app-plan-sync.json'+```++If `docs/.run-plan.json` is missing, the payload must cover every section that can be derived from+the app: routes and layouts for `screens`, generated models/services and the manifest for+`dataModel`, `power.config.json` plus generated registrations for connectors, `src/native/` and+template dependencies for native capabilities, and brand/token files for `design`. Mark this first+snapshot `inferred: true` and use the note `Plan inferred from existing app state because no prior+create-run plan was present.` Unknown facts stay explicitly unknown; do not guess.++Update `docs/create-app-plan.html` in the background. Do not open or focus it during `/edit-app`.+Run the sync command after an inferred baseline is created, after approved plan sections are saved,+and again after Step 8 verification so the page ends on the app's actual current state. Tell the+user when the living app plan has been updated to reflect the latest verified changes.+## When to use- "Improve the search screen to make it easier to use on mobile"@@ -42,8 +208,8 @@ Use `--plan-only` only when the user explicitly asks to update planning docs wit- Explicit implementation-only request → the matching leaf skill under[app-edit-routing.md](../../shared/references/app-edit-routing.md); do not inferthis from a short request or the absence of screen details.-- The plan file is missing → stop and ask to restore it or confirm a bounded- implementation-only operation; never re-scaffold over the existing app.+- No recognizable generated app root (`package.json` plus `app/`) → stop and ask for the app+ directory. A missing plan by itself is handled by the inferred-baseline path below.## Workflow@@ -105,19 +271,31 @@ Before any project read or command, executeResolve the absolute `working_dir` once, bind every shell call to it with thefail-closed guard, and use absolute paths for file tools. Forward that same rootto every data child; a previous `cd` or inherited launch cwd is not a handoff.+Immediately run the edit documentation protocol's `temp` command and bind its returned+`directory`, `progress`, `progressHtml`, and `sync` paths as `<edit-temp-dir>` values before any+inferred-plan sync or progress write below.```bashcd -- '<working_dir>' || { echo "BLOCKED: cannot enter working_dir" >&2; exit 1; }-test -f native-app-plan.md && echo "OK: plan found" || echo "ERROR: no plan"+test -f native-app-plan.md && echo "OK: plan found" || echo "INFO: plan will be inferred"test -f package.json && echo "OK: package found" || echo "ERROR: no package"test -d app && echo "OK: app routes found" || echo "ERROR: no app routes"test -f memory-bank.md && echo "OK: memory bank found" || echo "WARN: no memory bank"git status --short```-If `native-app-plan.md` is missing → STOP. Ask to restore the existing plan or-explicitly limit the request to implementation-only work. Do not reconstruct the-full app plan from one feature request or run `/create-mobile-app` over this app.+If `package.json` or `app/` is missing, STOP because this is not a recognizable generated app.+If `native-app-plan.md` is missing, inspect the current app before asking edit questions. Build an+inferred current-state baseline from routes/layouts, `power.config.json`, generated+models/services, `.datamodel-manifest.json`, `src/native/`, package dependencies, brand/token+files, and `memory-bank.md` when present. Write `native-app-plan.md` with every evidenced section,+label it `Inferred current-state baseline`, and mark unresolved facts as unknown. Do not run+`/create-mobile-app`, invent missing business intent, or treat inference as mutation approval.+Create `<edit-temp-dir>/app-plan-sync.json` from the same evidence and run the `sync` command so imported apps+receive `docs/create-app-plan.html` before planning begins.++Create the edit progress payload now with `inspect: active`, run the `progress` command, and open+`<edit-temp-dir>/edit-app-progress.html`.Read if present:@@ -153,6 +331,8 @@ plan section and stop unchanged; for a mixed request, continue with only therequested plan proposal.Use this fast path when the request is only to enable Application Insights, change its resource, or disable it. Application Insights is host/runtime configuration, not a connector or plan section, so do not run the planner, data-model, native, design, screen, or preview flows.+For a configuration-only request, use a `configure-insights` checklist row. Mark `inspect: done`+and `configure-insights: active` before delegation.If the request also adds or changes custom events in app screens, configure Application Insights here first, then continue through the normal edit workflow for those source changes.@@ -179,13 +359,17 @@ Handle the return per the status protocol (AGENTS.md rule #12):- `DONE` → print the action completed. Then, if the return includes `instrumentation_offer: available` (a successful enable/change-resource), ask the user one question, defaulting to **No**: "Application Insights is on. Want me to add custom telemetry to your app's major operations (create / update / delete)?"- **Yes** → continue into the normal edit workflow (Step 1 onward) with this brief: *"Add custom events at each successful create, update, and delete boundary for the app's main entities; emit named events through `getCustomEventsLogger` with approved scalar properties only (no operation results, payloads, form values, free text, record titles, personal identifiers, tokens, precise coordinates, nested objects, or complete URLs); use `trackScenario()` for any duration."* Screen-planner and screen-builder own the source edits under their existing privacy allowlist.- - **No** (or `instrumentation_offer: none`) → stop; do not continue to Step 1.-- `DONE_WITH_CONCERNS` → surface concerns, then stop.+ - **No** (or `instrumentation_offer: none`) → mark `configure-insights: done`, mark every remaining row `skipped`, clear `waiting`, set top-level `phase: done` and `status: done`, publish the progress page, then stop.+- `DONE_WITH_CONCERNS` → mark `configure-insights: done`, mark every remaining row `skipped`, clear `waiting`, set top-level `phase: done` and `status: done`, include the concerns in the note, publish the progress page, surface the concerns, then stop.- `NEEDS_CONTEXT` → surface the question, re-invoke with the answer.-- `BLOCKED` → surface the error (usually `app.json` unusable) and stop.+- `BLOCKED` → mark `configure-insights: failed`, mark every remaining row `skipped`, clear `waiting`, set top-level `phase: done` and `status: failed`, publish the progress page, surface the error (usually `app.json` unusable), then stop.### Step 1 — Discover intent + inspect existing app+Update `<edit-temp-dir>/edit-app-progress.json`: keep `inspect` active while reading the app, then mark it+`done` once the existing routes, data surface, native wrappers, and design constraints are known.+Run the protocol's `progress --json-file` command after each update.+Infer from `$ARGUMENTS` when possible, but do not mutate files until you have a concrete edit brief. This is the mini `/create-mobile-app` requirements phase for one existing-app change.First inspect the app so questions can use real options instead of abstractions:@@ -316,6 +500,11 @@ If a single PDF/signature request requires multiple plan sections, say so and ru**Telemetry checkpoint: `analyze_edit_impact`**+Before showing the impact question, mark `inspect: done`, set `impact: waiting`, set top-level+`phase: impact`, `waiting: true`, and run `progress --json-file`. If the user proceeds, change+`impact` to `done`, set `plan: active`, clear `waiting`, and run it again. A cancellation sets the+top-level status to `done` with all unstarted operations `skipped`.+Before spawning architects or mutating files, show a rough impact preview and ask for proceed/edit/cancel. This mirrors `/create-mobile-app` Step 2c at edit scale.Compute:@@ -374,6 +563,10 @@ jump from design refresh straight to verification if screen changes are needed.**Telemetry checkpoint: `revise_affected_app_plan`**+Keep `plan: active` while architects or inline planning update the affected sections. If a planner+needs user context, change `plan` to `waiting`, set `waiting: true`, and run the progress command+before asking. Restore it to `active` after the answer.+Reuse the same planning primitives as `/create-mobile-app`, but only for the affected surfaces:| Surface | Reuse from create flow | Edit-app scope |@@ -457,6 +650,15 @@ app mutation, and unknown first lines are `BLOCKED: malformed agent return`.Every Data Model result, including inline output, must pass the shared decisionvalidator; `DONE` alone never authorizes Step 3.+Before Step 3, rebuild the progress payload's `changes` array from the completed affected-section+proposals.+Every change must explain why it is necessary.+For a Data Model delta, include the affected tables, relevant columns, and relationships from the+validated normalized contract so the Changes tab renders the proposed ER diagram.+For a Screens delta, include the affected existing and proposed screens plus their real navigation+edges so the Changes tab renders the updated screen graph.+Run `progress --json-file` after writing this payload and before changing `approve` to `waiting`.+For Native Capabilities (no separate agent), do it inline: read the current capability table, apply the change, regenerate the table. For PDF/pen rows, include storage/output notes in the table or immediately below it:- `native-pdf-viewer` 0.2.9+ opens HTTPS URLs and local `file://` URIs; it does not support `content://`, `blob:`, or `http://`.@@ -482,6 +684,11 @@ server tables/records, and carry the approved removal set through Step 6.5.**Telemetry checkpoint: `approve_app_mutation_plan`**+Before asking for approval, mark `plan: done`, set `approve: waiting`, set top-level+`phase: approval`, `waiting: true`, and run `progress --json-file`. A revision returns `plan` to+`active`. Approval marks `approve: done`, sets `save-plan: active`, clears `waiting`, and runs the+command again. Cancellation settles the page with remaining operations `skipped`.+For Dataverse planning, require exit `0` from`validate-dataverse-planning-decisions.js` for the current normalized contractand snapshot before showing this gate. Revisions repeat that check. There is@@ -492,6 +699,10 @@ proposal and concerns to that owner now, without saving the live plan oropening an implementation gate. Do not turn the caller's planning consentinto approval to apply the edit. A direct `--plan-only` request retains theexplicit plan-document approval below.+Before returning, mark `inspect`, `impact`, and `plan` as `done`; mark approval, save,+implementation, verification, preview, sync, and device rows `skipped`; clear `waiting`; set+top-level `phase: done`, `status: done`, and `devicePreviewReady: false`; and publish one final+progress write. The note must say that the validated proposal was returned to the owning workflow.Show the user a side-by-side diff (or before/after) for every changed plan section. Also show an app mutation preview:@@ -519,6 +730,8 @@ If `$ARGUMENTS` includes `--plan-only`, change option (a) to "Approve and save p### Step 4 — Write plan diff+Keep `save-plan: active` while writing the approved `native-app-plan.md` sections.+Replace the approved section(s) in `native-app-plan.md` with the approved content (preserve all other sections verbatim). Print a unified diff so the user has a record:```@@ -530,7 +743,19 @@ diff --git native-app-plan.md native-app-plan.md+ | 🆕 Create (Tier 2) | contoso_case | Lookup → account, severity, status |```-If this is `--plan-only`, update `memory-bank.md` with `plan_only: true`, print the exact follow-up commands, and stop. Otherwise continue immediately.+If this is `--plan-only`, update `memory-bank.md` with `plan_only: true`, mark `save-plan: done`,+mark every implementation, verification, preview, and device-handoff row `skipped`, set top-level+`phase: done`, `status: done`, and `devicePreviewReady: false`, and publish one final progress+write. Keep `docs/create-app-plan.html` unchanged because it describes the current app, while+`native-app-plan.md` holds the approved but unapplied intent. Then print the exact follow-up+commands and stop.++For an implementation run, keep `docs/create-app-plan.html` unchanged until Step 8 verifies the+implemented state.+The approved proposal belongs in `native-app-plan.md` and the edit progress page, not in the living+current-app plan.+Mark `save-plan: done` and the first applicable implementation operation `active` in the progress+page.The saved plan describes approved intent, not successful application. When theData Model changed, merge its newly accepted `_dm_section.md` proposal here;@@ -548,6 +773,11 @@ paths. A plan-only save does not create this implementation approval context.**Telemetry checkpoint: `apply_app_mutations`**+Update the progress page after every applicable operation below. Mark each of `data`, `native`, and+`design` active only while its leaf runs, then `done`, `skipped`, or `failed` from the actual+result. Run `progress --json-file` after each transition so the checklist identifies the operation+that is currently running.+Apply sections in dependency order so screens always build against the current data/native surface:Run only operations in the approved delta, not every section of the existing@@ -703,6 +933,10 @@ Step 6.5; an `in-sync` result never resolves a pending retirement.**Telemetry checkpoint: `rebuild_affected_screens`**+Set `screens: active` before route/layout/shared-code work. Update its note after each builder wave,+for example `Wave 2 of 3 complete`, and run the progress command. Mark it `done` only after the+navigation/skeleton gate and every required builder wave pass.+Use the plan diff plus the user's request to build the affected screen set:| Change type | Screens to rebuild |@@ -812,6 +1046,10 @@ with Step 5.6's addition-only result.**Telemetry checkpoint: `validate_edited_app`**+Set `verify: active` before the first gate and run the progress command. On a failed gate, keep it+active while applying the bounded repair and record the failing command in its note. Mark it+`failed` if verification cannot be completed; mark it `done` only after every required rerun passes.+Run verification after mutations. Batch-fix root causes, then rerun the failed gate once. Verification is selected by what changed, but TypeScript is always required after an app mutation.Required gates, selected by what changed:@@ -861,9 +1099,73 @@ If verification fails because the edit exposed stale generated services, rerun t**Telemetry checkpoint: `refresh_app_preview_and_history`**+Mark `preview: active` while regenerating `preview.html`, or `skipped` when no visible surface+changed. Then build `<edit-temp-dir>/app-plan-sync.json` from the verified app state and mark+`sync-plan: active`. The payload must contain complete snapshots for every changed section,+including removals, plus the preview and verification notes owned by those sections. Run:++```bash+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' sync \+ --json-file '<edit-temp-dir>/app-plan-sync.json'+```++After the sync succeeds, mark `sync-plan: done`, settle every applicable checklist row, set+top-level `phase: done` and `status: done`, and run the progress command one last time, but only+after the device-test handoff below has updated the phone state.+Before that final progress write, reconcile each change entry with the verified app state.+Update data-model tables and relationships from the final normalized contract and update screen+nodes and edges from the final routes and navigation layouts.+The completed edit page and `docs/create-app-plan.html` must describe the same final structure.+If sync rendering fails, record the concern but do not misreport the app edit or verification as+failed.+Before Step 8, `npx --no-install tsc --noEmit` must be clean after all code edits from this `/edit-app` run. If any code was written after Step 7's `tsc`, rerun `npx --no-install tsc --noEmit`, batch-fix root causes, and continue only when TypeScript is error-free.-If any UI, design, navigation, native interaction, or visible data state changed — or if the user explicitly asked for a preview — read and execute `/preview-screens` after verification. This regenerates `preview.html` and opens it according to the project's `visual_companion` setting.+If any UI, design, navigation, native interaction, or visible data state changed - or if the user+explicitly asked for a preview - read and execute `/preview-screens` after verification with+`MOBILE_APP_ORCHESTRATING=1` and `MOBILE_APP_EMBED_PREVIEW=1`.+This regenerates `preview.html` without opening a separate browser page.+After the file is written, put the same screens in the phone rail and publish the progress page:++```bash+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' phone --stage screens \+ --preview-file '<working_dir>/preview.html'+```++Keep the progress page open.+It shows the screens in a sandboxed phone carousel, links to `preview.html` for a full-size view, and+keeps the living `docs/create-app-plan.html` in sync through the same phone state.+If the preview was skipped or generation failed, leave the phone on its current progress state and+report the concern.++Unless this is `--plan-only`, finish with a real-device handoff. Read+`/create-mobile-app` Step 12 from **Launch command** through **Put the QR in the plan** and execute+that sequence from the same `<working_dir>`. Before launching, apply `/debug-app` Phase 0.0's+project-local log, PID, and port-ownership checks to every+`<working_dir>/.powernative/metro-logs/metro-*-pid-*-port-*.log` candidate.++- When exactly one session is live, reuse it. Read its native Metro URL from the sanitized log,+ verify that the URL port matches the live log's port, and do not run `npm run dev`.+- When no session is live, start Metro with the template-owned `npm run dev` and capture the URL it+ prints.+- When several sessions are live, or the PID, port, log, and URL disagree, show the sessions and+ ask which one to use. Do not start another server while the choice is unresolved.++Generate `.expo/metro-qr.png` from the selected URL with the pinned+`npx --no-install qrcode`. Then update both documents through the existing phone command:++```bash+node "${PLUGIN_ROOT}/scripts/app-docs.js" --working-dir '<working_dir>' phone --stage qr \+ --qr-image '<working_dir>/.expo/metro-qr.png' --qr-url "<metro-url>"+```++Do not open `docs/create-app-plan.html`; its phone changes in the background. Run the final+`progress` write with `devicePreviewReady: true` after this command succeeds so the already-open+edit page replaces the screen carousel with the same QR code and shows the App Store and Google Play+buttons for Power Apps Mobile Preview. If Metro or QR generation fails,+keep `devicePreviewReady: false`; the completed edit page then shows `Device preview unavailable`+even when the living plan contains a QR from an earlier run. Report the preview concern separately,+and do not turn a verified app edit into a failure.If the user gives a concrete runtime symptom and Metro is already running from the native dev-client flow, you may invoke `/debug-app "<symptom>"` after the static verification and preview steps. This is an optional symptom-debug handoff, not a verification gate: do not run screen-by-screen runtime checks, do not crawl routes, do not use React Native Web, and do not call Metro HTTP endpoints directly.@@ -884,7 +1186,11 @@ Append an edit entry to `memory-bank.md`:- Blocks/concerns: <none or list>```-Final summary must say what changed in the app, what verification ran, where the preview is, and whether a symptom-debug handoff was requested. Do not end by saying the codebase was not changed unless this was explicitly `--plan-only`.+Final summary must say what changed in the app, what verification ran, where the preview is, whether+the living app plan was updated to reflect the latest verified changes, and whether a symptom-debug+handoff was requested. Claim the plan was updated only when the final sync succeeded; otherwise+state that the app edit verified but the living plan refresh failed and include that concern. Do+not end by saying the codebase was not changed unless this was explicitly `--plan-only`.If any `offlineRetirement` outcome is `pending`, return `DONE_WITH_CONCERNS` andstate the unfinished decision separately: "App changes completed. The offlineprofile still includes Orders; deciding whether to retain or remove that coveragediff --git a/plugins/mobile-apps/skills/preview-screens/SKILL.md b/plugins/mobile-apps/skills/preview-screens/SKILL.mdindex cd34f62cc..c64536499 100644--- a/plugins/mobile-apps/skills/preview-screens/SKILL.md+++ b/plugins/mobile-apps/skills/preview-screens/SKILL.md@@ -69,6 +69,10 @@ Glob pattern="app/**/*.tsx" path="<working_dir>"- `+not-found.tsx` (Expo Router error boundary)- Files in directories starting with `.`- `index.tsx` at the app root if it only contains an auth redirect (read it to check)+- The untouched template `app/(app)/home.tsx` when at least one other visible screen exists.+ Recognize it only when its source still contains both `Power Apps Standalone` and+ `Build your first screen by connecting data sources`.+ Keep it when it is the only visible screen so the preview is never empty.**Derive screen names** from file paths:- `app/(app)/home.tsx` → "Home"@@ -85,7 +89,12 @@ Build an ordered list: `[ { path, screenName, screenId } ]`.Sort the list with this priority:-1. **Home / dashboard first.** The first screen matching any of these paths (in this priority): `app/(app)/home.tsx`, `app/(app)/index.tsx`, `app/(app)/dashboard.tsx`, `app/index.tsx` (only if it's a real home screen — not the auth redirect you already filtered out in Step 2). If `native-app-plan.md` flags one screen as the home/landing screen, prefer that.+1. **Home / dashboard first.** Prefer the screen that `native-app-plan.md` identifies as the+ home or landing screen.+ Otherwise, use the first remaining screen matching any of these paths (in this priority):+ `app/(app)/home.tsx`, `app/(app)/index.tsx`, `app/(app)/dashboard.tsx`, `app/index.tsx`+ (only if it is a real home screen, not an auth redirect or the untouched starter route filtered+ out in Step 2).2. **Then up to two detail screens.** A "detail" screen is any TSX whose route segment uses a dynamic param — file path contains `[` and `]` (e.g. `app/(app)/recipes/[id].tsx`, `app/(app)/orders/[orderId]/edit.tsx`). Take the first two in the order they were discovered (alphabetical by path is fine).3. **Then everything else** in discovery order.@@ -191,6 +200,7 @@ grep -E "^visual_companion:[[:space:]]*(yes|no)" '<working_dir>/memory-bank.md'| Flag | Action ||---|---|+| `MOBILE_APP_EMBED_PREVIEW=1` | Print the link and stop. The owning edit plan embeds the screens. || `visual_companion: no` | Print the link and stop. Do not auto-open. || `visual_companion: yes` (or missing memory-bank, or standalone invocation) | Print the link, then auto-open. |diff --git a/plugins/mobile-apps/template/AGENTS.md b/plugins/mobile-apps/template/AGENTS.mdindex a036d33f8..31615cfb5 100644--- a/plugins/mobile-apps/template/AGENTS.md+++ b/plugins/mobile-apps/template/AGENTS.md@@ -97,8 +97,10 @@ caller context first; creation can already have a plan without being finished.entry point with its standalone prerequisites and approval gates. Do notsilently widen it to full app creation.- **Existing or customized app** — use the existing-app routing below. A missing- plan does not make the app fresh; ask to restore the plan or approve bounded- implementation-only work rather than re-scaffolding it.+ plan does not make the app fresh. After full-integration consent, invoke+ `edit-app`; its read-only inspection infers the current-state baseline before its+ impact and mutation approval gates. Keep implementation-only work bounded to its+ leaf workflow.- **Unclear state or intent** — ask before choosing creation or editing. Do notinfer a fresh starter solely from missing generated markers.