Skip to content

[Blazor] Add agentic generative UI state rendering - #68333

Merged
ilonatommy merged 10 commits into
mainfrom
javiercn-components-ai-07-agentic-generative-ui
Aug 26, 2026
Merged

ilonatommy merged 10 commits into
mainfrom
javiercn-components-ai-07-agentic-generative-ui

Conversation

@javiercn

@javiercn javiercn commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

Overview

This is position 7 in the native Components.AI stack tracked by #68340 and depends on #68330. Relative only to parent javiercn-components-ai-06-tool-generative-ui (cf1d845394a3dc815941446e78c79dfc49ce4a89), the stack-relative diff adds protocol-neutral typed observable state to Components.AI and uses it to implement the canonical Agentic Generative UI plan scenario; AG-UI types remain confined to test assets, and the browser still reaches a separate API host through AGUI.Client 0.0.5 over HTTP/SSE. Handwritten runtime/browser coverage and the deterministic model recording remain separate from product and dojo commits.

Design

The product contract adds a typed agent whose state is replaced atomically and observed independently of rendered chat blocks:

// src/Components/AI/src/Engine/UIAgentOfT.cs
// The generic agent retains every existing UIAgent behavior and adds one typed observable value.
public class UIAgent<TState> : UIAgent where TState : class, new()
{
    public AgentState<TState> State { get; }

    internal override ChatResponseUpdate ApplyStateMapper(ChatResponseUpdate update)
    {
        var context = new StateMapperContext(update);
        Options.StateMapper?.Invoke(context);

        if (context.StateValue is not null)
        {
            if (context.StateValue is not TState typedState)
            {
                throw new InvalidOperationException(
                    $"The state mapper returned a value of type '{context.StateValue.GetType()}', " +
                    $"but this agent requires state of type '{typeof(TState)}'.");
            }

            State.Value = typedState;
        }

        // State content can be removed without discarding unrelated text in the same update.
        return context.HasHandledContent ? context.GetFilteredUpdate() : update;
    }
}
// src/Components/AI/src/Engine/AgentState.cs
// Replacement triggers all current observers; snapshotting permits a callback to unsubscribe safely.
public T Value
{
    get => _value;
    set
    {
        ArgumentNullException.ThrowIfNull(value);
        _value = value;
        foreach (var callback in _callbacks.ToArray())
        {
            callback();
        }
    }
}

public IDisposable OnChanged(Action callback);

UIAgentOptions.StateMapper is the extension point, while StateMapperContext.Update, UnhandledContents, MarkHandled, and SetState separate two concerns: extracting structured state and deciding which AIContent should continue into block rendering. This boundary was chosen instead of adding AG-UI event types to the shipping assembly; any IChatClient provider can map its own raw representation or content shape.

Progress-like content is the other public equivalence class. ActivityContentBlock carries an application-defined ActivityType and JsonElement payload, while one generic handler owns the common snapshot/update/completion lifecycle:

// src/Components/AI/src/Pipeline/ActivityHandler.cs
// Derived handlers only recognize and mutate their protocol-specific payloads.
if (state.Id == string.Empty)
{
    if (TryCreateBlock(context, state))
    {
        if (state.Id.Length == 0)
        {
            state.Id = context.Update.MessageId ?? Guid.NewGuid().ToString("N");
        }

        OnContentUpdated(state);
        return BlockMappingResult<TBlock>.Emit(state, state);
    }

    return BlockMappingResult<TBlock>.Pass();
}

if (TryUpdateBlock(context, state, out var isCompleted))
{
    OnContentUpdated(state);
    return isCompleted
        ? BlockMappingResult<TBlock>.Complete()
        : BlockMappingResult<TBlock>.Update(state);
}

return BlockMappingResult<TBlock>.Pass();

Snapshot creation, in-place delta notification, completion, and unrelated-activity pass-through are implemented once; concrete activity protocols vary only in TryCreateBlock and TryUpdateBlock.

Implementation

The mapper runs at the existing streaming boundary. The filtered update reaches both conversation history and the block pipeline, so handled state content is not sent back to the model on the next turn. Fully filtered state-only updates do not create empty assistant history messages:

// src/Components/AI/src/Engine/UIAgent.cs
await foreach (var update in _chatClient.GetStreamingResponseAsync(
    _history, chatOptions, cancellationToken).ConfigureAwait(false))
{
    var processUpdate = ApplyStateMapper(update);
    if (processUpdate.Contents.Count == 0 && update.Contents.Count > 0)
    {
        continue;
    }

    assistantUpdates.Add(processUpdate);
    await foreach (var block in pipeline.Process(processUpdate, cancellationToken)
        .ConfigureAwait(false))
    {
        yield return block;
    }
}

The dojo server exposes two tool-result classes through one endpoint: create_plan becomes a full snapshot, and every update_plan_step result becomes an RFC 6902 delta. The five step updates are equivalent instances of the same path rather than five bespoke behaviors.

// src/Components/AI/testassets/AGUIDojoApi/ChatClientAgentFactory.cs
var options = new AGUIStreamOptions();
options.MapResultAsStateSnapshot("create_plan");
options.MapResultAsStateDelta("update_plan_step");
return options;
// src/Components/AI/testassets/AGUIDojoApi/AgenticGenerativeUI/AgenticPlanningTools.cs
// For step index 2, this path is "/steps/2/status" and the value is "completed".
changes.Add(new JsonPatchOperation
{
    Op = "replace",
    Path = $"/steps/{index}/status",
    Value = status is PlanStepStatus.Pending ? "pending" : "completed",
});

The Blazor scenario maps the two event classes into one PlanState. Snapshots replace the whole plan; deltas clone the current plan before applying valid replace operations, so assigning the returned instance reliably notifies observers and rerenders the board.

// src/Components/AI/testassets/DojoClient/Components/Scenarios/AgenticGenerativeUI/AgenticGenerativeUIScenario.razor
options.StateMapper = context =>
{
    if (context.Update.RawRepresentation is StateDeltaEvent delta)
    {
        context.SetState(ApplyPlanDelta(_agent.State.Value, delta.Delta));
        return;
    }

    if (context.Update.RawRepresentation is not StateSnapshotEvent snapshot)
    {
        return;
    }

    var state = snapshot.Snapshot.Deserialize<PlanState>(_jsonOptions);
    if (state is not null)
    {
        context.SetState(state);
    }
};

_stateChangedRegistration = _agent.State.OnChanged(
    () => _ = InvokeAsync(StateHasChanged));

The E2E model replacement is applied only to AGUIDojoApi; DojoClient receives only the API URL and continues to construct its keyed AGUIChatClient. This proves the transport instead of short-circuiting it in-process.

// src/Components/AI/testassets/DojoClient.E2E.Tests/Tests/AgenticGenerativeUIScenarioTests.cs
_api = await StartServerAsync<AGUIDojoApiAssembly>(TestRoot.Servers, options =>
{
    options.ConfigureServices<DojoModelOverrides>(
        nameof(DojoModelOverrides.AgenticGenerativeUI));
});

_ui = await StartServerAsync<global::DojoClient.Components.App>(TestRoot.Servers, options =>
{
    options.EnvironmentVariables["AGUI_DOJO_API_URL"] = _api.AppUrl;
});

Outcome

The 16 runtime tests are compressed into three behavior classes: observable state semantics (5), state extraction/filtering including mixed and raw updates (6), and activity snapshot/delta/completion/isolation (5). The single browser test loops over all five equivalent deltas, independently gates the final summary, and checks progress, current/completed styling, running/done state, and input enablement.

Review guidance: Read UIAgent.ApplyStateMapper, StateMapperContext filtering, UIAgent<TState> assignment, ApplyPlanDelta, and the API-only replay registration closely. The plan DTOs, repeated step markup, CSS, and generated recording are representative data/presentation and can be skimmed.

Acceptance criteria:

  1. A create_plan snapshot renders one five-step board at 0/5, with the first pending step current.
  2. Each released update_plan_step delta completes exactly one additional step and advances progress by 20%, reaching 5/5 without duplicating the activity.
  3. The final summary streams while the activity is running; completion marks it done and re-enables input.
  4. The browser request crosses DojoClient → AGUIChatClient → HTTP/SSE → AGUIDojoApi; only the API model is replayed.
Validation class Result
Dependency-aware DojoClient.E2E.Tests build Passed — 0 warnings, 0 errors
Typed-state runtime tests 16/16 passed — 0 failed, 0 skipped
Real dual-host AgenticGenerativeUIScenarioTests 1/1 passed — 0 failed, 0 skipped; HTTP/SSE response 200

@javiercn
javiercn requested a review from a team as a code owner August 10, 2026 22:01
@javiercn
javiercn force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from 9c64244 to 2d7502c Compare August 11, 2026 07:15
@javiercn

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@javiercn

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-components-e2e

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@javiercn

Copy link
Copy Markdown
Member Author

/azp run aspnetcore-ci

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@javiercn
javiercn force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from 2d7502c to 982e84e Compare August 12, 2026 13:15
Copilot AI lite review requested due to automatic review settings August 12, 2026 16:47
@kotlarmilos
kotlarmilos force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from 982e84e to 8ccd67b Compare August 12, 2026 16:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR extends Microsoft.AspNetCore.Components.AI with (1) protocol-neutral typed, observable agent state (UIAgent<TState> + AgentState<T>) via a new StateMapper extension point, and (2) a reusable “activity/progress” block mapping abstraction (ActivityContentBlock + ActivityHandler<TBlock>). It also adds an “Agentic Generative UI” dojo scenario (snapshot + JSON Patch deltas over real HTTP/SSE) and corresponding runtime + E2E coverage.

Changes:

  • Add typed observable state to UIAgent via AgentState<T>, UIAgent<TState>, and StateMapperContext content filtering.
  • Add reusable activity snapshot/delta handling via ActivityHandler<TBlock> and ActivityContentBlock.
  • Add Agentic Generative UI dojo scenario + deterministic recordings + E2E test validating snapshot + delta progression over HTTP/SSE.
Show a summary per file
File Description
src/Components/AI/testassets/DojoClient/Program.cs Registers keyed chat client for the new agentic scenario endpoint.
src/Components/AI/testassets/DojoClient/DojoScenarios.cs Adds AgenticGenerativeUIEndpoint constant.
src/Components/AI/testassets/DojoClient/Components/Scenarios/AgenticGenerativeUI/PlanState.cs Adds plan DTOs used by the scenario’s typed state.
src/Components/AI/testassets/DojoClient/Components/Scenarios/AgenticGenerativeUI/PlanProgressCard.razor.css Styles the plan progress card UI.
src/Components/AI/testassets/DojoClient/Components/Scenarios/AgenticGenerativeUI/PlanProgressCard.razor Renders plan progress and per-step state based on typed agent state.
src/Components/AI/testassets/DojoClient/Components/Scenarios/AgenticGenerativeUI/AgenticGenerativeUIScenario.razor.css Scenario-specific layout and activity status styling.
src/Components/AI/testassets/DojoClient/Components/Scenarios/AgenticGenerativeUI/AgenticGenerativeUIScenario.razor Implements the scenario, state mapping (snapshot/delta), and rerender subscription.
src/Components/AI/testassets/DojoClient/Components/Pages/Home.razor Adds navigation link to the new scenario.
src/Components/AI/testassets/DojoClient/Components/_Imports.razor Adds usings for AG-UI abstractions + scenario namespace.
src/Components/AI/testassets/DojoClient.E2E.Tests/Tests/AgenticGenerativeUIScenarioTests.cs Adds dual-host Playwright test validating snapshot + 5 deltas + streaming summary.
src/Components/AI/testassets/DojoClient.E2E.Tests/ServiceOverrides/DojoModelOverrides.cs Adds API-only recorded model override for the new scenario.
src/Components/AI/testassets/DojoClient.E2E.Tests/Baselines/AgenticGenerativeUI.recording.json Adds deterministic recording for tool calls + checkpointed frames.
src/Components/AI/testassets/AGUIDojoApi/ScriptedChatClient.cs Extends scripted model behavior to drive plan creation/step progression and final summary.
src/Components/AI/testassets/AGUIDojoApi/Program.cs Maps the new /agentic_generative_ui dojo endpoint with tools + stream mapping.
src/Components/AI/testassets/AGUIDojoApi/ChatClientAgentFactory.cs Adds agentic system prompt, tools, and AG-UI stream options mapping results to snapshot/delta.
src/Components/AI/testassets/AGUIDojoApi/AgenticGenerativeUI/PlanStepStatus.cs Adds status enum serialized as pending/completed.
src/Components/AI/testassets/AGUIDojoApi/AgenticGenerativeUI/PlanStep.cs Adds plan step DTO for API-side snapshot.
src/Components/AI/testassets/AGUIDojoApi/AgenticGenerativeUI/Plan.cs Adds plan DTO containing steps.
src/Components/AI/testassets/AGUIDojoApi/AgenticGenerativeUI/JsonPatchOperation.cs Adds JSON Patch operation DTO used for deltas.
src/Components/AI/testassets/AGUIDojoApi/AgenticGenerativeUI/AgenticPlanningTools.cs Implements create_plan snapshot and update_plan_step delta tool results.
src/Components/AI/test/Pipeline/StateMapperTests.cs Adds tests for state extraction, filtering, and raw update handling.
src/Components/AI/test/Pipeline/ActivityHandlerTests.cs Adds tests for snapshot/delta/update/completion activity lifecycle behavior.
src/Components/AI/test/Engine/AgentStateTests.cs Adds tests for AgentState initialization + notifications + unsubscribe during callback.
src/Components/AI/src/PublicAPI.Unshipped.txt Declares the new public API surface area.
src/Components/AI/src/Pipeline/UIAgentOptions.cs Adds StateMapper option for state mapping/filtering.
src/Components/AI/src/Pipeline/StateMapperContext.cs Introduces context for mapping state and filtering handled AIContent.
src/Components/AI/src/Pipeline/ActivityHandler.cs Adds generic base handler for mapping activity snapshots/deltas into mutable blocks.
src/Components/AI/src/Engine/UIAgentOfT.cs Adds UIAgent<TState> with typed observable State and mapper integration.
src/Components/AI/src/Engine/UIAgent.cs Integrates state mapping/filtering into streaming update processing.
src/Components/AI/src/Engine/AgentState.cs Adds observable typed state container with change subscriptions.
src/Components/AI/src/Blocks/ActivityContentBlock.cs Adds public activity/progress block surface (type + payload).

Review details

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

  • Files reviewed: 31/31 changed files
  • Comments generated: 3
  • Review effort level: Lite

@javiercn
javiercn force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from 8ccd67b to e5891af Compare August 13, 2026 10:00
@ilonatommy
ilonatommy force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from e5891af to fbf110e Compare August 14, 2026 12:37
Comment thread src/Components/AI/src/Engine/UIAgent.cs Resolved
@ilonatommy
ilonatommy force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from fbf110e to 95fc816 Compare August 20, 2026 06:55
Base automatically changed from javiercn-components-ai-06-tool-generative-ui to main August 25, 2026 14:21
Rationale: let provider-neutral Components.AI applications react to structured model state snapshots and deltas without coupling the runtime to AG-UI or rendering protocol events as chat content.

Implementation: add UIAgent<TState>, observable AgentState<T>, state-mapper filtering in the existing streaming loop, and reusable activity blocks whose payload updates notify existing renderers.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 323b0ef8-7905-4041-8388-a08586c0bd34
Rationale: demonstrate canonical Agentic Generative UI across the real DojoClient to AGUIDojoApi HTTP/SSE boundary by rendering structured plan state independently of conversational text.

Implementation: add the /agentic_generative_ui endpoint and keyed AGUIChatClient, map create_plan results to snapshots and update_plan_step results to JSON Patch deltas, and render a progress board that reacts to each typed state update.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 323b0ef8-7905-4041-8388-a08586c0bd34
javiercn and others added 4 commits August 25, 2026 16:30
Rationale: lock down typed state replacement, content filtering, activity notifications, and the canonical Agentic Generative UI progression without replacing DojoClient's real AG-UI transport.

Implementation: add focused runtime tests for observable state, state mapping, and activity deltas plus dual-host browser assertions that gate every plan step and final response independently.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 323b0ef8-7905-4041-8388-a08586c0bd34
Rationale: keep deterministic Agentic Generative UI browser coverage independent of live model credentials while exercising the real AG-UI HTTP/SSE boundary.

Implementation: record the create_plan snapshot, five sequential update_plan_step deltas, accumulated tool results, and independently gated final summary.

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 323b0ef8-7905-4041-8388-a08586c0bd34
Keep fully handled updates in assistant response aggregation while continuing to suppress them from block rendering. Add regression coverage for a metadata-bearing state update followed by an unidentified text continuation.

Co-authored-by: Copilot <[email protected]>

Copilot-Session: baddc46b-b86e-4be5-add2-1a7b3cac8195
@ilonatommy
ilonatommy force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from 913754f to 092e9dd Compare August 25, 2026 15:22
Co-authored-by: Copilot <[email protected]>

Copilot-Session: baddc46b-b86e-4be5-add2-1a7b3cac8195
@ilonatommy

ilonatommy commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Dojo scenario is missing suggestions (e.g. "simple plan"/"complex plan") with proper customization, it can be a part of #68372, #68441, #68436.

The initial (1st render) suggestions got added in 00e1554.

Also collapsible entries with status (create_plan, update_plan_step etc) are missing. Should be resolved in #68416.

dojo-generative-UI.mp4

@ilonatommy
ilonatommy force-pushed the javiercn-components-ai-07-agentic-generative-ui branch from 30207dc to 3592d4d Compare August 26, 2026 09:42
@ilonatommy
ilonatommy merged commit d1786d5 into main Aug 26, 2026
29 checks passed
@ilonatommy
ilonatommy deleted the javiercn-components-ai-07-agentic-generative-ui branch August 26, 2026 13:14
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Aug 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants