Skip to content

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.

model-apps: harden Playwright launcher, add hooks/validators + 1DS telemetry, version check (v2.3.0) (#262)

Akshay Maloo6b51549b5a84
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
index 0ff0d263c..6585e5513 100644
--- a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
@@ -61,7 +61,7 @@
## Phase 5b — Single-page fast path
- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched for page-builder)
-- Data mode: connector (SharePoint Online)
+- Data mode: mock + connectors (SharePoint Online)
- Read sample: plugins/model-apps/samples/7-responsive-cards.tsx (card list layout pattern for document display)
- Read references/verified-icons.txt to source icon names
- Wrote sharepoint-docs.tsx
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index ef9089a06..4f42cbcfd 100644
--- a/plugins/model-apps/.claude-plugin/plugin.json
+++ b/plugins/model-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.2.0",
+ "version": "2.3.0",
"description": "Build and deploy Power Apps generative pages for model-driven apps with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index ef9089a06..4f42cbcfd 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.2.0",
+ "version": "2.3.0",
"description": "Build and deploy Power Apps generative pages for model-driven apps with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index a90bfa6b1..daf05164c 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -41,14 +41,15 @@ agents/ ← Agent definitions (invoked by skills via Task
references/ ← Shared reference docs
rules.md ← Full code-gen rules, DataAPI types, layout patterns, common errors
plan-schema.md ← Schema contract for genpage-plan.md
- data-caching.md ← Rule 15 list/detail caching pattern (loaded conditionally)
+ data-caching.md ← Rule 15 on-mount fetch: de-dupe + cache (loaded conditionally)
localization.md ← Multi-language + RTL pattern (loaded conditionally)
supported-dependencies.md ← Versioned package list for generated pages
troubleshooting.md ← Deployment/runtime/env issues
verified-icons.txt ← ~5000 Fluent UI icon names; Grep-validated by page-builder
samples/ ← Example .tsx files (12 samples)
scripts/
- launch-playwright-mcp.js ← Playwright MCP server launcher (detects system browser)
+ launch-playwright-mcp.js ← Playwright MCP server launcher (fullscreen; uses lib/detect-browser.js)
+ playwright-mcp-fullscreen.config.json ← Fullscreen browser config for the launcher
regenerate-verified-icons.js ← Regenerates references/verified-icons.txt from npm
check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match
dataverse-request.js ← General Dataverse Web API wrapper (escape hatch)
@@ -63,12 +64,23 @@ scripts/
lib/
dataverse-auth.js ← Shared auth + HTTP helpers (uses `az account get-access-token`)
supported-dependencies.js ← Single source of truth for runtime + dev deps versions
- tests/ ← node --test coverage for the scripts above
+ detect-browser.js ← System Chromium/Edge/Chrome detection (used by the launcher)
+ modelapps-hook-utils.js ← Tracked-skill discovery + validator lookup for the hooks
+ telemetry/ ← Bundled 1DS telemetry: ikey.json (this plugin's config) + lib/ (copy of shared/telemetry/lib)
+ tests/ ← node --test coverage for the scripts + hooks
+hooks/ ← Lifecycle hooks (registered in hooks/hooks.json)
+ run-skill-posttool-validation.js ← Runs a skill's validate*.js after the Skill tool returns
+ validate-icon-imports.js ← PostToolUse: blocks unverified @fluentui/react-icons in genpage .tsx
+ validate-write-safety.js ← PreToolUse: flags (non-blocking) out-of-cwd writes in a genpage session
+ run-skill-pretool-telemetry.js ← PreToolUse(Skill): emits skill_started (ships disabled)
+ run-user-prompt-telemetry.js ← UserPromptSubmit: emits skill_started for /model-apps:<skill>
skills/
genpage/
SKILL.md ← Orchestrator skill (delegates to agents)
edit-flow.md ← Edit flow steps (loaded only on edit path)
verify-flow.md ← Playwright browser verification (loaded only when user opts in)
+ report-issue/ ← Bug-report skill (bundled shared workflow)
+ telemetry/ ← /model-apps:telemetry on|off|status control skill
```
## Skills
@@ -76,6 +88,8 @@ skills/
| Skill | Description |
|-------|-------------|
| `/genpage` | Build and deploy generative pages for a model-driven Power App |
+| `/report-issue` | File a bug report against this plugin's GitHub repo |
+| `/telemetry` | Enable/disable/check anonymous usage telemetry (`on \| off \| status`) |
## Agents
@@ -150,6 +164,55 @@ The **`connectors`** flag currently ships OFF: GenPage connector support needs t
pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX authoring control
(power-platform-ux), and the maker/admin ECS setting to all be released first.
+## Hooks & Validators
+
+Hooks are registered centrally in `hooks/hooks.json` (auto-loaded by the plugin
+host). Every hook **fails open** on any internal error (exit 0) and **fails closed**
+(exit 2) only on a real violation, so a hook bug can never break a genpage run.
+
+- **PostToolUse(Skill)** — `run-skill-posttool-validation.js` runs a skill's
+ `skills/<skill>/scripts/validate*.js` when present. Tracked skills are discovered
+ from `skills/*/SKILL.md` by `scripts/lib/modelapps-hook-utils.js` (the telemetry
+ control skill is excluded from tracking).
+- **PostToolUse(Write|Edit|MultiEdit)** — `validate-icon-imports.js` validates
+ `@fluentui/react-icons` named imports in genpage-generated `.tsx` files against
+ `references/verified-icons.txt`, automating the page-builder's manual grep. It is
+ gated to genpage output (the file's `export default GeneratedComponent` marker or
+ a sibling `genpage-plan.md`) so it never fires on unrelated React files.
+- **PreToolUse(Write|Edit|MultiEdit)** — `validate-write-safety.js` **flags
+ (non-blocking, exit 1)** writes outside the cwd, and **only during an active
+ genpage session** (a `genpage-plan.md` at/under cwd). It never blocks and is a
+ clean no-op in unrelated projects — the plugin installs globally, so it must not
+ constrain other work. Silence with `MODEL_APPS_SKIP_WRITE_GUARD=1`.
+- **Master kill-switch** — `MODEL_APPS_DISABLE_HOOKS=1` (or `true`) disables **all**
+ model-apps hooks (validators + telemetry emit); checked before any stdin/work.
+ Both escape hatches are documented in `README.md`.
+
+## Telemetry
+
+This plugin ships 1DS telemetry for `skill_started`. The canonical library is the
+repo-root `shared/telemetry/`; `scripts/lib/telemetry/lib` is a **physical copy**
+(never a symlink) so installed plugins don't depend on symlink handling. Edit
+`shared/telemetry/lib/` first, then refresh this plugin's copy in the same change.
+
+- **Posture:** the committed `ikey.json` ships **`disabled: true`** (Tier-1 static,
+ no resolver) — currently carrying the **provisioned model-apps key + collector +
+ `event_stream_name`, staged disabled**. It emits nothing — no POST, no local log —
+ while `disabled: true`; flip `disabled` to `false` only after the Geneva mapping
+ is validated in DGrep (see the ADE provisioning runbook). `disabled: true` is the
+ active guard; the placeholder-key gate is a secondary defense for un-provisioned
+ copies. **Provision a fresh key; never copy another plugin's `ikey.json`**
+ (CI-enforced: `node scripts/validate-telemetry-ikeys.js`).
+- **Emission:** `hooks/run-skill-pretool-telemetry.js` (PreToolUse Skill) and
+ `hooks/run-user-prompt-telemetry.js` (UserPromptSubmit `/model-apps:<skill>`).
+- **Privacy:** anonymous, default-on. Users opt out of transmission via
+ `/model-apps:telemetry off`; the local diagnostic mirror
+ (`~/.power-platform-skills/telemetry/model-apps/sessions/<id>/events.jsonl`) is
+ still written. CI/automation opt out via
+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1` (highest precedence).
+- **Fail closed:** telemetry never changes a script's exit code; emission is
+ fire-and-forget via a detached dispatcher child. See `shared/telemetry/README.md`.
+
## Development Standards
- **React 17 + TypeScript** — all generated code
@@ -182,6 +245,7 @@ After modifying this plugin:
5. Test skill invocation with `/genpage`
6. Test with both Dataverse entity pages and mock data pages (smoke + edit)
7. Verify Playwright browser verification works (navigate, snapshot, click, screenshot)
+8. Hooks/validators + telemetry hooks are covered by step 2. Keep `scripts/lib/telemetry/ikey.json` shipping `disabled: true` until a key is provisioned (a test enforces this), and run `node scripts/validate-telemetry-ikeys.js` after touching `ikey.json`
## Eval Suite
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index c32559e3d..c6da836ee 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -2,7 +2,65 @@
All notable changes to the **model-apps** plugin.
-## [Unreleased] — 2.2.0
+## 2.3.0 — 2026-07-23
+
+Plugin observability + authoring guardrails: default-on (but ship-disabled)
+anonymous telemetry with a local diagnostic log, PostToolUse validators, and a
+hardened Playwright launcher. No breaking changes.
+
+### Added
+- **Anonymous 1DS telemetry (default-on, ships `disabled` until provisioned).**
+ Copied the shared telemetry library into `scripts/lib/telemetry/lib` with a
+ plugin-owned `ikey.json` (Tier-1 static key; ships `disabled: true` until go-live).
+ Emits `skill_started` via PreToolUse(Skill) + UserPromptSubmit hooks and writes
+ a local diagnostic mirror at
+ `~/.power-platform-skills/telemetry/model-apps/sessions/<id>/events.jsonl`. New
+ `/model-apps:telemetry on|off|status` control skill; CI/automation opt-out via
+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1`. Fail-closed throughout —
+ never changes a skill's exit code. Carries **no user-level identifier** (no Entra
+ object id) — only org/tenant GUIDs when signed in.
+- **PostToolUse validators (`hooks/hooks.json`).** A per-skill validator runner
+ plus an `@fluentui/react-icons` allowlist check that validates every genpage
+ `.tsx` write against `references/verified-icons.txt`, automating the
+ page-builder's manual icon-grep step (hallucinated or sized icon names are
+ blocked at write time).
+- **PreToolUse write-safety guard.** **Flags (non-blocking, exit 1)**
+ Write/Edit/MultiEdit outside the cwd, and only during an active genpage session
+ (a `genpage-plan.md` at/under cwd) — so a globally-installed plugin never blocks
+ or interferes with unrelated work. Silence with `MODEL_APPS_SKIP_WRITE_GUARD=1`.
+
+### Fixed
+- **Generated-page double-fetch / render flash on open.** Generated data pages
+ could fetch twice and re-flash the spinner because (1) the webplayer host
+ double-mounts the page on open (a cache-bypassing app relaunch ~300ms after
+ the first mount re-runs the data effect — confirmed via network capture: two
+ `POST .../powerapps/apps/<app>/launch`, the second `bypass-cache=true`), and
+ (2) `dataApi` is a new reference each render, so listing it in a `useEffect`
+ dep array re-fires the effect every render. Reworked the data-fetch guidance
+ (`references/data-caching.md`, `rules.md` Rule 15) and every exemplar
+ (samples 3/9/10/11, `localization.md`) to use an **in-flight-promise de-dupe +
+ `window` cache** (concurrent mounts share one round-trip; later mounts paint
+ from cache with no spinner) and a **readiness boolean** dependency —
+ `dataApi` is now forbidden in any dependency array. The de-dupe applies to any
+ page that fetches on mount, including single-visit overviews/dashboards
+ (previously excluded from caching); `Needs caching:` in the plan schema now
+ means "fetches on mount." The host relaunch itself is a platform-side issue
+ tracked separately.
+- **Playwright MCP launcher.** `scripts/launch-playwright-mcp.js` now exports
+ `launch()` — satisfying the `.mcp.json` contract instead of relying on a
+ require-time side-effect — adds `-y` (avoids the npx first-run prompt hang),
+ opens the browser fullscreen via `playwright-mcp-fullscreen.config.json`, and
+ quotes the config path so Windows paths with spaces work. Browser detection
+ extracted to the reusable `scripts/lib/detect-browser.js`.
+- Eval fixture `18-sharepoint-connectors-on`: relabel the connector-only page
+ `Data mode: mock + connectors` to match the page-builder contract (connectors
+ are orthogonal to the Dataverse axis).
+
+### Tests
+- New `node:test` coverage for the launcher, `modelapps-hook-utils`, the
+ icon-import and write-safety validators, and the telemetry pretool hook.
+
+## 2.2.0
Local-dev ergonomics, sample coverage, and an automated eval suite with
real and synthetic fixtures. Builds on v2.1; no breaking changes.
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index ff18734e2..e09568c7f 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -121,6 +121,59 @@ The plugin invokes multiple tools during a session. To reduce approval prompts:
claude --dangerously-skip-permissions
```
+## Hooks and guardrails
+
+The plugin registers lifecycle hooks (in `hooks/hooks.json`) that run automatically
+while it's loaded. They are **fail-open**: any internal error exits 0, so a hook can
+never fail or abort a skill run. Because the plugin installs **globally**, the hooks
+are scoped so they don't interfere with unrelated projects: the write-safety guard
+only **flags** (never blocks) and only during an active genpage session, and the icon
+validator only fires on genpage output. At most, the icon validator blocks a single
+tool call (the agent reworks it) — never the whole skill.
+
+| Hook | When | What it does |
+|---|---|---|
+| Write-safety | before Write/Edit/MultiEdit | **Flags (non-blocking)** writes outside the cwd — only during a genpage session (a `genpage-plan.md` at/under cwd). Never blocks; silent in unrelated projects. |
+| Icon validator | after a genpage `.tsx` write | Blocks `@fluentui/react-icons` imports that aren't in the verified list. |
+| Skill validator | after a skill runs | Runs the skill's `validate*.js` if it has one. |
+| Telemetry | on skill start / prompt | Emits anonymous `skill_started` (see [Telemetry](#telemetry)). |
+
+**Escape hatches** (environment variables — set to `1` or `true`):
+
+| Variable | Effect |
+|---|---|
+| `MODEL_APPS_DISABLE_HOOKS` | Disables **all** model-apps hooks (validators + telemetry emit). |
+| `MODEL_APPS_SKIP_WRITE_GUARD` | Disables **only** the write-safety guard (keeps the others). |
+
+```powershell
+# Windows (PowerShell)
+$env:MODEL_APPS_DISABLE_HOOKS = "1"
+```
+
+```bash
+# macOS / Linux (bash)
+export MODEL_APPS_DISABLE_HOOKS=1
+```
+
+## Telemetry
+
+model-apps ships anonymous, opt-out usage telemetry (1DS). The committed config ships
+**disabled** (`disabled: true`) — it emits nothing until go-live, even though it now
+carries the provisioned model-apps key + stream (staged, not yet enabled). `disabled:
+true` is the active guard; the placeholder-key check is only a secondary guard for
+un-provisioned copies. Once enabled it is **on by default** (you opt out).
+
+- **What's collected:** skill name, plugin/PAC/agent versions, OS/Node versions, and
+ Dataverse org/tenant GUIDs when signed in. **Never** file paths, prompts, tool
+ inputs, entity/table names, URLs, credentials, usernames, hostnames, or any
+ user-level identifier (no Entra object id).
+- **Local diagnostic mirror:** every event is also written to
+ `~/.power-platform-skills/telemetry/model-apps/sessions/<id>/events.jsonl` (even
+ when you've opted out of transmission) — hand over that one file when filing an issue.
+- **Opt out** per-user with `/model-apps:telemetry off` (re-enable with `on`, check
+ with `status`), or for CI/automation set
+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT=1` (highest precedence).
+
## Technology Stack
- **React 17 + TypeScript** — all generated page code
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index 775a8f52e..a7f1a4755 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -132,21 +132,21 @@ Read the relevant sample file identified in the plan:
${PLUGIN_ROOT}/samples/[sample-name].tsx
```
-If **Data mode** is `dataverse` AND the page fits the "list / detail / pages
-the user navigates back to" profile (per the plan's Per-Page Specification),
-also read the data caching reference:
+If **Data mode** is `dataverse` AND the page **fetches data on mount** (any
+list, detail, or single-visit overview/dashboard — per the plan's Per-Page
+Specification), also read the data fetching reference:
```
${PLUGIN_ROOT}/references/data-caching.md
```
-Skip the caching reference for forms, single-visit dashboards, mock-data pages,
-or any page where the user is not expected to navigate away and return.
+Skip it only for mock-data pages and forms with no initial fetch.
Use the sample as a structural reference — follow its patterns for component
-organization, DataAPI usage, and styling approach. For pages that need caching,
-the data-caching reference is authoritative for the inline IIFE + cache
-guard + batched state pattern.
+organization, DataAPI usage, and styling approach. For any page that fetches on
+mount, the data-fetching reference is authoritative for the in-flight de-dupe +
+`window` cache + readiness-dep pattern that survives the host double-mount.
+**Never put `dataApi` in a dependency array** (see rules.md Rule 15).
## Step 4 — Create a Task
diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.md
index 024ef8b2f..74dce72cf 100644
--- a/plugins/model-apps/agents/genpage-planner.md
+++ b/plugins/model-apps/agents/genpage-planner.md
@@ -415,10 +415,11 @@ prefix you embed in a column name is a silent footgun.
`crb2b_playerresult.crb2b_playername`), but write only suffixes in the document.
For the `## Per-Page Specifications` section, set the **`Needs caching:`** field
-(exact key, with space) per page: `true` for list pages, detail pages, or any
-page where the user is likely to navigate away and return; `false` for forms,
-single-visit dashboards, or mock-data pages. The page-builder reads this field
-to decide whether to load `references/data-caching.md`.
+(exact key, with space) per page: `true` for any page that **fetches data on
+mount** — list, detail, or single-visit overview/dashboard (all need the
+in-flight de-dupe that survives the host double-mount); `false` only for
+mock-data pages and forms with no initial fetch. The page-builder reads this
+field to decide whether to load `references/data-caching.md`.
For the `## Relevant Samples` section: pick the most structurally relevant sample
from `${PLUGIN_ROOT}/samples/` (e.g., 7-responsive-cards.tsx for card
diff --git a/plugins/model-apps/docs/architecture.md b/plugins/model-apps/docs/architecture.md
index a4340f269..bf4167d81 100644
--- a/plugins/model-apps/docs/architecture.md
+++ b/plugins/model-apps/docs/architecture.md
@@ -130,7 +130,7 @@ plugins/model-apps/
├── references/ <-- read on demand by agents
│ ├── rules.md <-- code-gen rules (page-builder hot path)
│ ├── plan-schema.md <-- plan doc contract
-│ ├── data-caching.md <-- Rule 15 list/detail pattern
+│ ├── data-caching.md <-- Rule 15 on-mount fetch: de-dupe + cache
│ ├── localization.md <-- multi-language + RTL pattern
│ ├── supported-dependencies.md <-- v2.2: package.json input list
│ ├── troubleshooting.md <-- deploy / runtime / env issues
diff --git a/plugins/model-apps/hooks/hooks.json b/plugins/model-apps/hooks/hooks.json
new file mode 100644
index 000000000..9ab8fbcf6
--- /dev/null
+++ b/plugins/model-apps/hooks/hooks.json
@@ -0,0 +1,60 @@
+{
+ "_comment": "PreToolUse: write-safety FLAGS (non-blocking, exit 1) Write/Edit/MultiEdit outside the cwd only during an active genpage session (genpage-plan.md at/under cwd); skill-pretool-telemetry emits anonymous skill_started (ships disabled until provisioned). PostToolUse: per-skill validator + on every code write validate @fluentui/react-icons imports against references/verified-icons.txt. UserPromptSubmit: emit skill_started for /model-apps:<skill> slash commands. All telemetry is fail-closed and default-off in ikey.json. Run the host from the target project folder (or pass it as cwd).",
+ "hooks": {
+ "PreToolUse": [
+ {
+ "matcher": "Write|Edit|MultiEdit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','validate-write-safety.js'));\"",
+ "timeout": 10
+ }
+ ]
+ },
+ {
+ "matcher": "Skill|skill",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-pretool-telemetry.js'));\"",
+ "timeout": 30
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "Skill|skill",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-posttool-validation.js'));\"",
+ "timeout": 30
+ }
+ ]
+ },
+ {
+ "matcher": "Write|Edit|MultiEdit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','validate-icon-imports.js'));\"",
+ "timeout": 10
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-user-prompt-telemetry.js'));\"",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/model-apps/hooks/run-skill-posttool-validation.js b/plugins/model-apps/hooks/run-skill-posttool-validation.js
new file mode 100644
index 000000000..a34652922
--- /dev/null
+++ b/plugins/model-apps/hooks/run-skill-posttool-validation.js
@@ -0,0 +1,82 @@
+#!/usr/bin/env node
+
+/**
+ * PostToolUse hook for model-apps skills.
+ *
+ * After a Skill tool call returns, look up whether the invoked skill has a
+ * registered validator (skills/<skill>/scripts/validate*.js). If so, run it with
+ * the same stdin payload and propagate its stdout/stderr/exit code back.
+ *
+ * Mirrors the mobile-apps / power-pages validation-only hook. This plugin's
+ * version intentionally has NO ALM reconcile branch (genpage has no ALM plan) and
+ * no telemetry coupling — telemetry is emitted by the separate PreToolUse /
+ * UserPromptSubmit hooks. Adding a new validator = drop a validate*.js under the
+ * skill's scripts/ dir; modelapps-hook-utils.js discovers it automatically.
+ *
+ * Fail-open: any internal error exits 0 so a hook bug can never break a skill run.
+ */
+
+const path = require('path');
+const { spawnSync } = require('child_process');
+const {
+ getTrackedSkillFromToolInput,
+ getValidatorScript,
+} = require('../scripts/lib/modelapps-hook-utils');
+
+const DEBUG = process.env.DEBUG === '1' || process.env.DEBUG === 'true';
+
+// Master kill-switch: MODEL_APPS_DISABLE_HOOKS=1 disables every model-apps hook
+// (validators + telemetry emit) — an operator escape hatch if a hook ever
+// misbehaves. Checked before any stdin/work so it is a clean no-op (exit 0).
+if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISABLE_HOOKS === 'true') {
+ process.exit(0);
+}
+
+function debug(msg) {
+ if (DEBUG) process.stderr.write(msg);
+}
+
+debug('[model-apps hook] run-skill-posttool-validation.js started\n');
+
+let inputData = '';
+
+process.stdin.on('data', (chunk) => {
+ inputData += chunk;
+});
+
+process.stdin.on('end', () => {
+ debug(`[model-apps hook] stdin closed, received ${inputData.length} bytes\n`);
+ try {
+ const input = JSON.parse(inputData);
+ const skillName = getTrackedSkillFromToolInput(input.tool_input);
+ if (!skillName) {
+ debug('[model-apps hook] No tracked skill detected — skipping validation\n');
+ process.exit(0);
+ }
+
+ const validatorScript = getValidatorScript(skillName);
+ if (!validatorScript) {
+ debug(`[model-apps hook] Skill "${skillName}" has no validator — skipping\n`);
+ process.exit(0);
+ }
+
+ debug(`[model-apps hook] Running validator for skill "${skillName}": ${validatorScript}\n`);
+
+ const validatorPath = path.join(__dirname, '..', validatorScript);
+ const result = spawnSync(process.execPath, [validatorPath], {
+ input: inputData,
+ encoding: 'utf8',
+ cwd: input.cwd || process.cwd(),
+ });
+
+ if (result.stdout) process.stdout.write(result.stdout);
+ if (result.stderr) process.stderr.write(result.stderr);
+
+ debug(`[model-apps hook] Validator exited with code ${result.status ?? 0}\n`);
+ process.exit(result.status ?? 0);
+ } catch (err) {
+ // Never block on a hook-side bug — the skill already ran.
+ process.stderr.write(`[model-apps hook] Unexpected error: ${err.message}\n`);
+ process.exit(0);
+ }
+});
diff --git a/plugins/model-apps/hooks/run-skill-pretool-telemetry.js b/plugins/model-apps/hooks/run-skill-pretool-telemetry.js
new file mode 100644
index 000000000..f85310753
--- /dev/null
+++ b/plugins/model-apps/hooks/run-skill-pretool-telemetry.js
@@ -0,0 +1,198 @@
+#!/usr/bin/env node
+"use strict";
+
+/**
+ * PreToolUse(Skill) telemetry hook for the model-apps plugin.
+ *
+ * Emits an anonymous `skill_started` event when a tracked model-apps skill is
+ * invoked via the Skill tool. Uses the shared 1DS library copied into this plugin
+ * at scripts/lib/telemetry/lib. Mirrors the power-pages pretool hook — the only
+ * plugin-specific bits are the pluginName ("model-apps"), the hook-utils import,
+ * and this plugin's own ikey.json.
+ *
+ * Posture: this plugin's committed ikey.json ships `disabled: true` (the primary
+ * gate — currently carrying the provisioned key + stream, staged disabled), so
+ * today the hook short-circuits at `if (disabled)` and emits nothing (no local
+ * log, no POST). When enabled (`disabled: false`), a secondary non-placeholder/
+ * provisioned check gates emission, and the same code path emits. Once the Kusto
+ * mapping is validated and disabled is flipped to false, telemetry flows. Every
+ * branch is fail-closed: a missing lib, unreadable config, thrown resolver, or
+ * bad stdin all exit 0 so the hook can never break a skill run.
+ */
+
+const path = require("node:path");
+const fs = require("node:fs");
+const os = require("node:os");
+const crypto = require("node:crypto");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..");
+const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");
+
+// Master kill-switch: MODEL_APPS_DISABLE_HOOKS=1 disables every model-apps hook
+// (validators + telemetry emit) — an operator escape hatch. Checked before any
+// requires/stdin/work so it is a clean no-op (exit 0). Telemetry also has its own
+// finer-grained opt-out (ikey.json disabled, /model-apps:telemetry off, *_OPTOUT).
+if (process.env.MODEL_APPS_DISABLE_HOOKS === "1" || process.env.MODEL_APPS_DISABLE_HOOKS === "true") {
+ process.exit(0);
+}
+
+let emitSpawn, eventsLib, sessionLib, pacAuthLib, agentInfoLib, resolverLoader;
+try {
+ emitSpawn = require(path.join(TELEMETRY_DIR, "lib", "emit-spawn"));
+ eventsLib = require(path.join(TELEMETRY_DIR, "lib", "events"));
+ sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));
+ pacAuthLib = require(path.join(TELEMETRY_DIR, "lib", "pac-auth"));
+ agentInfoLib = require(path.join(TELEMETRY_DIR, "lib", "agent-info"));
+ resolverLoader = require(path.join(TELEMETRY_DIR, "lib", "resolver-loader"));
+} catch {
+ process.exit(0);
+}
+
+let hookUtils;
+try {
+ hookUtils = require(path.join(PLUGIN_ROOT, "scripts", "lib", "modelapps-hook-utils"));
+} catch {
+ process.exit(0);
+}
+
+function readPluginVersion() {
+ try {
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")
+ );
+ return manifest.version || "unknown";
+ } catch {
+ return "unknown";
+ }
+}
+
+function readIkey() {
+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate
+ // ikey.json so tests can flip disabled/provisioned state without mutating the
+ // checked-in config. Mirrors emit-dispatcher.js / emit-from-prompt.js.
+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ const ikeyPath =
+ override && override.trim() ? override : path.join(TELEMETRY_DIR, "ikey.json");
+ try {
+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));
+ return { cfg, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };
+ } catch {
+ // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching the
+ // dispatcher's kill-switch semantics so a missing/corrupt config can't be
+ // bypassed into an emit attempt.
+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };
+ }
+}
+
+function osFriendlyName(platform) {
+ if (platform === "win32") return "Windows";
+ if (platform === "darwin") return "Mac";
+ if (platform === "linux") return "Linux";
+ return platform;
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let buf = "";
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (c) => (buf += c));
+ process.stdin.on("end", () => resolve(buf));
+ process.stdin.on("error", () => resolve(buf));
+ });
+}
+
+(async () => {
+ const raw = await readStdin();
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ process.exit(0);
+ }
+
+ const skillName = hookUtils.getTrackedSkillFromToolInput(parsed.tool_input);
+ if (!skillName) process.exit(0);
+
+ // Repo-side hard-off / unconfigured: gate BEFORE the pac shell-outs
+ // (`pac auth who` + `pac --version`) so a disabled or unconfigured plugin costs
+ // effectively nothing. The user opt-out is NOT a fast-path: the enriched event
+ // is still built and dispatched so the detached dispatcher can write the local
+ // diagnostic mirror; it reads the per-plugin config and skips the POST.
+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();
+ if (disabled) process.exit(0);
+ const resolver = resolverLoader.loadResolver(path.dirname(ikeyPath));
+ let provisioned;
+ try {
+ provisioned =
+ resolver && typeof resolver.isProvisioned === "function"
+ ? resolver.isProvisioned(cfg)
+ // Tier-1 static-key fallback (no resolver): a real key must be present AND
+ // must not be the shipped placeholder sentinel. Without the sentinel check,
+ // flipping `disabled:false` before replacing the key would still be treated
+ // as provisioned — incurring the pac shellouts and a local-mirror write even
+ // though the dispatcher can never POST a placeholder key. Matches the
+ // dispatcher's own PLACEHOLDER_IKEY guard.
+ : !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING");
+ } catch {
+ // A plugin resolver threw — treat as not provisioned so a bad resolver can't
+ // crash the pretool hook and impact the tool run (fail closed).
+ provisioned = false;
+ }
+ if (!provisioned) process.exit(0);
+
+ const correlation_id = crypto.randomUUID();
+ const configDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";
+ const fakeProbe = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";
+
+ let pacAuth = null;
+ try {
+ pacAuth = pacAuthLib.readPacAuth();
+ } catch {
+ pacAuth = null;
+ }
+
+ let agentInfo = {};
+ try {
+ agentInfo = {
+ ...agentInfoLib.readAiAgent(),
+ pacCliVersion: agentInfoLib.readPacCliVersion(),
+ };
+ } catch {
+ agentInfo = {};
+ }
+
+ const fields = {
+ pluginName: "model-apps",
+ pluginVersion: readPluginVersion(),
+ sessionId: sessionLib.getSessionId(sessionLib.resolveHostSessionId(parsed)),
+ correlationId: correlation_id,
+ osName: osFriendlyName(process.platform),
+ osVersion: os.release(),
+ nodeVersion: "v" + String(process.versions.node).split(".")[0],
+ skillName,
+ };
+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;
+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;
+ // model-apps intentionally does NOT send the Entra directory object id
+ // (aadObjectId) that power-pages attaches as eventInfo — no user-level
+ // identifier reaches telemetry. Org/tenant GUIDs (org-level) still flow.
+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;
+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;
+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;
+
+ try {
+ emitSpawn.fireAndForget(eventsLib.buildSkillStarted(eventStreamName, fields), {
+ cloud: (pacAuth && pacAuth.cloud) || "",
+ configDir,
+ fakeProbe,
+ // Point the dispatcher at the same ikey.json readIkey() used — the override
+ // seam when set, otherwise this plugin's real config — so a bundled library
+ // copy never falls back to shared/telemetry's placeholder ikey.json.
+ ikeyJsonPath: ikeyPath,
+ });
+ } catch {
+ // fail closed
+ }
+
+ process.exit(0);
+})().catch(() => process.exit(0));
diff --git a/plugins/model-apps/hooks/run-user-prompt-telemetry.js b/plugins/model-apps/hooks/run-user-prompt-telemetry.js
new file mode 100644
index 000000000..521b9839a
--- /dev/null
+++ b/plugins/model-apps/hooks/run-user-prompt-telemetry.js
@@ -0,0 +1,97 @@
+#!/usr/bin/env node
+"use strict";
+
+/**
+ * UserPromptSubmit telemetry hook for the model-apps plugin.
+ *
+ * Emits `skill_started` when the submitted prompt is a tracked `/model-apps:<skill>`
+ * (or bare `/<skill>`) slash command. This complements the PreToolUse(Skill) hook:
+ * some hosts surface a slash-command skill as a prompt rather than a Skill tool call.
+ *
+ * Delegates all gating (repo kill switch, provisioned check, opt-out, local mirror,
+ * POST) to the shared emit-from-prompt helper. Fail-closed: any error exits 0 so
+ * telemetry never blocks the user's prompt.
+ */
+
+const path = require("node:path");
+const fs = require("node:fs");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..");
+const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");
+
+// Master kill-switch: MODEL_APPS_DISABLE_HOOKS=1 disables every model-apps hook
+// (validators + telemetry emit) — an operator escape hatch. Checked before any
+// requires/stdin/work so it is a clean no-op (exit 0). Telemetry also has its own
+// finer-grained opt-out (ikey.json disabled, /model-apps:telemetry off, *_OPTOUT).
+if (process.env.MODEL_APPS_DISABLE_HOOKS === "1" || process.env.MODEL_APPS_DISABLE_HOOKS === "true") {
+ process.exit(0);
+}
+
+let emitFromPrompt, hookUtils, sessionLib, pacAuthLib;
+try {
+ emitFromPrompt = require(path.join(TELEMETRY_DIR, "lib", "emit-from-prompt"));
+ hookUtils = require(path.join(PLUGIN_ROOT, "scripts", "lib", "modelapps-hook-utils"));
+ sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));
+ pacAuthLib = require(path.join(TELEMETRY_DIR, "lib", "pac-auth"));
+} catch {
+ process.exit(0);
+}
+
+function readPluginVersion() {
+ try {
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")
+ );
+ return manifest.version || "unknown";
+ } catch {
+ return "unknown";
+ }
+}
+
+function readStdin() {
+ return new Promise((resolve) => {
+ let buf = "";
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (c) => (buf += c));
+ process.stdin.on("end", () => resolve(buf));
+ process.stdin.on("error", () => resolve(buf));
+ });
+}
+
+(async () => {
+ const raw = await readStdin();
+ if (!raw) process.exit(0);
+
+ let parsed;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ process.exit(0);
+ }
+
+ const prompt = typeof parsed.prompt === "string" ? parsed.prompt : "";
+ if (!prompt) process.exit(0);
+
+ try {
+ emitFromPrompt.emitSkillStartedFromPrompt(prompt, {
+ pluginName: "model-apps",
+ pluginVersion: readPluginVersion(),
+ trackedSkills: hookUtils.TRACKED_SKILLS,
+ telemetryDir: TELEMETRY_DIR,
+ sessionId: sessionLib.resolveHostSessionId(parsed),
+ // Drop the Entra directory object id before the shared helper attaches it as
+ // eventInfo — model-apps telemetry carries no user-level identifier (an
+ // intentional drift from power-pages). Org/tenant GUIDs still flow via the
+ // helper's own pacAuth reads.
+ _readPacAuth: () => {
+ const a = pacAuthLib.readPacAuth();
+ if (a && a.objectId) delete a.objectId;
+ return a;
+ },
+ });
+ } catch {
+ // fail closed — telemetry never blocks the user's prompt
+ }
+
+ process.exit(0);
+})().catch(() => process.exit(0));
diff --git a/plugins/model-apps/hooks/validate-icon-imports.js b/plugins/model-apps/hooks/validate-icon-imports.js
new file mode 100644
index 000000000..ab3549ae7
--- /dev/null
+++ b/plugins/model-apps/hooks/validate-icon-imports.js
@@ -0,0 +1,229 @@
+#!/usr/bin/env node
+
+/**
+ * PostToolUse hook: validate @fluentui/react-icons imports against the plugin's
+ * verified icon allowlist. Automates the manual "Grep each icon name against
+ * verified-icons.txt" step that genpage-page-builder does by hand
+ * (agents/genpage-page-builder.md Step 2.5), so a hallucinated or wrong-variant
+ * icon name is caught deterministically at write time instead of only when the
+ * deployed page throws "X is not exported from @fluentui/react-icons" at runtime.
+ *
+ * Fires after Write / Edit / MultiEdit on TS/JS(X) files. Exit codes:
+ * 0 = pass / not applicable (fail-OPEN — any doubt or internal error → allow)
+ * 2 = block + corrective message on stderr (Claude Code convention)
+ *
+ * SCOPING — why this does not fire on every React file in the repo:
+ * The verified list is an ALLOWLIST (must-be-in-list), not a denylist. Running an
+ * allowlist check on arbitrary .tsx files would false-positive on any legitimate
+ * Fluent icon this plugin's snapshot doesn't know about. So we only validate files
+ * that are genpage output: the final file contains `export default GeneratedComponent`
+ * (every genpage page ends with it — see references/rules.md), OR a sibling
+ * `genpage-plan.md` sits in the same directory (the genpage working dir). Any other
+ * file is ignored.
+ *
+ * The icons list (references/verified-icons.txt) is the same source page-builder
+ * greps; it holds ~5000 UNSIZED names (Regular/Filled variants only), one per line,
+ * with `#` comment lines. Because it is unsized-only, a sized import like
+ * `Add24Regular` is naturally rejected too — matching the "unsized variants only"
+ * rule (references/rules.md).
+ */
+
+const fs = require('fs');
+const path = require('path');
+
+const PLUGIN_ROOT = path.resolve(__dirname, '..');
+const VERIFIED_ICONS_PATH = path.join(PLUGIN_ROOT, 'references', 'verified-icons.txt');
+const ICON_MODULE = '@fluentui/react-icons';
+
+// Master kill-switch: MODEL_APPS_DISABLE_HOOKS=1 disables every model-apps hook
+// (validators + telemetry emit) — an operator escape hatch if a hook ever
+// misbehaves. Checked before any stdin/work so it is a clean no-op (exit 0).
+if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISABLE_HOOKS === 'true') {
+ process.exit(0);
+}
+
+function isWriteTool(toolName) {
+ return toolName === 'Write' || toolName === 'Edit' || toolName === 'MultiEdit';
+}
+
+function isWatchedFile(filePath) {
+ return typeof filePath === 'string' && /\.(tsx|ts|jsx|js)$/i.test(filePath);
+}
+
+/**
+ * In PostToolUse the file is already on disk, so the on-disk content is the
+ * authoritative final state (catches imports added by an Edit that only touched a
+ * fragment). Fall back to the tool_input content only if the read fails.
+ */
+function readFinalContent(toolName, toolInput, absPath) {
+ if (absPath) {
+ try {
+ return fs.readFileSync(absPath, 'utf8');
+ } catch {
+ // fall through to tool_input
+ }
+ }
+ if (toolName === 'Write' && typeof toolInput.content === 'string') return toolInput.content;
+ if (toolName === 'Edit' && typeof toolInput.new_string === 'string') return toolInput.new_string;
+ if (toolName === 'MultiEdit' && Array.isArray(toolInput.edits)) {
+ return toolInput.edits
+ .map((e) => (e && typeof e.new_string === 'string' ? e.new_string : ''))
+ .join('\n');
+ }
+ return '';
+}
+
+function isGenpageFile(content, absPath) {
+ // The canonical genpage default export is `export default GeneratedComponent;`
+ // (references/rules.md). Accept the inline `function`/`class` forms too. The
+ // sibling genpage-plan.md check below is the primary, reliable gate for real
+ // runs (the working dir always has it); this content marker is a fallback for
+ // files written outside a recognized working dir.
+ if (/export\s+default\s+(?:function\s+|class\s+)?GeneratedComponent\b/.test(content)) return true;
+ if (absPath) {
+ try {
+ // The genpage working dir always contains genpage-plan.md alongside the .tsx.
+ return fs.existsSync(path.join(path.dirname(absPath), 'genpage-plan.md'));
+ } catch {
+ return false;
+ }
+ }
+ return false;
+}
+
+function loadVerifiedIcons() {
+ // Returns a Set of verified names, or null if the list can't be read (→ fail open).
+ try {
+ const raw = fs.readFileSync(VERIFIED_ICONS_PATH, 'utf8');
+ const set = new Set();
+ for (const line of raw.split(/\r?\n/)) {
+ const name = line.trim();
+ if (!name || name.startsWith('#')) continue; // skip header/comment/blank lines
+ set.add(name);
+ }
+ return set.size > 0 ? set : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Extract the named specifiers imported from `@fluentui/react-icons`.
+ * Handles: `import { A, B as C } from '@fluentui/react-icons'` and the
+ * `import type { ... }` form. Only the local-source name before `as` matters —
+ * that's the icon export being referenced.
+ *
+ * Only real, top-level import statements are matched: `/* ... *\/` block comments
+ * are stripped first, and the pattern is anchored to the start of a line so a
+ * commented-out example (`// import { Foo } from '@fluentui/react-icons'`) or an
+ * indented occurrence inside prose is ignored. This is fail-open: if stripping
+ * ever drops a genuine import, we under-report (miss a bad icon) rather than
+ * wrongly block a legitimate write.
+ *
+ * Example matched block:
+ * import { AddRegular, DeleteRegular as Trash } from "@fluentui/react-icons";
+ * → ["AddRegular", "DeleteRegular"]
+ */
+function extractIconImports(content) {
+ const names = [];
+ // Strip comments before matching so a comment inside a multi-line import block
+ // can't defeat validation two ways: (a) a `//` line leaves the next specifier
+ // starting with `//…` so it fails the identifier test and is silently skipped,
+ // and (b) a `}` inside a `//` comment prematurely ends the `[^}]+` capture and
+ // the whole import fails to match — both fail OPEN (a bad icon slips through).
+ // The `(?<!:)` lookbehind on the line-comment strip preserves `https://` URLs.
+ const code = content
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
+ .replace(/(?<!:)\/\/[^\n]*/g, '');
+ const escapedModule = ICON_MODULE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const re = new RegExp(
+ "^[ \\t]*import\\s+(?:type\\s+)?\\{([^}]+)\\}\\s*from\\s*['\"]" + escapedModule + "['\"]",
+ 'gm'
+ );
+ let m;
+ while ((m = re.exec(code)) !== null) {
+ for (const raw of m[1].split(',')) {
+ const spec = raw.trim();
+ if (!spec) continue;
+ const local = spec.split(/\s+as\s+/)[0].trim();
+ // Skip anything that isn't a bare identifier (defensive against odd syntax).
+ if (/^[A-Za-z_$][\w$]*$/.test(local)) names.push(local);
+ }
+ }
+ return names;
+}
+
+function buildBlockMessage(relPath, invalid) {
+ const lines = [];
+ // User-facing summary — short, no jargon. States what happened (a block); the
+ // auto-fix only occurs when an agent is driving, so it is phrased as a
+ // conditional expectation — a user editing manually gets an actionable note
+ // rather than a promise the hook can't keep.
+ lines.push(
+ `[model-apps] The write was blocked: it imported ${invalid.length} icon name(s) that aren't in the verified @fluentui/react-icons list (listed below). If an agent is generating this page, it will switch to verified icons and retry. If you're editing by hand, replace them with verified names from references/verified-icons.txt.`
+ );
+ lines.push('');
+ // Model-facing block.
+ lines.push(`For the agent: BLOCKED — unverified @fluentui/react-icons imports in ${relPath}:`);
+ for (const name of invalid) {
+ lines.push(` - ${name}`);
+ }
+ lines.push('');
+ lines.push(
+ 'Every icon imported from "@fluentui/react-icons" must be an UNSIZED name that exists verbatim in ' +
+ 'references/verified-icons.txt (e.g. `AddRegular`, `DeleteFilled`) — never a sized variant like ' +
+ '`Add24Regular`, and never a guessed name. Grep the closest verified name ' +
+ '(`Grep pattern: "^<IconName>$" path: references/verified-icons.txt`), replace each invalid ' +
+ 'import + its JSX usage, and re-issue the Write/Edit. Do not import icons from any other library.'
+ );
+ return lines.join('\n');
+}
+
+let inputData = '';
+process.stdin.on('data', (chunk) => {
+ inputData += chunk;
+});
+process.stdin.on('end', () => {
+ let input;
+ try {
+ input = JSON.parse(inputData || '{}');
+ } catch {
+ process.exit(0); // can't parse → don't block
+ }
+
+ const toolName = input.tool_name || input.toolName;
+ const toolInput = input.tool_input || input.toolInput || {};
+ if (!isWriteTool(toolName)) process.exit(0);
+
+ const filePath = toolInput.file_path || toolInput.filePath;
+ if (!isWatchedFile(filePath)) process.exit(0);
+
+ const cwd = input.cwd || process.cwd();
+ const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
+
+ const content = readFinalContent(toolName, toolInput, absPath);
+ if (!content) process.exit(0);
+
+ // Only validate genpage-generated pages (see SCOPING note above).
+ if (!isGenpageFile(content, absPath)) process.exit(0);
+
+ const imported = extractIconImports(content);
+ if (imported.length === 0) process.exit(0);
+
+ const verified = loadVerifiedIcons();
+ if (!verified) process.exit(0); // can't load the allowlist → fail open
+
+ // De-dupe while preserving order for a stable message.
+ const seen = new Set();
+ const invalid = [];
+ for (const name of imported) {
+ if (verified.has(name) || seen.has(name)) continue;
+ seen.add(name);
+ invalid.push(name);
+ }
+ if (invalid.length === 0) process.exit(0);
+
+ const relPath = path.relative(cwd, absPath) || absPath;
+ process.stderr.write(buildBlockMessage(relPath, invalid) + '\n');
+ process.exit(2);
+});
diff --git a/plugins/model-apps/hooks/validate-write-safety.js b/plugins/model-apps/hooks/validate-write-safety.js
new file mode 100644
index 000000000..1c90670b8
--- /dev/null
+++ b/plugins/model-apps/hooks/validate-write-safety.js
@@ -0,0 +1,170 @@
+#!/usr/bin/env node
+
+/**
+ * PreToolUse guardrail for Write / Edit / MultiEdit.
+ *
+ * Path safety — reject writes whose absolute path escapes the current working
+ * directory. Stops a runaway sub-agent (e.g. a parallel genpage page-builder)
+ * from clobbering ~/.bashrc, /etc/*, sibling repos, etc. genpage always works
+ * inside a working directory created under the cwd (SKILL Phase 0), so every
+ * legitimate write stays under it.
+ *
+ * SCOPING (global-install safety): this plugin's hooks are installed globally, so
+ * this guard must NOT constrain writes in unrelated projects. It therefore only
+ * enforces during an active genpage session — detected by a `genpage-plan.md` at
+ * or one level under the cwd (genpage Phase 0 creates the working dir as a child
+ * of cwd and writes the plan into it). With no genpage-plan.md present the hook is
+ * a clean no-op (exit 0), so a globally-installed model-apps plugin never blocks
+ * ordinary out-of-cwd writes.
+ *
+ * This intentionally does NOT scan content for secrets. Per repo convention,
+ * secret handling is done via agent instructions in SKILL.md (no fixed regex can
+ * cover every credential shape); this guard is strictly about write location.
+ *
+ * NON-BLOCKING by design = exit 1 (Claude Code shows the stderr message to the
+ * USER and lets the write proceed; only exit 2 would block). We deliberately do
+ * NOT hard-block: the skill may legitimately run from an unusual cwd or a temp
+ * dir, so a false positive must never stop the user's write — it only flags a
+ * possibly-runaway out-of-cwd write for the user to notice.
+ *
+ * Silence: set MODEL_APPS_SKIP_WRITE_GUARD=1 (this guard) or
+ * MODEL_APPS_DISABLE_HOOKS=1 (all model-apps hooks).
+ */
+
+const path = require('path');
+const os = require('os');
+const fs = require('fs');
+
+const DEBUG = process.env.DEBUG === '1' || process.env.DEBUG === 'true';
+const SKIP = process.env.MODEL_APPS_SKIP_WRITE_GUARD === '1' || process.env.MODEL_APPS_SKIP_WRITE_GUARD === 'true';
+
+// Master kill-switch: MODEL_APPS_DISABLE_HOOKS=1 disables every model-apps hook
+// (validators + telemetry emit) — an operator escape hatch if a hook ever
+// misbehaves. Checked before any stdin/work so it is a clean no-op (exit 0).
+if (process.env.MODEL_APPS_DISABLE_HOOKS === '1' || process.env.MODEL_APPS_DISABLE_HOOKS === 'true') {
+ process.exit(0);
+}
+
+function debug(msg) {
+ if (DEBUG) process.stderr.write(`[write-safety] ${msg}\n`);
+}
+
+// Non-blocking warning. Exit 1 (not 2) so Claude Code shows this on stderr to the
+// USER and still lets the write through — the guard flags, it does not block.
+function warn(userMsg) {
+ process.stderr.write(`[model-apps] ${userMsg}\n`);
+ process.exit(1);
+}
+
+/**
+ * The cwd is the project root for any skill invocation. Any Write/Edit must stay
+ * under it. Exceptions: $TMPDIR scratch and the host's own ~/.claude/ state dir
+ * (EnterPlanMode persists plan files there before the orchestrator sees them —
+ * blocking those would break plan-mode UX).
+ */
+function isWithin(child, parent) {
+ // Windows paths are case-insensitive, so compare case-folded there — otherwise a
+ // target that differs only by drive-letter/segment casing (e.g. `d:\proj\x` vs a
+ // `D:\proj\x` cwd) is wrongly rejected. The `path.sep` boundary stops `/foobar`
+ // from matching a `/foo` parent. (Symlink/junction escape is NOT resolved here:
+ // realpath needs the target to exist, but PreToolUse fires before the write; a
+ // lexical check matches the mobile-apps/power-pages guardrails.)
+ const fold = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
+ const c = fold(child);
+ const p = fold(parent);
+ return c === p || c.startsWith(p + path.sep);
+}
+
+function isPathSafe(targetPath, cwd) {
+ if (!targetPath || typeof targetPath !== 'string') return true; // not our concern
+ const abs = path.resolve(cwd, targetPath);
+
+ if (isWithin(abs, path.resolve(cwd))) return true;
+ if (isWithin(abs, path.resolve(os.tmpdir()))) return true;
+
+ const home = os.homedir();
+ if (home && isWithin(abs, path.resolve(home, '.claude'))) return true;
+
+ return false;
+}
+
+/**
+ * True when the cwd looks like an active genpage run: a `genpage-plan.md` sits at
+ * the cwd or in one of its immediate child directories. genpage Phase 0 creates
+ * the working directory as a direct child of cwd and the planner writes
+ * genpage-plan.md into it (skills/genpage/SKILL.md), so the plan is at either
+ * `<cwd>/genpage-plan.md` (host started inside the working dir) or
+ * `<cwd>/<workdir>/genpage-plan.md` (host started at the project root). Shallow,
+ * bounded, and fail-open: any error → false (treat as "not a genpage session" and
+ * do NOT warn), because a hook must never interfere with unrelated work.
+ */
+function isGenpageSession(cwd) {
+ try {
+ if (fs.existsSync(path.join(cwd, 'genpage-plan.md'))) return true;
+ let scanned = 0;
+ for (const entry of fs.readdirSync(cwd, { withFileTypes: true })) {
+ if (!entry.isDirectory() || entry.name === 'node_modules' || entry.name === '.git') continue;
+ if (++scanned > 1000) break; // bound syscalls on very large project roots
+ if (fs.existsSync(path.join(cwd, entry.name, 'genpage-plan.md'))) return true;
+ }
+ } catch {
+ return false;
+ }
+ return false;
+}
+
+/**
+ * Extract the target path(s) from a tool_input regardless of Write/Edit/MultiEdit
+ * shape. All three carry a single `file_path`; MultiEdit's per-edit entries share it.
+ */
+function extractWritePaths(toolName, toolInput) {
+ if (!toolInput || typeof toolInput !== 'object') return [];
+ const fp = toolInput.file_path || toolInput.filePath;
+ if (typeof fp === 'string' && fp) return [fp];
+ return [];
+}
+
+let inputData = '';
+process.stdin.on('data', (c) => { inputData += c; });
+process.stdin.on('end', () => {
+ if (SKIP) {
+ debug('MODEL_APPS_SKIP_WRITE_GUARD=1 — bypassing');
+ process.exit(0);
+ }
+
+ let input;
+ try {
+ input = JSON.parse(inputData);
+ } catch (err) {
+ debug(`stdin parse failed: ${err.message}`);
+ process.exit(0); // never block on hook-side bugs
+ }
+
+ const toolName = input.tool_name || input.toolName || '';
+ const toolInput = input.tool_input || input.toolInput || {};
+ const cwd = input.cwd || process.cwd();
+
+ if (!['Write', 'Edit', 'MultiEdit'].includes(toolName)) {
+ process.exit(0);
+ }
+
+ // Global-install safety: only enforce during an active genpage session, so a
+ // globally-installed model-apps plugin never blocks writes in unrelated projects.
+ if (!isGenpageSession(cwd)) {
+ debug('no genpage-plan.md at/under cwd — not a genpage session, allowing');
+ process.exit(0);
+ }
+
+ for (const p of extractWritePaths(toolName, toolInput)) {
+ if (!isPathSafe(p, cwd)) {
+ warn(
+ `Heads up: a genpage ${toolName} targeted "${p}", which is outside your project folder ` +
+ `(${cwd}). Allowing it, but flagging in case a sub-agent went off-track. ` +
+ `Silence with MODEL_APPS_SKIP_WRITE_GUARD=1 or MODEL_APPS_DISABLE_HOOKS=1.`
+ );
+ }
+ }
+
+ debug(`OK ${toolName} ${extractWritePaths(toolName, toolInput).join(',')}`);
+ process.exit(0);
+});
diff --git a/plugins/model-apps/references/data-caching.md b/plugins/model-apps/references/data-caching.md
index b736a34b6..bd085c91a 100644
--- a/plugins/model-apps/references/data-caching.md
+++ b/plugins/model-apps/references/data-caching.md
@@ -1,134 +1,218 @@
-# Data Caching Pattern (Dataverse list/detail pages)
+# Data Fetching Pattern (Dataverse pages — de-dupe + cache)
-**Read this when:** a Dataverse page fetches data on mount AND the user is
-likely to navigate away and return (e.g., list page paired with a detail page,
-or a tabbed UI that can be re-opened). Do NOT apply blindly to every Dataverse
-page — single-visit pages, forms with no fetching, and short-lived dialogs
-don't need caching.
+**Read this when:** a page fetches Dataverse data on mount via `props.dataApi`.
+This is the default for **any** data-backed page — not only list/detail pages.
+The in-flight de-dupe below is what makes a page survive the genpage host's
+**double mount** (see below); the resolved cache additionally skips the spinner
+on return navigation. Skip this ONLY for pages that never fetch on mount:
+mock-data pages, forms with no initial fetch, and short-lived dialogs.
-## Why caching is needed
+## Why this pattern is needed
-The genpage platform **re-evaluates the module script on every navigation**.
-Module-level variables (`let _cache = null`) reset on each visit. Without
-caching, return visits re-fetch and re-show a loading spinner even when the
-data hasn't changed.
+Two independent platform behaviors make a naive on-mount fetch run more than once:
-## How the cache works
+1. **The host double-mounts the page on open.** When a generative page opens,
+ the PowerApps webplayer host launches the hosted app twice — a cached mount,
+ then a cache-bypassing re-mount ~300ms later (observed as two
+ `POST .../powerapps/apps/<app>/launch` calls, the second with
+ `bypass-cache=true`). Each fresh mount re-runs the data effect. This happens
+ **even when the effect's dependency array is correct**, so it cannot be fixed
+ by tuning deps alone — it must be de-duped.
+2. **`dataApi` is a new reference every render.** The host hands a fresh
+ `dataApi` object on each render. Putting `dataApi` in a `useEffect` /
+ `useMemo` / `useCallback` dependency array therefore re-fires the effect on
+ every render (not just on mount). **Never put `dataApi` in a dependency
+ array** — depend on a readiness boolean instead (see the pattern).
-Persist data on the `window` object using the naming convention
-`window.__pp<EntityName>Cache`. The `window` object survives module re-evaluation
-within the browser tab's lifetime.
+`window` state survives both the module re-evaluation the host does on
+navigation AND the double-mount (the second mount runs in the same window), so
+the fix lives on `window`:
-Always use a **single batched state object** (`{ records, loading, error }`)
-to avoid intermediate renders in React 17.
+- **In-flight promise** (`window.__pp<Entity>Inflight`) — concurrent mounts share
+ ONE pending fetch, so the double-mount makes a single network round-trip.
+- **Resolved cache** (`window.__pp<Entity>Cache`) — once resolved, later mounts
+ and return visits read the cache: no re-fetch, no spinner.
-## Pattern 1 — List page (array cache)
+Always use a **single batched state object** (`{ records, loading, error }`) and
+one `setData(...)` call to avoid intermediate renders in React 17.
-Use when a page shows a list/grid of records and the user may navigate away
-(e.g., to a detail page) and return.
+## Pattern 1 — List / array cache
+
+Use for any page that fetches a set of rows on mount.
```typescript
-// Module-level: read from window on eval (survives navigation)
-let _recordsCache: MyRow[] | null = (window as any).__ppMyEntityCache ?? null;
+// Module-level key aliases. The VALUES live on `window` (the single source of
+// truth) so they stay coherent across module re-evaluation and the double-mount.
+// IMPORTANT: make each key UNIQUE PER PAGE + QUERY (include the page name), never
+// entity-only — two different pages that query the same entity with different
+// select/filter must NOT share a cache or in-flight entry, or the second page
+// reads the first's rows (missing columns) or awaits the wrong query. `MyEntity`
+// below stands for "<PageName>_<entity>", e.g. "AccountOverview_account".
+const winAny = window as any;
+const CACHE_KEY = "__ppMyEntityCache";
+const INFLIGHT_KEY = "__ppMyEntityInflight";
// In component:
+const dataReady = !!dataApi; // the host may hand `dataApi` after first render
const [{ records, loading, error }, setData] = useState<{
records: MyRow[];
loading: boolean;
error: string | null;
-}>({ records: _recordsCache ?? [], loading: _recordsCache === null, error: null });
+}>(() => {
+ const cached = winAny[CACHE_KEY] as MyRow[] | undefined;
+ return { records: cached ?? [], loading: cached === undefined, error: null };
+});
useEffect(() => {
- if (!dataApi) { setData(prev => ({ ...prev, loading: false })); return; }
- if (_recordsCache !== null) return; // already cached — skip fetch, no spinner
- (async () => {
- try {
- const result = await dataApi.queryTable("myentity", {
- select: ["name", "statuscode"], // use VERIFIED column names
- });
- _recordsCache = result.rows;
- (window as any).__ppMyEntityCache = result.rows;
- setData({ records: result.rows, loading: false, error: null });
- } catch (err) {
- if (_recordsCache === null) {
- setData({ records: [], loading: false, error: "Unable to load records." });
- }
- }
- })();
-}, [dataApi]);
+ if (!dataReady) return; // wait until the host hands us the DataAPI
+
+ // Read the AUTHORITATIVE window cache (never a module-local snapshot): the
+ // other mount may have resolved it between this mount's render and this
+ // effect, and a module re-eval can leave a local copy stale. Sync state on a
+ // hit (reference compare avoids a redundant render) so we never stick on the
+ // spinner and we pick up an invalidated/replaced array.
+ const cached = winAny[CACHE_KEY] as MyRow[] | undefined;
+ if (cached !== undefined) {
+ if (records !== cached) setData({ records: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // De-dupe the host double-mount: share ONE in-flight promise on `window` so a
+ // racing second mount awaits it instead of firing a duplicate query.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<MyRow[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi
+ .queryTable("myentity", { select: ["name", "statuscode"] }) // VERIFIED columns
+ .then((result: { rows: MyRow[] }) => {
+ winAny[CACHE_KEY] = result.rows; // window = source of truth
+ return result.rows;
+ })
+ // Clear only if still ours — a concurrent refresh may have replaced
+ // this entry with a newer promise we must not delete.
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+
+ inflight
+ .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })
+ .catch(() => { if (!cancelled) setData({ records: [], loading: false, error: "Unable to load records." }); });
+
+ return () => { cancelled = true; };
+ // Depend on readiness only — NOT `dataApi` (a new ref each render would
+ // re-fire this effect every render). `dataReady` flips false->true once.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+}, [dataReady]);
```
-## Pattern 2 — Detail page (per-record Map cache)
+## Pattern 2 — Detail / per-record Map cache
-Use when a page receives a `recordId` via `pageInput` and displays a single
-record. The Map keyed by `recordId` caches multiple detail views.
+Use when a page receives a `recordId` via `pageInput` and displays one record.
+The Maps are keyed by `recordId` so multiple detail views cache independently.
```typescript
-// Module-level: IIFE re-attaches to the existing window Map on module re-eval
-const _detailCache: Map<string, MyRow> = (() => {
- if (!(window as any).__ppMyEntityDetailCache) {
- (window as any).__ppMyEntityDetailCache = new Map<string, MyRow>();
- }
- return (window as any).__ppMyEntityDetailCache;
-})();
+const winAny = window as any;
+// Re-attach to the existing window Maps on module re-eval.
+const _detailCache: Map<string, MyRow> =
+ winAny.__ppMyEntityDetailCache ?? (winAny.__ppMyEntityDetailCache = new Map());
+const _detailInflight: Map<string, Promise<MyRow>> =
+ winAny.__ppMyEntityDetailInflight ?? (winAny.__ppMyEntityDetailInflight = new Map());
// In component:
const recordId = pageInput?.recordId;
+const dataReady = !!dataApi && !!recordId;
const cachedRecord = recordId ? (_detailCache.get(recordId) ?? null) : null;
-const [{ record, loading, error }, setData] = useState({
+const [{ record, loading, error }, setData] = useState(() => ({
record: cachedRecord,
loading: !!recordId && cachedRecord === null,
error: null as string | null,
-});
+}));
useEffect(() => {
- if (!dataApi || !recordId) return;
- if (_detailCache.has(recordId)) return; // cached — no spinner
- (async () => {
- try {
- const row = await dataApi.retrieveRow("myentity", {
- id: recordId,
- select: ["name", "statuscode"], // use VERIFIED column names
- });
- _detailCache.set(recordId, row);
- setData({ record: row, loading: false, error: null });
- } catch (err) {
- if (!_detailCache.has(recordId)) {
- setData({ record: null, loading: false, error: "Unable to load record." });
- }
- }
- })();
-}, [dataApi, recordId]);
+ if (!dataReady) return;
+ const id = recordId as string;
+
+ // Sync from the authoritative window Map on a hit — the other mount may have
+ // resolved it between this mount's render and this effect, or `recordId` may
+ // have changed in place. Reference compare avoids a redundant render.
+ const hit = _detailCache.get(id);
+ if (hit !== undefined) {
+ if (record !== hit) setData({ record: hit, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // Share one in-flight fetch per recordId across concurrent mounts.
+ let pending = _detailInflight.get(id);
+ if (!pending) {
+ pending = dataApi
+ .retrieveRow("myentity", { id, select: ["name", "statuscode"] }) // VERIFIED columns
+ .then((row: MyRow) => { _detailCache.set(id, row); return row; })
+ // Delete only if still ours (a concurrent refresh may have replaced it).
+ .finally(() => { if (_detailInflight.get(id) === pending) _detailInflight.delete(id); });
+ _detailInflight.set(id, pending);
+ }
+
+ pending
+ .then((row) => { if (!cancelled) setData({ record: row, loading: false, error: null }); })
+ .catch(() => { if (!cancelled) setData({ record: null, loading: false, error: "Unable to load record." }); });
+
+ return () => { cancelled = true; };
+ // Readiness + recordId only — never `dataApi`.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+}, [dataReady, recordId]);
```
-## Cache invalidation
+## Cache invalidation and manual refresh
-After a mutation (create/update/delete via `dataApi`), invalidate the
-relevant cache(s) before refetching. Each cache lives at its own `window`
-key — be precise about which one you're clearing:
+After a mutation (create/update/delete), or when a manual refresh control fires,
+evict the relevant cache(s) **and any in-flight promise** before refetching, then
+bump a `reloadKey` state so the effect re-runs. Clear the in-flight entry too —
+otherwise the effect reuses the stale pending promise instead of fetching fresh:
```typescript
await dataApi.updateRow("myentity", recordId, changes);
+const w = window as any;
-// 1) Detail cache (Map keyed by recordId) — just evict the one row:
+// Detail: evict just the one row + its in-flight entry.
_detailCache.delete(recordId);
+_detailInflight.delete(recordId);
-// 2) List cache (whole array) — evict the entire array so the list refetches
-// next time it mounts. The cache is at __ppMyEntityCache (NOT ...DetailCache):
-delete (window as any).__ppMyEntityCache;
+// List: evict the whole array + its in-flight promise so the next mount refetches.
+delete w.__ppMyEntityCache;
+delete w.__ppMyEntityInflight;
+
+// Then trigger a re-run (readiness dep won't change, so use an explicit key):
+setReloadKey((k) => k + 1); // add `reloadKey` to the effect's dep array
```
-If the page only has a detail cache (no sibling list), skip step 2. If you
-have a list but no detail page open, skip step 1.
+When a page has a manual refresh button or a `reloadKey`, add it to the effect's
+dependency array alongside `dataReady` (e.g. `[dataReady, reloadKey]`).
+
+> **Concurrency note.** Because the effect reads the `window` cache as the source
+> of truth, deleting the cache key here makes the next mount refetch. One residual
+> edge case: if you invalidate while an *earlier* fetch is still in flight, that
+> earlier promise can still write its (now stale) result into the cache when it
+> resolves. For pages with frequent mutations racing initial loads, gate cache
+> writes behind a `window.__pp<Entity>Gen` counter you bump on every invalidation,
+> and only write the cache when the captured generation still matches. For the
+> common single-load-then-mutate flow this is unnecessary.
+
+## Scope — de-dupe always, cache when it helps
+
+The **in-flight de-dupe** (and readiness-only deps) applies to **any page that
+fetches on mount** — it is the fix for the host double-mount, so don't skip it.
-## When NOT to use this pattern
+Skip the whole pattern only for pages that **never fetch on mount**:
+- Mock-data pages (no real fetch)
+- Forms with no initial fetch
-- Forms that submit and navigate away (no return path)
-- Mock-data pages (no real fetch to cache)
-- Pages that must always show fresh data (real-time dashboards)
-- Pages visited only once per session
-- When the data set is large enough that `window` retention becomes a memory concern
+For the **resolved cache** specifically, keep the de-dupe but drop (or
+short-TTL) the persisted array/Map when:
+- The page must always show fresh data (real-time dashboards) — clear
+ `__pp<Entity>Cache` after first paint, or refetch on a timer.
+- The data set is large enough that `window` retention is a memory concern.
## What to substitute in the snippets above
@@ -138,5 +222,6 @@ Replace these placeholders with values verified from `RuntimeTypes.ts`:
|-------------|--------------|
| `MyRow` | The actual `TableRow<...>` type for your entity |
| `"myentity"` | The entity's logical name (singular, lowercase) |
-| `__ppMyEntityCache` / `__ppMyEntityDetailCache` | `__pp<EntityName>Cache` — distinct per entity to avoid collisions |
+| `__ppMyEntityCache` / `__ppMyEntityDetailCache` | Unique per **page + query** — include the page name, not just the entity, so two pages querying the same entity with different select/filter don't collide (e.g. `__ppAccountOverview_accountCache`) |
+| `__ppMyEntityInflight` / `__ppMyEntityDetailInflight` | The in-flight promise — same page+query scoping as the cache key |
| `select: [...]` | Actual column names from RuntimeTypes.ts |
diff --git a/plugins/model-apps/references/localization.md b/plugins/model-apps/references/localization.md
index f9aef1845..2fad6c64c 100644
--- a/plugins/model-apps/references/localization.md
+++ b/plugins/model-apps/references/localization.md
@@ -78,27 +78,46 @@ Detect RTL from the language LCID. Arabic (1025, 2049, 3073, 4097, 5121) and Heb
Retrieve these columns: `uilanguageid`, `localeid`, `decimalsymbol`, `numberseparator`, `currencysymbol`, `dateformatstring`, `dateseparator`.
```typescript
-const [userSettings, setUserSettings] = React.useState<any>(null);
+// Cache user settings on `window` + de-dupe the host double-mount so we retrieve
+// them once (see references/data-caching.md). Keyed globally — settings are
+// per-user and stable for the session.
+const winAny = window as unknown as Record<string, unknown>;
+const SETTINGS_KEY = "__ppUserSettings";
+const SETTINGS_INFLIGHT = "__ppUserSettingsInflight";
+
+const [userSettings, setUserSettings] = React.useState<any>(
+ () => (winAny[SETTINGS_KEY] as any) ?? null,
+);
+const dataReady = !!dataApi; // never depend on `dataApi` itself — see Rule 15
React.useEffect(() => {
- const fetchUserSettings = async () => {
- try {
- const currentUserId = (typeof Xrm !== "undefined" &&
- Xrm.Utility?.getGlobalContext()?.userSettings?.userId)
- ?.replace("{", "").replace("}", "");
- if (!currentUserId) return;
- const settings = await dataApi.retrieveRow("usersettings" as any, {
- id: currentUserId,
- select: ["uilanguageid", "localeid", "decimalsymbol", "numberseparator",
- "currencysymbol", "dateformatstring", "dateseparator"] as any,
- });
- setUserSettings(settings);
- } catch (error) {
- console.error("Failed to fetch user settings", error);
- }
- };
- void fetchUserSettings();
-}, [dataApi]);
+ if (!dataReady) return;
+ if (winAny[SETTINGS_KEY] !== undefined) { setUserSettings(winAny[SETTINGS_KEY]); return; }
+ const currentUserId = (typeof Xrm !== "undefined" &&
+ Xrm.Utility?.getGlobalContext()?.userSettings?.userId)
+ ?.replace("{", "").replace("}", "");
+ if (!currentUserId) return;
+ let cancelled = false;
+
+ // Share one in-flight fetch across the two host mounts.
+ let pending = winAny[SETTINGS_INFLIGHT] as Promise<any> | undefined;
+ if (!pending) {
+ pending = dataApi.retrieveRow("usersettings" as any, {
+ id: currentUserId,
+ select: ["uilanguageid", "localeid", "decimalsymbol", "numberseparator",
+ "currencysymbol", "dateformatstring", "dateseparator"] as any,
+ })
+ .then((settings: any) => { winAny[SETTINGS_KEY] = settings; return settings; })
+ .finally(() => { if (winAny[SETTINGS_INFLIGHT] === pending) delete winAny[SETTINGS_INFLIGHT]; });
+ winAny[SETTINGS_INFLIGHT] = pending;
+ }
+ pending
+ .then((settings: any) => { if (!cancelled) setUserSettings(settings); })
+ .catch((error: any) => { if (!cancelled) console.error("Failed to fetch user settings", error); });
+
+ return () => { cancelled = true; };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+}, [dataReady]);
```
Provide formatting helpers that use these settings. **NEVER hardcode date formats or currency symbols.**
diff --git a/plugins/model-apps/references/plan-schema.md b/plugins/model-apps/references/plan-schema.md
index 05646c881..bd398ac2f 100644
--- a/plugins/model-apps/references/plan-schema.md
+++ b/plugins/model-apps/references/plan-schema.md
@@ -144,10 +144,11 @@ connector bindings." sentinel).]
- **File:** [name].tsx
- **Purpose:** [one-line description]
- **Entities:** [comma-separated logical names OR "mock data"]
-- **Needs caching:** true / false — set true for list pages, detail pages, or any
- page where the user is likely to navigate away and return; false for forms,
- single-visit dashboards, mock-data pages. When true, the page-builder reads
- `references/data-caching.md`.
+- **Needs caching:** true / false — set true for any page that **fetches data on
+ mount** (list, detail, or single-visit overview/dashboard); all need the
+ in-flight de-dupe that survives the host double-mount. Set false only for
+ forms with no initial fetch and mock-data pages. When true, the page-builder
+ reads `references/data-caching.md`.
- **Key Features:** [what this specific page should do]
- **Components:** [Fluent UI V9 components to use]
- **Layout:** [responsive design approach]
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index f7cfa5094..63f12ea2e 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -20,7 +20,7 @@ Comprehensive rules for generating generative page code. Read this file during c
12. **Forbidden Functions**: Don't use `createTheme`, `mergeThemes`, `useTheme` (don't exist in Fluent UI V9)
13. **Navigation**: Use the `Xrm.Navigation.navigateTo` API for all in-app navigation. Never construct raw URLs or manipulate `window.location` — see **Special Patterns > Generative Page Navigation**.
14. **Batched async state — no intermediate renders**: React 17 does NOT batch `setState` calls inside async functions. Every separate `setState` triggers its own render. When a component fetches multiple pieces of data (e.g., a record plus related records), use a **single state object** and a **single `setData(...)` call** at the end: `const [{ record, related, loading, error }, setData] = useState({...})`. For multi-entity fetches, use `Promise.all` or `Promise.allSettled` so one `setData` completes the entire load. Never call `setLoading(false)` in a `finally` block when the data setters are in the `try` block — this always produces an intermediate render. **PageInput exception:** initial `useState({ loading: !!recordId, ... })` (PageInput rendering pattern) does NOT violate this rule — that's a synchronous initial value, not a separate `setState` call after fetch. The rule is per-effect: independent effects (e.g., usersettings fetch + record fetch) can each have their own single batched `setData`.
-15. **Data fetching — inline IIFE + cache guard (Dataverse list/detail pages)**: For pages where the user navigates away and returns (list paired with detail, tabbed UIs), use the module-level `window` cache + inline async IIFE pattern documented in `references/data-caching.md`. Never use `useCallback` for data-fetching functions — `dataApi` gets a new object reference after the initial render, so a `useCallback` recreates, re-fires the effect, and any `setData(loading: true)` call resets the spinner causing flicker. The cache guard (`if (cache.has(key)) return`) is the fix. **Do NOT apply this pattern to forms, single-visit dashboards, or mock-data pages.** See the reference for the full pattern.
+15. **Data fetching — de-dupe + cache, and NEVER `dataApi` in a dependency array (any Dataverse page that fetches on mount)**: The genpage host (a) hands a **new `dataApi` reference every render** and (b) **double-mounts the page on open** — a cache-bypassing re-mount ~300ms after the first. Both make a naive on-mount fetch run 2+ times → double fetch + spinner re-flash. Fixes: **(1)** Never put `dataApi` in a `useEffect`/`useMemo`/`useCallback` dependency array, and never `useCallback` a fetch function — it re-fires the effect on every render. Depend on a **readiness boolean** (`const dataReady = !!dataApi;`) plus `recordId`/`reloadKey` as needed. **(2)** Wrap the fetch in the **in-flight-promise de-dupe + `window` cache** pattern in `references/data-caching.md` so concurrent mounts share ONE round-trip and later mounts read cache. The in-flight de-dupe — not the dep array — is what defeats the host double-mount (correct deps alone do NOT). Apply to **any page that fetches on mount**, including single-visit overviews/dashboards. **Skip only mock-data pages and forms with no initial fetch.** See the reference for the full pattern.
16. **Overlays must be confined to the page container (`mountNode`)**: The generated page shares the DOM with the genpage *designer* — the preview is NOT an isolated iframe. Every Fluent surface that renders through a portal (`Dialog` via `DialogSurface`, `Popover`, `Menu`, `Tooltip`, `Combobox`/`Dropdown` listbox, `DatePicker`, `TimePicker`) defaults to portalling to `document.body` of the **designer**, so without a `mountNode` it escapes the preview and can cover the designer chrome — including the coding-agent panel. Establish a single `containerRef`/`mountNode` on the page root and thread it to every overlay. See **Special Patterns > Dialogs and Overlays**.
17. **No full-viewport modal scrims; prefer non-modal or in-page panels**: A default `<Dialog>` is `modalType="modal"` — it draws a `position: fixed` backdrop and traps focus across the whole window, which in the designer blankets the agent panel and locks the user out (they can't even ask the agent to remove it). Default dialogs to `modalType="non-modal"` **and** pass `mountNode`, or use an in-page absolutely-positioned panel. The page root must establish a containing block (`position: relative` + `contain: layout`) so even a fixed-position overlay is clipped to the page. Never size overlays to the viewport. See **Special Patterns > Dialogs and Overlays**.
18. **Never nest a `<Dialog>` inside another `<Dialog>`**: Stacked modal scrims and nested focus traps make dialogs impossible to dismiss reliably. Render sibling dialogs as separate top-level surfaces switched by state, never one `<Dialog>` as a child of another's JSX.
@@ -213,10 +213,13 @@ export interface PageInput {
const { dataApi, pageInput } = props;
const recordId = pageInput?.recordId;
const entityName = pageInput?.entityName;
+const dataReady = !!dataApi; // never depend on `dataApi` itself — see Rule 15
const [row, setRow] = useState(undefined);
useEffect(() => {
- if (entityName === "account" && recordId && dataApi) {
+ if (entityName === "account" && recordId && dataReady) {
+ // Full pages should also de-dupe the host double-mount — see
+ // references/data-caching.md. Kept minimal here for the illustration.
(async () => {
const r = await dataApi.retrieveRow("account", {
id: recordId,
@@ -225,7 +228,8 @@ useEffect(() => {
setRow(r);
})();
}
-}, [dataApi, entityName, recordId]);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+}, [dataReady, entityName, recordId]);
```
### Example — `data` with safe casting
@@ -403,25 +407,29 @@ Recurring CSS bugs that type-check and compile but render wrong. Check for these
3. **`tokens.fontFamilyNumeric` is Bahnschrift, not Segoe UI.** Using it for tabular numbers (counts, %, ranks, dates) renders those digits in Bahnschrift — visibly mismatched against Segoe UI everywhere else. Fix: use `tokens.fontFamilyBase` and keep `fontVariantNumeric: "tabular-nums"` for aligned digits.
4. **Gradient hero with white text: `colorPalette*Background2/3` tokens are light tints, not dark.** A gradient built from e.g. `colorPalettePurpleBackground3` / `colorPaletteTealBackground2` with `color: colorNeutralForegroundOnBrand` (white) renders white-on-light → unreadable; those `Background2/3` palette tokens are pale. Fix: build the gradient from the dark, saturated `colorPalette*Foreground2` stops (e.g. `colorPalettePurpleForeground2`, `colorPaletteTealForeground2`), which are dark enough for white text to pass AA.
-### Data Caching Across Navigations
+### Data Fetching: the host double-mount, de-dupe, and caching
-The genpage platform **re-evaluates the module script on every navigation** — including when the user navigates back to a page they've already visited. This means module-level variables (e.g., `let _cache = null`) are reset on each visit, causing the component to re-fetch data and show a loading spinner even on return visits.
+Two host behaviors make a naive on-mount fetch run more than once:
-**Fix: initialize module-level variables from `window`, and write back to `window` on fetch.** The `window` object persists for the lifetime of the browser session regardless of module re-evaluation.
+1. **Double-mount on open.** The PowerApps webplayer host launches the hosted app twice when a generative page opens — a cached mount, then a cache-bypassing re-mount ~300ms later (two `POST .../powerapps/apps/<app>/launch` calls, the second `bypass-cache=true`). Each fresh mount re-runs the data effect **even with a correct dependency array**.
+2. **Module re-evaluation on navigation.** Navigating back to a visited page re-evaluates the module script, resetting module-level variables (`let _cache = null`).
-Use `window.__pp<EntityName>Cache` as a naming convention to avoid collisions with other scripts.
+`window` survives both (the second mount runs in the same window), so the fix lives on `window`:
-**Always use a single batched state object** (`{ records, loading, error }`) — multiple separate `setState` calls in an async function produce separate renders in React 17, each potentially showing an intermediate state.
+- **In-flight promise** (`window.__pp<EntityName>Inflight`) — concurrent mounts share ONE pending fetch, so the double-mount is a single round-trip. This is the piece that defeats the double-mount; the dependency array cannot.
+- **Resolved cache** (`window.__pp<EntityName>Cache`) — later mounts and return visits read cache: no re-fetch, no spinner.
**Key rules:**
-- Initialize module-level variables from `window.__pp<EntityName>Cache` (naming convention to avoid collisions)
-- Write back to `window` after fetch so the data survives module re-evaluation
-- Use a single batched state object (`{ records, loading, error }`) — separate `setState` calls in async functions produce intermediate renders in React 17
-- For detail pages, use a `Map<string, MyRow>` on `window` keyed by `recordId`
+- **Never put `dataApi` in a dependency array** (`useEffect`/`useMemo`/`useCallback`) and never `useCallback` a fetch function — the host hands a new `dataApi` ref every render, so it re-fires the effect each render. Depend on a **readiness boolean** (`const dataReady = !!dataApi;`) plus `recordId`/`reloadKey` as needed.
+- **Scope each `window` key by page + query** (include the page name, e.g. `__ppAccountOverview_accountCache`), not just the entity — two pages querying the same entity with different `select`/`filter` must not share a cache or in-flight entry.
+- Seed initial `useState` from the `window` cache so the second mount paints final content with no spinner.
+- Use a single batched state object (`{ records, loading, error }`) — separate `setState` calls in async functions produce intermediate renders in React 17.
+- For detail pages, key both the cache and the in-flight map by `recordId` (`Map<string, ...>` on `window`).
+- On mutation or manual refresh, clear the cache **and** the in-flight promise before refetching.
-**When to apply:** Any time a page fetches Dataverse data and the user may navigate away and return (e.g., an explorer page paired with a detail page). First visit shows a spinner; return visits render instantly.
+**When to apply:** any page that fetches Dataverse data on mount (list, detail, and single-visit overviews/dashboards). Skip only mock-data pages and forms with no initial fetch.
-See [`references/data-caching.md`](./data-caching.md) for complete list-page and detail-page caching examples.
+See [`references/data-caching.md`](./data-caching.md) for the complete list and detail patterns.
### Charts and Visualization
- Use D3.js for all charts
diff --git a/plugins/model-apps/samples/10-detail-with-pageinput.tsx b/plugins/model-apps/samples/10-detail-with-pageinput.tsx
index d37e046c4..c3297b162 100644
--- a/plugins/model-apps/samples/10-detail-with-pageinput.tsx
+++ b/plugins/model-apps/samples/10-detail-with-pageinput.tsx
@@ -23,8 +23,9 @@ import { ArrowLeftRegular } from '@fluentui/react-icons';
// blank-flip-to-spinner flicker
// - Early-return when required input is missing (no conditional wrapper div)
// - Rule 14: SINGLE batched setData call after fetch
-// - Map<recordId, row> cache on window (Rule 15 detail-page pattern) so
-// return visits render instantly
+// - Map<recordId, row> cache + in-flight-promise Map on window (Rule 15
+// detail-page pattern) so the host double-mount fetches once and return
+// visits render instantly; readiness-only deps (never `dataApi`)
// - Lookup formatted-value access via @OData.Community.Display.V1.FormattedValue
type ContactRow = TableRow<{
@@ -40,11 +41,18 @@ type ContactRow = TableRow<{
type ReadableContact = ReadableTableRow<ContactRow>;
-// Map cache: key by recordId so each detail visit hits its own cached row.
-const CACHE_KEY = '__ppContactDetailCache';
-const winAny = window as unknown as Record<string, Map<string, ReadableContact> | undefined>;
-const cache: Map<string, ReadableContact> = winAny[CACHE_KEY] ?? new Map();
+// Map caches keyed by recordId — one resolved-row cache + one in-flight-promise
+// cache so concurrent mounts (the host double-mounts on open) share one fetch per
+// record. Both live on window to survive back-navigation. See data-caching.md.
+const CACHE_KEY = '__ppContactDetail_contactCache';
+const INFLIGHT_KEY = '__ppContactDetail_contactInflight';
+const winAny = window as unknown as Record<string, unknown>;
+const cache: Map<string, ReadableContact> =
+ (winAny[CACHE_KEY] as Map<string, ReadableContact> | undefined) ?? new Map();
winAny[CACHE_KEY] = cache;
+const inflight: Map<string, Promise<ReadableContact>> =
+ (winAny[INFLIGHT_KEY] as Map<string, Promise<ReadableContact>> | undefined) ?? new Map();
+winAny[INFLIGHT_KEY] = inflight;
// ---------- Styles ----------
@@ -138,18 +146,29 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
const [data, setData] = useState<{ record: ReadableContact | null; loading: boolean; error: string | null }>(
() => ({
record: cached ?? null,
- loading: !cached,
+ loading: cached === undefined,
error: null,
}),
);
+ const dataReady = !!dataApi;
+
useEffect(() => {
- // Cache hit — already pre-warmed in initial state, nothing to fetch.
- if (cache.has(recordId)) return;
+ if (!dataReady) return;
+ const hit = cache.get(recordId);
+ if (hit !== undefined) {
+ // The other mount may have resolved it between render and this effect,
+ // or recordId changed in place — sync so we don't stick on the spinner.
+ if (data.record !== hit) setData({ record: hit, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
- (async () => {
- try {
- const row = (await dataApi.retrieveRow('contact', {
+ // Share one in-flight fetch per recordId across concurrent mounts.
+ let pending = inflight.get(recordId);
+ if (!pending) {
+ pending = dataApi
+ .retrieveRow('contact', {
id: recordId,
select: [
'contactid',
@@ -161,15 +180,29 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
'address1_stateorprovince',
'_parentcustomerid_value',
],
- })) as ReadableContact;
- cache.set(recordId, row);
- setData({ record: row, loading: false, error: null });
- } catch (err) {
+ })
+ .then((row) => {
+ const typed = row as ReadableContact;
+ cache.set(recordId, typed);
+ return typed;
+ })
+ // Delete only if still ours (a concurrent refresh may have replaced it).
+ .finally(() => { if (inflight.get(recordId) === pending) inflight.delete(recordId); });
+ inflight.set(recordId, pending);
+ }
+
+ pending
+ .then((row) => { if (!cancelled) setData({ record: row, loading: false, error: null }); })
+ .catch((err) => {
+ if (cancelled) return;
const message = err instanceof Error ? err.message : 'Failed to load contact.';
setData({ record: null, loading: false, error: message });
- }
- })();
- }, [dataApi, recordId]);
+ });
+
+ return () => { cancelled = true; };
+ // Readiness + recordId only — never `dataApi`. See Rule 15.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady, recordId]);
const goBack = () => {
const xrm = (window as unknown as { Xrm?: { Navigation?: { navigateTo: (opts: unknown) => unknown } } }).Xrm;
diff --git a/plugins/model-apps/samples/11-kanban-with-dnd.tsx b/plugins/model-apps/samples/11-kanban-with-dnd.tsx
index 67c34d967..3e3ff9e52 100644
--- a/plugins/model-apps/samples/11-kanban-with-dnd.tsx
+++ b/plugins/model-apps/samples/11-kanban-with-dnd.tsx
@@ -28,7 +28,7 @@ import { GeneratedComponentProps, Task } from './RuntimeTypes';
// - Three columns mapped to task statuscode values (Not Started=2,
// In Progress=3, Completed=5 — Dataverse defaults for the `task` entity;
// see task_statuscode in RuntimeTypes)
-// - Window cache (window.__genpage_tasks_v1) for the inline IIFE pattern
+// - Page-scoped window cache (window.__ppTaskBoard_taskCache) + in-flight de-dupe
// - Realistic empty / loading / error states
// - Logical CSS properties (paddingInline, paddingBlock, marginInlineStart)
// - Unsized Fluent icons (ClipboardTaskRegular, PlayRegular, CheckmarkCircleRegular)
@@ -128,36 +128,65 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
void pageInput; // board does not consume incoming pageInput
const styles = useStyles();
- const [tasks, setTasks] = React.useState<Task[]>([]);
- const [loading, setLoading] = React.useState(true);
- const [error, setError] = React.useState<string | null>(null);
+ // Page-scoped window keys (unique per page + query) so this board doesn't
+ // collide with other pages caching the same entity — see data-caching.md.
+ const CACHE_KEY = '__ppTaskBoard_taskCache';
+ const INFLIGHT_KEY = '__ppTaskBoard_taskInflight';
+ const winAny = window as unknown as Record<string, unknown>;
+ // Single batched fetch state (Rule 14 — React 17 doesn't batch setState in
+ // async callbacks, so one object + one setData avoids intermediate renders).
+ // Lazy-init from the window cache so the host's second mount paints tasks
+ // immediately instead of flashing the spinner (see references/data-caching.md).
+ const [{ tasks, loading, error }, setData] = React.useState<{ tasks: Task[]; loading: boolean; error: string | null }>(
+ () => {
+ const cached = winAny[CACHE_KEY] as Task[] | undefined;
+ return { tasks: cached ?? [], loading: cached === undefined, error: null };
+ },
+ );
const [draggingId, setDraggingId] = React.useState<string | null>(null);
const [hoverColumn, setHoverColumn] = React.useState<StatusValue | null>(null);
+ const dataReady = !!dataApi;
+
React.useEffect(() => {
- (async () => {
- const cacheKey = '__genpage_tasks_v1';
- const w = window as unknown as Record<string, Task[] | undefined>;
- if (w[cacheKey]) {
- setTasks(w[cacheKey] as Task[]);
- setLoading(false);
- return;
- }
- try {
- const result = await dataApi.queryTable<Task>('task', {
+ if (!dataReady) return;
+ const cacheKey = CACHE_KEY;
+ const inflightKey = INFLIGHT_KEY;
+ const w = winAny;
+
+ const cached = w[cacheKey] as Task[] | undefined;
+ if (cached !== undefined) {
+ setData({ tasks: cached, loading: false, error: null });
+ return;
+ }
+
+ let cancelled = false;
+
+ // De-dupe the host double-mount: concurrent mounts share one fetch.
+ let pending = w[inflightKey] as Promise<Task[]> | undefined;
+ if (!pending) {
+ pending = dataApi
+ .queryTable<Task>('task', {
select: ['activityid', 'subject', 'description', 'statuscode', 'prioritycode'],
top: 200,
- });
- // queryTable returns DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() } — access records via .rows
- w[cacheKey] = result.rows;
- setTasks(result.rows);
- } catch (e) {
- setError(e instanceof Error ? e.message : String(e));
- } finally {
- setLoading(false);
- }
- })();
- }, [dataApi]);
+ })
+ // queryTable returns DataTable<T> = { rows: T[], ... } — read .rows
+ .then((result) => {
+ w[cacheKey] = result.rows;
+ return result.rows;
+ })
+ .finally(() => { if (w[inflightKey] === pending) delete w[inflightKey]; });
+ w[inflightKey] = pending;
+ }
+
+ pending
+ .then((rows) => { if (!cancelled) setData({ tasks: rows, loading: false, error: null }); })
+ .catch((e) => { if (!cancelled) setData((prev) => ({ ...prev, loading: false, error: e instanceof Error ? e.message : String(e) })); });
+
+ return () => { cancelled = true; };
+ // Readiness only — never `dataApi`. See Rule 15.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady]);
const handleDragStart = (e: React.DragEvent<HTMLDivElement>, taskId: string) => {
e.dataTransfer.effectAllowed = 'move';
@@ -199,16 +228,14 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
t.activityid === taskId ? { ...t, statuscode: targetStatus } : t,
);
const prevTasks = tasks;
- setTasks(nextTasks);
- const w = window as unknown as Record<string, Task[] | undefined>;
- w.__genpage_tasks_v1 = nextTasks;
+ setData((prev) => ({ ...prev, tasks: nextTasks }));
+ winAny[CACHE_KEY] = nextTasks;
try {
await dataApi.updateRow('task', taskId, { statuscode: targetStatus });
} catch (err) {
- setTasks(prevTasks);
- w.__genpage_tasks_v1 = prevTasks;
- setError(err instanceof Error ? err.message : String(err));
+ setData((prev) => ({ ...prev, tasks: prevTasks, error: err instanceof Error ? err.message : String(err) }));
+ winAny[CACHE_KEY] = prevTasks;
}
};
diff --git a/plugins/model-apps/samples/3-account-crud-dataverse.tsx b/plugins/model-apps/samples/3-account-crud-dataverse.tsx
index 9c9151373..a3f7cd415 100644
--- a/plugins/model-apps/samples/3-account-crud-dataverse.tsx
+++ b/plugins/model-apps/samples/3-account-crud-dataverse.tsx
@@ -20,8 +20,25 @@ import type {
QueryTableOptions,
} from "./RuntimeTypes";
+// Module-level key aliases — VALUES live on `window` (single source of truth) so
+// they survive the host double-mount on open and back-navigation, and stay
+// coherent across module re-evaluation. See references/data-caching.md.
+const CACHE_KEY = "__ppAccountCrud_accountCache";
+const INFLIGHT_KEY = "__ppAccountCrud_accountInflight";
+const winAny = window as unknown as Record<string, unknown>;
+
const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
- const [accounts, setAccounts] = useState<ReadableTableRow<account>[]>([]);
+ const dataReady = !!dataApi;
+ // Single batched fetch state (Rule 14 — React 17 doesn't batch setState in
+ // async callbacks, so one object + one setData avoids intermediate renders).
+ // `loading` also gates mutations until the initial load resolves, so a
+ // create/update can't race an in-flight first fetch (stale-write the cache).
+ const [{ accounts, loading }, setData] = useState<{ accounts: ReadableTableRow<account>[]; loading: boolean }>(
+ () => {
+ const cached = winAny[CACHE_KEY] as ReadableTableRow<account>[] | undefined;
+ return { accounts: cached ?? [], loading: cached === undefined };
+ },
+ );
const [selectedAccount, setSelectedAccount] = useState<ReadableTableRow<account> | null>(null);
const [formData, setFormData] = useState<WritableTableRow<account>>({
name: "",
@@ -32,38 +49,74 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
telephone1: "",
});
- // Fetch accounts from Dataverse
+ // Fetch accounts from Dataverse (de-duped against the host double-mount)
useEffect(() => {
- const fetchAccounts = async () => {
+ if (!dataReady) return;
+
+ // Authoritative window cache — sync on a hit so a mount that renders while
+ // another mount's fetch is resolving doesn't stay stuck on the old list.
+ const cached = winAny[CACHE_KEY] as ReadableTableRow<account>[] | undefined;
+ if (cached !== undefined) {
+ if (accounts !== cached || loading) setData({ accounts: cached, loading: false });
+ return;
+ }
+ let cancelled = false;
+
+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableTableRow<account>[]> | undefined;
+ if (!inflight) {
const query: QueryTableOptions<account> = {
select: ["name", "address1_city", "address1_stateorprovince", "address1_postalcode", "address1_country", "telephone1", "accountid"],
pageSize: 50,
orderBy: "name asc",
};
- const result = await dataApi.queryTable("account", query);
- setAccounts(result.rows);
- };
- fetchAccounts();
- }, [dataApi]);
+ inflight = dataApi
+ .queryTable("account", query)
+ .then((result) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows;
+ })
+ // Clear only if still ours — a concurrent refresh may have replaced it.
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+
+ inflight
+ .then((rows) => { if (!cancelled) setData({ accounts: rows, loading: false }); })
+ .catch((err) => { if (!cancelled) { console.error("Failed to load accounts", err); setData((prev) => ({ ...prev, loading: false })); } });
+
+ return () => { cancelled = true; };
+ // Readiness only — never `dataApi` (new ref each render). See Rule 15.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady]);
const handleInputChange = (field: keyof WritableTableRow<account>, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
const handleAddOrUpdate = async () => {
+ if (loading) return; // don't mutate while the initial load is still in flight
if (selectedAccount) {
await dataApi.updateRow("account", selectedAccount.accountid, formData);
} else {
await dataApi.createRow("account", formData);
}
- // Refresh list
+ // Refresh list — evict the stale cache and publish the refetch as the
+ // shared in-flight promise, so a mount that happens WHILE this refresh is
+ // pending awaits THIS query instead of returning the stale cache. Mirrors
+ // the initial-fetch de-dupe (references/data-caching.md invalidation).
const query: QueryTableOptions<account> = {
select: ["name", "address1_city", "address1_stateorprovince", "address1_postalcode", "address1_country", "telephone1", "accountid"],
pageSize: 50,
orderBy: "name asc",
};
- const result = await dataApi.queryTable("account", query);
- setAccounts(result.rows);
+ delete winAny[CACHE_KEY];
+ const refetch = dataApi
+ .queryTable("account", query)
+ .then((result) => { winAny[CACHE_KEY] = result.rows; return result.rows; })
+ .finally(() => { if (winAny[INFLIGHT_KEY] === refetch) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = refetch;
+ const rows = await refetch;
+ setData({ accounts: rows, loading: false });
// Reset form
setFormData({
name: "",
@@ -153,7 +206,7 @@ const GeneratedComponent = ({ dataApi }: GeneratedComponentProps) => {
<Input aria-label="Zip" placeholder="Enter zip code" value={formData.address1_postalcode || ""} onChange={(e, data) => handleInputChange("address1_postalcode", data.value)} />
<Input aria-label="Country" placeholder="Enter country" value={formData.address1_country || ""} onChange={(e, data) => handleInputChange("address1_country", data.value)} />
<Input aria-label="Phone" placeholder="Enter phone number" value={formData.telephone1 || ""} onChange={(e, data) => handleInputChange("telephone1", data.value)} />
- <Button style={{ width: "100%", marginTop: "12px" }} appearance="primary" onClick={handleAddOrUpdate}>
+ <Button style={{ width: "100%", marginTop: "12px" }} appearance="primary" onClick={handleAddOrUpdate} disabled={loading}>
{selectedAccount ? "Update Account" : "Add Account"}
</Button>
</section>
diff --git a/plugins/model-apps/samples/9-list-with-caching.tsx b/plugins/model-apps/samples/9-list-with-caching.tsx
index cb91e9640..772ee941f 100644
--- a/plugins/model-apps/samples/9-list-with-caching.tsx
+++ b/plugins/model-apps/samples/9-list-with-caching.tsx
@@ -22,11 +22,12 @@ import {
} from '@fluentui/react-components';
import { SearchRegular } from '@fluentui/react-icons';
-// Sample: list page with data caching (Rule 15).
+// Sample: list page with data fetching (Rule 15).
// Demonstrates:
// - Rule 14: SINGLE batched setData({records, loading, error}) — no separate setState
-// - Rule 15: window cache + inline async IIFE + cache guard
-// - No useCallback for dataApi (it gets a new ref each render — would re-fire)
+// - Rule 15: window cache + in-flight-promise de-dupe + readiness-only deps
+// (survives the host double-mount on open — one fetch, no spinner re-flash)
+// - dataApi is NEVER in the dep array (new ref each render — would re-fire)
// - Cross-page navigation via Xrm.Navigation.navigateTo to a sibling generative page
// - PAGEREF_ placeholder for the detail page (multi-page-build pattern)
// - DataGrid with createTableColumn + columnSizingOptions
@@ -41,13 +42,16 @@ type ContactRow = TableRow<{
type ReadableContact = ReadableTableRow<ContactRow>;
-// ---------- Module-level cache ----------
-// Initialise from window so the data survives module re-evaluation on
-// back-navigation. Cache key = entity logical name. The window object persists
-// for the browser session; module-level `let` does not.
-const CACHE_KEY = '__ppContactListCache';
-const winAny = window as unknown as Record<string, ReadableContact[] | undefined>;
-let cache: ReadableContact[] | null = winAny[CACHE_KEY] ?? null;
+// ---------- Module-level cache + in-flight de-dupe ----------
+// The VALUES live on `window` (the single source of truth) so they survive module
+// re-evaluation on back-navigation AND the host's double-mount on open (a second
+// mount ~300ms later re-runs the effect). CACHE_KEY holds resolved rows;
+// INFLIGHT_KEY holds the pending promise so a racing second mount shares one
+// round-trip. Read `window` in the effect — never a module-local snapshot, which
+// a re-eval can leave stale. See references/data-caching.md.
+const CACHE_KEY = '__ppContactList_contactCache';
+const INFLIGHT_KEY = '__ppContactList_contactInflight';
+const winAny = window as unknown as Record<string, unknown>;
// ---------- Styles ----------
@@ -87,36 +91,61 @@ const GeneratedComponent = (props: GeneratedComponentProps) => {
const styles = useStyles();
const [data, setData] = useState<{ records: ReadableContact[]; loading: boolean; error: string | null }>(
- () => ({
- records: cache ?? [],
- loading: cache === null,
- error: null,
- }),
+ () => {
+ const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
+ return { records: cached ?? [], loading: cached === undefined, error: null };
+ },
);
const [search, setSearch] = useState('');
+ const dataReady = !!dataApi;
+
useEffect(() => {
- // Cache guard — already loaded, skip fetch entirely.
- if (cache !== null) return;
-
- // Inline async IIFE — no useCallback. dataApi gets a new object ref each
- // render, so a useCallback would recreate and re-fire this effect.
- (async () => {
- try {
- const result = await dataApi.queryTable('contact', {
+ if (!dataReady) return; // wait until the host hands us the DataAPI
+
+ // Read the authoritative window cache — the other mount may have resolved
+ // it between this render and this effect. Sync state on a hit so we never
+ // stick on the spinner (reference compare avoids a redundant render).
+ const cached = winAny[CACHE_KEY] as ReadableContact[] | undefined;
+ if (cached !== undefined) {
+ if (data.records !== cached) setData({ records: cached, loading: false, error: null });
+ return;
+ }
+ let cancelled = false;
+
+ // De-dupe the host double-mount: reuse an in-flight fetch if one exists,
+ // else start one and publish its promise on window so a racing second
+ // mount awaits it instead of firing a duplicate query.
+ let inflight = winAny[INFLIGHT_KEY] as Promise<ReadableContact[]> | undefined;
+ if (!inflight) {
+ inflight = dataApi
+ .queryTable('contact', {
select: ['contactid', 'fullname', 'emailaddress1', 'telephone1', 'jobtitle'],
orderBy: 'fullname asc',
pageSize: 100,
- });
- cache = result.rows as ReadableContact[];
- winAny[CACHE_KEY] = cache;
- setData({ records: cache, loading: false, error: null });
- } catch (err) {
+ })
+ .then((result) => {
+ winAny[CACHE_KEY] = result.rows;
+ return result.rows as ReadableContact[];
+ })
+ // Clear only if still ours — a concurrent refresh may have replaced it.
+ .finally(() => { if (winAny[INFLIGHT_KEY] === inflight) delete winAny[INFLIGHT_KEY]; });
+ winAny[INFLIGHT_KEY] = inflight;
+ }
+
+ inflight
+ .then((rows) => { if (!cancelled) setData({ records: rows, loading: false, error: null }); })
+ .catch((err) => {
+ if (cancelled) return;
const message = err instanceof Error ? err.message : 'Failed to load contacts.';
setData({ records: [], loading: false, error: message });
- }
- })();
- }, [dataApi]);
+ });
+
+ return () => { cancelled = true; };
+ // Depend on readiness only — never `dataApi` (new ref each render would
+ // re-fire this effect on every render). See Rule 15.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dataReady]);
const filtered = data.records.filter((c) => {
if (!search) return true;
diff --git a/plugins/model-apps/scripts/launch-playwright-mcp.js b/plugins/model-apps/scripts/launch-playwright-mcp.js
index 435e90282..3582ddb4a 100644
--- a/plugins/model-apps/scripts/launch-playwright-mcp.js
+++ b/plugins/model-apps/scripts/launch-playwright-mcp.js
@@ -1,77 +1,67 @@
-#!/usr/bin/env node
-
-// Launches the Playwright MCP server with the best available browser.
-// Detects system-installed Chromium-based browsers in preference order,
-// then falls back to Playwright's bundled Chromium.
-// Self-contained — no external dependencies required.
-
-const { execSync, spawn } = require('child_process');
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-function exists(filePath) {
- try { return fs.existsSync(filePath); } catch { return false; }
-}
-
-function whichExists(cmd) {
- try {
- execSync(`which ${cmd}`, { stdio: 'ignore' });
- return true;
- } catch {
- return false;
- }
-}
-
-function detectBrowser() {
- const platform = os.platform();
-
- if (platform === 'win32') {
- const localAppData = process.env.LOCALAPPDATA || '';
- const programFiles = process.env.PROGRAMFILES || '';
- const programFilesX86 = process.env['PROGRAMFILES(X86)'] || '';
-
- // Edge — pre-installed on all Windows 10/11 machines
- const edgePaths = [
- path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
- path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
- path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
- ];
- for (const p of edgePaths) {
- if (exists(p)) return 'msedge';
- }
-
- // Chrome
- const chromePaths = [
- path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),
- path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
- path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
- ];
- for (const p of chromePaths) {
- if (exists(p)) return 'chrome';
- }
- } else if (platform === 'darwin') {
- // macOS
- if (exists('/Applications/Google Chrome.app')) return 'chrome';
- if (exists('/Applications/Microsoft Edge.app')) return 'msedge';
- } else {
- // Linux
- if (whichExists('google-chrome')) return 'chrome';
- if (whichExists('google-chrome-stable')) return 'chrome';
- if (whichExists('microsoft-edge')) return 'msedge';
- if (whichExists('microsoft-edge-stable')) return 'msedge';
- if (whichExists('chromium-browser')) return 'chromium';
- if (whichExists('chromium')) return 'chromium';
- }
-
- // Fallback: Playwright's bundled Chromium (requires `npx playwright install chromium`)
- return 'chromium';
-}
-
-const browser = detectBrowser();
-const child = spawn('npx', ['@playwright/mcp@latest', '--browser', browser], {
- stdio: 'inherit',
- shell: true,
-});
-
-child.on('exit', (code) => process.exit(code || 0));
+#!/usr/bin/env node
+
+// Launches the Playwright MCP server with the best available browser.
+// Detects system-installed Chromium-based browsers in preference order,
+// then falls back to Playwright's bundled Chromium.
+// Self-contained — no external dependencies required.
+
+const { spawn } = require('child_process');
+const path = require('path');
+const { detectBrowser } = require('./lib/detect-browser');
+
+function quoteShellArg(value, platform = process.platform) {
+ const argument = String(value);
+
+ if (platform === 'win32') {
+ if (argument.includes('"')) {
+ throw new Error('Cannot quote an argument containing double quotes for cmd.exe.');
+ }
+
+ return `"${argument}"`;
+ }
+
+ return `'${argument.replace(/'/g, "'\\''")}'`;
+}
+
+function buildMcpArgs(browser, {
+ configPath = path.join(__dirname, 'playwright-mcp-fullscreen.config.json'),
+ platform = process.platform,
+} = {}) {
+ return [
+ '-y',
+ '@playwright/mcp@latest',
+ '--browser',
+ browser,
+ '--config',
+ quoteShellArg(configPath, platform),
+ ];
+}
+
+function launch({
+ browser = detectBrowser(),
+ spawnFn = spawn,
+ onExit = (code) => process.exit(code || 0),
+ onError = (err) => {
+ // `spawn` emits 'error' (not 'exit') when npx itself can't be launched
+ // (ENOENT, EACCES, ...). Without a handler Node throws the error as an
+ // uncaught exception; surface it and exit non-zero so the MCP host sees the
+ // server failed to start.
+ process.stderr.write(`Failed to launch Playwright MCP server: ${err && err.message ? err.message : err}\n`);
+ process.exit(1);
+ },
+} = {}) {
+ const child = spawnFn('npx', buildMcpArgs(browser), {
+ stdio: 'inherit',
+ shell: true,
+ });
+
+ child.on('exit', onExit);
+ child.on('error', onError);
+ return child;
+}
+
+if (require.main === module) {
+ launch();
+}
+
+module.exports = { buildMcpArgs, launch, quoteShellArg };
diff --git a/plugins/model-apps/scripts/lib/detect-browser.js b/plugins/model-apps/scripts/lib/detect-browser.js
new file mode 100644
index 000000000..0e8c8245b
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/detect-browser.js
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+
+// Detects the best available Chromium-based browser on the system.
+// Returns a Playwright channel name ('msedge', 'chrome', 'chromium').
+// Used by the Playwright MCP launcher.
+
+const { execFileSync } = require('child_process');
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+
+function exists(filePath) {
+ try { return fs.existsSync(filePath); } catch { return false; }
+}
+
+function whichExists(cmd) {
+ try {
+ // execFileSync (no shell) avoids interpolating `cmd` into a shell command
+ // string. Call sites pass fixed literals today, but this removes the
+ // injection-prone `which ${cmd}` pattern outright.
+ execFileSync('which', [cmd], { stdio: 'ignore' });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function detectBrowser() {
+ const platform = os.platform();
+
+ if (platform === 'win32') {
+ const localAppData = process.env.LOCALAPPDATA || '';
+ const programFiles = process.env.PROGRAMFILES || '';
+ const programFilesX86 = process.env['PROGRAMFILES(X86)'] || '';
+
+ // Edge — pre-installed on all Windows 10/11 machines
+ const edgePaths = [
+ path.join(programFilesX86, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
+ path.join(programFiles, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
+ path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
+ ];
+ for (const p of edgePaths) {
+ if (exists(p)) return 'msedge';
+ }
+
+ // Chrome
+ const chromePaths = [
+ path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe'),
+ path.join(programFiles, 'Google', 'Chrome', 'Application', 'chrome.exe'),
+ path.join(programFilesX86, 'Google', 'Chrome', 'Application', 'chrome.exe'),
+ ];
+ for (const p of chromePaths) {
+ if (exists(p)) return 'chrome';
+ }
+ } else if (platform === 'darwin') {
+ // macOS
+ if (exists('/Applications/Google Chrome.app')) return 'chrome';
+ if (exists('/Applications/Microsoft Edge.app')) return 'msedge';
+ } else {
+ // Linux
+ if (whichExists('google-chrome')) return 'chrome';
+ if (whichExists('google-chrome-stable')) return 'chrome';
+ if (whichExists('microsoft-edge')) return 'msedge';
+ if (whichExists('microsoft-edge-stable')) return 'msedge';
+ if (whichExists('chromium-browser')) return 'chromium';
+ if (whichExists('chromium')) return 'chromium';
+ }
+
+ // Fallback: Playwright's bundled Chromium (requires `npx playwright install chromium`)
+ return 'chromium';
+}
+
+module.exports = { detectBrowser };
diff --git a/plugins/model-apps/scripts/lib/modelapps-hook-utils.js b/plugins/model-apps/scripts/lib/modelapps-hook-utils.js
new file mode 100644
index 000000000..ebcb809ae
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/modelapps-hook-utils.js
@@ -0,0 +1,138 @@
+// Shared helpers for the model-apps plugin hooks. Mirrors the power-pages /
+// mobile-apps `*-hook-utils.js` pattern: the list of "tracked" skills is derived
+// at load time from the skills/*/SKILL.md directories so a new skill is picked up
+// automatically without editing a hardcoded list.
+//
+// Why derive instead of hardcode: the PostToolUse validation hook and the
+// telemetry hooks both need to answer "did the Skill tool just run one of OUR
+// skills?" Deriving from disk keeps that answer correct as skills are added or
+// removed, and keeps a single source of truth shared by every hook.
+
+const fs = require('fs');
+const path = require('path');
+
+const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');
+const SKILLS_DIR = path.join(PLUGIN_ROOT, 'skills');
+
+// Skills that must never emit usage telemetry about themselves. The telemetry
+// control skill is excluded so checking/toggling telemetry does not self-emit.
+const EXCLUDED_FROM_TRACKING = new Set(['telemetry']);
+
+function discoverValidatorScript(skillName) {
+ const scriptsDir = path.join(SKILLS_DIR, skillName, 'scripts');
+ if (!fs.existsSync(scriptsDir)) {
+ return null;
+ }
+
+ // First `validate*.js` (sorted) wins. A skill without one is still tracked for
+ // telemetry/detection but simply has no post-run validator.
+ const validators = fs
+ .readdirSync(scriptsDir, { withFileTypes: true })
+ .filter((entry) => entry.isFile() && /^validate.*\.js$/.test(entry.name))
+ .map((entry) => entry.name)
+ .sort();
+
+ if (validators.length === 0) {
+ return null;
+ }
+
+ return path.posix.join('skills', skillName, 'scripts', validators[0]);
+}
+
+function discoverTrackedSkills() {
+ // Null-prototype map: membership is tested via bracket access (TRACKED_SKILLS[name]),
+ // so a plain {} would make inherited keys like "toString"/"constructor"/"__proto__"
+ // test truthy and emit bogus skill names. A null-proto object has no such keys.
+ const trackedSkills = Object.create(null);
+
+ if (!fs.existsSync(SKILLS_DIR)) {
+ return trackedSkills;
+ }
+
+ const entries = fs
+ .readdirSync(SKILLS_DIR, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ for (const entry of entries) {
+ const skillName = entry.name;
+ if (EXCLUDED_FROM_TRACKING.has(skillName)) {
+ continue;
+ }
+ if (!fs.existsSync(path.join(SKILLS_DIR, skillName, 'SKILL.md'))) {
+ continue;
+ }
+
+ const validatorScript = discoverValidatorScript(skillName);
+ trackedSkills[skillName] = validatorScript ? { validatorScript } : {};
+ }
+
+ return trackedSkills;
+}
+
+const TRACKED_SKILLS = discoverTrackedSkills();
+
+function detectTrackedSkill(value) {
+ if (typeof value !== 'string') {
+ return null;
+ }
+
+ const trimmed = value.trim();
+ if (TRACKED_SKILLS[trimmed]) {
+ return trimmed;
+ }
+
+ // Strip leading slash and optional plugin prefix: /genpage, model-apps:genpage,
+ // /model-apps:genpage. Claude Code namespaces plugin skills as `plugin:skill`.
+ const normalized = trimmed.replace(/^\/?(?:model-apps:)?/, '').toLowerCase();
+ if (TRACKED_SKILLS[normalized]) {
+ return normalized;
+ }
+
+ // Fall back to searching for model-apps:<skill> anywhere in the string.
+ const commandMatch = trimmed.match(/model-apps:([a-z0-9-]+)/i);
+ if (!commandMatch) {
+ return null;
+ }
+
+ const skillName = commandMatch[1].toLowerCase();
+ return TRACKED_SKILLS[skillName] ? skillName : null;
+}
+
+function getTrackedSkillFromToolInput(toolInput) {
+ if (!toolInput || typeof toolInput !== 'object') {
+ return null;
+ }
+
+ // The Skill tool surfaces the invoked skill under different keys across host
+ // versions; probe the known ones, then fall back to scanning the serialized
+ // input for a `model-apps:<skill>` command token.
+ for (const field of ['skill', 'skill_name', 'skillName', 'name', 'commandName', 'command']) {
+ const skillName = detectTrackedSkill(toolInput[field]);
+ if (skillName) {
+ return skillName;
+ }
+ }
+
+ try {
+ return detectTrackedSkill(JSON.stringify(toolInput));
+ } catch {
+ return null;
+ }
+}
+
+function getValidatorScript(skillName) {
+ return TRACKED_SKILLS[skillName]?.validatorScript ?? null;
+}
+
+// Ordered list of tracked skill names — used by the UserPromptSubmit telemetry
+// hook to match a `/model-apps:<skill>` slash command in raw prompt text.
+const TRACKED_SKILL_NAMES = Object.keys(TRACKED_SKILLS);
+
+module.exports = {
+ TRACKED_SKILLS,
+ TRACKED_SKILL_NAMES,
+ detectTrackedSkill,
+ getTrackedSkillFromToolInput,
+ getValidatorScript,
+};
diff --git a/plugins/model-apps/scripts/lib/telemetry/ikey.json b/plugins/model-apps/scripts/lib/telemetry/ikey.json
new file mode 100644
index 000000000..951fbd62a
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/ikey.json
@@ -0,0 +1,6 @@
+{
+ "instrumentationKey": "17d9aee1951341508c46b0aad2f3fcb5-a41425e0-9b67-482e-971f-ad83c3b467e3-6814",
+ "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/",
+ "event_stream_name": "ModelAppsAIPluginEvent",
+ "disabled": true
+}
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.js b/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.js
new file mode 100644
index 000000000..3904f5bc1
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/agent-info.js
@@ -0,0 +1,214 @@
+"use strict";
+
+const fs = require("node:fs");
+const path = require("node:path");
+const { execFileSync } = require("node:child_process");
+
+let pacCliVersionCache;
+
+// Reads the PAC CLI version once per process via `pac --version`. Best-effort
+// and fail-closed: missing executable, timeout, or unparseable output all
+// resolve to "".
+//
+// PAC 2.x prints the version banner ("Version: X.Y.Z+...") to stdout as part
+// of its preamble but then treats `--version` as an unknown command and
+// exits with status 1. execFileSync throws on non-zero exit, attaching the
+// captured stdout to err.stdout — so we parse that fallback path too.
+function readPacCliVersion(opts = {}) {
+ if (pacCliVersionCache !== undefined) return pacCliVersionCache;
+ if (opts._exec === false) {
+ pacCliVersionCache = "";
+ return "";
+ }
+ const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;
+ let stdout = "";
+ try {
+ stdout = exec("pac", ["--version"], {
+ encoding: "utf8",
+ timeout: 8000,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ } catch (err) {
+ stdout = (err && err.stdout) ? String(err.stdout) : "";
+ }
+ const match = String(stdout || "").match(/Version:\s*(\d+\.\d+\.\d+(?:\.\d+)?)/);
+ pacCliVersionCache = match ? match[1] : "";
+ return pacCliVersionCache;
+}
+
+// Test seam.
+function _resetCache() {
+ pacCliVersionCache = undefined;
+}
+
+// Parses a dotted semver out of the AI_AGENT env var. Claude Code sets
+// AI_AGENT=claude-code_<maj>-<min>-<patch>_agent (e.g.
+// "claude-code_2-1-156_agent"); the version segment uses dashes, so we
+// normalize separators to dots. The "claude-code" name prefix carries no
+// digits, so the first numeric run is the version.
+function parseVersionFromAiAgent(aiAgent) {
+ if (typeof aiAgent !== "string") return "";
+ const match = aiAgent.match(/\d+(?:[._-]\d+)+/);
+ return match ? match[0].replace(/[._-]/g, ".") : "";
+}
+
+// Reads the Claude Code CLI version. Primary source is the installed
+// package.json: the hook subprocess inherits CLAUDE_CODE_EXECPATH from Claude
+// Code, and jumping one directory above the executable's bin/ lands on the npm
+// package root. That layout only exists for npm-global installs — the native
+// installer ships a standalone binary with no sibling package.json — so when
+// the read yields nothing, fall back to the version carried in AI_AGENT, which
+// Claude Code sets regardless of install method.
+function readClaudeCodeVersion(env) {
+ const execPath = env.CLAUDE_CODE_EXECPATH;
+ if (execPath) {
+ try {
+ const pkgPath = path.join(path.dirname(execPath), "..", "package.json");
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
+ if (pkg && typeof pkg.version === "string") return pkg.version;
+ } catch {
+ // pkg unreadable; fall through to the AI_AGENT fallback
+ }
+ }
+ return parseVersionFromAiAgent(env.AI_AGENT);
+}
+
+function isTruthyEnv(value) {
+ if (typeof value !== "string") return false;
+ const normalized = value.trim().toLowerCase();
+ return normalized !== "" && normalized !== "0" && normalized !== "false";
+}
+
+function firstEnv(env, keys) {
+ for (const key of keys) {
+ if (typeof env[key] === "string" && env[key]) return env[key];
+ }
+ return "";
+}
+
+function normalizeAgentName(name) {
+ return String(name || "").toLowerCase().replace(/[^a-z0-9]/g, "");
+}
+
+const AGENT_DETECTORS = [
+ {
+ name: "Claude Code",
+ aliases: ["claude", "claudecode"],
+ isPresent: (env) => isTruthyEnv(env.CLAUDECODE),
+ version: readClaudeCodeVersion,
+ },
+ {
+ name: "Copilot CLI",
+ aliases: ["copilot", "copilotcli", "githubcopilot", "githubcopilotcli"],
+ isPresent: (env) => isTruthyEnv(env.COPILOT_CLI),
+ version: (env) =>
+ firstEnv(env, ["COPILOT_CLI_BINARY_VERSION", "COPILOT_CLI_VERSION"]),
+ },
+ {
+ name: "Codex",
+ aliases: ["codex", "codexcli", "openaicodex"],
+ isPresent: (env) => isTruthyEnv(env.CODEX_CLI) || isTruthyEnv(env.CODEX),
+ version: (env) =>
+ firstEnv(env, [
+ "CODEX_CLI_BINARY_VERSION",
+ "CODEX_CLI_VERSION",
+ "CODEX_VERSION",
+ ]) || parseVersionFromAiAgent(env.AI_AGENT),
+ },
+ {
+ name: "OpenCode",
+ aliases: ["opencode", "opencodecli", "open_code"],
+ isPresent: (env) => isTruthyEnv(env.OPENCODE_CLI) || isTruthyEnv(env.OPENCODE),
+ version: (env) =>
+ firstEnv(env, [
+ "OPENCODE_CLI_BINARY_VERSION",
+ "OPENCODE_CLI_VERSION",
+ "OPENCODE_VERSION",
+ ]) || parseVersionFromAiAgent(env.AI_AGENT),
+ },
+ {
+ name: "Hermes",
+ aliases: ["hermes", "hermescli", "hermesagent"],
+ isPresent: (env) =>
+ isTruthyEnv(env.HERMES_CLI) ||
+ isTruthyEnv(env.HERMES) ||
+ isTruthyEnv(env.HERMES_AGENT),
+ version: (env) =>
+ firstEnv(env, [
+ "HERMES_CLI_BINARY_VERSION",
+ "HERMES_CLI_VERSION",
+ "HERMES_AGENT_VERSION",
+ "HERMES_VERSION",
+ ]) || parseVersionFromAiAgent(env.AI_AGENT),
+ },
+ {
+ name: "OpenClaw",
+ aliases: ["openclaw", "openclawcli"],
+ isPresent: (env) =>
+ isTruthyEnv(env.OPENCLAW_CLI) || isTruthyEnv(env.OPENCLAW),
+ version: (env) =>
+ firstEnv(env, [
+ "OPENCLAW_CLI_BINARY_VERSION",
+ "OPENCLAW_CLI_VERSION",
+ "OPENCLAW_VERSION",
+ ]) || parseVersionFromAiAgent(env.AI_AGENT),
+ },
+];
+
+function detectorForName(name) {
+ const normalized = normalizeAgentName(name);
+ return AGENT_DETECTORS.find((detector) =>
+ detector.aliases.some((alias) => normalizeAgentName(alias) === normalized)
+ );
+}
+
+function detectFromAiAgent(env) {
+ const aiAgent = env.AI_AGENT;
+ if (typeof aiAgent !== "string" || !aiAgent) return null;
+ const normalized = normalizeAgentName(aiAgent);
+ const detector = AGENT_DETECTORS.find((candidate) =>
+ candidate.aliases.some((alias) => normalized.includes(normalizeAgentName(alias)))
+ );
+ if (!detector) return null;
+ return {
+ aiAgentName: detector.name,
+ aiAgentVersion: detector.version(env) || parseVersionFromAiAgent(aiAgent),
+ };
+}
+
+function detectKnownAgent(env) {
+ for (const detector of AGENT_DETECTORS) {
+ if (detector.isPresent(env)) {
+ return {
+ aiAgentName: detector.name,
+ aiAgentVersion: detector.version(env) || "",
+ };
+ }
+ }
+ return detectFromAiAgent(env);
+}
+
+// Detects the AI agent host. Prefers explicit env vars; falls back to
+// built-in detection for known CLI hosts. When AI_AGENT_NAME is set explicitly
+// but AI_AGENT_VERSION is empty, backfill the version from whichever detector
+// matches — avoids emitting an empty aiAgentVersion just because the settings
+// file only carried half the pair.
+function readAiAgent(env = process.env) {
+ const explicitName = env.AI_AGENT_NAME;
+ const explicitVersion = env.AI_AGENT_VERSION;
+ if (explicitName) {
+ let version = explicitVersion || "";
+ if (!version) {
+ const explicitDetector = detectorForName(explicitName);
+ const detected = detectKnownAgent(env);
+ if (explicitDetector) version = explicitDetector.version(env) || "";
+ if (!version && detected) version = detected.aiAgentVersion || "";
+ }
+ return { aiAgentName: explicitName, aiAgentVersion: version };
+ }
+ const detected = detectKnownAgent(env);
+ if (detected) return detected;
+ return { aiAgentName: "", aiAgentVersion: "" };
+}
+
+module.exports = { readPacCliVersion, readAiAgent, _resetCache };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.js
new file mode 100644
index 000000000..3984b8230
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/emit-dispatcher.js
@@ -0,0 +1,253 @@
+#!/usr/bin/env node
+"use strict";
+
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const https = require("node:https");
+const { FIELD_TYPES, pick } = require("./events");
+const { loadResolver } = require("./resolver-loader");
+const { isTransmissionOptedOut } = require("./user-config");
+
+function exitSilently() {
+ process.exit(0);
+}
+process.on("uncaughtException", exitSilently);
+process.on("unhandledRejection", exitSilently);
+process.stdin.on("error", exitSilently);
+
+const PLACEHOLDER_IKEY = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING";
+const DEFAULT_LOCAL_DIR = path.join(os.homedir(), ".power-platform-skills");
+const FAKE_PROBE = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";
+const CONFIG_DIR_ENV = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";
+const CLOUD_ENV = process.env.POWER_PLATFORM_SKILLS_CLOUD || "";
+// Override env vars — TEST seams only. Production resolves the iKey/collector
+// via the plugin resolver / static config in ikey.json and never sets these.
+const IKEY_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_IKEY || "";
+const COLLECTOR_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_COLLECTOR || "";
+
+function localConfigDir() {
+ return CONFIG_DIR_ENV || DEFAULT_LOCAL_DIR;
+}
+
+// Anonymous telemetry is default-on. The user opt-out is per-plugin and lives in
+// config.json (telemetry[<pluginName>] === "off"), written by the telemetry skill.
+// It suppresses TRANSMISSION only; the local mirror is written before this gate.
+function isUserOptedOut(pluginName) {
+ return isTransmissionOptedOut(localConfigDir(), pluginName);
+}
+
+// Path to the ikey.json config. Overridable via POWER_PLATFORM_SKILLS_IKEY_JSON
+// so tests can point at a temp file with their own disabled / region state.
+function ikeyJsonPath() {
+ return (
+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON ||
+ path.join(__dirname, "..", "ikey.json")
+ );
+}
+
+// Returns the parsed ikey.json, or null when it is missing/unreadable. null is
+// treated as the repo kill switch (fail CLOSED): if we cannot read the config
+// we cannot confirm emission is authorized, so we suppress rather than risk a
+// POST / local log in an unexpected state.
+function readIkeyConfig() {
+ try {
+ return JSON.parse(fs.readFileSync(ikeyJsonPath(), "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+// Repo-side kill switch: a missing/unreadable config (null) or an explicit
+// `"disabled": true` suppresses ALL events regardless of opt-out or region
+// state. Lets infrastructure PRs land while the tenant-side annotation + Kusto
+// table are still being provisioned. Flip `disabled` to false when ready.
+function isDisabledByConfig(cfg) {
+ return !cfg || cfg.disabled === true;
+}
+
+// Reserved meta fields that builders always write into event.data. They are
+// not user-facing telemetry columns, so they live outside FIELD_TYPES but
+// must survive sanitization.
+const RESERVED_META_FIELDS = new Set(["eventName", "eventType", "severity"]);
+
+// Defense-in-depth allowlist filter. The builders in events.js are the
+// intended entry point and already enforce FIELD_TYPES, but the dispatcher
+// receives JSON over stdin from a separate process and cannot assume that.
+// Re-run pick() against FIELD_TYPES here so any field that bypasses the
+// builders is dropped before it reaches the wire.
+function sanitizeData(data) {
+ if (!data || typeof data !== "object") return {};
+ const filtered = pick(data, Object.keys(FIELD_TYPES));
+ for (const key of RESERVED_META_FIELDS) {
+ if (typeof data[key] === "string") filtered[key] = data[key];
+ }
+ return filtered;
+}
+
+// Build the CS4.0 envelope from a pre-sanitized payload + timestamp. `sanitized`
+// is shared with the local mirror so `data`/`time` stay byte-identical for
+// every field except `eventInfo`: the tenant-side field mapping flattens
+// `data.<key>` to a single `data_<key>` leaf and doesn't recurse into nested
+// objects, so `eventInfo` is stringified just for the wire to survive that
+// flattening. Kusto reads it back with `parse_json()`/`todynamic()`; the
+// local mirror keeps the real object for human readability.
+function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName) {
+ const wireData = { ...sanitized };
+ if (wireData.eventInfo !== undefined) {
+ wireData.eventInfo = JSON.stringify(wireData.eventInfo);
+ }
+ return {
+ ver: "4.0",
+ name: eventStreamName || eventName || "",
+ time,
+ iKey: "o:" + String(resolvedIKey || "").split("-")[0],
+ data: wireData,
+ };
+}
+
+function writeProbe(filePath, { headers, body }) {
+ try {
+ fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");
+ } catch {
+ // ignore
+ }
+}
+
+function writeLocalLog(record) {
+ try {
+ const { appendLocal } = require("./local-log");
+ appendLocal(record, { configDir: localConfigDir() });
+ } catch {
+ // fail closed
+ }
+}
+
+// ---- Read config + repo-side kill switch (applies before ANY side effect) --
+// The `disabled` repo config (and an unreadable config) is the one true
+// hard-off: no local log, no POST. The per-plugin user opt-out is NOT checked
+// here — it suppresses transmission only, and is applied below AFTER the local
+// mirror is written. cfg is reused for resolver context + static fallback in
+// the stdin handler.
+const cfg = readIkeyConfig();
+if (isDisabledByConfig(cfg)) exitSilently();
+const resolver = loadResolver(path.dirname(ikeyJsonPath()));
+
+// ---- Read stdin ------------------------------------------------------------
+let raw = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", (c) => (raw += c));
+process.stdin.on("end", async () => {
+ let event;
+ try {
+ event = JSON.parse(raw);
+ } catch {
+ return exitSilently();
+ }
+
+ // Compute the sanitized payload + timestamp ONCE. The sanitized data is
+ // exactly what lands in Kusto (its field names ARE the Kusto column names),
+ // except `eventInfo` which buildEnvelope() re-serializes for the wire only.
+ const time = new Date().toISOString();
+ const sanitized = sanitizeData(event.data);
+ const localRecord = { time, name: event.name, data: sanitized };
+
+ // Mirror to the local log for EVERY event that clears the repo kill switch —
+ // irrespective of whether a real iKey resolves AND irrespective of the
+ // per-plugin transmission opt-out. The file stays on the user's machine; it
+ // is a local diagnostic mirror of what is (or would be) sent to Kusto, not
+ // transmitted telemetry. (A `disabled: true` repo config wrote nothing — it
+ // short-circuited before stdin was even read.)
+ writeLocalLog(localRecord);
+
+ // User opt-out (per plugin) — transmission only; the local mirror above is kept.
+ const pluginName = event && event.data && event.data.pluginName;
+ if (isUserOptedOut(pluginName)) return exitSilently();
+
+ // Resolve the destination iKey + collector. Precedence: env override (test
+ // seam) → plugin resolver.js (region/tenant/etc., owned by the plugin) →
+ // static single-key config in ikey.json → none. The shared dispatcher knows
+ // nothing about regions; the plugin's resolver.js owns that.
+ let iKey = IKEY_OVERRIDE;
+ let collectorUrl = COLLECTOR_OVERRIDE;
+ if (!iKey || !collectorUrl) {
+ if (resolver && typeof resolver.resolve === "function") {
+ let resolved = null;
+ try {
+ resolved = await resolver.resolve({
+ event,
+ cfg,
+ cloud: CLOUD_ENV,
+ configDir: CONFIG_DIR_ENV || undefined,
+ });
+ } catch {
+ // A plugin resolver threw/rejected — continue with no resolution rather
+ // than letting the global unhandledRejection handler exit. The local
+ // mirror was already written above; the static fallback below still
+ // runs, so a transient resolver failure degrades to the configured
+ // static key (or "no transmission") instead of crashing.
+ resolved = null;
+ }
+ if (resolved) {
+ iKey = iKey || resolved.iKey || "";
+ collectorUrl = collectorUrl || resolved.collectorUrl || "";
+ }
+ }
+ // Static fallback — documented precedence is resolver → static → none, so
+ // this runs whether or not a resolver was present. A resolver that returns
+ // nothing (or threw) still falls through to a configured static key rather
+ // than silently disabling transmission.
+ iKey = iKey || cfg.instrumentationKey || "";
+ collectorUrl = collectorUrl || cfg.collector_url || "";
+ }
+
+ // Placeholder / unprovisioned mode → local mirror already written; no POST.
+ const keyMissing = !iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl;
+ if (keyMissing) {
+ return exitSilently();
+ }
+
+ // Real iKey → Common Schema envelope (reuses the same time + sanitized data
+ // as the local mirror) → HTTPS POST.
+ const envelope = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);
+ const body = JSON.stringify(envelope) + "\n";
+ const headers = {
+ "Content-Type": "application/x-json-stream; charset=utf-8",
+ "x-apikey": iKey,
+ "Content-Length": Buffer.byteLength(body),
+ };
+
+ // Test seam: if POWER_PLATFORM_SKILLS_FAKE_HTTPS is set, write the probe
+ // payload to that file and exit without calling the real network.
+ if (FAKE_PROBE) {
+ writeProbe(FAKE_PROBE, { headers, body });
+ return exitSilently();
+ }
+
+ let url;
+ try {
+ url = new URL(collectorUrl);
+ } catch {
+ return exitSilently();
+ }
+ const req = https.request(
+ {
+ hostname: url.hostname,
+ port: url.port || undefined,
+ path: url.pathname + (url.search || ""),
+ method: "POST",
+ headers,
+ },
+ (res) => {
+ res.on("data", () => {});
+ res.on("end", exitSilently);
+ }
+ );
+ req.on("error", exitSilently);
+ req.setTimeout(4000, () => {
+ req.destroy();
+ exitSilently();
+ });
+ req.write(body);
+ req.end();
+});
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.js
new file mode 100644
index 000000000..0ec329005
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/emit-from-prompt.js
@@ -0,0 +1,147 @@
+"use strict";
+
+const fs = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+const crypto = require("node:crypto");
+
+const { detectSlashCommand } = require("./prompt-detector");
+const { buildSkillStarted } = require("./events");
+const { getSessionId } = require("./session");
+const { fireAndForget } = require("./emit-spawn");
+const { loadResolver } = require("./resolver-loader");
+const { readPacAuth } = require("./pac-auth");
+const { readPacCliVersion, readAiAgent } = require("./agent-info");
+
+function readIkey(telemetryDir) {
+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate
+ // ikey.json so tests don't have to mutate the checked-in config file.
+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;
+ const overridePath = override && override.trim() ? override : "";
+ // Guard a missing/invalid telemetryDir (a caller bug this fail-closed helper
+ // must tolerate): with no override there is no config to read, so fail CLOSED
+ // (disabled: true) instead of letting path.join throw out of the library.
+ if (!overridePath && (typeof telemetryDir !== "string" || !telemetryDir)) {
+ return { cfg: null, dir: "", ikeyPath: "", eventStreamName: "", disabled: true };
+ }
+ const ikeyPath = overridePath || path.join(telemetryDir, "ikey.json");
+ const dir = path.dirname(ikeyPath);
+ try {
+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));
+ return { cfg, dir, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };
+ } catch {
+ // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching
+ // emit-dispatcher.js's isDisabledByConfig(). If we can't read the config we
+ // cannot confirm emission is authorized, so suppress.
+ return { cfg: null, dir, ikeyPath, eventStreamName: "", disabled: true };
+ }
+}
+
+function osFriendlyName(platform) {
+ if (platform === "win32") return "Windows";
+ if (platform === "darwin") return "Mac";
+ if (platform === "linux") return "Linux";
+ return platform;
+}
+
+function emitSkillStartedFromPrompt(promptText, opts = {}) {
+ const {
+ pluginName,
+ pluginVersion,
+ trackedSkills,
+ telemetryDir,
+ sessionId, // primed from Claude Code's hook payload (parsed.session_id)
+ _emit, // test seam; defaults to fireAndForget
+ _readPacAuth, // test seam; defaults to lib/pac-auth
+ _readAgentInfo, // test seam; defaults to lib/agent-info
+ } = opts;
+
+ const skillName = detectSlashCommand(promptText, { pluginName, trackedSkills });
+ if (!skillName) return { emitted: false, skillName: null };
+
+ // Repo-side hard-off: short-circuit BEFORE any PAC / agent-info shellouts
+ // (~3-5s combined) so a disabled or half-provisioned plugin pays effectively
+ // no cost. The user opt-out is NOT checked here: the event is still built and
+ // dispatched so the detached dispatcher can write the local diagnostic mirror;
+ // the dispatcher reads the per-plugin config and skips the POST when opted out.
+ const { cfg, dir, ikeyPath, eventStreamName, disabled } = readIkey(telemetryDir);
+ if (disabled) return { emitted: false, skillName };
+ // Provisioning fast-gate (generic): a plugin resolver decides "is there a key
+ // worth paying the pac shellout for?"; default is "static key present".
+ const resolver = loadResolver(dir);
+ let provisioned;
+ try {
+ provisioned =
+ resolver && typeof resolver.isProvisioned === "function"
+ ? resolver.isProvisioned(cfg)
+ // Static-key fallback (no resolver): a real key must be present AND not be
+ // the shipped placeholder sentinel — otherwise a plugin that flipped
+ // `disabled:false` before replacing the key would be treated as provisioned
+ // and pay the pac/agent-info shellouts + dispatch (local-log write) even
+ // though the dispatcher can never POST a placeholder key. Matches the
+ // dispatcher's PLACEHOLDER_IKEY guard and the pretool hook's gate.
+ : !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING");
+ } catch {
+ // A plugin-provided resolver threw (or assumed cfg non-null) — treat as not
+ // provisioned so a bad resolver can't break prompt handling (fail closed).
+ provisioned = false;
+ }
+ if (!provisioned) return { emitted: false, skillName };
+
+ const pacReader = typeof _readPacAuth === "function" ? _readPacAuth : readPacAuth;
+ let pacAuth = null;
+ try {
+ pacAuth = pacReader();
+ } catch {
+ pacAuth = null;
+ }
+
+ const agentReader =
+ typeof _readAgentInfo === "function"
+ ? _readAgentInfo
+ : () => ({
+ ...readAiAgent(),
+ pacCliVersion: readPacCliVersion(),
+ });
+ let agentInfo;
+ try {
+ agentInfo = agentReader() || {};
+ } catch {
+ agentInfo = {};
+ }
+
+ const fields = {
+ pluginName,
+ pluginVersion: pluginVersion || "unknown",
+ sessionId: getSessionId(sessionId),
+ correlationId: crypto.randomUUID(),
+ osName: osFriendlyName(process.platform),
+ osVersion: os.release(),
+ nodeVersion: "v" + String(process.versions.node).split(".")[0],
+ skillName,
+ };
+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;
+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;
+ if (pacAuth && pacAuth.objectId) fields.eventInfo = { aadObjectId: pacAuth.objectId };
+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;
+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;
+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;
+
+ const event = buildSkillStarted(eventStreamName, fields);
+
+ const emit = typeof _emit === "function" ? _emit : fireAndForget;
+ try {
+ emit(event, {
+ cloud: (pacAuth && pacAuth.cloud) || "",
+ configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "",
+ fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",
+ ikeyJsonPath: ikeyPath,
+ });
+ } catch {
+ // fail closed — telemetry never propagates errors
+ }
+
+ return { emitted: true, skillName };
+}
+
+module.exports = { emitSkillStartedFromPrompt };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/emit-spawn.js b/plugins/model-apps/scripts/lib/telemetry/lib/emit-spawn.js
new file mode 100644
index 000000000..0bd839d8a
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/emit-spawn.js
@@ -0,0 +1,72 @@
+"use strict";
+
+const { spawn } = require("node:child_process");
+const path = require("node:path");
+const { telemetryOptOutEnvVarName } = require("./user-config");
+
+const DISPATCHER = path.resolve(__dirname, "emit-dispatcher.js");
+
+function fireAndForget(event, opts = {}) {
+ const iKey = opts.iKey || "";
+ const collectorUrl = opts.collectorUrl || "";
+ const configDir = opts.configDir || "";
+ const fakeProbe = opts.fakeProbe || "";
+ const cloud = opts.cloud || "";
+ const pluginName = event && event.data && event.data.pluginName;
+ const optOutVarName = pluginName ? telemetryOptOutEnvVarName(pluginName) : "";
+ const optOutValue =
+ optOutVarName && process.env[optOutVarName] ? process.env[optOutVarName] : "";
+ // Absolute path to the CALLING plugin's ikey.json. Tests and shared-source
+ // development can execute this module from shared/telemetry/lib, whose default
+ // __dirname-based ikey path is the shared placeholder, not the plugin's real
+ // config. Passing the path explicitly makes the dispatcher read the right file
+ // regardless of whether this library is running from shared/ or a plugin copy.
+ const ikeyJsonPath = opts.ikeyJsonPath || "";
+
+ try {
+ const child = spawn(process.execPath, [DISPATCHER], {
+ detached: true,
+ stdio: ["pipe", "ignore", "ignore"],
+ env: {
+ // Pass only the minimum env the dispatcher needs. Avoid spreading
+ // process.env so secrets (AZURE_CLIENT_SECRET, GITHUB_TOKEN, etc.)
+ // never reach the telemetry child.
+ PATH: process.env.PATH || "",
+ SystemRoot: process.env.SystemRoot || "",
+ HOME: process.env.HOME || "",
+ USERPROFILE: process.env.USERPROFILE || "",
+ APPDATA: process.env.APPDATA || "",
+ POWER_PLATFORM_SKILLS_IKEY: iKey,
+ POWER_PLATFORM_SKILLS_COLLECTOR: collectorUrl,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe,
+ POWER_PLATFORM_SKILLS_CLOUD: cloud,
+ // ikey.json path: an explicit env override (test seam) wins; otherwise
+ // the calling plugin's ikey.json path so the dispatcher reads the
+ // plugin's real config rather than shared/'s placeholder.
+ POWER_PLATFORM_SKILLS_IKEY_JSON:
+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON || ikeyJsonPath || "",
+ // The opt-out is enforced in the detached dispatcher, which reads the
+ // child's process.env — so the minimal allowlist must forward this var
+ // explicitly or the highest-precedence opt-out never reaches it. Forward
+ // only when actually set: an empty/unset value is a no-op for the
+ // dispatcher's check (it trims and matches only "1"/"true"), so there's
+ // no point planting an empty var in the child env.
+ ...(optOutVarName && optOutValue
+ ? { [optOutVarName]: optOutValue }
+ : {}),
+ },
+ });
+ try {
+ child.stdin.write(JSON.stringify(event));
+ child.stdin.end();
+ } catch {
+ // child may have already exited; swallow.
+ }
+ child.unref();
+ } catch {
+ // spawn failed — fail closed.
+ }
+}
+
+module.exports = { fireAndForget };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/events.js b/plugins/model-apps/scripts/lib/telemetry/lib/events.js
new file mode 100644
index 000000000..be29c6832
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/events.js
@@ -0,0 +1,138 @@
+"use strict";
+
+// Per-field type metadata. Drives the type-aware picker so the wire payload
+// always matches the Kusto column type. Types and defaults:
+//
+// "string" — Kusto column type `string`. Empty strings ARE sent (lets
+// errorClass/errorDescription distinguish "explicit empty"
+// from "not present"). Non-strings are dropped.
+// "int" — Kusto column type `int`. Coerced via Number(); non-finite
+// or negative values clamp to 0. Sent as number, not string.
+// "object" — Kusto column type `dynamic` (JSON). Plain objects and
+// arrays pass through; primitives, Date, RegExp, etc. are
+// dropped to avoid Kusto type confusion. Validated here as a
+// real object; emit-dispatcher.js re-serializes it to a JSON
+// string just before it hits the wire (see buildEnvelope),
+// so the Kusto side must `parse_json()` / `todynamic()` it.
+// "enum:a|b|c" — Kusto column type `string`. Only the listed values are
+// accepted; anything else is dropped.
+//
+// Both `null` and `undefined` are dropped uniformly. Empty string is allowed
+// only for "string" types (deliberate — see above).
+const FIELD_TYPES = {
+ // Common — identity / context
+ pluginName: "string",
+ pluginVersion: "string",
+ sessionId: "string",
+ correlationId: "string",
+ osName: "string",
+ osVersion: "string",
+ nodeVersion: "string",
+ // Common — PAC + agent
+ orgId: "string",
+ tenantId: "string",
+ pacCliVersion: "string",
+ aiAgentName: "string",
+ aiAgentVersion: "string",
+ // Common — caller-supplied dynamic JSON
+ eventInfo: "object",
+ // Skill
+ skillName: "string",
+ // Completed-only
+ outcome: "enum:success|failure",
+ durationMs: "int",
+ errorClass: "string",
+ errorDescription: "string",
+};
+
+const COMMON_FIELDS = [
+ "pluginName",
+ "pluginVersion",
+ "sessionId",
+ "correlationId",
+ "osName",
+ "osVersion",
+ "nodeVersion",
+ "orgId",
+ "tenantId",
+ "pacCliVersion",
+ "aiAgentName",
+ "aiAgentVersion",
+ "eventInfo",
+];
+
+const SKILL_FIELDS = ["skillName"];
+const COMPLETED_FIELDS = ["outcome", "durationMs", "errorClass", "errorDescription"];
+
+function isPlainStructured(v) {
+ if (v === null || typeof v !== "object") return false;
+ if (Array.isArray(v)) return true;
+ // Only plain objects (prototype Object.prototype or null) pass through —
+ // class instances like Date, RegExp, Map, Set, and Error are rejected so
+ // the dynamic `eventInfo` field can't carry unexpected shapes.
+ const proto = Object.getPrototypeOf(v);
+ return proto === Object.prototype || proto === null;
+}
+
+function clampInt(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 0) return 0;
+ return Math.floor(n);
+}
+
+// Type-aware pick. Drops null/undefined for every type. For each kept value,
+// validates against its declared type and coerces as needed.
+function pick(input, keys) {
+ const out = {};
+ if (!input || typeof input !== "object") return out;
+ for (const k of keys) {
+ const v = input[k];
+ if (v === undefined || v === null) continue;
+ const type = FIELD_TYPES[k];
+ if (type === "string") {
+ if (typeof v === "string") out[k] = v;
+ } else if (type === "int") {
+ out[k] = clampInt(v);
+ } else if (type === "object") {
+ if (isPlainStructured(v)) out[k] = v;
+ } else if (typeof type === "string" && type.startsWith("enum:")) {
+ const allowed = type.slice(5).split("|");
+ if (typeof v === "string" && allowed.includes(v)) out[k] = v;
+ }
+ // unknown types: drop (defensive — no field should hit this branch).
+ }
+ return out;
+}
+
+function buildEvent(envelopeName, eventName, info, severity) {
+ return {
+ name: envelopeName,
+ data: { eventName, eventType: "Trace", severity, ...info },
+ };
+}
+
+function buildSkillStarted(envelopeName, input) {
+ return buildEvent(
+ envelopeName,
+ "skill_started",
+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),
+ "Info"
+ );
+}
+
+function buildSkillCompleted(envelopeName, input) {
+ const severity = input && input.outcome === "failure" ? "Error" : "Info";
+ return buildEvent(
+ envelopeName,
+ "skill_completed",
+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS, ...COMPLETED_FIELDS]),
+ severity
+ );
+}
+
+module.exports = {
+ buildSkillStarted,
+ buildSkillCompleted,
+ FIELD_TYPES,
+ pick,
+};
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/local-log.js b/plugins/model-apps/scripts/lib/telemetry/lib/local-log.js
new file mode 100644
index 000000000..ed61032d4
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/local-log.js
@@ -0,0 +1,170 @@
+"use strict";
+
+const fs = require("node:fs");
+const path = require("node:path");
+
+const LOG_FILE_NAME = "events.jsonl";
+const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB per-session size safety cap
+const MAX_LOG_AGE_DAYS = 14;
+const MAX_LOG_AGE_MS = MAX_LOG_AGE_DAYS * 24 * 60 * 60 * 1000;
+
+// pluginName and sessionId become DIRECTORY names, so each is reduced to one safe
+// path segment — a malformed record must never write outside telemetry/. Reject
+// "." / ".." outright, then collapse anything outside [A-Za-z0-9_-] to "_". Dots
+// are excluded so "../evil" can't leave a ".." fragment (it becomes "___evil");
+// an empty result falls back to the sentinel.
+function sanitizeSegment(value, fallback) {
+ if (typeof value !== "string") return fallback;
+ if (value === "." || value === "..") return fallback;
+ const cleaned = value.replace(/[^A-Za-z0-9_-]/g, "_");
+ if (!cleaned) return fallback;
+ return cleaned;
+}
+
+// <configDir>/telemetry/<plugin>/sessions — the directory that holds one
+// subdirectory per session. Pure path helper, no I/O.
+function pluginLogDir(configDir, pluginName) {
+ const plugin = sanitizeSegment(pluginName, "unknown");
+ return path.join(configDir, "telemetry", plugin, "sessions");
+}
+
+function sessionDir(configDir, pluginName, sessionId) {
+ const session = sanitizeSegment(sessionId, "nosession");
+ return path.join(pluginLogDir(configDir, pluginName), session);
+}
+
+// events.YYYYMMDDHHMMSS.old — UTC stamp so rolled files sort chronologically.
+function rotationName(now = new Date()) {
+ const pad = (n) => String(n).padStart(2, "0");
+ const stamp =
+ now.getUTCFullYear().toString() +
+ pad(now.getUTCMonth() + 1) +
+ pad(now.getUTCDate()) +
+ pad(now.getUTCHours()) +
+ pad(now.getUTCMinutes()) +
+ pad(now.getUTCSeconds());
+ return `events.${stamp}.old`;
+}
+
+// Per-session size cap. A single session almost never reaches 10 MB; this is a
+// safety valve against a pathological runaway session, not the primary
+// retention mechanism (that is age-based pruning of whole session dirs).
+function rotateIfNeeded(dir, logFile) {
+ try {
+ const stat = fs.statSync(logFile);
+ if (stat.size > ROTATE_BYTES) {
+ try {
+ fs.renameSync(logFile, path.join(dir, rotationName()));
+ } catch {
+ // best effort: if rename fails (file locked, etc.), keep appending.
+ }
+ }
+ } catch {
+ // no existing log — nothing to rotate
+ }
+}
+
+function appendLocal(record, { configDir } = {}) {
+ if (!configDir) return;
+ const data = (record && record.data) || {};
+ // Deterministic path — derived purely from the record. No directory scan, so
+ // the many short-lived dispatcher processes that may write the same session
+ // concurrently cannot race on "find this session's file".
+ const dir = sessionDir(configDir, data.pluginName, data.sessionId);
+ let created;
+ try {
+ // mkdirSync(recursive) returns the first path it created, or undefined if the
+ // dir already existed — a free "is this a brand-new session?" signal.
+ created = fs.mkdirSync(dir, { recursive: true });
+ } catch {
+ return;
+ }
+ const logFile = path.join(dir, LOG_FILE_NAME);
+ rotateIfNeeded(dir, logFile);
+ try {
+ fs.appendFileSync(logFile, JSON.stringify(record) + "\n", "utf8");
+ } catch {
+ // swallow — fail closed; telemetry must never break a skill run
+ }
+ // The retention sweep scans every session dir, so run it only on a session's
+ // first event (when we just created its dir), not on every append.
+ if (created) pruneOldSessions(configDir, data.pluginName);
+}
+
+// Best-effort age-based retention — the primary cleanup mechanism. Remove any
+// session dir whose events.jsonl was last written more than MAX_LOG_AGE_DAYS ago;
+// a dir with no readable log is judged by its OWN mtime, so a just-created dir from
+// a concurrent dispatcher isn't deleted out from under it. Never throws.
+function pruneOldSessions(configDir, pluginName, now = Date.now()) {
+ if (!configDir) return; // fail closed: pluginLogDir -> path.join would throw on undefined
+ const sessionsRoot = pluginLogDir(configDir, pluginName);
+ let entries;
+ try {
+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });
+ } catch {
+ return; // no sessions dir yet — nothing to prune
+ }
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const dir = path.join(sessionsRoot, entry.name);
+ try {
+ let mtimeMs;
+ try {
+ mtimeMs = fs.statSync(path.join(dir, LOG_FILE_NAME)).mtimeMs;
+ } catch {
+ // No readable log file — fall back to the directory's own mtime.
+ mtimeMs = fs.statSync(dir).mtimeMs;
+ }
+ if (now - mtimeMs > MAX_LOG_AGE_MS) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ } catch {
+ // best effort per dir; skip on any error
+ }
+ }
+}
+
+// Absolute path to the most-recently-written session's events.jsonl for a plugin,
+// or null when there are none ("most recent" = highest events.jsonl mtime). Dirs
+// without a readable events.jsonl are skipped so the returned path always exists —
+// status surfaces it for the user to share, and a phantom path would point them at
+// a file that isn't there. Read-only.
+function latestSessionLog(configDir, pluginName) {
+ if (!configDir) return null; // fail closed: pluginLogDir -> path.join would throw on undefined
+ const sessionsRoot = pluginLogDir(configDir, pluginName);
+ let entries;
+ try {
+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });
+ } catch {
+ return null;
+ }
+ let best = null;
+ let bestMtime = -Infinity;
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const logFile = path.join(sessionsRoot, entry.name, LOG_FILE_NAME);
+ let mtimeMs;
+ try {
+ // Skip dirs without a readable events.jsonl so `best` can't point at a missing file.
+ mtimeMs = fs.statSync(logFile).mtimeMs;
+ } catch {
+ continue;
+ }
+ if (mtimeMs > bestMtime) {
+ bestMtime = mtimeMs;
+ best = logFile;
+ }
+ }
+ return best;
+}
+
+module.exports = {
+ appendLocal,
+ pluginLogDir,
+ latestSessionLog,
+ pruneOldSessions,
+ sanitizeSegment,
+ LOG_FILE_NAME,
+ ROTATE_BYTES,
+ MAX_LOG_AGE_DAYS,
+};
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.js b/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.js
new file mode 100644
index 000000000..71b268b59
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/pac-auth.js
@@ -0,0 +1,76 @@
+"use strict";
+
+const { execFileSync } = require("node:child_process");
+
+// Reads PAC CLI auth state by shelling out to `pac auth who` and parsing the
+// banner output. Matches the convention used by
+// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /
+// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.
+//
+// PAC's JSON profile files are an internal/undocumented format that varies
+// across versions. The banner output is stable and is what other code paths
+// already parse via the AUTH_KEYS list documented in the VSCode 1DS extension.
+//
+// Best-effort and fail-closed: missing executable, timeout, non-zero exit, or
+// unparseable output all resolve to null. The result is cached per process so
+// repeated hook invocations only fork once.
+
+// Cold-start `pac auth who` on Windows is consistently ~3.5-4s (.NET runtime
+// startup + cached-token validation). 3s was too tight and produced silent
+// timeouts that surfaced as missing orgId/tenantId in every event. 8s gives
+// comfortable headroom while staying well under the hook's 30s budget.
+const TIMEOUT_MS = 8000;
+
+let cache;
+
+function _resetCache() {
+ cache = undefined;
+}
+
+function pickLine(text, label) {
+ // Match "Label: value" — case-insensitive, trims whitespace.
+ const re = new RegExp("^\\s*" + label + "\\s*:\\s*(\\S.*?)\\s*$", "im");
+ const match = text.match(re);
+ return match ? match[1] : null;
+}
+
+function readPacAuth(opts = {}) {
+ if (cache !== undefined) return cache;
+ if (opts._exec === false) {
+ cache = null;
+ return null;
+ }
+ const exec = typeof opts._exec === "function" ? opts._exec : execFileSync;
+ let output;
+ try {
+ output = exec("pac", ["auth", "who"], {
+ encoding: "utf8",
+ timeout: TIMEOUT_MS,
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ } catch {
+ cache = null;
+ return null;
+ }
+ if (typeof output !== "string" || !output) {
+ cache = null;
+ return null;
+ }
+ const tenantId = pickLine(output, "Tenant Id");
+ const orgId = pickLine(output, "Organization Id");
+ const cloud = pickLine(output, "Cloud");
+ const objectId = pickLine(output, "Entra ID Object Id");
+ if (!tenantId && !orgId) {
+ cache = null;
+ return null;
+ }
+ cache = {
+ orgId: orgId || "",
+ tenantId: tenantId || "",
+ cloud: cloud || "",
+ objectId: objectId || "",
+ };
+ return cache;
+}
+
+module.exports = { readPacAuth, _resetCache };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/prompt-detector.js b/plugins/model-apps/scripts/lib/telemetry/lib/prompt-detector.js
new file mode 100644
index 000000000..60474128b
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/prompt-detector.js
@@ -0,0 +1,28 @@
+"use strict";
+
+function detectSlashCommand(promptText, { pluginName, trackedSkills } = {}) {
+ if (typeof promptText !== "string" || !promptText) return null;
+ if (!pluginName || !trackedSkills) return null;
+
+ // Match both the namespaced form (`/<plugin>:<skill>`) and the bare form
+ // (`/<skill>`). The `pluginName:` prefix is optional because the host tool
+ // controls how the slash command is surfaced in the prompt and may emit the
+ // bare form without the plugin namespace. Either way the captured skill name
+ // is validated against trackedSkills below, so a bare `/foo` only counts when
+ // `foo` is a known skill. The trailing boundary lookahead still rejects a
+ // different plugin's namespaced command (e.g. `/other-plugin:add-seo`, where
+ // `other-plugin` is followed by `:` rather than a word boundary).
+ const escapedPlugin = pluginName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const re = new RegExp(
+ String.raw`^\s*\/(?:` + escapedPlugin + String.raw`:)?([a-z0-9-]+)(?=\s|$|\r|\n)`
+ );
+ const match = promptText.match(re);
+ if (!match) return null;
+
+ const skillName = match[1];
+ return Object.prototype.hasOwnProperty.call(trackedSkills, skillName)
+ ? skillName
+ : null;
+}
+
+module.exports = { detectSlashCommand };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/resolver-loader.js b/plugins/model-apps/scripts/lib/telemetry/lib/resolver-loader.js
new file mode 100644
index 000000000..5c5c2bb67
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/resolver-loader.js
@@ -0,0 +1,26 @@
+"use strict";
+
+const path = require("node:path");
+
+// Discover an optional, plugin-provided resolver module that owns iKey/collector
+// selection (region routing, tenant routing, etc.). Convention: a `resolver.js`
+// next to the plugin's ikey.json. The shared library never imports a resolver
+// directly — it loads whatever the plugin drops here and calls the documented
+// contract: { resolve({event, cfg, cloud, configDir}), isProvisioned(cfg) }.
+//
+// Returns the resolver module, or null when none is present or it fails to load
+// (callers then fall back to static config / a generic gate — fail open).
+function loadResolver(dir) {
+ if (!dir) return null;
+ try {
+ // path.resolve (not path.join): require() treats a non-"./"-prefixed
+ // relative path as a module ID and searches node_modules. A relative `dir`
+ // (e.g. from a relative POWER_PLATFORM_SKILLS_IKEY_JSON override) would then
+ // miss the intended resolver.js. Resolve to an absolute path first.
+ return require(path.resolve(dir, "resolver.js"));
+ } catch {
+ return null;
+ }
+}
+
+module.exports = { loadResolver };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/scrubber.js b/plugins/model-apps/scripts/lib/telemetry/lib/scrubber.js
new file mode 100644
index 000000000..517188404
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/scrubber.js
@@ -0,0 +1,11 @@
+"use strict";
+
+// Placeholder. The spec allowlist already restricts payload fields to values
+// that cannot contain PII. This module exists as a documented seam for a
+// future regex-based pass if the allowlist ever needs to carry user strings.
+
+function scrub(value) {
+ return value;
+}
+
+module.exports = { scrub };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/session.js b/plugins/model-apps/scripts/lib/telemetry/lib/session.js
new file mode 100644
index 000000000..cbf89884d
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/session.js
@@ -0,0 +1,43 @@
+"use strict";
+
+const crypto = require("node:crypto");
+
+// Hooks run as fresh Node processes, so a module-level UUID would be unique
+// per hook invocation — every event in a Claude Code session would carry a
+// different sessionId, breaking session-scoped analysis. Each hook reads
+// Claude Code's session_id from the stdin payload and primes this cache
+// with it so all events emitted from that hook (and within that process)
+// share a single sessionId.
+let cached;
+
+function getSessionId(override) {
+ if (typeof override === "string" && override) {
+ cached = override;
+ return cached;
+ }
+ if (!cached) cached = crypto.randomUUID();
+ return cached;
+}
+
+// Multi-host session-id resolver. Both Claude Code and GitHub Copilot CLI
+// surface their session id through the hook stdin payload. Field-name
+// convention may vary by host; check known variants in precedence order.
+// Returns "" when no usable id is present so the caller's subsequent
+// getSessionId("") falls back to a per-process UUID.
+function resolveHostSessionId(payload) {
+ if (!payload || typeof payload !== "object") return "";
+ if (typeof payload.session_id === "string" && payload.session_id) {
+ return payload.session_id;
+ }
+ if (typeof payload.sessionId === "string" && payload.sessionId) {
+ return payload.sessionId;
+ }
+ return "";
+}
+
+// Test seam.
+function _resetCache() {
+ cached = undefined;
+}
+
+module.exports = { getSessionId, resolveHostSessionId, _resetCache };
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js
new file mode 100644
index 000000000..7b13e16f4
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/telemetry-config.js
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+"use strict";
+
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { setTelemetryChoice, effectiveTelemetryChoice } = require("./user-config");
+const { pluginLogDir, latestSessionLog } = require("./local-log");
+
+const ANONYMITY =
+ "ℹ️ No personal data is collected. Telemetry is anonymous — it records only\n" +
+ " operational fields like skill name, plugin version, OS/Node versions,\n" +
+ " PAC CLI and agent versions, and Dataverse org/tenant IDs when available.\n" +
+ " It never includes file paths, prompts, tool inputs, site names, URLs,\n" +
+ " credentials, usernames, or hostnames.";
+
+function getArg(name) {
+ const i = process.argv.indexOf(`--${name}`);
+ return i !== -1 && i + 1 < process.argv.length ? process.argv[i + 1] : null;
+}
+
+function configDir() {
+ return (
+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||
+ path.join(os.homedir(), ".power-platform-skills")
+ );
+}
+
+// --plugin wins; otherwise auto-detect from the plugin manifest 4 levels up
+// (.../plugins/<plugin>/scripts/lib/telemetry/lib/telemetry-config.js).
+function resolvePlugin() {
+ const explicit = getArg("plugin");
+ if (explicit) return explicit;
+ try {
+ const manifestPath = path.resolve(
+ __dirname, "..", "..", "..", "..", ".claude-plugin", "plugin.json"
+ );
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
+ return manifest.name || null;
+ } catch {
+ return null;
+ }
+}
+
+function out(s) {
+ process.stdout.write(s + "\n");
+}
+
+// Print where this plugin's local diagnostic logs live and name the newest
+// session file, so a user can hand over exactly the log for the session they
+// just hit a problem in. Reuses the shared layout helpers (DRY — no path logic
+// is duplicated in the skill).
+function emitLogLocations(dir, plugin) {
+ out(`Logs directory: ${pluginLogDir(dir, plugin)}`);
+ const latest = latestSessionLog(dir, plugin);
+ if (latest) {
+ out(`Most recent session: ${latest}`);
+ out("ℹ️ Share that file when reporting an issue (it covers your latest session).");
+ } else {
+ out(`No local logs yet for ${plugin}.`);
+ }
+}
+
+function main() {
+ const action = getArg("action");
+ const plugin = resolvePlugin();
+ if (!plugin || !["on", "off", "status"].includes(action)) {
+ out("Usage: telemetry-config.js --action <on|off|status> [--plugin <name>]");
+ process.exit(2);
+ }
+ const dir = configDir();
+
+ if (action === "status") {
+ const on = effectiveTelemetryChoice(dir, plugin) !== "off"; // default ON; honors env override when no stored choice
+ if (on) {
+ out(`Telemetry (${plugin}): ON`);
+ out(ANONYMITY);
+ emitLogLocations(dir, plugin);
+ } else {
+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);
+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);
+ emitLogLocations(dir, plugin);
+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);
+ out(ANONYMITY);
+ }
+ process.exit(0);
+ }
+
+ if (!setTelemetryChoice(dir, plugin, action)) {
+ out(`Could not update the telemetry setting (config dir not writable).`);
+ process.exit(1);
+ }
+ if (action === "off") {
+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);
+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);
+ emitLogLocations(dir, plugin);
+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);
+ } else if (effectiveTelemetryChoice(dir, plugin) === "off") {
+ // The preference was saved as ON, but the highest-precedence environment
+ // opt-out still forces transmission off — report the EFFECTIVE state so we
+ // never claim ON while an opt-out is suppressing it.
+ out(`Telemetry (${plugin}): preference saved as ON, but an environment opt-out is currently in effect — nothing is transmitted until it is cleared.`);
+ } else {
+ out(`Telemetry (${plugin}): ON`);
+ }
+ out(ANONYMITY);
+ process.exit(0);
+}
+
+main();
diff --git a/plugins/model-apps/scripts/lib/telemetry/lib/user-config.js b/plugins/model-apps/scripts/lib/telemetry/lib/user-config.js
new file mode 100644
index 000000000..ea0597f73
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/telemetry/lib/user-config.js
@@ -0,0 +1,106 @@
+"use strict";
+
+const fs = require("node:fs");
+const path = require("node:path");
+
+const CONFIG_FILE_NAME = "config.json";
+
+function configPath(configDir) {
+ return path.join(configDir, CONFIG_FILE_NAME);
+}
+
+function isPlainObject(value) {
+ return value && typeof value === "object" && !Array.isArray(value);
+}
+
+// Reads the whole config object; returns {} on any error (missing/corrupt).
+function readConfig(configDir) {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(configPath(configDir), "utf8"));
+ // Arrays pass `typeof === "object"` but break the merge-write: setTelemetryChoice
+ // would set `.telemetry` on the array and JSON.stringify would silently drop it,
+ // reporting success while persisting nothing. Treat non-plain objects as empty.
+ return isPlainObject(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+
+// Returns "on" | "off" | null (null = unset / not a valid value).
+function readTelemetryChoice(configDir, pluginName) {
+ if (!configDir || !pluginName) return null;
+ const t = readConfig(configDir).telemetry;
+ if (!isPlainObject(t)) return null;
+ const v = t[pluginName];
+ return v === "on" || v === "off" ? v : null;
+}
+
+// Builds the per-plugin opt-out var name: POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT
+// where <PLUGIN> is the plugin name uppercased with non-alphanumeric runs -> "_".
+function telemetryOptOutEnvVarName(pluginName) {
+ return (
+ "POWER_PLATFORM_SKILLS_TELEMETRY_" +
+ String(pluginName).toUpperCase().replace(/[^A-Z0-9]+/g, "_") +
+ "_OPTOUT"
+ );
+}
+
+// True when the per-plugin opt-out env var is set to a truthy value (`1` or
+// `true`, case-insensitive). Follows the dotnet `*_TELEMETRY_OPTOUT` convention:
+// the var only disables — it is never used to re-enable. Unset / empty / `0` /
+// `false` / anything else => not opted out. `env` is injectable so tests never
+// mutate the real process.env.
+function readTelemetryEnvOptOut(pluginName, env = process.env) {
+ if (!pluginName) return false;
+ const v = String(env[telemetryOptOutEnvVarName(pluginName)] || "").trim().toLowerCase();
+ return v === "1" || v === "true";
+}
+
+// Resolves the effective on/off choice by precedence (highest first):
+// 1. the env-var opt-out (when truthy => "off"; overrides everything below)
+// 2. persisted config.json per-plugin choice (set via the slash skill)
+// 3. null = default-on
+// The env var has the highest precedence and can only force "off"; it never
+// re-enables a config opt-out.
+function effectiveTelemetryChoice(configDir, pluginName, env = process.env) {
+ if (readTelemetryEnvOptOut(pluginName, env)) return "off";
+ return readTelemetryChoice(configDir, pluginName) ?? null;
+}
+
+function isTransmissionOptedOut(configDir, pluginName, env = process.env) {
+ return effectiveTelemetryChoice(configDir, pluginName, env) === "off";
+}
+
+// Merge-writes { telemetry: { [pluginName]: choice } }, preserving every other
+// key. Returns true on success, false on bad input or I/O failure. Never throws.
+function setTelemetryChoice(configDir, pluginName, choice) {
+ if (!configDir || !pluginName) return false;
+ if (choice !== "on" && choice !== "off") return false;
+ try {
+ fs.mkdirSync(configDir, { recursive: true });
+ } catch {
+ return false;
+ }
+ const cfg = readConfig(configDir);
+ // `telemetry` itself can also be malformed, e.g. `"telemetry": []`. Assigning
+ // `cfg.telemetry[pluginName]` on an array creates a non-index property that
+ // JSON.stringify drops, so normalize any non-plain telemetry value before write.
+ if (!isPlainObject(cfg.telemetry)) cfg.telemetry = {};
+ cfg.telemetry[pluginName] = choice;
+ try {
+ fs.writeFileSync(configPath(configDir), JSON.stringify(cfg, null, 2) + "\n", "utf8");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+module.exports = {
+ readTelemetryChoice,
+ setTelemetryChoice,
+ isTransmissionOptedOut,
+ telemetryOptOutEnvVarName,
+ readTelemetryEnvOptOut,
+ effectiveTelemetryChoice,
+ CONFIG_FILE_NAME,
+};
diff --git a/plugins/model-apps/scripts/playwright-mcp-fullscreen.config.json b/plugins/model-apps/scripts/playwright-mcp-fullscreen.config.json
new file mode 100644
index 000000000..b1d791712
--- /dev/null
+++ b/plugins/model-apps/scripts/playwright-mcp-fullscreen.config.json
@@ -0,0 +1,13 @@
+{
+ "browser": {
+ "launchOptions": {
+ "args": [
+ "--start-maximized",
+ "--start-fullscreen"
+ ]
+ },
+ "contextOptions": {
+ "viewport": null
+ }
+ }
+}
diff --git a/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.js b/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.js
new file mode 100644
index 000000000..56a21a491
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/launch-playwright-mcp.test.js
@@ -0,0 +1,73 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const test = require('node:test');
+const { EventEmitter } = require('node:events');
+
+const {
+ buildMcpArgs,
+ launch,
+ quoteShellArg,
+} = require('../launch-playwright-mcp');
+
+test('buildMcpArgs launches Playwright MCP with fullscreen config', () => {
+ const expectedConfigPath = path.join(__dirname, '..', 'playwright-mcp-fullscreen.config.json');
+ const args = buildMcpArgs('chrome');
+ const configIndex = args.indexOf('--config');
+
+ assert.deepEqual(args.slice(0, 4), ['-y', '@playwright/mcp@latest', '--browser', 'chrome']);
+ assert.equal(args.includes('--viewport-size'), false);
+ assert.notEqual(configIndex, -1);
+ assert.equal(args[configIndex + 1], quoteShellArg(expectedConfigPath));
+});
+
+test('buildMcpArgs quotes Windows config paths containing spaces', () => {
+ const configPath = 'C:\\Users\\Power User\\.claude\\plugins\\model-apps\\scripts\\playwright-mcp-fullscreen.config.json';
+ const args = buildMcpArgs('msedge', { configPath, platform: 'win32' });
+ const configIndex = args.indexOf('--config');
+
+ assert.equal(args[configIndex + 1], `"${configPath}"`);
+});
+
+test('fullscreen config maximizes the browser and uses the real viewport size', () => {
+ const configPath = path.join(__dirname, '..', 'playwright-mcp-fullscreen.config.json');
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
+
+ assert.deepEqual(config.browser.launchOptions.args, ['--start-maximized', '--start-fullscreen']);
+ assert.equal(config.browser.contextOptions.viewport, null);
+});
+
+test('launch wires spawn and process exit handling', () => {
+ let spawnCall;
+ const child = new EventEmitter();
+
+ launch({
+ browser: 'msedge',
+ spawnFn(command, args, options) {
+ spawnCall = { command, args, options };
+ return child;
+ },
+ onExit(code) {
+ spawnCall.exitCode = code;
+ },
+ });
+
+ assert.equal(spawnCall.command, 'npx');
+ assert.deepEqual(spawnCall.args.slice(0, 4), ['-y', '@playwright/mcp@latest', '--browser', 'msedge']);
+ assert.deepEqual(spawnCall.options, { stdio: 'inherit', shell: true });
+
+ child.emit('exit', 7);
+ assert.equal(spawnCall.exitCode, 7);
+});
+
+test('launch handles the child error event (npx fails to spawn)', () => {
+ const child = new EventEmitter();
+ let handled;
+ launch({
+ browser: 'chrome',
+ spawnFn: () => child,
+ onError: (err) => { handled = err.message; },
+ });
+ child.emit('error', new Error('spawn npx ENOENT'));
+ assert.equal(handled, 'spawn npx ENOENT');
+});
diff --git a/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.js b/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.js
new file mode 100644
index 000000000..6b58edb7a
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/modelapps-hook-utils.test.js
@@ -0,0 +1,68 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const {
+ TRACKED_SKILLS,
+ TRACKED_SKILL_NAMES,
+ detectTrackedSkill,
+ getTrackedSkillFromToolInput,
+ getValidatorScript,
+} = require('../lib/modelapps-hook-utils');
+
+test('discovers genpage and report-issue as tracked skills', () => {
+ assert.ok(TRACKED_SKILLS.genpage, 'genpage should be tracked');
+ assert.ok(TRACKED_SKILLS['report-issue'], 'report-issue should be tracked');
+ assert.ok(TRACKED_SKILL_NAMES.includes('genpage'));
+});
+
+test('excludes the telemetry control skill from tracking (never self-emits)', () => {
+ // Even once skills/telemetry exists, it must not be tracked.
+ assert.equal(TRACKED_SKILLS.telemetry, undefined);
+ assert.equal(TRACKED_SKILL_NAMES.includes('telemetry'), false);
+});
+
+test('null-prototype map does not report inherited keys as skills', () => {
+ assert.equal(detectTrackedSkill('toString'), null);
+ assert.equal(detectTrackedSkill('constructor'), null);
+ assert.equal(detectTrackedSkill('__proto__'), null);
+});
+
+test('detectTrackedSkill normalizes slash and plugin prefixes', () => {
+ assert.equal(detectTrackedSkill('genpage'), 'genpage');
+ assert.equal(detectTrackedSkill('/genpage'), 'genpage');
+ assert.equal(detectTrackedSkill('model-apps:genpage'), 'genpage');
+ assert.equal(detectTrackedSkill('/model-apps:genpage'), 'genpage');
+ assert.equal(detectTrackedSkill('GENPAGE'), 'genpage');
+});
+
+test('detectTrackedSkill finds a model-apps:<skill> token embedded in text', () => {
+ assert.equal(detectTrackedSkill('please run model-apps:report-issue now'), 'report-issue');
+});
+
+test('detectTrackedSkill returns null for unknown or non-string input', () => {
+ assert.equal(detectTrackedSkill('not-a-real-skill'), null);
+ assert.equal(detectTrackedSkill(null), null);
+ assert.equal(detectTrackedSkill(42), null);
+});
+
+test('getTrackedSkillFromToolInput probes known fields', () => {
+ assert.equal(getTrackedSkillFromToolInput({ skill: 'genpage' }), 'genpage');
+ assert.equal(getTrackedSkillFromToolInput({ name: '/model-apps:genpage' }), 'genpage');
+ assert.equal(getTrackedSkillFromToolInput({ command: 'model-apps:report-issue' }), 'report-issue');
+});
+
+test('getTrackedSkillFromToolInput falls back to serialized scan', () => {
+ assert.equal(getTrackedSkillFromToolInput({ nested: { x: 'model-apps:genpage' } }), 'genpage');
+});
+
+test('getTrackedSkillFromToolInput returns null for non-objects / no match', () => {
+ assert.equal(getTrackedSkillFromToolInput(null), null);
+ assert.equal(getTrackedSkillFromToolInput('genpage'), null);
+ assert.equal(getTrackedSkillFromToolInput({ skill: 'unknown' }), null);
+});
+
+test('getValidatorScript returns null when a skill has no validator', () => {
+ // genpage currently ships no skills/genpage/scripts/validate*.js.
+ assert.equal(getValidatorScript('genpage'), null);
+ assert.equal(getValidatorScript('nope'), null);
+});
diff --git a/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js b/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js
new file mode 100644
index 000000000..58bdac13a
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/telemetry-hook-pretool.test.js
@@ -0,0 +1,145 @@
+"use strict";
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");
+const HOOK = path.join(PLUGIN_ROOT, "hooks", "run-skill-pretool-telemetry.js");
+const SHIPPED_IKEY = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry", "ikey.json");
+
+function mkTemp() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-tel-"));
+}
+
+function runHook({ input, configDir, ikeyPath, fakeProbe }) {
+ return spawnSync(process.execPath, [HOOK], {
+ input,
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",
+ // Clear the CI/automation opt-out so the provisioned path still reaches its probe.
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "",
+ // Route emission to a local probe instead of a real OneCollector.
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",
+ },
+ // The provisioned path shells out to `pac auth who` + `pac --version`; give it
+ // room so pac cold-start doesn't flake when pac is installed.
+ timeout: 30_000,
+ });
+}
+
+function sleep(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+function waitForFile(filePath, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ while (!fs.existsSync(filePath) && Date.now() < deadline) sleep(25);
+ return fs.existsSync(filePath);
+}
+
+// Tier-1 (flat static key, no resolver) provisioned config, isolated to a temp dir
+// so emission runs against example.invalid instead of any real collector.
+function writeProvisionedConfig(configDir) {
+ const ikeyPath = path.join(configDir, "ikey.json");
+ fs.writeFileSync(
+ ikeyPath,
+ JSON.stringify({
+ instrumentationKey: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",
+ collector_url: "https://example.invalid/OneCollector/1.0/",
+ event_stream_name: "ModelAppsTestStream",
+ disabled: false,
+ })
+ );
+ return ikeyPath;
+}
+
+test("ikey.json is never shipped enabled with the placeholder key", () => {
+ const cfg = JSON.parse(fs.readFileSync(SHIPPED_IKEY, "utf8"));
+ if (cfg.instrumentationKey === "PLACEHOLDER_REPLACE_BEFORE_SHIPPING") {
+ // Unprovisioned placeholder must stay hard-off.
+ assert.equal(cfg.disabled, true, "a placeholder key must ship disabled:true");
+ }
+ // A real (provisioned) key may ship staged (disabled:true) or live (disabled:false) —
+ // both valid. The guard only forbids enabling a placeholder key.
+});
+
+test("exits 0 and emits nothing when tool_input has no tracked skill", () => {
+ const { status } = runHook({
+ input: JSON.stringify({ tool_input: { skill: "other-plugin:foo" } }),
+ configDir: mkTemp(),
+ });
+ assert.equal(status, 0);
+});
+
+test("exits 0 on malformed stdin", () => {
+ const { status } = runHook({ input: "{not json", configDir: mkTemp() });
+ assert.equal(status, 0);
+});
+
+test("shipped disabled config → tracked skill emits nothing (no probe, hard-off)", () => {
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ // No ikey override → the hook reads the shipped ikey.json (disabled:true) and
+ // short-circuits before spawning the dispatcher.
+ const { status } = runHook({
+ input: JSON.stringify({ tool_input: { skill: "genpage" } }),
+ configDir,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.equal(waitForFile(probePath, 1500), false, "disabled config must not write a probe");
+});
+
+test("provisioned Tier-1 config → tracked skill emits skill_started to the probe", () => {
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = writeProvisionedConfig(configDir);
+
+ const { status } = runHook({
+ input: JSON.stringify({ tool_input: { skill: "genpage" } }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.ok(waitForFile(probePath, 5000), "dispatcher should have written the probe");
+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));
+ const body = JSON.parse(probe.body);
+ assert.equal(body.name, "ModelAppsTestStream");
+ assert.equal(body.data.eventName, "skill_started");
+ assert.equal(body.data.pluginName, "model-apps");
+ assert.equal(body.data.skillName, "genpage");
+ assert.equal(body.data.eventInfo, undefined, "model-apps must not send eventInfo/aadObjectId");
+});
+
+test("enabled config but placeholder key → treated as unprovisioned (no probe)", () => {
+ // Flipping disabled:false before replacing the placeholder must NOT emit: the
+ // hook's Tier-1 provisioned check rejects the sentinel, so no dispatch happens.
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = path.join(configDir, "ikey.json");
+ fs.writeFileSync(
+ ikeyPath,
+ JSON.stringify({
+ instrumentationKey: "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",
+ collector_url: "https://example.invalid/OneCollector/1.0/",
+ event_stream_name: "ModelAppsTestStream",
+ disabled: false,
+ })
+ );
+ const { status } = runHook({
+ input: JSON.stringify({ tool_input: { skill: "genpage" } }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.equal(waitForFile(probePath, 1500), false, "placeholder key must not emit a probe");
+});
diff --git a/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js b/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js
new file mode 100644
index 000000000..0552bb5df
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/telemetry-hook-userprompt.test.js
@@ -0,0 +1,143 @@
+"use strict";
+
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { spawnSync } = require("node:child_process");
+
+const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");
+const HOOK = path.join(PLUGIN_ROOT, "hooks", "run-user-prompt-telemetry.js");
+
+function mkTemp() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "modelapps-uptel-"));
+}
+
+function runHook({ input, configDir, ikeyPath, fakeProbe }) {
+ return spawnSync(process.execPath, [HOOK], {
+ input,
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,
+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath || "",
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "",
+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe || "",
+ },
+ timeout: 30_000,
+ });
+}
+
+function sleep(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+function waitForFile(filePath, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ while (!fs.existsSync(filePath) && Date.now() < deadline) sleep(25);
+ return fs.existsSync(filePath);
+}
+
+function writeProvisionedConfig(configDir) {
+ const ikeyPath = path.join(configDir, "ikey.json");
+ fs.writeFileSync(
+ ikeyPath,
+ JSON.stringify({
+ instrumentationKey: "test-ikey-32-chars-minimum-aaaaaaaaaaaaaa",
+ collector_url: "https://example.invalid/OneCollector/1.0/",
+ event_stream_name: "ModelAppsTestStream",
+ disabled: false,
+ })
+ );
+ return ikeyPath;
+}
+
+test("exits 0 and emits nothing for a non-slash prompt", () => {
+ const { status } = runHook({
+ input: JSON.stringify({ prompt: "just a normal question" }),
+ configDir: mkTemp(),
+ });
+ assert.equal(status, 0);
+});
+
+test("exits 0 and emits nothing for another plugin's slash command", () => {
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = writeProvisionedConfig(configDir);
+ const { status } = runHook({
+ input: JSON.stringify({ prompt: "/power-pages:create-site" }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.equal(waitForFile(probePath, 1500), false, "unrelated command must not emit");
+});
+
+test("provisioned config → /model-apps:genpage prompt emits skill_started, WITHOUT aadObjectId", () => {
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = writeProvisionedConfig(configDir);
+
+ const { status } = runHook({
+ input: JSON.stringify({ prompt: "/model-apps:genpage build a dashboard", session_id: "s1" }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.ok(waitForFile(probePath, 5000), "dispatcher should have written the probe");
+ const probe = JSON.parse(fs.readFileSync(probePath, "utf8"));
+ const body = JSON.parse(probe.body);
+ assert.equal(body.name, "ModelAppsTestStream");
+ assert.equal(body.data.eventName, "skill_started");
+ assert.equal(body.data.pluginName, "model-apps");
+ assert.equal(body.data.skillName, "genpage");
+ // The _readPacAuth wrapper strips objectId, so no user-level identifier is sent.
+ assert.equal(body.data.eventInfo, undefined, "prompt path must not send eventInfo/aadObjectId");
+});
+
+test("bare /genpage prompt is also recognized (host may drop the plugin prefix)", () => {
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = writeProvisionedConfig(configDir);
+ const { status } = runHook({
+ input: JSON.stringify({ prompt: "/genpage make a page" }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.ok(waitForFile(probePath, 5000), "bare /genpage should emit");
+ const body = JSON.parse(JSON.parse(fs.readFileSync(probePath, "utf8")).body);
+ assert.equal(body.data.skillName, "genpage");
+});
+
+test("exits 0 on malformed stdin", () => {
+ const { status } = runHook({ input: "{not json", configDir: mkTemp() });
+ assert.equal(status, 0);
+});
+
+test("enabled config but placeholder key → prompt path emits nothing (no probe)", () => {
+ const configDir = mkTemp();
+ const probePath = path.join(configDir, "probe.json");
+ const ikeyPath = path.join(configDir, "ikey.json");
+ fs.writeFileSync(
+ ikeyPath,
+ JSON.stringify({
+ instrumentationKey: "PLACEHOLDER_REPLACE_BEFORE_SHIPPING",
+ collector_url: "https://example.invalid/OneCollector/1.0/",
+ event_stream_name: "ModelAppsTestStream",
+ disabled: false,
+ })
+ );
+ const { status } = runHook({
+ input: JSON.stringify({ prompt: "/model-apps:genpage x" }),
+ configDir,
+ ikeyPath,
+ fakeProbe: probePath,
+ });
+ assert.equal(status, 0);
+ assert.equal(waitForFile(probePath, 1500), false, "placeholder key must not emit on the prompt path");
+});
diff --git a/plugins/model-apps/scripts/tests/validate-icon-imports.test.js b/plugins/model-apps/scripts/tests/validate-icon-imports.test.js
new file mode 100644
index 000000000..fd8d3aaf9
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/validate-icon-imports.test.js
@@ -0,0 +1,196 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+const HOOK = path.join(__dirname, '..', '..', 'hooks', 'validate-icon-imports.js');
+
+// Run the hook as a child process with a JSON stdin payload (its real entry
+// shape). Returns { status, stderr }.
+function runHook(payload, env) {
+ const res = spawnSync(process.execPath, [HOOK], {
+ input: JSON.stringify(payload),
+ encoding: 'utf8',
+ env: { ...process.env, ...(env || {}) },
+ });
+ return { status: res.status, stderr: res.stderr || '' };
+}
+
+// Write a temp .tsx file on disk (the hook reads the final on-disk content in
+// PostToolUse) and return its path plus a Write tool payload.
+function writeTemp(dir, name, content) {
+ const filePath = path.join(dir, name);
+ fs.writeFileSync(filePath, content, 'utf8');
+ return filePath;
+}
+
+function payloadFor(filePath, content, tool = 'Write') {
+ const toolInput = tool === 'Write'
+ ? { file_path: filePath, content }
+ : { file_path: filePath, new_string: content };
+ return { tool_name: tool, tool_input: toolInput, cwd: path.dirname(filePath) };
+}
+
+const GENPAGE_HEADER =
+ "import * as React from 'react';\nconst GeneratedComponent = () => null;\nexport default GeneratedComponent;\n";
+
+let tmp;
+test.beforeEach(() => {
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-icons-'));
+});
+test.afterEach(() => {
+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
+});
+
+test('valid verified icons in a genpage file pass (exit 0)', () => {
+ const content = `import { AddRegular, DeleteRegular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('hallucinated icon name in a genpage file is blocked (exit 2)', () => {
+ const bad = 'TotallyMadeUpIconRegular';
+ const content = `import { AddRegular, ${bad} } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status, stderr } = runHook(payloadFor(fp, content));
+ assert.equal(status, 2);
+ assert.match(stderr, new RegExp(bad));
+});
+
+test('sized icon variant is rejected (unsized-only rule) (exit 2)', () => {
+ const content = `import { Add24Regular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status, stderr } = runHook(payloadFor(fp, content));
+ assert.equal(status, 2);
+ assert.match(stderr, /Add24Regular/);
+});
+
+test('`as` alias uses the source export name for validation', () => {
+ const content = `import { DeleteRegular as Trash } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+// Regression guard: the generator (and samples 8/11) format long icon imports
+// across multiple lines. The extractor's `{([^}]+)}` capture must span newlines,
+// or a multi-line block would silently bypass validation.
+test('multi-line verified icon import passes (exit 0)', () => {
+ const content =
+ "import {\n AddRegular,\n DeleteRegular,\n EditRegular,\n} from '@fluentui/react-icons';\n" +
+ GENPAGE_HEADER;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('hallucinated icon inside a multi-line import is blocked (exit 2)', () => {
+ const bad = 'TotallyMadeUpIconRegular';
+ const content =
+ `import {\n AddRegular,\n ${bad},\n DeleteRegular,\n} from '@fluentui/react-icons';\n` +
+ GENPAGE_HEADER;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status, stderr } = runHook(payloadFor(fp, content));
+ assert.equal(status, 2);
+ assert.match(stderr, new RegExp(bad));
+});
+
+test('a `//` comment inside a multi-line import does not hide the next bad icon (exit 2)', () => {
+ // Regression: a `//` line leaves the following specifier starting with `//…`,
+ // which used to fail the identifier test and be silently skipped (fail-open).
+ const bad = 'FakeCommentHiddenRegular';
+ const content =
+ `import {\n AddRegular, // a trailing comment\n ${bad},\n} from '@fluentui/react-icons';\n` +
+ GENPAGE_HEADER;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status, stderr } = runHook(payloadFor(fp, content));
+ assert.equal(status, 2);
+ assert.match(stderr, new RegExp(bad));
+});
+
+test('a `//` comment inside a valid multi-line import still passes (exit 0)', () => {
+ const content =
+ `import {\n AddRegular, // create\n DeleteRegular, // remove\n} from '@fluentui/react-icons';\n` +
+ GENPAGE_HEADER;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('a `}` inside a `//` comment does not truncate the import capture (exit 2)', () => {
+ // Regression: a `}` in a comment used to end the `[^}]+` capture early, so the
+ // whole import failed to match and every icon (incl. bad ones) slipped through.
+ const bad = 'BraceCommentBypassRegular';
+ const content =
+ `import {\n AddRegular, // note: shaped like {}\n ${bad},\n} from '@fluentui/react-icons';\n` +
+ GENPAGE_HEADER;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status, stderr } = runHook(payloadFor(fp, content));
+ assert.equal(status, 2);
+ assert.match(stderr, new RegExp(bad));
+});
+
+test('non-genpage file is ignored even with a bad icon (exit 0)', () => {
+ // No `export default GeneratedComponent` and no sibling genpage-plan.md.
+ const content = "import { NotARealIconRegular } from '@fluentui/react-icons';\nexport const x = 1;\n";
+ const fp = writeTemp(tmp, 'random.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('sibling genpage-plan.md opts a file into validation (exit 2 on bad icon)', () => {
+ fs.writeFileSync(path.join(tmp, 'genpage-plan.md'), '# plan\n', 'utf8');
+ const content = "import { NotARealIconRegular } from '@fluentui/react-icons';\nexport const x = 1;\n";
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status, stderr } = runHook(payloadFor(fp, content));
+ assert.equal(status, 2);
+ assert.match(stderr, /NotARealIconRegular/);
+});
+
+test('non-tsx file is ignored (exit 0)', () => {
+ const content = "import { NotARealIconRegular } from '@fluentui/react-icons';\n";
+ const fp = writeTemp(tmp, 'notes.md', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('non-write tool is ignored (exit 0)', () => {
+ const { status } = runHook({ tool_name: 'Read', tool_input: { file_path: 'x.tsx' } });
+ assert.equal(status, 0);
+});
+
+test('file with no @fluentui/react-icons imports passes (exit 0)', () => {
+ const content = `import * as React from 'react';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('commented-out import (line comment) is not treated as a real import (exit 0)', () => {
+ const content = `// import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('block-commented import is not treated as a real import (exit 0)', () => {
+ const content = `/* import { TotallyMadeUpIconRegular } from '@fluentui/react-icons'; */\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content));
+ assert.equal(status, 0);
+});
+
+test('MODEL_APPS_DISABLE_HOOKS=1 disables the validator (exit 0 despite bad icon)', () => {
+ const content = `import { TotallyMadeUpIconRegular } from '@fluentui/react-icons';\n${GENPAGE_HEADER}`;
+ const fp = writeTemp(tmp, 'page.tsx', content);
+ const { status } = runHook(payloadFor(fp, content), { MODEL_APPS_DISABLE_HOOKS: '1' });
+ assert.equal(status, 0);
+});
+
+test('unparseable stdin does not block (exit 0)', () => {
+ const res = spawnSync(process.execPath, [HOOK], { input: 'not json', encoding: 'utf8' });
+ assert.equal(res.status, 0);
+});
diff --git a/plugins/model-apps/scripts/tests/validate-write-safety.test.js b/plugins/model-apps/scripts/tests/validate-write-safety.test.js
new file mode 100644
index 000000000..9d5d359ed
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/validate-write-safety.test.js
@@ -0,0 +1,126 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+
+const HOOK = path.join(__dirname, '..', '..', 'hooks', 'validate-write-safety.js');
+
+function runHook(payload, env) {
+ const res = spawnSync(process.execPath, [HOOK], {
+ input: JSON.stringify(payload),
+ encoding: 'utf8',
+ env: { ...process.env, ...(env || {}) },
+ });
+ return { status: res.status, stderr: res.stderr || '' };
+}
+
+let cwd;
+test.beforeEach(() => {
+ cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'genpage-ws-'));
+ // Mark this as an active genpage session so the (session-scoped) guard engages.
+ fs.writeFileSync(path.join(cwd, 'genpage-plan.md'), '# plan\n', 'utf8');
+});
+test.afterEach(() => {
+ try { fs.rmSync(cwd, { recursive: true, force: true }); } catch { /* ignore */ }
+});
+
+test('write inside the working directory is allowed (exit 0)', () => {
+ const payload = {
+ tool_name: 'Write',
+ tool_input: { file_path: path.join(cwd, 'sub', 'page.tsx'), content: 'x' },
+ cwd,
+ };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('relative path resolving under cwd is allowed (exit 0)', () => {
+ const payload = { tool_name: 'Edit', tool_input: { file_path: 'RuntimeTypes.ts', new_string: 'x' }, cwd };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('write escaping the working directory is flagged, non-blocking (exit 1)', () => {
+ // Target the drive/filesystem root so the path is outside BOTH cwd and the
+ // tmpdir scratch exception (cwd itself lives under tmpdir here).
+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-evil', 'evil.ts');
+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
+ const { status, stderr } = runHook(payload);
+ assert.equal(status, 1); // non-blocking: exit 1 (only exit 2 would block)
+ assert.match(stderr, /outside your project folder/);
+});
+
+test('parent-traversal path escaping to the root is flagged, non-blocking (exit 1)', () => {
+ const target = path.join(path.parse(cwd).root, 'model-apps-guard-evil2.ts');
+ const rel = path.relative(cwd, target); // e.g. ..\..\..\model-apps-guard-evil2.ts
+ const payload = { tool_name: 'Edit', tool_input: { file_path: rel, new_string: 'x' }, cwd };
+ assert.equal(runHook(payload).status, 1);
+});
+
+test('outside-cwd write is NOT flagged when there is no genpage session (exit 0)', () => {
+ fs.rmSync(path.join(cwd, 'genpage-plan.md'), { force: true }); // no active genpage run
+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-evil', 'evil.ts');
+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('genpage-plan.md in a working subdir activates the guard (exit 1)', () => {
+ fs.rmSync(path.join(cwd, 'genpage-plan.md'), { force: true });
+ const wd = path.join(cwd, 'my-page');
+ fs.mkdirSync(wd);
+ fs.writeFileSync(path.join(wd, 'genpage-plan.md'), '# plan\n', 'utf8');
+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-evil', 'evil.ts');
+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
+ assert.equal(runHook(payload).status, 1);
+});
+
+test('tmpdir scratch writes are allowed (exit 0)', () => {
+ const payload = {
+ tool_name: 'Write',
+ tool_input: { file_path: path.join(os.tmpdir(), 'scratch-xyz.txt'), content: 'x' },
+ cwd,
+ };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('non-write tools are ignored (exit 0)', () => {
+ const payload = { tool_name: 'Read', tool_input: { file_path: '/etc/passwd' }, cwd };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('MODEL_APPS_SKIP_WRITE_GUARD=1 bypasses the guard (exit 0)', () => {
+ const outside = path.join(path.dirname(cwd), 'sibling', 'evil.ts');
+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
+ assert.equal(runHook(payload, { MODEL_APPS_SKIP_WRITE_GUARD: '1' }).status, 0);
+});
+
+test('MODEL_APPS_SKIP_WRITE_GUARD=true also bypasses the guard (exit 0)', () => {
+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-evil', 'evil.ts');
+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
+ assert.equal(runHook(payload, { MODEL_APPS_SKIP_WRITE_GUARD: 'true' }).status, 0);
+});
+
+test('missing file_path is not our concern (exit 0)', () => {
+ const payload = { tool_name: 'Write', tool_input: { content: 'x' }, cwd };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('Windows: in-cwd target with different drive-letter casing is allowed (exit 0)', { skip: process.platform !== 'win32' }, () => {
+ // A tool may emit `d:\...` while cwd is `D:\...`; case-insensitive containment
+ // on Windows must not reject a legitimate in-project write.
+ const target = path.join(cwd, 'sub', 'page.tsx');
+ const lowered = target.charAt(0).toLowerCase() + target.slice(1);
+ const payload = { tool_name: 'Write', tool_input: { file_path: lowered, content: 'x' }, cwd };
+ assert.equal(runHook(payload).status, 0);
+});
+
+test('MODEL_APPS_DISABLE_HOOKS=1 disables the guard (exit 0 for an outside write)', () => {
+ const outside = path.join(path.parse(cwd).root, 'model-apps-guard-evil', 'evil.ts');
+ const payload = { tool_name: 'Write', tool_input: { file_path: outside, content: 'x' }, cwd };
+ assert.equal(runHook(payload, { MODEL_APPS_DISABLE_HOOKS: '1' }).status, 0);
+});
+
+test('unparseable stdin does not block (exit 0)', () => {
+ const res = spawnSync(process.execPath, [HOOK], { input: 'not json', encoding: 'utf8' });
+ assert.equal(res.status, 0);
+});
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index 4390ae83e..fe8497eef 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -1,6 +1,6 @@
---
name: genpage
-version: 2.2.0
+version: 2.3.0
description: Creates, updates, and deploys Power Apps generative pages for model-driven apps using React v17, TypeScript, and Fluent UI V9. Orchestrates specialist agents for planning, entity creation, and code generation. Use it when user asks to build, retrieve, or update a page in an existing Microsoft Power Apps model-driven app. Use it when user mentions "generative page", "page in a model-driven", or "genux".
author: Microsoft Corporation
argument-hint: "<page description> | edit"
diff --git a/plugins/model-apps/skills/telemetry/SKILL.md b/plugins/model-apps/skills/telemetry/SKILL.md
new file mode 100644
index 000000000..16e4b4c5a
--- /dev/null
+++ b/plugins/model-apps/skills/telemetry/SKILL.md
@@ -0,0 +1,14 @@
+---
+name: telemetry
+description: >
+ Use this skill when the user wants to enable, disable, turn on or off, opt out
+ of, opt in to, or check the status of model-apps telemetry / anonymous usage
+ data. Triggers: "disable telemetry", "turn off telemetry", "opt out of
+ telemetry", "stop collecting usage data", "enable telemetry", "telemetry status".
+user-invocable: true
+argument-hint: "on | off | status"
+allowed-tools: Bash
+model: haiku
+---
+
+**Workflow: [telemetry-workflow.md](${PLUGIN_ROOT}/skills/telemetry/telemetry-workflow.md)** — Read and follow all steps defined in that bundled file.
diff --git a/plugins/model-apps/skills/telemetry/telemetry-workflow.md b/plugins/model-apps/skills/telemetry/telemetry-workflow.md
new file mode 100644
index 000000000..6845a76b3
--- /dev/null
+++ b/plugins/model-apps/skills/telemetry/telemetry-workflow.md
@@ -0,0 +1,38 @@
+# Telemetry control workflow
+
+The user invoked `/model-apps:telemetry [on | off | status]` to control anonymous
+usage telemetry for this plugin. Default to `status` when no argument is given.
+
+## Steps
+
+1. Read the action from `$ARGUMENTS`. It must be one of `on`, `off`, or `status`.
+ If it is empty or anything else, use `status`.
+2. Run the synced CLI (it auto-detects the plugin from the plugin manifest):
+
+ ```bash
+ node "${PLUGIN_ROOT}/scripts/lib/telemetry/lib/telemetry-config.js" --action <action>
+ ```
+
+3. Show the command's stdout to the user verbatim. Do not add or remove lines.
+
+## What to know (for answering follow-ups)
+
+- `off` stops transmission to Microsoft. **Nothing leaves the machine.**
+- `on` re-enables transmission. The choice is **per-user and per-plugin** and
+ takes effect on the next event (no restart).
+- **Anonymous — no personal data.** It records operational fields only: skill name,
+ plugin/PAC/agent versions, OS/Node versions, and Dataverse org/tenant GUIDs when
+ signed in. It never includes file paths, prompts, tool inputs, entity/table names,
+ URLs, credentials, usernames, hostnames, or any user-level identifier (no Entra
+ object id).
+- Once telemetry is enabled (provisioned), the local diagnostic mirror is written
+ for every event — even when you've opted out of transmission — at
+ `~/.power-platform-skills/telemetry/model-apps/sessions/<sessionId>/events.jsonl`.
+ While telemetry ships disabled (`disabled: true`), nothing is written. `status`
+ prints the mirror's location so you can hand over one self-contained file when
+ filing an issue.
+- **Automation/CI** can disable telemetry by setting the opt-out env var
+ `POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT` to `1` or `true` (the dotnet
+ `*_TELEMETRY_OPTOUT` convention) instead of running this command. This opt-out
+ has the highest precedence — it overrides a saved choice from this command and
+ even `on`. It suppresses transmission only, like `off`.
diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js
index 8030b58a0..0ec329005 100644
--- a/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js
+++ b/plugins/power-pages/scripts/lib/telemetry/lib/emit-from-prompt.js
@@ -74,7 +74,13 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {
provisioned =
resolver && typeof resolver.isProvisioned === "function"
? resolver.isProvisioned(cfg)
- : !!(cfg && cfg.instrumentationKey);
+ // Static-key fallback (no resolver): a real key must be present AND not be
+ // the shipped placeholder sentinel — otherwise a plugin that flipped
+ // `disabled:false` before replacing the key would be treated as provisioned
+ // and pay the pac/agent-info shellouts + dispatch (local-log write) even
+ // though the dispatcher can never POST a placeholder key. Matches the
+ // dispatcher's PLACEHOLDER_IKEY guard and the pretool hook's gate.
+ : !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING");
} catch {
// A plugin-provided resolver threw (or assumed cfg non-null) — treat as not
// provisioned so a bad resolver can't break prompt handling (fail closed).
diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/prompt-detector.js b/plugins/power-pages/scripts/lib/telemetry/lib/prompt-detector.js
index 69ebd6701..60474128b 100644
--- a/plugins/power-pages/scripts/lib/telemetry/lib/prompt-detector.js
+++ b/plugins/power-pages/scripts/lib/telemetry/lib/prompt-detector.js
@@ -4,8 +4,8 @@ function detectSlashCommand(promptText, { pluginName, trackedSkills } = {}) {
if (typeof promptText !== "string" || !promptText) return null;
if (!pluginName || !trackedSkills) return null;
- // Match both the namespaced form (`/power-pages:add-seo`) and the bare form
- // (`/add-seo`). The `pluginName:` prefix is optional because the host tool
+ // Match both the namespaced form (`/<plugin>:<skill>`) and the bare form
+ // (`/<skill>`). The `pluginName:` prefix is optional because the host tool
// controls how the slash command is surfaced in the prompt and may emit the
// bare form without the plugin namespace. Either way the captured skill name
// is validated against trackedSkills below, so a bare `/foo` only counts when
diff --git a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js
index 7dbe62041..7b13e16f4 100644
--- a/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js
+++ b/plugins/power-pages/scripts/lib/telemetry/lib/telemetry-config.js
@@ -78,9 +78,9 @@ function main() {
emitLogLocations(dir, plugin);
} else {
out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);
- out(`A local diagnostic log is still kept.`);
+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);
emitLogLocations(dir, plugin);
- out(`Re-enable anytime with /${plugin}:telemetry on.`);
+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);
out(ANONYMITY);
}
process.exit(0);
@@ -92,9 +92,14 @@ function main() {
}
if (action === "off") {
out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);
- out(`A local diagnostic log is still kept.`);
+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);
emitLogLocations(dir, plugin);
- out(`Re-enable anytime with /${plugin}:telemetry on.`);
+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);
+ } else if (effectiveTelemetryChoice(dir, plugin) === "off") {
+ // The preference was saved as ON, but the highest-precedence environment
+ // opt-out still forces transmission off — report the EFFECTIVE state so we
+ // never claim ON while an opt-out is suppressing it.
+ out(`Telemetry (${plugin}): preference saved as ON, but an environment opt-out is currently in effect — nothing is transmitted until it is cleared.`);
} else {
out(`Telemetry (${plugin}): ON`);
}
diff --git a/shared/telemetry/lib/emit-from-prompt.js b/shared/telemetry/lib/emit-from-prompt.js
index 8030b58a0..0ec329005 100644
--- a/shared/telemetry/lib/emit-from-prompt.js
+++ b/shared/telemetry/lib/emit-from-prompt.js
@@ -74,7 +74,13 @@ function emitSkillStartedFromPrompt(promptText, opts = {}) {
provisioned =
resolver && typeof resolver.isProvisioned === "function"
? resolver.isProvisioned(cfg)
- : !!(cfg && cfg.instrumentationKey);
+ // Static-key fallback (no resolver): a real key must be present AND not be
+ // the shipped placeholder sentinel — otherwise a plugin that flipped
+ // `disabled:false` before replacing the key would be treated as provisioned
+ // and pay the pac/agent-info shellouts + dispatch (local-log write) even
+ // though the dispatcher can never POST a placeholder key. Matches the
+ // dispatcher's PLACEHOLDER_IKEY guard and the pretool hook's gate.
+ : !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING");
} catch {
// A plugin-provided resolver threw (or assumed cfg non-null) — treat as not
// provisioned so a bad resolver can't break prompt handling (fail closed).
diff --git a/shared/telemetry/lib/prompt-detector.js b/shared/telemetry/lib/prompt-detector.js
index 69ebd6701..60474128b 100644
--- a/shared/telemetry/lib/prompt-detector.js
+++ b/shared/telemetry/lib/prompt-detector.js
@@ -4,8 +4,8 @@ function detectSlashCommand(promptText, { pluginName, trackedSkills } = {}) {
if (typeof promptText !== "string" || !promptText) return null;
if (!pluginName || !trackedSkills) return null;
- // Match both the namespaced form (`/power-pages:add-seo`) and the bare form
- // (`/add-seo`). The `pluginName:` prefix is optional because the host tool
+ // Match both the namespaced form (`/<plugin>:<skill>`) and the bare form
+ // (`/<skill>`). The `pluginName:` prefix is optional because the host tool
// controls how the slash command is surfaced in the prompt and may emit the
// bare form without the plugin namespace. Either way the captured skill name
// is validated against trackedSkills below, so a bare `/foo` only counts when
diff --git a/shared/telemetry/lib/telemetry-config.js b/shared/telemetry/lib/telemetry-config.js
index 7dbe62041..7b13e16f4 100644
--- a/shared/telemetry/lib/telemetry-config.js
+++ b/shared/telemetry/lib/telemetry-config.js
@@ -78,9 +78,9 @@ function main() {
emitLogLocations(dir, plugin);
} else {
out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);
- out(`A local diagnostic log is still kept.`);
+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);
emitLogLocations(dir, plugin);
- out(`Re-enable anytime with /${plugin}:telemetry on.`);
+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);
out(ANONYMITY);
}
process.exit(0);
@@ -92,9 +92,14 @@ function main() {
}
if (action === "off") {
out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);
- out(`A local diagnostic log is still kept.`);
+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);
emitLogLocations(dir, plugin);
- out(`Re-enable anytime with /${plugin}:telemetry on.`);
+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);
+ } else if (effectiveTelemetryChoice(dir, plugin) === "off") {
+ // The preference was saved as ON, but the highest-precedence environment
+ // opt-out still forces transmission off — report the EFFECTIVE state so we
+ // never claim ON while an opt-out is suppressing it.
+ out(`Telemetry (${plugin}): preference saved as ON, but an environment opt-out is currently in effect — nothing is transmitted until it is cleared.`);
} else {
out(`Telemetry (${plugin}): ON`);
}
diff --git a/shared/telemetry/tests/telemetry-config.test.js b/shared/telemetry/tests/telemetry-config.test.js
index 2b7a2ab99..5a388a5dd 100644
--- a/shared/telemetry/tests/telemetry-config.test.js
+++ b/shared/telemetry/tests/telemetry-config.test.js
@@ -44,6 +44,22 @@ test("on writes the per-plugin opt-in and confirms", () => {
assert.equal(cfg.telemetry["power-pages"], "on");
});
+test("on reports the env opt-out override instead of falsely claiming ON", () => {
+ // The highest-precedence env opt-out forces transmission off; `on` saves the
+ // preference but must NOT report plain "ON" while the env var suppresses it.
+ const dir = mkTmp();
+ const { status, stdout } = run(["--action", "on", "--plugin", "power-pages"], dir, {
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1",
+ });
+ assert.equal(status, 0);
+ assert.match(stdout, /preference saved as ON/i);
+ assert.match(stdout, /environment opt-out is currently in effect/i);
+ assert.doesNotMatch(stdout, /^Telemetry \(power-pages\): ON$/m);
+ // The preference is still persisted (so it takes effect once the env var clears).
+ const cfg = JSON.parse(fs.readFileSync(path.join(dir, "config.json"), "utf8"));
+ assert.equal(cfg.telemetry["power-pages"], "on");
+});
+
test("status reports ON by default and never reads ikey.json", () => {
const dir = mkTmp();
const { status, stdout } = run(["--action", "status", "--plugin", "power-pages"], dir);
@@ -57,7 +73,7 @@ test("status reports OFF after opt-out", () => {
run(["--action", "off", "--plugin", "power-pages"], dir);
const { stdout } = run(["--action", "status", "--plugin", "power-pages"], dir);
assert.match(stdout, /Telemetry \(power-pages\): OFF/);
- assert.match(stdout, /local diagnostic log is still kept/i);
+ assert.match(stdout, /local diagnostic log is kept whenever telemetry is enabled/i);
});
test("usage error on bad action", () => {
@@ -78,7 +94,7 @@ test("status reflects the env opt-out when config is unset, with no env-var word
);
assert.equal(status, 0);
assert.match(stdout, /Telemetry \(power-pages\): OFF/);
- assert.match(stdout, /local diagnostic log is still kept/i);
+ assert.match(stdout, /local diagnostic log is kept whenever telemetry is enabled/i);
// truthful-but-quiet: status must NOT name or explain the env var
assert.ok(
!/POWER_PLATFORM_SKILLS_TELEMETRY/.test(stdout),
@@ -123,6 +139,6 @@ test("status names the most recent session log when one exists", () => {
test("off output names the logs directory too", () => {
const dir = mkTmp();
const { stdout } = run(["--action", "off", "--plugin", "power-pages"], dir);
- assert.match(stdout, /local diagnostic log is still kept/i);
+ assert.match(stdout, /local diagnostic log is kept whenever telemetry is enabled/i);
assert.match(stdout, /Logs directory:/);
});