---
title: Agentic Page Builder widget development
---

> **Documentation indexes**
> The indexes below list current page URLs with titles and descriptions. Links on this page point to the Markdown versions of the linked pages.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

[Work effectively with KentiCopilot](https://docs.kentico.com/guides/development/kenticopilot/work-effectively-with-kenticopilot.md) introduces the principles behind effective agent-assisted development: explore before coding, provide specific context, preserve decisions, and verify the result. Here, we apply those principles to the _Content Promotion_ [Page Builder widget](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/widgets-for-page-builder.md). Follow the implementation decisions, example prompts, and verification checks to see how the principles work in practice, including the pitfalls we encountered and how we resolved them.

A _widget_ that combines content selection, editor configuration, and visitor tracking calls for decisions that an agent cannot resolve from code alone. We've created a case study, the _Content Promotion_ widget in the [Xperience by Kentico Training guides](https://github.com/Kentico/xperience-by-kentico-training-guides/), that illustrates how we supplied those decisions and verified the implementation.

## Content promotion widget from editor's perspective

With the widget, editors can promote a [website page](https://docs.kentico.com/documentation/business-users/website-content.md), a reusable [content item](https://docs.kentico.com/documentation/business-users/content-hub/content-items.md), or create [widget-specific content](https://docs.kentico.com/documentation/business-users/website-content/widgets-and-page-builder.md) in place (defined as _Manual mode_ in the widget). They can override the default data, hide selected elements, apply different designs, [personalize the widget](https://docs.kentico.com/guides/digital-marketing/xperience-essentials/personalize-website-content-essentials.md), and [record a visitor interaction](https://docs.kentico.com/guides/digital-marketing/work-with-contacts/learn-about-contacts-customer-journey.md). The implementation session used Claude Code, but the approach works with any AI coding agent that can inspect your project and use the Xperience documentation.

![Content Promotion widget example](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/content-promotion-widget.png "Content Promotion widget example")

🎮 [Video showing Content Promotion widget capabilities (interactive demo)](https://demo.arcade.software/ZY7PEaICDK1voVsQs9ih)

> **Info:** The _Content Promotion_ widget is intentionally broad: it combines multiple content sources, editor configurations, and digital marketing scenarios. That makes it a useful case study, but it could overwhelm editors who are new to Page Builder or moving from another solution. Start your own widget with a clear business outcome, then expose only the content choices and settings editors need to achieve it.

## Before you start

You need a running Xperience project with [Page Builder widgets](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/widgets-for-page-builder.md), sample content, and an editor account. Learn how to build [basic call to action](https://docs.kentico.com/guides/development/page-builder/build-simple-cta-widget.md) and [advanced](https://docs.kentico.com/guides/development/page-builder/define-advanced-widget.md) widgets, and understand [widget properties](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/widgets-for-page-builder/widget-properties.md) before you decide which choices editors need to make.

An agent needs access to your repository, the commands that build and test it, and current Xperience references. The [KentiCopilot](https://docs.kentico.com/guides/development/kenticopilot.md) tools provide skills and documentation access for that work.

### Prepare the project with Agentify

Before implementation, run the [Agentify skill](https://github.com/Kentico/xperience-by-kentico-kenticopilot/tree/main/plugins/kentico-web-development/skills/agentify). It audits the project, determines if it is ready for agentic development, and establishes which instructions an agent needs to work well in it: a project description, coding conventions, the project scaffolding approach, and how to build and test the solution. It also connects the agent to MCP servers, such as [Documentation MCP server](https://docs.kentico.com/documentation/developers-and-admins/installation/mcp-server.md) and [Management MCP server](https://docs.kentico.com/documentation/developers-and-admins/api/management-api/configure-management-mcp-server.md), or if you specify it in your instructions to [Playwright MCP](https://playwright.dev/docs/getting-started-mcp) for testing purposes. As a result, the context it provides (and you clarify and validate) keeps the agent's suggestions grounded in the Xperience and the project's own patterns.

Ask for the audit first and keep the fixes for a separate step, so you can review the findings before anything changes.

#### Review the readiness report

The audit found missing agent instructions and guidance skills, incomplete MCP configuration, and a CI workflow that pinned the wrong SDK. The excerpt below shows how the report connected its evidence to a proposed fix.

![Agentify readiness report for the Training guides project, with findings for agent instructions, guidance skills, and Kentico MCP servers](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/agentic-readiness-report.png "Agentify readiness report for the Training guides project, with findings for agent instructions, guidance skills, and Kentico MCP servers")

```markdown title="Excerpt from the readiness report"
Agent instructions — missing

- Evidence: No AGENTS.md or CLAUDE.md anywhere in the repository. The only
  machine-readable context is .github/workflows/dotnet.yml, which still pins
  dotnet-version 8.0.x while src/global.json requires SDK 10.0.100 — stale,
  and misleading to an agent.
- Gap: An assistant has no description of the solution layout, no build,
  test, or CI restore commands, no coding conventions, no statement of how
  to validate a change, and no guidance on when to reach for the Kentico
  MCP servers.
- Recommended fix: Create a tool-agnostic AGENTS.md at the repository root,
  and add thin pointer files that redirect to it.
```

The MCP finding also exposed an additional problem: a user-local settings file enabled the _Management MCP_ and _Playwright_ servers, but the repository never defined them. The setup worked on one machine and resolved to nothing for anyone who cloned the repository.

The report ends with a list of the fixes the skill proposes to apply. In this case study, the agent also stated that it would ask before changing the CI workflow, because that change affects builds. Apply the fixes that match your project, and decide the rest yourself.

#### Check what the skill produced

For the [Training guides project](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished), the approved fixes produced the following context:

- `AGENTS.md` at the repository root holds the project overview, the repository layout, the commands that work in the project, the coding conventions, and a validation checklist. `CLAUDE.md` and `.github/copilot-instructions.md` contain only a pointer to it.
- A `design-conventions` skill in `.claude/skills/` describes the SCSS pipeline and the rule that compiled CSS is generated output, never edited by hand.
- The `.mcp.json` defines the [Management MCP server](https://docs.kentico.com/documentation/developers-and-admins/api/management-api/configure-management-mcp-server.md), and `AGENTS.md` explains when to use it and when to use the [Documentation MCP server](https://docs.kentico.com/documentation/developers-and-admins/installation/mcp-server.md).

![The generated AGENTS.md next to the agent's summary of the changes it made](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/agentify-applied-fixes.png "The generated AGENTS.md next to the agent's summary of the changes it made")

Two choices in the generated configuration are worth copying into your own project:

- The [Documentation MCP server](https://docs.kentico.com/documentation/developers-and-admins/installation/mcp-server.md) is absent from `.mcp.json`. Since we use one machine to create guides covering different topics, in our case, other _KentiCopilot_ plugins, such as `kentico-kx-13-migration` plugin, already registered the _Kentico Documentation MCP_ server globally. Registering it again at the project level could create a duplicate instance and increase token usage.
- The [Management MCP](https://docs.kentico.com/documentation/developers-and-admins/api/management-api.md) registration is limited to the development environment and stays off until a secret is supplied. The secret comes from an environment variable, so nothing sensitive is committed. Alternatively, you can store the _Management MCP_ key into your `appsettings.Development.json` config which also means that your secret will be committed to the repository as plain text.

> **Warning:** The _Management MCP_ provides basic authentication and no per-operation authorization. Enable it only for local development, and never on a publicly reachable instance.

#### Treat the result as a starting point

The audit performed by the `/agentify` skill can only describe what the repository states. During implementation, a few gaps surfaced that the audit could not have found:

- While creating the `AGENTS.md`, the agent stated that the unit tests should use the Kentico `CMS.Tests` base classes (as suggested in the _Documentation MCP_). However, the TrainingGuides repository already contains tests that use xUnit and Moq, so the agent followed the existing tests stated in the file.
- The command list had no way to compile SCSS. The project relied on an editor extension that an agent cannot run, and a plain `sass` compile silently dropped the vendor prefixes the extension added.
- The agent noted that the repository doesn't contain any brand-specific instructions. Information about the typography, brand design conventions or how to handle imagery correctly is very important. Supply it to ensure the generated code aligns with your brand guidelines. We've left an example of a [TODO](https://github.com/Kentico/xperience-by-kentico-training-guides/blob/finished/.claude/skills/design-conventions/SKILL.md?plain=1#L66) specified by the agent in `AGENTS.md` so you can see what to expect.

Update `AGENTS.md` whenever the project proves it wrong, so every later session starts from the corrected instructions. You can steer the agent in future conversations, but those instructions are lost when the conversation ends.

## Combine KentiCopilot with your development workflow

KentiCopilot skills and a development workflow answer different questions. The skills in the [kentico-web-development plugin](https://github.com/Kentico/xperience-by-kentico-kenticopilot/tree/main/plugins/kentico-web-development), such as the [Page Builder widget skill](https://github.com/Kentico/xperience-by-kentico-kenticopilot/tree/main/plugins/kentico-web-development/skills/page-builder-widgets), tell the agent what correct Xperience patterns and code look like: how to structure a widget, define its properties, and retrieve content. A workflow tells the agent how to proceed: when to ask questions, when to write a specification, and how to test and review the result.

### The workflow used in this guide

This case study pairs _KentiCopilot_ with [Matt Pocock's skills](https://claude.com/marketplace/plugins/mattpocock-skills), a public collection of development workflow skills.

| Phase                   | Workflow skill | Role in the case study                                                                                                        |
| ----------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Clarify the requirement | `grill-me`     | The agent explored the project, then asked questions in rounds, each with a recommended answer, until the design was settled. |
| Record the agreement    | `to-spec`      | The agent turned the agreed answers into a written specification with scope boundaries, open questions, and decisions.        |
| Build the behavior      | `tdd`          | The agent implemented one slice at a time: one failing test, the minimal code to pass it, then the next slice.                |
| Fix review findings     | `implement`    | After a code review, the agent fixed each finding as a separate ticket against the same specification.                        |

The KentiCopilot `page-builder-widgets` skill and the [Documentation MCP server](https://docs.kentico.com/documentation/developers-and-admins/installation/mcp-server.md) supplied the Xperience knowledge during these phases.

> **Info:** Skill names and commands differ between [collections](https://www.aihero.dev/skills), such as [the Superpowers collection](https://github.com/obra/superpowers/tree/main/skills), and often change between their versions. In this case study, we describe how we approached developing the widget, so you can pick any of the skills you prefer and adapt them to your workflow.

_KentiCopilot_ does not prescribe a workflow. Pair the plugins with your team's own process, or with any published set of workflow skills.

![Prompt to build the widget according to agreed specification combining /tdd skill with the Page Builder skill](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/implement-with-page-builder-skill.png "Prompt to build the widget according to agreed specification combining /tdd skill with the Page Builder skill")

### Adapt the skills to your project

The _KentiCopilot_ plugins are open source. Treat them as a starting point, and adapt them to your projects the same way you adapt any other development tool.

In our agentic development case study, the _testing skill_ that comes from the agentic flow supported by findings in the [Documentation MCP](https://docs.kentico.com/documentation/developers-and-admins/customization/write-automated-tests/set-up-test-projects.md) assumed [NUnit](https://docs.nunit.org/) testing framework and the Kentico test base classes, while the [Training guides](https://github.com/Kentico/xperience-by-kentico-training-guides/blob/finished/src/TrainingGuides.Admin.Tests/TrainingGuides.Admin.Tests.csproj) project used [xUnit and Moq](https://docs.kentico.com/guides/architecture/xperience-implementation-handbook/test-your-solution.md). The agent raised questions during the investigation and, after the team confirmed the approach, followed the project's existing tests instead of the skill. In your own projects, encode that kind of decision in the skill or in `AGENTS.md`, so the agent does not have to rediscover it in every session.

Start small. Run one feature through the _KentiCopilot_ skills and a workflow you already know, note where the agent needed correction, and move each correction into a skill or the project instructions.

## The agentic workflow overview

The diagram maps the workflow from requirements to verification in unit tests, Page Builder, the live site, and the build.

![Agentic widget workflow from the requirement through investigation, behavior decisions, and test-first slices to verification of unit tests, the Page Builder editor, the live site, and the build](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/agentic-widget-workflow.drawio.svg "Agentic widget workflow from the requirement through investigation, behavior decisions, and test-first slices to verification of unit tests, the Page Builder editor, the live site, and the build")

## Manage the agent's context window

Repository investigation, documentation responses, test output, and browser checks filled the session's context quickly. We kept decisions outside the conversation and used verified implementation checkpoints to continue the work across sessions. For background on context limits, see [What is the context window](https://www.aihero.dev/what-is-the-context-window) or the video [Most devs don't understand how context windows work](https://www.youtube.com/watch?v=-uW5-TaVXu4).

These habits kept the agent's context small during this case study:

- **Break work into small slices.** Give the agent one feature or slice at a time, and verify the result before starting the next.
- **Keep decisions in files, not in the conversation.** The specification, the ticket breakdown, and `AGENTS.md` survived compaction and new sessions. A new session read them and continued from the same agreement.
- **Restart at a verified checkpoint.** Monitor context usage while the agent works. Before starting another slice in a fresh session, verify the current result and record its state, unresolved questions, and next action. In this case study, we checked the base widget in Page Builder before continuing in a fresh session.
- **Delegate investigation.** Subagents read code and documentation in their own context and return a short summary. See [Work effectively with KentiCopilot](https://docs.kentico.com/guides/development/kenticopilot/work-effectively-with-kenticopilot.md) for details.

> **Tip:** Most agentic coding tools let you customize the status line or show the context usage on demand. In Claude Code, configure a [custom status line](https://code.claude.com/docs/en/statusline), or check the usage at any time with the `/context` command.
>
> ![Customized terminal status line showing the repository, branch, file change counts, model, and the tokens used in the current session](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/example-console-for-ai-development.png "Customized terminal status line showing the repository, branch, file change counts, model, and the tokens used in the current session")

### Check the session before you start a task

A new session does not guarantee that the agent has the context you prepared. For example, during the case study implementation, MCP servers were sometimes not connected at the start of a session, even though the project defined them.

Check your agent’s documentation for how it reports and restores MCP connections. The instruction file that only asks the agent to read `AGENTS.md` depends on the agent actually reading it. Without the [Documentation MCP server](https://docs.kentico.com/documentation/developers-and-admins/installation/mcp-server.md), an agent that needs an Xperience API has to guess the API shape or inspect the compiled Kentico assemblies, which costs tokens and produces code based on implementation details instead of the documented API.

Start each coding session with a readiness check. The agent reports what it loaded and stops before any work if something is missing.

> **Tip:** Most agents offer a way to show which MCP servers are connected and which instruction files the session loaded; check your agent’s documentation for the current commands. Agents also differ in which instruction files they read by default, and in whether `AGENTS.md` is one of them. To load `AGENTS.md` without relying on the agent, import it in `CLAUDE.md` with the `@AGENTS.md` syntax instead of asking the agent to read it. Consider creating a skill to ensure the agent always confirms its context at the start of a session.

## Start with a problem, not a prompt

A request such as "build a promotion widget" leaves the agent to invent the content sources, editor controls, fallback behavior, and test boundary. Start with the business outcome instead. In our case study, editors needed one component that could promote an article page, a service, a product, or a manually written offer while keeping a familiar editing experience.

Write down the decisions that affect behavior before asking for an implementation. The written requirement survives a compacted agent session and lets another developer understand why an option exists. It also limits what the agent investigates, so it's less likely to add abstractions.

How much you write before the first prompt depends on how much you already know. Choose a starting point:

- **Start from an outline** when you know the outcome but not the details. The agent investigates the project and the documentation, and its questions fill the gaps.
- **Start from detailed requirements** when the decisions already exist, for example from a content modeling session or a stakeholder workshop. The case study used this approach.

### Start from an outline when requirements are thin

An outline-first start works well in the following situations:

- You start a greenfield project or a new feature area, and there are no existing components to copy.
- Stakeholders have described the outcome, but not the content sources, editor options, or edge cases.
- You inherited a project and do not yet know its content model, conventions, or test setup.
- You need a proof of concept or an estimate before anyone commits to a full specification.

Write a short specification with only what you know, and let the investigation turn the unknowns into specific questions. Take the questions you cannot answer back to your stakeholders. The agent's report then gives everyone a concrete list of decisions to make, instead of a vague request for more information.

The following example shows a minimal _Content Promotion_ widget specification.

```markdown title="content-promotion-widget-spec.md"
# Content Promotion widget

## Selection

- Support a selected page, a reusable content item, or manual content.
- Record the identifier returned by each selector and the API that accepts it.

## Editor experience

- Display only properties that apply to the selected source.
- Display a Page Builder-only warning when the card has no destination.

## Testing

- Unit test view-model mapping and configuration rules.
- Verify the configuration dialog and the published card in a browser.
```

The requirement does not need to be a complete design. Ask the agent to explore the project, similar components, and product documentation before requesting code. A useful first message makes the agent report uncertainty and wait for the product decisions that only you can make.

You can inspect an [example of the spec file](https://github.com/Kentico/xperience-by-kentico-training-guides/blob/finished/docs/content-promotion-widget-spec.md) in the finished branch of the repository.

> **Warning:** Do not treat a polished prompt as a specification. The _Content Promotion_ widget changed because investigation showed that the project already supported Page Builder personalization. The right requirement was to preserve that platform behavior, not to add a per-widget switch that Xperience does not need.

### Start from detailed requirements

When you already know the behavior, the styling, and the decisions that are settled, put them all into the first prompt. The case study started this way: the prompt described the behavior and the styling, listed the decisions that were not open for discussion, and asked the agent to question only the parts that genuinely branch, using the `grill-me` skill. Listing the settled decisions up front keeps the questioning short.

## Decide what the component owns

The _Content Promotion_ widget splits its work between a service and the ASP.NET Core [view component](https://learn.microsoft.com/aspnet/core/mvc/views/view-components). `ContentPromotionService`, behind `IContentPromotionService`, owns the content rules.

The service retrieves the selected item, applies the hide, override and inherit rules, resolves the link, and builds the type-specific extras. The view component calls the service and adds only presentation: the CSS classes for card design, layout and alignment. The service has a single consumer, so the split isn't about reuse. It puts the rules behind one interface, so their tests mock only the retrieval collaborators, and the view component tests mock the service.

The most expensive early mistake was passing one kind of identifier where another was required. [Combined content selector](https://docs.kentico.com/documentation/developers-and-admins/customization/extend-the-administration-interface/ui-form-components/reference-admin-ui-form-components.md#combined-content-selector) returns a content item identifier, but page-specific operations require a page identifier. The widget passed the content item GUID to the URL retrieval operation. A project decorator caught the resulting error and returned an empty URL, so the call to action disappeared without an error instead of throwing an exception.

The fix retrieves the page first, then passes its page identifier to the URL operation.

Your reference project should ideally include examples showing how you handle content item and page identifiers to prevent similar mistakes. If you don't have an example yet, you can use the _Content Promotion_ widget as a reference.

> **Key:** Record every identifier contract in the requirement or decision log.

The content model also shapes what the widget owns. A reusable schema filter can exclude page types that only reference the schema through a field. The same filter can include variant types that are not valid promotion targets. Model the actual choices editors need, then use a page-versus-item mode when the project has intentionally different content families.

Widget properties provide editors with a configuration dialog. Use [visibility conditions](https://docs.kentico.com/documentation/developers-and-admins/development/builders/builder-component-properties-visibility-and-validation.md) to show a dependent property only after its controlling property appears earlier in the form. Xperience combines multiple visibility conditions with AND semantics, so model the rule rather than assuming that two attributes express an OR.

```csharp title="ContentPromotionWidgetProperties.cs"
using System;
using Kentico.PageBuilder.Web.Mvc;
using Kentico.Xperience.Admin.Base.FormAnnotations;
(...)
public class ContentPromotionWidgetProperties : IWidgetProperties
{
    (...)
    [TextInputComponent(
        Label = "{$TrainingGuides.ContentPromotionWidget.LinkUrl.Label$}",
        ExplanationText = "{$TrainingGuides.ContentPromotionWidget.LinkUrl.ExplanationText$}",
        Order = 110)]

    // The field appears only when the source isn't a page and no target page is selected.
    [VisibleIfNotEqualTo(nameof(ContentSource), ContentPromotionSource.PAGE, StringComparison.OrdinalIgnoreCase)]
    [VisibleIfEmpty(nameof(LinkTargetPage))]
    public string LinkUrl { get; set; } = string.Empty;
    (...)
}
```

This property model shows the minimum shape: `IWidgetProperties` defines the model, and an editing component exposes a property in the widget configuration dialog. Add visibility attributes only after verifying the intended rule and its order against the current Xperience reference.

> **Warning:** Do not keep a workaround without checking your installed product version and the latest [XbyK release](https://docs.kentico.com/changelog.md). During the development of this case study, we ran into a product bug that affected the page selector. Simply updating the product was the right fix.

![Content Promotion widget selectors showing page and content-item choices with different identifier contracts](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/content-promotion-widget-selectors.png "Content Promotion widget selectors showing page and content-item choices with different identifier contracts")

## Ensure tests catch a wrong implementation

A working build does not prove that the component works. Ask the agent to agree the test seam before it writes the behavior, then run a focused test that fails for the expected reason.

We already mentioned that we used test-driven development in this case study: the agent wrote a focused test, made it fail, implemented only enough behavior to pass, then improved the code while the test protected the result.

The agent followed the project-specific instructions in AGENTS.md and used the existing xUnit and Moq setup instead of the generic NUnit guidance retrieved from [Documentation MCP](https://docs.kentico.com/documentation/developers-and-admins/customization/write-automated-tests/set-up-test-projects.md). Most tests target `ContentPromotionService` directly. The view component tests only check the CSS classes it adds to the view model.

The test needs to observe a behavior that would change if the implementation were wrong. One early test expected an image property to be `null`. It passed before the image behavior existed because the property was never assigned. Another mocked URL retrieval with a content item GUID, repeating the same identifier mistake as the production code. Giving the page and content item deliberately different GUIDs made the test fail and exposed the faulty assumption.

For example, the `ContentPromotionServiceTests.cs` keeps the identifiers distinct.

```csharp title="ContentPromotionServiceTests.cs"
(...)
private readonly Mock<IContentItemRetrieverService> contentItemRetrieverServiceMock = new();
private readonly Mock<IWebPageUrlRetriever> webPageUrlRetrieverMock = new();
// ... taxonomy, language, product mocks
private readonly ContentPromotionService contentPromotionService;   // built in the constructor
(...)
// The URL collaborator is a two-step chain of calls:
// Load target page by content item GUID
IContentItemRetrieverService.RetrieveWebPageForUrlByContentItemGuid(guid, …)
// Retrieve the URL for the loaded page
IWebPageUrlRetriever.Retrieve(page, …)
```

The following example shows the test for resolving a link when the content source is a page. We've adapted its code sample to show the setup:

```csharp title="ContentPromotionServiceTests.cs"
[Fact]
public async Task ResolveLink_PageSource_LinksToTheSelectedPageItself()
{
    // Arrange
    var articlePage = new ArticlePage();
    webPageUrlRetrieverMock
        .Setup(x => x.Retrieve(articlePage, It.IsAny<CancellationToken>()))
        .ReturnsAsync(new WebPageUrl(PAGE_RELATIVE_URL, PAGE_RELATIVE_URL));

    var properties = new ContentPromotionWidgetProperties
    {
        ContentSource = ContentPromotionSource.PAGE
    };

    // Act
    var result = await contentPromotionService.ResolveLink(properties, articlePage);

    // Assert
    Assert.Equal(PAGE_RELATIVE_URL, result?.LinkUrl);
}
```

See the complete implementation in [ContentPromotionServiceTests](https://github.com/Kentico/xperience-by-kentico-training-guides/blob/finished/src/TrainingGuides.Web.Tests/Features/ContentPromotion/Services/ContentPromotionServiceTests.cs).

For example:

```csharp title="PromotionWidgetTests.cs"
using System;
using Xunit;

public sealed class PromotionWidgetTests
{
    [Fact]
    public async Task BuildsLinkFromTheSelectedPageIdentifier()
    {
        // Arrange
        var contentItemGuid = Guid.NewGuid();
        var pageGuid = Guid.NewGuid();
        var fixture = new PromotionWidgetFixture(contentItemGuid, pageGuid);

        // Act
        var link = await fixture.Service.ResolveLink(fixture.Properties, fixture.SelectedPage);

        // Assert
       Assert.Equal("/contact-us", link?.LinkUrl);
    }
  (...)
}
```

Keep the test close to the rule it proves. Mark paths that require real assets, generated entities, or a database as manual or integration coverage as manual or integration coverage. Substitutes for those dependencies tend to break.

Pause after a meaningful vertical slice and inspect the component in a running Page Builder page. The agent can finish data retrieval and view-model mapping while you verify that the widget appears in the picker and renders the intended base state. Continue with presentation details after that check. This pause prevents a long implementation from getting built on an invisible or misregistered component.

> **Warning:** Investigate a test that passes immediately. Temporarily change or remove the behavior to prove the assertion can fail.

### Keep the tests useful

The widget accumulated more than one hundred tests while its behavior and design evolved. That is useful during discovery, but the finished solution does not need multiple tests that prove the same rule or tests for behavior that no longer exists. After the implementation is stable, review the suite by behavior and retain the clearest test for each rule. Keep tests that document distinct decisions, boundary conditions, regressions, or integration requirements.

Ask the agent to propose deletions before changing the suite. Review its evidence, including the behavior each candidate test proves and the test that will still protect it. Do not use test count as a quality measure.

## Verify the editor and live-site behavior

Unit tests prove mapping, validation rules, and error states. They do not prove that the widget is registered in the widget selector, the configuration dialog exposes the right controls, the stylesheet is served, or a published page behaves correctly. Combine manual _Page Builder_ checks with [Playwright](https://playwright.dev/docs/intro) tests to cover those boundaries.

> **Tip:** For practical examples of administration UI automation, see [E2E testing for Xperience's administration UI extension](https://community.kentico.com/blog/e2e-testing-xperience-s-administration-ui-extension-with-confidence) on the [Community Portal](https://community.kentico.com).

The case-study E2E test created a unique page, opened Page Builder, added and configured the widget, published the page, then visited the page anonymously. It confirmed the editor-only notices, visibility rules, plain-text override behavior, the single stretched link, and consent-gated click tracking. Cleanup moved the test page to the recycle bin and permanently deleted it even when the test failed.

The following simplified test shows the shape of the scenario. The helper names are placeholders. The real suite uses a [`ContentPromotionEditor`](https://github.com/Kentico/xperience-by-kentico-training-guides/blob/finished/tests/e2e/content-promotion/contentPromotionEditor.ts) page object and page helpers, and you need to provide equivalents and authenticated storage state in your project.

```typescript title="Simplified E2E test"
import { expect, test } from "@playwright/test";

test("an editor publishes a promotion that a visitor can open", async ({ page }) => {
    await test.step("Configure and publish the widget", async () => {
        await configurePromotionWidget(page, {
            callToActionText: "Contact us",
            linkUrl: "/contact-us",
        });
        await publishCurrentPage(page);
    });

    await test.step("Verify the published card", async () => {
        await page.goto(getPublishedPageUrl());
        await expect(page.getByRole("link", { name: "Contact us" })).toHaveAttribute("href", "/contact-us");
    });
});
```

The helper names keep the test focused on the behavior it proves. The real suite placed the _Page Builder_ interactions in page objects because the editor runs inside an iframe and some controls have only `title` attributes. Explore the UI with a browser first, then transfer selectors and deterministic waits into the test. Do not replace an observed response wait with a fixed delay.

The visitor requirements include privacy behavior. [Custom activities](https://docs.kentico.com/documentation/developers-and-admins/digital-marketing-setup/set-up-activities/custom-activities.md) require tracking consent on website channels. The test first asserted that the tracking script was absent without consent. After accepting cookies, it waited for the cookie-banner response, reloaded the page, selected the card, and observed the tracking request. [navigator.sendBeacon()](https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon) requests can appear as `ping` requests in Playwright.

> **Warning:** Treat E2E artifacts as part of your threat model. A failing sign-in test can record a typed password in a trace, screenshot, page snapshot, or HTML report. Clear the password field before the sign-in step finishes, and disable unnecessary artifact capture for that project. Run one suite at a time when runs share output directories.

![Empty Content Promotion widget dialog properties](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/empty-content-promotion-widget-properties-dialog.png "Empty Content Promotion widget dialog properties")

The following video shows the editor-to-live-site E2E flow including a test of the consent-gated tracking request.

🎬 [Video](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/e2e-test-video-widget-configuration-tracking.webm)

## Debug the layer that owns the failure

The _Content Promotion_ widget had two styling failures that looked like one. First, the SCSS source had changed but the compiled stylesheet had not. Later, the compiler wrote CSS to a default location because its project configuration lived in a file that the editor extension did not load. Once the correct CSS existed, the browser still served a cached asset. The _Content Promotion_ widget had three styling failures that looked like one.

Those failures needed different repairs. Use this checklist to identify which layer is missing the change before asking the agent to modify more code.

```markdown title="Widget rendering diagnostic checklist"
- Confirm that the source file contains the expected change.
- Confirm that the generated CSS or compiled asset contains the change.
- Inspect the HTTP response for the asset the browser requested.
- Confirm that the browser renders the returned bytes.
- Check the installed Xperience version before keeping a product workaround.
```

Build-output locks need a different check. When a running site locks an assembly or generated file, stop the site before the build, use a separate output location, or change the workflow. Do not keep retrying the same build and attribute the error to the widget.

## Stay in charge of decisions

An agent can recommend a decision and record its assumptions. You, the developer, own the decision when the choice changes editor experience or the scope of the work.

For the _Content Promotion_ widget, we decided on several implementation choices that you cannot infer from the codebase:

- Shipped warnings instead of a fallback CTA label.
- Ignored a stored Hide elements value in manual mode.
- Chose the currency format.
- Approved the test cleanup table before tests were removed.
- Declined a status enum for the remaining selection-failed flag, and declined collapsing the service into a single `BuildCard` method.

Those choices could not be inferred from the codebase.

Use a compact decision record when the agent presents a meaningful alternative. The record gives a later reviewer enough context to distinguish a trade-off from an overlooked defect.

```markdown title="Decision record"
## Call to action without text

**Context:** A destination exists, but the card has no call-to-action text.

**Options:** Render a fallback label, or show an editor-only warning.

**Decision:** Show an editor-only warning.

**Reason:** The editor should supply copy that matches the campaign. A generic fallback changes the intended message.
```

Give the agent bounded autonomy after you agree how decisions work. For example, ask the agent to recommend an option, continue with the recommendation when no product decision is involved, and list each assumption in the implementation summary. Ask the agent to report pre-existing defects and create a follow-up instead of silently changing unrelated code.

Use this short check before letting the agent continue:

- Is the expected behavior written down?
- Does the choice affect editors, visitors, or a business rule?
- Does the existing project provide a clear pattern?
- Can a focused test or running check falsify the behavior?

If the answer to the second question is yes and the third is no, make the decision yourself.

![Call to action decision flow of the Content Promotion widget, from loading the selected item to logging a click activity](https://docs.kentico.com/docsassets/guides/build-page-builder-widgets-with-agent/cta-decision-flow.drawio.svg "Call to action decision flow of the Content Promotion widget, from loading the selected item to logging a click activity")

The flow shows how these decisions combine into the widget's call to action behavior:

- **Hidden widget.** When the selected item cannot be loaded, or the widget has no content to show, visitors see nothing and editors see a notice in Page Builder edit mode.
- **Destination.** A page source links to the selected page. Other sources link to the link target page, or to the typed URL when no target page is selected. A selected page always wins, even when it cannot be loaded.
- **Card without a link.** When the widget has no destination, the call to action is hidden, or the call to action text is empty, visitors still see the card, but they cannot click it. Editors see a warning that names the cause.
- **Clickable card.** With a destination and visible call to action text, the whole card becomes a single link.
- **Click tracking.** A click logs a custom activity only when the visitor consents to tracking and the widget has a valid tracking value. The link opens either way.

You can find the complete document that describes _Call to action_ behavior in the [Training guides repository](https://github.com/Kentico/xperience-by-kentico-training-guides/blob/finished/docs/example-call-to-action-decision-flow.md).

## Apply the workflow to your next component

Use the same loop for [Page Builder sections](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/sections-for-page-builder.md), [page templates](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/page-templates-for-page-builder.md), [custom form fields](https://docs.kentico.com/guides/digital-marketing/work-with-forms/add-a-custom-form-field.md), or smaller widget increments.

Start with a requirement that names the user outcome and exclusions. Ask the agent to investigate the project and documentation. Decide the data and editor options. Build behavior that can fail. Then validate the unit, editor, live-site, and operational layers that the component reaches.

> **Key:** The agent accelerates the work. Your requirements, decisions, and verification make the result dependable.

Use a lighter version of the loop for a small, local component with no external data or editor configuration. Invest more when a component combines several content sources, has a flexible editor experience, affects tracking or personalization, or introduces a new testing surface.

For a shorter example, watch [Rapidly implement widgets with KentiCopilot](https://docs.kentico.com/guides/development/kenticopilot/implement-widgets-kenticopilot.md). The video builds a simpler _Featured article_ widget without the test-driven workflow used in this case study. To learn more about configuring variants for different audiences, see [content personalization](https://docs.kentico.com/documentation/developers-and-admins/digital-marketing-setup/content-personalization.md).
