A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
fix(mobile-apps): stop endless plan page reloads (#872)
Priyanshu Agrawal80e2f451b8f1
diff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.jsonindex fc9d8e73c..86ddbc3a7 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.6.1",+ "version": "0.6.2","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 fc9d8e73c..86ddbc3a7 100644--- a/plugins/mobile-apps/.plugin/plugin.json+++ b/plugins/mobile-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "mobile-app",- "version": "0.6.1",+ "version": "0.6.2","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/README.md b/plugins/mobile-apps/README.mdindex 20d3a2e5c..44882a4fc 100644--- a/plugins/mobile-apps/README.md+++ b/plugins/mobile-apps/README.md@@ -219,6 +219,11 @@ What happens:End state: a working app you can iterate on with hot reload. ~5–12 minutes for the planning gates, then scaffolding runs.+The build and edit plan pages automatically check for new progress.+They pause when waiting for your input or after 30 consecutive reloads without a progress change.+Reload the browser after answering a question or resuming an interrupted run.+Render timestamps do not reset the limit; new progress does.+### 2. Add Dataverse tables to an existing app```textdiff --git a/plugins/mobile-apps/assets/run-plan.html b/plugins/mobile-apps/assets/run-plan.htmlindex d638ccf38..c22f3675e 100644--- a/plugins/mobile-apps/assets/run-plan.html+++ b/plugins/mobile-apps/assets/run-plan.html@@ -325,6 +325,9 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi<span class="topbar-sep">|</span><span id="updatedAt" data-generated="__ATTR_GENERATED_ISO__">Updated __HTML_GENERATED_AT__ UTC</span></div>+ <div class="topbar-sub">+ <span id="refreshStatus" role="status"></span>+ </div></div></div><div class="topbar-right">@@ -1844,22 +1847,10 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi});renderSteps();- /**- * The agent rewrites this file in place, and the page is opened over file://, where fetch() is- * CORS-blocked - so there is no way to poll for changes and patch the DOM. A reload is the only- * mechanism available, which makes *when* it happens the whole design:- *- * - Restore the open tab and scroll position through sessionStorage, so a reload never throws- * the reader back to the top of Overview.- * - Pause while the reader is actually using the page. Being yanked mid-sentence is worse than- * seeing a slightly stale plan.- * - Stop entirely once nothing is in progress.- */+ // Both automatic and manual refreshes replace the document. Keep the reader's+ // tab and scroll position; the shared controller below owns when to refresh.var STORE_TAB = 'mobile-plan-tab';var STORE_SCROLL = 'mobile-plan-scroll';- var RELOAD_MS = 10000;- var QUIET_MS = 30000;- var lastInteraction = 0;function showTab(tab) {var button = document.querySelector('.nav-btn[data-tab="' + tab + '"]');@@ -1873,16 +1864,11 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margidocument.querySelectorAll('.nav-btn').forEach(function (btn) {btn.addEventListener('click', function () {- lastInteraction = Date.now();showTab(btn.dataset.tab);try { sessionStorage.setItem(STORE_TAB, btn.dataset.tab); } catch (e) { /* private mode */ }});});- ['scroll', 'keydown', 'pointerdown'].forEach(function (event) {- window.addEventListener(event, function () { lastInteraction = Date.now(); }, { passive: true });- });-window.addEventListener('beforeunload', function () {try { sessionStorage.setItem(STORE_SCROLL, String(window.scrollY)); } catch (e) { /* ignore */ }});@@ -1894,25 +1880,9 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margiif (savedScroll > 0) window.scrollTo(0, savedScroll);} catch (e) { /* sessionStorage unavailable; first-tab default is fine */ }- if (!summary.settled) {- setInterval(function () {- // Never interrupt someone who is reading. The next tick picks it up.- if (Date.now() - lastInteraction < QUIET_MS) return;- if (document.hidden) return;- try { sessionStorage.setItem(STORE_SCROLL, String(window.scrollY)); } catch (e) { /* ignore */ }- // A plain reload() is not enough. This page is opened over file://, so it carries no- // cache headers, and `render-template.js` publishes each rewrite with an atomic rename -- // a new inode at the same path. Browsers are free to serve the copy they already have,- // which is why the build animation could persist until a hard refresh. Reloading through- // a URL that differs every time is the only lever a file:// page has.- var fresh = location.href.split('#')[0].split('?')[0] + '?t=' + Date.now();- // replace(), not assign(): this fires every few seconds, and each one would otherwise be- // a back-button entry the reader has to escape.- location.replace(fresh);- }, RELOAD_MS);- }})();</script>+<script nonce="__ATTR_CSP_NONCE__" id="planRefreshScript">__RAW_AUTO_REFRESH__</script><footer class="ai-footer">AI-generated content may be incorrect</footer></body></html>diff --git a/plugins/mobile-apps/scripts/app-docs.js b/plugins/mobile-apps/scripts/app-docs.jsindex 899fad439..bfd5bcd89 100644--- a/plugins/mobile-apps/scripts/app-docs.js+++ b/plugins/mobile-apps/scripts/app-docs.js@@ -37,6 +37,7 @@ const path = require('node:path');const { pathToFileURL } = require('node:url');const { publishAtomic, renderTemplate } = require('./lib/render-template');+const { planRefreshScript } = require('./lib/plan-refresh');/*** The plan's state file is read by one process and rewritten by another as the run advances, so@@ -455,6 +456,18 @@ function render(projectRoot, state) {PHONE: state.phone || { stage: 'building', screens: [] },CAPABILITIES: capabilityLabels(state),BRAND_ICON: brandIconDataUri(),+ AUTO_REFRESH: planRefreshScript({+ startedAt: state.startedAt,+ phases: state.phases,+ sections: state.sections,+ sectionStates: state.sectionStates,+ phone: state.phone,+ }, {+ waiting: Boolean(summary.awaitingInput),+ settled: summary.settled,+ reloadMs: 10000,+ quietMs: 30000,+ }),},});}@@ -951,19 +964,14 @@ function writeEditProgress(projectRoot, options = {}) {+ `<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 autoRefresh = planRefreshScript({+ phase, note, status, waiting, items, changes, phone,+ }, {+ waiting: waiting || status === 'waiting',+ settled,+ reloadMs: 2500,+ quietMs: 10000,+ });const html = `<!DOCTYPE html><html lang="en">@@ -1136,6 +1144,9 @@ function writeEditProgress(projectRoot, options = {}) {<span>${escapeHtml(appName)}</span><span class="topbar-sep">|</span><span>Updated ${escapeHtml(generatedAt)} UTC</span></div>+ <div class="topbar-sub">+ <span id="refreshStatus" role="status"></span>+ </div></div></div><div class="topbar-right">@@ -1405,9 +1416,9 @@ function writeEditProgress(projectRoot, options = {}) {var savedScroll = Number(sessionStorage.getItem(STORE_SCROLL) || 0);if (savedScroll > 0) window.scrollTo(0, savedScroll);} catch (error) { /* sessionStorage unavailable; Changes stays selected */ }- ${autoRefresh}}());</script>+ <script nonce="${nonce}" id="planRefreshScript">${autoRefresh}</script></body></html>`;diff --git a/plugins/mobile-apps/scripts/lib/plan-refresh.js b/plugins/mobile-apps/scripts/lib/plan-refresh.jsnew file mode 100644index 000000000..c2575a79d--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/plan-refresh.js@@ -0,0 +1,68 @@+'use strict';++const crypto = require('node:crypto');++// Embedded in both standalone pages. Keep this function self-contained: file:// pages+// cannot fetch a helper or progress endpoint, and installed plugins have no repo-root assets.+function watchPlan(options) {+ var MAX_UNCHANGED_RELOADS = 30;+ var RELOAD_MS = options.reloadMs;+ var QUIET_MS = options.quietMs;+ var lastInteraction = 0;+ var message = document.getElementById('refreshStatus');+ var url = new URL(location.href);+ // Only our cache-busting navigations carry these fields, e.g.+ // ?planProgress=<sha256>&planReloads=3&t=<milliseconds>. Unlike sessionStorage,+ // the URL survives file:// reloads even when browser storage is unavailable.+ var previous = url.searchParams.get('planProgress');+ var rawCount = url.searchParams.get('planReloads') || '';+ var count = previous === options.progress && /^\d+$/.test(rawCount)+ ? Number(rawCount) : 0;+ if (!Number.isSafeInteger(count)) count = MAX_UNCHANGED_RELOADS;+ // Browser reload retains the polling query string, but must renew the budget.+ // location.replace() is a "navigate" entry, so automatic polls cannot reset it.+ // https://www.w3.org/TR/navigation-timing-2/#dom-performancenavigationtiming-type+ var navigation = performance.getEntriesByType('navigation')[0];+ if (navigation && navigation.type === 'reload') count = 0;++ function refresh() {+ var fresh = new URL(location.href);+ fresh.searchParams.set('planProgress', options.progress);+ fresh.searchParams.set('planReloads', String(count + 1));+ // Atomic rewrites have no file:// cache headers. A distinct URL picks up the+ // new file; replace avoids adding every poll to the reader's back history.+ fresh.searchParams.set('t', String(Date.now()));+ location.replace(fresh.href);+ }++ if (options.settled) {+ message.textContent = 'Auto-refresh off: run finished or stopped.';+ return;+ }+ if (options.waiting) {+ message.textContent = 'Auto-refresh paused while waiting for input. Reload the browser after answering.';+ return;+ }+ if (count >= MAX_UNCHANGED_RELOADS) {+ message.textContent = 'Auto-refresh paused: no new progress. Reload the browser to check or resume.';+ return;+ }+ message.textContent = 'Auto-refresh on while progress changes.';+ ['scroll', 'keydown', 'pointerdown'].forEach(function (event) {+ window.addEventListener(event, function () { lastInteraction = Date.now(); }, { passive: true });+ });+ setInterval(function () {+ if (Date.now() - lastInteraction < QUIET_MS) return;+ if (document.hidden) return;+ refresh();+ }, RELOAD_MS);+}++function planRefreshScript(progress, options) {+ // Hash actual progress, never render time or the random CSP nonce. Rewriting an+ // unchanged plan must not renew its polling budget or conceal an interrupted run.+ const marker = crypto.createHash('sha256').update(JSON.stringify(progress)).digest('hex');+ return `(${watchPlan.toString()})(${JSON.stringify({ ...options, progress: marker })});`;+}++module.exports = { planRefreshScript };diff --git a/plugins/mobile-apps/scripts/tests/app-docs.test.js b/plugins/mobile-apps/scripts/tests/app-docs.test.jsindex 52a95b2c0..43b458429 100644--- a/plugins/mobile-apps/scripts/tests/app-docs.test.js+++ b/plugins/mobile-apps/scripts/tests/app-docs.test.js@@ -6,6 +6,7 @@ const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const test = require('node:test');+const vm = require('node:vm');const {EDIT_ITEM_STATUSES, PHASES, PHONE_STAGES, SECTIONS, applyStep, initState, loadState, outputPath,@@ -23,6 +24,158 @@ function seeded(root) {return save(root, initState(root, { appName: 'Field Inspections', dataPlatform: 'dataverse' }));}+// Execute the script emitted into the real artifact across simulated navigations.+// Time advances only at timer ticks, so the production reload budget is tested without+// spending five minutes per case.+function refreshPage(html, href, {+ hidden = false, storageUnavailable = false, navigationType = 'navigate',+} = {}) {+ const script = html.match(/<script[^>]*id="planRefreshScript"[^>]*>([\s\S]*?)<\/script>/);+ assert.ok(script, 'the generated plan must include its refresh controller');+ const handlers = {};+ const intervals = [];+ const navigations = [];+ const message = { textContent: '' };+ let now = 100000;+ vm.runInNewContext(script[1], {+ URL,+ performance: { getEntriesByType: () => [{ type: navigationType }] },+ Date: { now: () => now },+ location: { href, replace: (fresh) => navigations.push(fresh) },+ document: {+ hidden,+ getElementById: (id) => id === 'refreshStatus' ? message : null,+ },+ window: { addEventListener: (event, callback) => { handlers[event] = callback; } },+ sessionStorage: storageUnavailable ? {+ getItem() { throw new Error('Storage unavailable'); },+ setItem() { throw new Error('Storage unavailable'); },+ } : {},+ setInterval: (callback) => intervals.push(callback),+ });+ return {+ intervals, navigations, handlers, message,+ tick() { now += 10000; intervals.forEach((callback) => callback()); },+ };+}++test('create and edit plans bound unchanged reloads, even without browser storage', () => {+ for (const edit of [false, true]) {+ const root = project('docs-refresh-cap');+ try {+ const state = initState(root, { appName: 'App' });+ applyStep(state, { id: 'requirements', status: 'active', note: 'Working' });+ const render = () => {+ if (edit) return writeEditProgress(root, { status: 'active', note: 'Working' });+ return save(root, state) && outputPath(root);+ };+ let href = 'file:///app/docs/plan.html?keep=value#changes';+ for (let attempt = 0; attempt < 30; attempt += 1) {+ // Each render stamps a new generated time/nonce but makes no progress.+ state.updatedAt = new Date(attempt * 1000).toISOString();+ const page = refreshPage(fs.readFileSync(render(), 'utf8'), href, { storageUnavailable: true });+ page.tick();+ assert.equal(page.navigations.length, 1);+ href = page.navigations[0];+ }+ const paused = refreshPage(fs.readFileSync(render(), 'utf8'), href);+ assert.equal(paused.intervals.length, 0, 'an interrupted run must stop polling');+ assert.match(paused.message.textContent, /no new progress/);+ assert.equal(new URL(href).searchParams.get('keep'), 'value');+ assert.equal(new URL(href).hash, '#changes');+ const manual = refreshPage(fs.readFileSync(render(), 'utf8'), href, { navigationType: 'reload' });+ assert.equal(manual.intervals.length, 1, 'manual refresh renews the progress check');+ manual.tick();+ assert.equal(new URL(manual.navigations[0]).searchParams.get('planReloads'), '1',+ 'browser reload starts a fresh budget even when the URL still carries the exhausted count');++ applyStep(state, { id: 'requirements', status: 'done' });+ applyStep(state, { id: 'architecture', status: 'active', note: 'Planning' });+ const changedFile = edit+ ? writeEditProgress(root, { status: 'active', phase: 'build', note: 'Building' })+ : save(root, state) && outputPath(root);+ const changed = refreshPage(fs.readFileSync(changedFile, 'utf8'), href);+ changed.tick();+ assert.equal(new URL(changed.navigations[0]).searchParams.get('planReloads'), '1',+ 'real progress renews the budget');+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+ }+});++test('initial and between-phase plans keep polling within the unchanged-reload budget', () => {+ const root = project('docs-refresh-between-phases');+ try {+ const state = initState(root, { appName: 'App' });+ for (const betweenPhases of [false, true]) {+ if (betweenPhases) applyStep(state, { id: 'requirements', status: 'done' });+ save(root, state);+ const html = fs.readFileSync(outputPath(root), 'utf8');+ let href = 'file:///app/docs/plan.html';+ for (let attempt = 0; attempt < 30; attempt += 1) {+ const page = refreshPage(html, href);+ page.tick();+ assert.equal(page.navigations.length, 1,+ `${betweenPhases ? 'between-phase' : 'initial'} plan must pick up the next update`);+ href = page.navigations[0];+ }+ assert.equal(refreshPage(html, href).intervals.length, 0,+ 'a plan with no active phase must still stop if progress never changes');+ applyStep(state, { id: 'architecture', status: 'active', note: 'Planning' });+ save(root, state);+ const resumed = refreshPage(fs.readFileSync(outputPath(root), 'utf8'), href);+ resumed.tick();+ assert.equal(new URL(resumed.navigations[0]).searchParams.get('planReloads'), '1',+ 'the next phase renews the budget');+ applyStep(state, { id: 'architecture', status: 'pending' });+ }+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});++test('input gates, terminal plans and reader activity do not trigger automatic reloads', () => {+ const root = project('docs-refresh-states');+ try {+ const state = initState(root, { appName: 'App' });+ for (const edit of [false, true]) {+ for (const status of ['waiting', 'done', 'failed']) {+ applyStep(state, {+ id: 'requirements', status: status === 'waiting' ? 'active' : status,+ note: status === 'waiting' ? 'Gate 1 - awaiting your approval' : '',+ });+ if (!edit && status === 'done') {+ // Completing one phase is a between-phase snapshot, not a finished run.+ for (const phase of state.phases) applyStep(state, { id: phase.id, status: 'done' });+ }+ const file = edit+ ? writeEditProgress(root, { status, waiting: status === 'waiting' })+ : save(root, state) && outputPath(root);+ const html = fs.readFileSync(file, 'utf8');+ assert.doesNotMatch(html, /id="refreshPlan"/, 'use browser reload instead of a dedicated button');+ const page = refreshPage(html, 'file:///app/plan.html', { navigationType: 'reload' });+ assert.equal(page.intervals.length, 0, `${edit ? 'edit' : 'create'} ${status}`);+ }+ }+ applyStep(state, { id: 'requirements', status: 'active', note: 'Working' });+ save(root, state);+ const html = fs.readFileSync(outputPath(root), 'utf8');+ const hidden = refreshPage(html, 'file:///app/plan.html', { hidden: true });+ hidden.tick();+ assert.equal(hidden.navigations.length, 0);+ const reading = refreshPage(html, 'file:///app/plan.html');+ reading.handlers.pointerdown();+ reading.tick();+ assert.equal(reading.navigations.length, 0);+ reading.tick();+ reading.tick();+ assert.equal(reading.navigations.length, 1);+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});+test('init creates docs/ with a plan that carries its own brand mark', () => {const root = project('docs-init');seeded(root);@@ -319,7 +472,8 @@ test('edit progress renders each operation state and settles when work completesassert.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.equal(refreshPage(html, 'file:///app/edit.html').intervals.length, 0,+ 'waiting for approval must pause polling');assert.match(html, /sessionStorage\.setItem\(STORE_SCROLL/);assert.match(html, /sessionStorage\.getItem\(STORE_SCROLL/);assert.match(html, /window\.scrollTo\(0, savedScroll\)/);@@ -345,7 +499,8 @@ test('edit progress renders each operation state and settles when work completes],});const completedHtml = fs.readFileSync(progress, 'utf8');- assert.doesNotMatch(completedHtml, /location\.replace\(fresh\)/);+ assert.equal(refreshPage(completedHtml, 'file:///app/edit.html').intervals.length, 0,+ 'completed edits must stop polling');assert.match(completedHtml, /sessionStorage\.getItem\(STORE_SCROLL/);assert.match(completedHtml, /window\.scrollTo\(0, savedScroll\)/);assert.match(completedHtml, /Scan to test the changes/);@@ -1521,18 +1676,20 @@ test('the plan never reloads over a reader, and never resets their place', () =>assert.match(template, /window\.scrollTo\(0, savedScroll\)/);// Reading, typing, scrolling or clicking defers the reload; a hidden tab never reloads.- assert.match(template, /Date\.now\(\) - lastInteraction < QUIET_MS/);- assert.match(template, /if \(document\.hidden\) return;/);+ const controller = fs.readFileSync(path.resolve(__dirname, '..', 'lib', 'plan-refresh.js'), 'utf8');+ assert.match(controller, /Date\.now\(\) - lastInteraction < QUIET_MS/);+ assert.match(controller, /if \(document\.hidden\) return;/);// And it stops altogether once the build is finished.- assert.match(template, /if \(!summary\.settled\)/);+ assert.match(controller, /if \(options\.settled\)/);// A bare reload() may serve the cached copy: a file:// page has no cache headers, and each// rewrite lands as a new inode at the same path via an atomic rename. The animation could// therefore persist until a hard refresh, so the refresh goes through a changing URL.- assert.doesNotMatch(template, /(?<!\/\/.*)\blocation\.reload\(\)/,+ assert.doesNotMatch(controller, /(?<!\/\/.*)\blocation\.reload\(\)/,'a plain reload can be served from the file:// cache');- assert.match(template, /location\.replace\(fresh\)/);- assert.match(template, /\?t=' \+ Date\.now\(\)/, 'the reload URL must differ every time');+ assert.match(controller, /location\.replace\(fresh\.href\)/);+ assert.match(controller, /searchParams\.set\('t', String\(Date\.now\(\)\)\)/,+ 'the reload URL must differ every time');// replace(), not assign(): this fires every few seconds and must not fill the back button.assert.doesNotMatch(template, /location\.assign\(/);diff --git a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js b/plugins/mobile-apps/scripts/tests/run-plan-page.test.jsindex dec3b2b51..0c3183b69 100644--- a/plugins/mobile-apps/scripts/tests/run-plan-page.test.js+++ b/plugins/mobile-apps/scripts/tests/run-plan-page.test.js@@ -117,15 +117,17 @@ async function runPage(htmlPath, { session = {} } = {}) {const renders = [];const errors = [];const sandbox = {+ URL,+ performance: { getEntriesByType: () => [{ type: 'navigate' }] },document,window: {document,addEventListener() {}, removeEventListener() {},- location: { hash: '', reload() {} },+ location: { href: 'file:///app/docs/create-app-plan.html', hash: '', reload() {}, replace() {} },matchMedia() { return { matches: false, addEventListener() {} }; },setTimeout() { return 0; }, setInterval() { return 0; }, scrollTo() {}, scrollY: 0,},- location: { hash: '', reload() {} },+ location: { href: 'file:///app/docs/create-app-plan.html', hash: '', reload() {}, replace() {} },sessionStorage: {store: new Map(Object.entries(session)),getItem(key) { return this.store.has(key) ? this.store.get(key) : null; },