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.

feat(model-apps): opt-in page telemetry for /genpage (behind default-OFF custom-telemetry flag) (#479)

Tony Nguyen5af7ff55e3b4
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index 589d334e1..dd2b38702 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -437,7 +437,7 @@ AGENTS.md ← Plugin guidance for AI agents (this file)
CLAUDE.md ← Symlink → AGENTS.md
README.md ← User-facing intro and prereqs
CHANGELOG.md ← Keep-a-Changelog
-feature-flags.json ← Default-OFF feature flags (currently connectors)
+feature-flags.json ← Default-OFF feature flags (connectors, custom-api, custom-telemetry)
.claude-plugin/plugin.json ← Legacy plugin metadata mirror
docs/
architecture.md ← Wiring/flow diagrams for BOTH skills (/genpage + /app-builder)
@@ -453,6 +453,7 @@ agents/ ← Agent definitions (invoked by skills via Task
references/ ← Shared reference docs
rules.md ← Full code-gen rules, DataAPI types, layout patterns, common errors
custom-api.md ← Dataverse Custom API (Action/Function) invocation contract (loaded when the plan has ## Custom API Bindings)
+ page-telemetry.md ← props.appInsights page telemetry contract (custom-telemetry gated; loaded only when the maker asked to measure something)
connectors.md ← GenPage connector binding contract and runtime patterns
plan-schema.md ← Schema contract for genpage-plan.md
data-caching.md ← Rule 15 on-mount fetch: de-dupe + cache (loaded conditionally)
@@ -633,20 +634,28 @@ once here and only the per-feature specifics are tabled below:
5. **Codegen** — `genpage-page-builder` emits feature code **only** when the plan carries an actual
binding table, never on an absent/sentinel section.
-| | `connectors` | `custom-api` |
-|---|---|---|
-| **Owner agent** | `genpage-connector-builder` | `genpage-customapi-builder` |
-| **Plan section** | `## Connector Bindings` | `## Custom API Bindings` |
-| **Gated scripts** | `list-connections.js`, `create-connection-reference.js` | `list-custom-apis.js` |
-| **Deploy phase** | SKILL Phase 4.5 | SKILL Phase 4.6 |
-| **ALM** | the `--connection-refs` branch of `add-page-to-solution.js` | none needed — `config.json`'s `actionBindings` travels inside the page's `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate deployment prerequisite, bound by name) |
-| **Emits** | connector code | `executeAction` / `executeFunction` / `listBoundActions` |
+| | `connectors` | `custom-api` | `custom-telemetry` |
+|---|---|---|---|
+| **Owner agent** | `genpage-connector-builder` | `genpage-customapi-builder` | none — codegen-only |
+| **Plan section** | `## Connector Bindings` | `## Custom API Bindings` | none — driven by the maker request, not the plan |
+| **Gated scripts** | `list-connections.js`, `create-connection-reference.js` | `list-custom-apis.js` | none |
+| **Deploy phase** | SKILL Phase 4.5 | SKILL Phase 4.6 | SKILL Phase 4.7 (probe only) |
+| **ALM** | the `--connection-refs` branch of `add-page-to-solution.js` | none needed — `config.json`'s `actionBindings` travels inside the page's `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate deployment prerequisite, bound by name) | none — telemetry rides the host runtime, nothing is packaged |
+| **Emits** | connector code | `executeAction` / `executeFunction` / `listBoundActions` | `props.appInsights` calls (`trackEvent` / `trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` / `stopTrack`) |
One connectors-only nuance: at Phase 4.5 the `/genpage` orchestrator re-probes and passes the
verbatim result as `Connectors: enabled|disabled` in every page-builder dispatch — **that dispatch
-value wins over the plan's `## Connector Bindings` section.**
+value wins over the plan's `## Connector Bindings` section.** Phase 4.7 does the same for
+`Telemetry: enabled|disabled`.
+
+`custom-telemetry` is the odd one out: it has no owner agent, no discovery script, no plan
+section and no deploy or ALM step. It gates **code generation only** — steps 2-4 of the
+checklist above are N/A, and its Phase 4.7 "deploy phase" is nothing but the re-probe that
+produces the dispatch line. It also carries a second gate the other flags do not have: even
+when `enabled`, `genpage-page-builder` instruments a page **only** when the maker explicitly
+asked to measure or track something. `enabled` is permission, not instruction.
-Both flags currently ship **OFF**, each waiting on cross-repo dependencies:
+All three flags currently ship **OFF**, each waiting on cross-repo dependencies:
- **`connectors`** — the pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX
authoring control (power-platform-ux), and the maker/admin ECS setting must all release first.
@@ -655,6 +664,9 @@ Both flags currently ship **OFF**, each waiting on cross-repo dependencies:
persist `actionBindings` into `config.json`, and the `GenUxPluginActionAllowList` ECS setting.
Note the maker-facing name is "Custom API" while the shipped wire contract stays
`actionBindings` / `executeAction` (see `references/custom-api.md`).
+- **`custom-telemetry`** — the page telemetry facade in the UCI host runtime, the GenUX
+ authoring control (power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the
+ `GenUxEnableCustomTelemetry` ECS setting (see `references/page-telemetry.md`).
## TSX source lexer — known limits
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 7a26307c7..367fb1666 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -21,6 +21,24 @@ an environment that supports them**.
### Added
+- **Generated pages can report to the customer's Application Insights** — behind the new
+ default-OFF `custom-telemetry` feature flag. When enabled, `genpage-page-builder` may
+ instrument a page through an optional `props.appInsights` surface (`trackEvent`,
+ `trackMetric`, `trackTrace`, `trackException`, `trackDependency`, `startTrack` /
+ `stopTrack`), with built-in call-site throttling for rapid-fire handlers.
+
+ The flag is permission, not instruction. Even with it on, a page is instrumented **only**
+ when the maker asked to measure, track, monitor, or diagnose something in their own words —
+ the default output is still a page with zero telemetry, so nothing changes for existing
+ prompts. `/genpage` re-probes the flag at Phase 4.7 and passes the verbatim result as
+ `Telemetry: enabled|disabled` into every page-builder dispatch, the same contract
+ `Connectors:` already uses; the dispatch value wins over anything else.
+
+ The contract — when to instrument, the API, naming and privacy rules, known-good shapes and
+ anti-patterns — lives in `references/page-telemetry.md`, read only when both gates pass.
+ It ships OFF pending the host runtime, authoring control, agent prompt and ECS setting
+ reaching PROD. Not to be confused with the plugin's own usage telemetry
+ (`/model-apps:telemetry`), which is unrelated and unchanged.
- **Per-form security roles** — `forms[].securityRoles`: offer a form to named `personas[]` or to
`everyone`. A form with no assignment is visible to **every** role, so this *restricts* a form;
undo with `everyone: true`, not by deleting the block. Takes effect after a publish. (AB#6648526)
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index 1024318a3..908fc5645 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -155,6 +155,21 @@ empty, is missing entirely, or contains no binding row, the page has **no Custom
do not read custom-api.md and do not emit any `executeAction` / `executeFunction` /
`listBoundActions` code.
+Only when your dispatch says **`Telemetry: enabled`** *and* the maker's own request
+asks to measure, track, monitor, or diagnose something do you instrument the page and
+also read:
+
+```
+${PLUGIN_ROOT}/references/page-telemetry.md
+```
+
+If your dispatch says `Telemetry: disabled` (or omits the line), or the request never
+asked for measurement, the page emits **no telemetry at all** — do not read
+page-telemetry.md, do not add an `appInsights` prop, and do not emit any `trackEvent` /
+`trackMetric` / `trackTrace` / `trackException` / `trackDependency` / `startTrack` /
+`stopTrack` call. `Telemetry: enabled` is permission, not instruction: the default
+output for an instrumentation-enabled run is still a page with zero telemetry.
+
Read the relevant sample file identified in the plan:
```
@@ -275,6 +290,7 @@ export default GeneratedComponent;
- **Responsive design** — flexbox, relative units, never `100vh`/`100vw`
- **WCAG AA accessibility** — ARIA labels, keyboard navigation, semantic HTML
- **Error handling** — all async `dataApi` calls wrapped in try-catch
+- **No telemetry by default** — never emit `props.appInsights` calls unless your dispatch says `Telemetry: enabled` **and** the maker asked to measure or track something. Absence of a request means zero telemetry, not "instrument the obvious things". See references/page-telemetry.md.
- **Lookup fields** — read display names via `@OData.Community.Display.V1.FormattedValue`; *set* a lookup on create/update with `_<field>_value: "/logicalSingular(guid)"`, never `@odata.bind` (the DataAPI silently drops it → orphaned row). See rules.md DataAPI Rule 13.
- **All hooks above early returns** — every `useMemo`/`useState`/`useEffect`/`useCallback` must precede any loading/empty `return`, or detail pages crash with React error #310 on first open. See rules.md Critical Rule 19.
- **Entity logical names** — singular lowercase (e.g., `"account"`)
diff --git a/plugins/model-apps/feature-flags.json b/plugins/model-apps/feature-flags.json
index e2bb19699..bba85b0b0 100644
--- a/plugins/model-apps/feature-flags.json
+++ b/plugins/model-apps/feature-flags.json
@@ -1,5 +1,6 @@
{
"_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD.",
"connectors": false,
- "custom-api": false
-}
\ No newline at end of file
+ "custom-api": false,
+ "custom-telemetry": false
+}
diff --git a/plugins/model-apps/references/page-telemetry.md b/plugins/model-apps/references/page-telemetry.md
new file mode 100644
index 000000000..9feecf8af
--- /dev/null
+++ b/plugins/model-apps/references/page-telemetry.md
@@ -0,0 +1,389 @@
+# Page Telemetry (`props.appInsights`)
+
+How a generated page reports its own custom telemetry to the customer's
+Application Insights resource.
+
+> **Not the plugin's own telemetry.** This document is about code the *generated
+> page* emits at runtime inside a model-driven app. It is unrelated to the
+> plugin's `skill_started` usage telemetry (`/model-apps:telemetry`), which
+> measures the authoring tool rather than the page.
+
+**Gated by the default-OFF `custom-telemetry` feature flag.** `genpage-page-builder`
+reads this file only when its dispatch says `Telemetry: enabled`. With the flag OFF
+a generated page contains no telemetry calls at all, exactly as before the feature
+existed.
+
+---
+
+## 1. When to instrument - read this first
+
+This section decides whether you write **any** telemetry at all. It outranks every
+other section in this document.
+
+- **Telemetry is opt-in per request.** Instrument the page **only** when the maker's
+ request describes a measurement, tracking, logging, analytics, monitoring, or
+ reporting need *in their own words*. Their words are the trigger - not the
+ availability of the API, and not the fact that you were given this file.
+- **The default is zero telemetry.** If the maker did not ask to measure or track
+ something, write **no** telemetry calls whatsoever. A page with no telemetry is
+ the correct and expected output for the overwhelming majority of requests. Do not
+ add telemetry to be helpful, thorough, or complete.
+- **Being handed this file is not a request to use it.** It is loaded whenever the
+ flag is on for the environment. Treat this section as a locked door: the maker's
+ own words are the only key.
+- **Do not infer intent from the page's subject matter.** A page about orders, KPIs,
+ revenue, dashboards, reports, or "metrics" as *displayed content* is not a request
+ to *emit* telemetry. Showing a number to the user and reporting a number to
+ Application Insights are unrelated concerns; only the latter needs this API.
+- **Do not infer intent from the words "error", "fail", or "retry"** when they
+ describe UI behavior the maker wants (an error message, a retry button). Those
+ describe what the user sees, not what gets reported.
+- **When intent is genuinely ambiguous, do not instrument.** Prefer omission; the
+ page can always be instrumented in a follow-up turn.
+- **A narrow request stays narrow.** If the maker asks for telemetry in one place,
+ instrument only that place. Never generalize it into page-wide instrumentation.
+- **An explicit refusal wins.** If the maker says not to add telemetry, or asks to
+ remove it, emit none regardless of anything else they said.
+
+### Trigger patterns
+
+Maker language that **does** authorize instrumentation, and what to add for each.
+Match on intent, not exact wording.
+
+| Maker says something like... | Add |
+|---|---|
+| "track when a user completes a task" | `trackEvent('TaskCompleted', { ... })` in the completion handler |
+| "log errors to App Insights" / "report failures" | `trackException(err, { ... })` in the relevant `catch` blocks |
+| "measure how many records load" | `trackMetric('AccountsLoaded', rows.length)` after the load resolves |
+| "track which filters users apply" | `trackEvent('FilterApplied', { ... }, { throttle: { key: 'FilterApplied', windowMs: 1000 } })` |
+| "track searches as the user types" | debounce at the source, then `trackEvent('Searched', { count }, { throttle: ... })` |
+| "how long the page takes to load data" | `startTrack` / `stopTrack` around the fetch |
+| "log when a form is submitted" | `trackEvent('FormSubmitted', { entityName, recordId, outcome })` |
+| "track navigation between pages" | `trackEvent('NavigatedToDetails', { entityName, recordId })` immediately before the navigation call |
+| a bare "add telemetry", no detail | ask **one** clarifying question about what they want to learn, then instrument only what they confirm |
+
+Counter-examples that **do not** authorize instrumentation: "show a chart of sales by
+region", "display the record count", "add a KPI tile", "show an error message if the
+save fails", "add a retry button", "make the page load fast".
+
+---
+
+## 2. The API
+
+```typescript
+/**
+ * The ONLY property keys a page may attach to a telemetry call.
+ * Any other key is silently dropped. Never pass customer data in these values.
+ */
+export interface GenUXTelemetryProperties {
+ /** Logical name of the table involved, e.g. 'account'. */
+ entityName?: string;
+ /** Id of the record involved. Ids only - never a name or other field value. */
+ recordId?: string;
+ /** Result of the action, e.g. 'success' | 'failure' | 'cancelled'. */
+ outcome?: string;
+ /** Coarse grouping for the call site, e.g. 'form' | 'grid' | 'chart'. */
+ category?: string;
+ /** The kind of thing acted on, e.g. 'order' | 'attachment'. */
+ itemType?: string;
+ /** What triggered the action, e.g. 'toolbar' | 'contextMenu' | 'autoRefresh'. */
+ source?: string;
+ /** HTTP or error status code, as a string. */
+ statusCode?: string;
+ /** A count, e.g. number of rows returned. Never derived from record content. */
+ count?: number;
+ /** A duration in milliseconds. */
+ durationMs?: number;
+ /** Short non-sensitive diagnostic detail. NEVER user input or record content. */
+ detail?: string;
+}
+
+/**
+ * Coalescing options for call sites that can fire rapidly.
+ * Calls sharing a `key` within the window collapse into one.
+ */
+export interface GenUXTelemetryThrottleOptions {
+ /** Stable identifier for this call site. Required. */
+ key: string;
+ /** Coalescing window in milliseconds. Defaults to 1000. */
+ windowMs?: number;
+ /** 'trailing' (default) reports the last call; 'leading' reports the first. */
+ mode?: 'trailing' | 'leading';
+}
+
+export interface GenUXTelemetryCallOptions {
+ throttle?: GenUXTelemetryThrottleOptions;
+}
+
+/**
+ * Every method is fire-and-forget: returns void, never throws, never returns data.
+ * Do NOT await these calls and do NOT wrap them in try/catch.
+ */
+export interface IGenUXPageAppInsightsTelemetry {
+ /** Report a caught error. Prefer this over trackTrace inside a catch block. */
+ trackException(error: unknown, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
+
+ /** Report a diagnostic message. Use sparingly. */
+ trackTrace(message: string, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
+
+ /** Report a call to an external system. */
+ trackDependency(name: string, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
+
+ /** Report a meaningful user action or page milestone. `name` must be a stable literal. */
+ trackEvent(name: string, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
+
+ /** Report a numeric measurement worth aggregating. */
+ trackMetric(name: string, value: number, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
+
+ /** Start timing an operation. Must be matched by exactly one stopTrack with the same name. */
+ startTrack(name: string): void;
+
+ /** Stop timing an operation started with startTrack; the duration is reported automatically. */
+ stopTrack(name: string, properties?: GenUXTelemetryProperties, options?: GenUXTelemetryCallOptions): void;
+}
+```
+
+### Declaring the prop
+
+`appInsights` is an **optional** addition to the page's props. When you instrument a
+page, declare the methods the page actually uses at the top of the file and intersect
+them into the component signature - do not assume `GeneratedComponentProps` already
+carries the prop, because the generated `RuntimeTypes.ts` may predate it:
+
+```typescript
+type PageTelemetry = {
+ trackEvent(name: string, properties?: Record<string, unknown>, options?: unknown): void;
+ trackException(error: unknown, properties?: Record<string, unknown>, options?: unknown): void;
+ trackMetric(name: string, value: number, properties?: Record<string, unknown>, options?: unknown): void;
+ startTrack(name: string): void;
+ stopTrack(name: string, properties?: Record<string, unknown>, options?: unknown): void;
+};
+
+const GeneratedComponent = (props: GeneratedComponentProps & { appInsights?: PageTelemetry }) => {
+ const { dataApi, pageInput, appInsights } = props;
+ // ...
+};
+```
+
+Only declare the methods the page actually calls. On a page you are **not**
+instrumenting, add none of this - the signature stays exactly
+`(props: GeneratedComponentProps)`.
+
+---
+
+## 3. Rules
+
+These apply **only** once section 1 has authorized instrumentation. They never
+justify adding telemetry on their own.
+
+- **Destructure it with the other props:** `const { dataApi, pageInput, appInsights } = props;`
+- **Call it straight off the prop — never wrap it in a `useRef`.** Read
+ `appInsights?.trackEvent(...)` directly from the destructured value at the call
+ site. Do **not** mirror it into a ref (`const telemetryRef = useRef(appInsights)`)
+ to "keep the latest reference" for an effect that omits it from its dependency
+ array. Telemetry is fire-and-forget, so the value captured by that render's
+ closure is always good enough — there is no stale-reference bug to defend
+ against. The ref is pure ceremony, and the usual way of maintaining it
+ (`telemetryRef.current = appInsights` in the component body) is a
+ **mutation during render**, which React does not permit. For the same reason,
+ do **not** add `appInsights` to a `useEffect` dependency array: the host hands a
+ new props object on every render, so depending on it re-fires the effect
+ (exactly the failure mode Rule 15 exists to prevent). Depend on the readiness
+ boolean as usual and let the effect close over `appInsights`.
+- **The prop is optional and is frequently absent** (older runtimes, the authoring
+ and preview surfaces, the feature turned off). **Always** call through optional
+ chaining - `appInsights?.trackEvent(...)`. Never store it in a non-optional
+ variable, and never branch page behavior on whether it exists.
+- **Fire-and-forget.** Every method returns `void`, never throws, and never returns
+ data. Never `await` a telemetry call, never wrap one in `try`/`catch`, and never
+ let a telemetry result affect rendering.
+- **Never on the critical path.** Emit after the work succeeds or fails - never
+ before it, and never in place of it.
+- **No customer data.** Never pass record contents, user-entered text, search terms,
+ names, email addresses, phone numbers, addresses, or free-form field values. Emit
+ shapes and outcomes ("saved", "failed", a count, a duration), not the data itself.
+- **Only the property keys in `GenUXTelemetryProperties` are allowed.** Any other key
+ is silently dropped, so do not invent keys.
+- **Always pass the contextually relevant properties** as the second argument -
+ entity name, record id, outcome, count, duration. Avoid empty property objects: an
+ event with no properties is rarely worth emitting. Do not pass page or correlation
+ context; the platform stamps that automatically.
+- **Be selective even when asked.** Instrument the moments the maker asked about and
+ stop there. A well-instrumented page emits a handful of calls, not dozens.
+- **Never instrument render**, per-row rendering, per-keystroke, mouse-move, scroll,
+ hover, or any effect that runs on every render. High-frequency call sites are the
+ main risk this API carries.
+- **Throttle rapid-fire call sites.** When an authorized call site can fire rapidly
+ but is still worth measuring (typing in a search box, dragging a slider, applying
+ filters), you **must** pass the throttle option with a stable, distinct `key` per
+ call site: `{ throttle: { key: 'ordersSearch', windowMs: 1000 } }`.
+- **Prefer `trackException` in catch blocks over `trackTrace`.** Reserve it for
+ errors genuinely worth surfacing - a failed save, a failed load, a rejected
+ request. Do **not** call it for expected empty states (a query returning zero rows,
+ an optional lookup finding nothing) or for validation the user is expected to hit;
+ those are normal outcomes, not failures.
+- **Instrument the error boundary.** If the page has a React error boundary - or you
+ add one for resilience - call
+ `appInsights?.trackException(error, { category: 'errorBoundary' })` from its
+ `componentDidCatch`. A render crash is the single most valuable error to report,
+ and it never reaches a `catch` block.
+- **`trackTrace`** is for a diagnostic breadcrumb at a key decision point in
+ genuinely complex logic (which branch a multi-step flow took, why a fallback
+ engaged). Do not narrate ordinary control flow with it.
+- **`trackMetric`** is only for a genuine number worth aggregating (row counts,
+ durations); **`trackDependency`** is for a call to an external system.
+- **`startTrack`/`stopTrack`** time an operation and compute the duration for you.
+ Every `startTrack` must have exactly one matching `stopTrack` with the same name,
+ including on the error path.
+- **Names are short, stable, PascalCase literals naming the business action**, not
+ the UI gesture. Good: `TaskCompleted`, `FilterApplied`, `RecordOpened`,
+ `FormSubmitted`. Bad: `ButtonClicked`, `CheckboxChanged`, `RowClicked` - these
+ describe the widget, not what happened, and are useless in aggregate. **Never build
+ a name by interpolating data**; a dynamic name creates unbounded distinct values
+ and makes the data unusable.
+- **Do not duplicate what the platform already reports.** No page-view events, and do
+ not manually track DataAPI calls unless the page makes outbound calls of its own.
+
+---
+
+## 4. Known-good shapes
+
+Shape references for pages whose maker **asked** to track or measure something - not
+a default template. Note how few calls even an intentionally instrumented page makes.
+
+```tsx
+// GOOD: one page-level load event, emitted once, with a count and a duration.
+const GeneratedComponent = (props: GeneratedComponentProps & { appInsights?: PageTelemetry }) => {
+ const { dataApi, pageInput, appInsights } = props;
+ const [orders, setOrders] = useState<TableRow[]>([]);
+
+ useEffect(() => {
+ let cancelled = false;
+ appInsights?.startTrack('OrdersLoad');
+ (async () => {
+ try {
+ const result = await dataApi.queryTable('order', { select: ['name', 'statuscode'], pageSize: 50 });
+ if (cancelled) {
+ return;
+ }
+ setOrders(result.rows);
+ // stopTrack reports the elapsed time for you - do not compute it yourself.
+ appInsights?.stopTrack('OrdersLoad', { outcome: 'success', entityName: 'order', count: result.rows.length });
+ } catch (error) {
+ // A catch block is the single highest-value place to instrument.
+ appInsights?.stopTrack('OrdersLoad', { outcome: 'failure', entityName: 'order' });
+ appInsights?.trackException(error, { entityName: 'order', category: 'grid', source: 'pageLoad' });
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ // Never put dataApi in a dependency array - see rules.md Rule 15.
+ }, []);
+
+ // ...
+};
+
+// GOOD: a completed user action, instrumented on BOTH the success and failure paths.
+const handleSubmit = async (): Promise<void> => {
+ try {
+ const recordId = await dataApi.createRow('order', values);
+ appInsights?.trackEvent('OrderSubmitted', {
+ outcome: 'success',
+ entityName: 'order',
+ recordId,
+ source: 'toolbar',
+ });
+ } catch (error) {
+ appInsights?.trackEvent('OrderSubmitted', { outcome: 'failure', entityName: 'order', source: 'toolbar' });
+ appInsights?.trackException(error, { entityName: 'order', category: 'form' });
+ }
+};
+
+// GOOD: a rapid-fire call site MUST pass a throttle with a stable key.
+const handleSearchChange = (value: string): void => {
+ setSearchText(value);
+ appInsights?.trackEvent(
+ 'OrdersSearched',
+ // The search TEXT is never sent - only the fact that a search happened.
+ { category: 'grid', count: value.length },
+ { throttle: { key: 'ordersSearch', windowMs: 1000 } }
+ );
+};
+
+// GOOD: an error boundary reports render crashes, which never reach a catch block.
+class PageErrorBoundary extends React.Component<{ appInsights?: PageTelemetry }, { hasError: boolean }> {
+ public state = { hasError: false };
+
+ public static getDerivedStateFromError(): { hasError: boolean } {
+ return { hasError: true };
+ }
+
+ public componentDidCatch(error: Error): void {
+ this.props.appInsights?.trackException(error, { category: 'errorBoundary', source: 'render' });
+ }
+
+ public render(): React.ReactNode {
+ return this.state.hasError ? <div>Something went wrong.</div> : this.props.children;
+ }
+}
+```
+
+---
+
+## 5. Anti-patterns
+
+```tsx
+// BAD: fires on every render, thousands of times. Never instrument render.
+const BadRow = ({ order }: { order: TableRow }) => {
+ appInsights?.trackEvent('RowRendered', { recordId: order.id });
+ return <div>{order.name}</div>;
+};
+
+// BAD: leaks customer data into telemetry.
+appInsights?.trackEvent('Searched', { detail: searchText });
+appInsights?.trackEvent('OrderSaved', { detail: customer.emailAddress });
+
+// BAD: dynamic event name creates unbounded distinct values.
+appInsights?.trackEvent(`Order_${order.id}_Saved`);
+
+// BAD: telemetry is fire-and-forget. Never await it, never try/catch it, never branch on it.
+await appInsights?.trackEvent('Saved');
+try {
+ appInsights?.trackEvent('Saved');
+} catch {
+ /* unnecessary - telemetry never throws */
+}
+
+// BAD: non-optional access crashes wherever the prop is absent
+// (preview, older runtimes, feature off).
+props.appInsights.trackEvent('Saved');
+
+// BAD: mirroring the prop into a ref "so the effect sees the latest one".
+// Telemetry is fire-and-forget, so closing over the prop is already correct —
+// and assigning to `.current` in the component body mutates during render.
+const telemetryRef = useRef(appInsights);
+telemetryRef.current = appInsights; // mutation during render
+useEffect(() => {
+ telemetryRef.current?.startTrack('OrdersLoad');
+}, [dataReady]);
+
+// GOOD: call the destructured prop directly; the effect closes over it.
+useEffect(() => {
+ appInsights?.startTrack('OrdersLoad');
+ // Do NOT add `appInsights` here — the host hands a new props object every
+ // render, so depending on it re-fires the effect (Rule 15).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+}, [dataReady]);
+
+// BAD: reporting an expected empty state as an error. Zero rows is a normal outcome.
+if (rows.length === 0) {
+ appInsights?.trackException(new Error('No orders found'), { entityName: 'order' });
+}
+
+// BAD: an un-throttled rapid call site.
+const onSliderChange = (v: number): void => appInsights?.trackMetric('SliderValue', v);
+
+// BAD: an empty property object - nothing to slice by, so the event tells you nothing.
+appInsights?.trackEvent('OrderSubmitted', {});
+```
diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.js
index 7d183a21d..fe45e03ef 100644
--- a/plugins/model-apps/scripts/lib/feature-flags.js
+++ b/plugins/model-apps/scripts/lib/feature-flags.js
@@ -116,6 +116,18 @@ const FLAGS = {
'GenUxPluginActionAllowList ECS setting — all live in PROD.',
enableEnv: 'GENPAGE_ENABLE_CUSTOM_API=1',
},
+ 'custom-telemetry': {
+ status: 'in-progress',
+ summary:
+ 'Custom page telemetry — a generated page reporting its own events, metrics, traces and ' +
+ "exceptions to the customer's Application Insights resource via an optional props.appInsights " +
+ 'surface, emitted only when the maker explicitly asks to measure or track something.',
+ dependencies:
+ 'the page telemetry facade in the UCI host runtime, the GenUX authoring control ' +
+ '(power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the ' +
+ 'GenUxEnableCustomTelemetry ECS setting — all live in PROD.',
+ enableEnv: 'GENPAGE_ENABLE_CUSTOM_TELEMETRY=1',
+ },
};
// Flag names the skill knows about, derived from the catalog. Used to validate the
diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.js
index fa7216db9..2c825ca80 100644
--- a/plugins/model-apps/scripts/tests/feature-flags.test.js
+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js
@@ -35,6 +35,12 @@ test('custom-api flag is OFF by default (no env override)', () => {
assert.equal(isCustomApiEnabled({ env: {} }), false);
});
+test('custom-telemetry flag is OFF by default (no env override)', () => {
+ // custom-telemetry has no helper of its own (it gates code generation, not scripts), so
+ // the generic probe is the contract the skill markdown actually calls.
+ assert.equal(isEnabled('custom-telemetry', { env: {} }), false);
+});
+
test('unknown flags are OFF (fail-closed)', () => {
assert.equal(isEnabled('does-not-exist', { env: {} }), false);
});
@@ -114,6 +120,13 @@ test('committed feature-flags.json ships custom-api: false', () => {
assert.equal(json['custom-api'], false);
});
+test('committed feature-flags.json ships custom-telemetry: false', () => {
+ const json = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
+ );
+ assert.equal(json['custom-telemetry'], false);
+});
+
// --- CLI probe (deterministic gate for the skill markdown) ------------------
test('CLI prints "disabled" and exits 1 when OFF', () => {
@@ -196,6 +209,10 @@ test('KNOWN_FLAGS includes custom-api', () => {
assert.ok(KNOWN_FLAGS.includes('custom-api'));
});
+test('KNOWN_FLAGS includes custom-telemetry', () => {
+ assert.ok(KNOWN_FLAGS.includes('custom-telemetry'));
+});
+
test('describe reports effective state and source per known flag', () => {
const envOn = describe({ env: { GENPAGE_ENABLE_CONNECTORS: '1' }, flags: { connectors: false } });
const c1 = envOn.find((f) => f.flag === 'connectors');
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index f73f41455..e631ca98d 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -402,6 +402,27 @@ it is missing, derive it as a **bare JSON array** of
`(Global)`, row) — see `${PLUGIN_ROOT}/references/custom-api.md`. Never the
`{ "actionBindings": [...] }` object wrapper (the deployed `config.json` shape `pac` writes).
+### Phase 4.7: Page Telemetry (Conditional)
+
+**Re-probe the feature gate here — do not rely on the plan content alone.**
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-telemetry
+```
+
+This phase has no bindings and no artifacts; it only decides whether page-builder is
+permitted to instrument. **If it prints `disabled`**, generated pages contain no
+telemetry calls at all — identical to before the feature existed.
+
+**Carry this decision into code generation.** The probe result is `Telemetry:
+disabled` / `Telemetry: enabled` for the rest of the run, and Phase 5 **must** pass it
+verbatim in every page-builder dispatch.
+
+`enabled` is permission, not instruction. Even when it is on, page-builder emits
+telemetry **only** when the maker asked to measure or track something in their own
+words; the default output is still a page with zero telemetry. See
+`${PLUGIN_ROOT}/references/page-telemetry.md`.
+
### Phase 5: Build Pages (Parallel)
Read `genpage-plan.md` and extract the pages table.
@@ -439,6 +460,10 @@ subagent. Inline the page-builder workflow directly in the orchestrator:
`${PLUGIN_ROOT}/references/data-caching.md`
5. If the plan's `## Environment` indicates non-English languages, also read
`${PLUGIN_ROOT}/references/localization.md`
+5b. Only when the Phase 4.7 probe printed `enabled` **and** the maker's own request
+ asks to measure, track, monitor, or diagnose something, also read
+ `${PLUGIN_ROOT}/references/page-telemetry.md`. In every other case the page
+ contains no telemetry calls — do not read it.
6. Read `genpage-plan.md` (already in working directory) and `RuntimeTypes.ts`
if Data mode is dataverse
7. Write the `.tsx` file to `<working-dir>/<filename>.tsx` following all rules
@@ -464,6 +489,7 @@ For each page, pass a prompt that includes:
- Absolute path to `genpage-plan.md`
- Data mode (see below) — either a RuntimeTypes path or an explicit mock flag
- **Connectors: `enabled` or `disabled`** — the Phase 4.5 probe result, verbatim
+- **Telemetry: `enabled` or `disabled`** — the Phase 4.7 probe result, verbatim
- Working directory
- Plugin root: `${PLUGIN_ROOT}`
@@ -475,6 +501,7 @@ For each page, pass a prompt that includes:
> - Plan document: [absolute path to genpage-plan.md]
> - Data mode: **dataverse**
> - Connectors: **[enabled|disabled from Phase 4.5]**
+> - Telemetry: **[enabled|disabled from Phase 4.7]**
> - RuntimeTypes: [absolute path to RuntimeTypes.ts]
> - Working directory: [absolute path from Phase 0]
> - Plugin root: ${PLUGIN_ROOT}
@@ -490,6 +517,7 @@ For each page, pass a prompt that includes:
> - Plan document: [absolute path to genpage-plan.md]
> - Data mode: **mock**
> - Connectors: **[enabled|disabled from Phase 4.5]**
+> - Telemetry: **[enabled|disabled from Phase 4.7]**
> - Working directory: [absolute path from Phase 0]
> - Plugin root: ${PLUGIN_ROOT}
>