Repository navigation
feat(024): AI agent devtools — MCP server + UIA-driven automation tools (phases 1–4) - #32
Merged
Chris Anderson (codemonkeychris) merged 30 commits intoApr 18, 2026
Merged
Conversation
- Add DevtoolsCliParser with subverb model (run|list|screenshot|tree) and --preview / --preview-list deprecation aliases. - Rename ReactorApp.Run preview: parameter to devtools: (preview: kept for one release; emits a one-shot stderr deprecation warning). - Rename TryRunPreview → TryRunDevtools; switch log prefixes from [preview] to [devtools] across ReactorApp and PreviewCaptureServer. - Update CLI scaffold (Reactor.Cli/Program.cs) to generate devtools: true and mention mur devtools / MCP endpoint. - Add unit coverage: CliFlagParsingTests (19 cases) and DevtoolsParamCompatTests (4 cases) — all passing. Deviation noted in the task list: [Obsolete] is not legal on a parameter declaration in C#, so the deprecation is surfaced via an inline comment + runtime stderr warning rather than the attribute. Refs docs/specs/024-ai-agent-devtools.md phase 1. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Spawn dotnet with '--devtools run --vscode' by default - Sniff stdout for `[preview]` prefix and relaunch with '--preview --vscode' when the target Reactor package predates the rename - Add dual telemetry event names (reactor_devtools_launch / reactor_preview_launch) for one-release compatibility; transport is a stub appendLine until a real sink is wired
- NodeIdBuilder: pure id-construction for the three rules in spec §13 (AutomationId, Reactor source, content-addressed from nearest stable ancestor). No WinUI dependency; fully unit-testable. - NodeRegistry: thread-safe forward/reverse maps with WeakReference<object> storage, per-window invalidation, and tombstoning so ids are never reused after a window closes or a component switches. - SelectorParser: five selector forms from spec §11 (node id, AutomationId, AutomationName, type path with optional index, Reactor source). - 25 new unit tests across these three components.
- DevtoolsMcpServer: HttpListener-based JSON-RPC 2.0 server bound to 127.0.0.1, dispatches tools/list / tools/call (plus bare method names). Prints MCP_ENDPOINT + MCP_PORT and a `[devtools] ready (build <tag>)` line after first render. --mcp-port pin honored for supervisor reloads. - McpToolRegistry: ordered tool registration, handler lookup, structured McpToolException for wire-error payloads. - JSON-RPC envelope types + standard error codes. - DevtoolsTools: four Phase 2 tools (version, components, switchComponent, reload). Reload flushes response, disposes listeners, exits 42. - ReactorApp.TryRunDevtools wires the MCP server alongside the VS Code capture server. Both share a single SwitchComponentCore callback so they can't drift on the active component. - 7 new unit tests for JSON-RPC envelope + registry behavior.
- `mur devtools [project] [--component Name] [--mcp-port N]` spawns the target via `dotnet run -- --devtools run` and respawns on exit code 42. - MCP port is pinned (picked on first launch or --mcp-port) so an agent can reconnect to the same endpoint across reloads. - On exit 42 the supervisor runs `dotnet build`; on build failure it waits rather than respawning, per spec — the agent sees a transport error and the human fixes the code before requesting reload again. - Child stdout/stderr stream verbatim (no buffering). - 9 unit tests for arg parsing (the dotnet-spawn paths are deferred to the Phase 2.18 Appium suite).
Check off phase 2.1, 2.2, 2.4–2.7, 2.14, 2.15 items that landed in this branch, and annotate the remaining items with where they'll be covered (tree walk §2.8, window registry §2.3, waitFor §2.13) so future work knows what's already done.
- WindowIdAllocator: pure title-slugifier + collision handling. Slugs
win; empty/garbage titles fall back to Win1/Win2/…; colliding slugs
get -2/-3/… suffixes. Ids are retired forever.
- WindowRegistry: live instance map keyed by WeakReference, attaches to
Window.Activated/Closed, exposes Snapshot/Resolve/TryDefault for the
tool surface. HWND + bounds read via user32 GetWindowRect.
- `windows` MCP tool returns [{id, title, hwnd, bounds, isMain, buildTag}].
- Wired into ReactorApp.TryRunDevtools — the primary window attaches
with isMain=true.
- 14 new unit tests covering slugify + allocator reservation semantics.
…tFor - TreeWalker: VisualTreeHelper-based walk rooted at Window.Content. Emits flat TreeNode[] with $schema: reactor-tree/1 pinned at the payload level. Summary view only (layout/visual/context land in §3.1). Registers each node with NodeRegistry for stable ids. - SelectorResolver: live IR→UIElement resolution. NodeId → registry. AutomationId/Name → descendant scan with ambiguity detection. Type path → chained descendant filter with index disambiguation. Structured errors for unknown-selector, ambiguous-selector, index-out-of-range, window-required, window-mismatch. - tree tool: selector-scoped subtree walk; window arg honored. - click tool: Invoke → Toggle → SelectionItem pattern cascade, returns which pattern fired via `via`. Pointer synthesis deferred (rare path). - type tool: TextBox.Text fast path plus IValueProvider.SetValue fallback. clear=true replaces, default appends. - focus tool: Control.Focus(FocusState.Programmatic). - waitFor tool: 50ms-tick predicate evaluator with configurable timeout. Predicate fields: selector, textEquals, textMatches, visible, count. count=0 treats absent element as satisfied. Returns elapsedMs on success, observed state on timeout. - 8 new schema + predicate unit tests.
- ScreenshotCapture: PrintWindow-based PNG capture helper. Shared between the MCP `screenshot` tool and the headless `--devtools screenshot` subverb. Client-space crop, optional chrome-included mode. - screenshot MCP tool: selector → client-space bounds → crop. waitIdle calls UpdateLayout on the content root before capture. Returns base64 PNG + exact bounds that were captured. - ReactorApp.RunScreenshotSubverb: runs the target Component to first render, captures a PNG, writes to --out, and exits 0 without starting any persistent server. - Task doc updated with phase 2 tool completion + notes on deferred items (pointer-synthesis fallback for click/type, reactor-source backref).
- Pull JSON-RPC dispatch out of DevtoolsMcpServer into a standalone McpDispatcher class that takes just an McpToolRegistry. Makes the full request→response pipeline unit-testable without standing up HTTP, a WinUI window, or a UI dispatcher. - DevtoolsMcpServer.DispatchRpc is now a one-liner delegating to the dispatcher. - 8 new integration tests covering tools/list, tools/call, bare-method direct calls, unknown-method errors, invalid-params shaping, parse errors, and JSON-RPC version validation.
- invoke: IInvokeProvider.Invoke pass-through, structured no-pattern
error if the element doesn't expose it.
- toggle: IToggleProvider.Toggle; returns resulting state
("on"/"off"/"indeterminate").
- select: ISelectionItemProvider.Select on an item selector scoped
under a container selector; validates container first.
- scroll: IScrollProvider by-offset OR IScrollItemProvider.ScrollIntoView
for a descendant (to takes precedence over by). Percent-based delta
clamped to [0, 100].
- fire: escape-hatch handler-injection tool. Resolves a live Component
by class name (v1: root only), finds a method by name via reflection,
invokes on the UI dispatcher. Response tagged via:
"reactor-event-injection" so the shortcut shows up in traces.
Handler args unpacked from JsonElement to CLR primitives.
- ReactorHost.RootComponent internal accessor for the fire tool.
- mur new help prints mur devtools guidance with --mcp-port example.
- docs/specs/notes/024-snapshot-diff-watch.md stub for the deferred
snapshot/diff primitives.
- 9 new unit tests for DevtoolsFireTool helpers.
TreeWalker now accepts a TreeView enum (summary default, full for layout
debugging). Full view populates typeFullName, tag, automationControlType,
isEnabled, isKeyboardFocusable, desiredSize, actualSize, layout {margin,
padding, alignments}, context {parent constraints}, and visual {opacity,
clip, z-index, render transform}. Default visual blocks (identity transform,
no clip, opacity 1) are omitted so the payload stays tight.
Tree tool schema accepts view: "summary" | "full"; TreeFullViewTests cover
the serialization contract on hand-built nodes (walking a real tree stays
in the self-host fixture planned for §3.11).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
RenderContext exposes an internal SnapshotHooks() API so devtools can read
the live hook table without opening a generic accessor. DevtoolsStateTool
wraps that with the spec §12 payload shape: primitives (and enums) pass
through as JSON literals; complex objects and collections return
{ $type, $shape } so the tool never leaks live DataContext values.
Registered on the MCP server alongside fire. BuildPayload and ShapeValue
are exposed for unit testing — the self-host fixture covers the live
hook-table path in a follow-up.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…fire errors SelectorResolver now rejects a NodeId selector when the caller pins an explicit `window` that disagrees with the id's `r:<window>/` scope. A dedicated ExtractWindowFromNodeId helper makes the parse path unit-testable. New SelectorResolverRuntimeTests cover unknown-selector, gone, mismatch, and the prefix parser; tree-walk resolution (ambiguous-selector, type-path) still lives with the self-host fixture. DevtoolsFireTool grows a ResolveTarget helper so the structured-error shapes (not-ready / unknown-component / unknown-event) can be asserted without a live MCP server. New FireResolutionTests exercises all three plus case-insensitive resolution. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Supervisor now recognizes --print-config and writes a labeled JSON document to stdout with one fragment per agent — Claude Code, VS Code, and Copilot — each wired to the requested --mcp-port (or a freshly allocated free port). The tool never touches disk; the user pastes the block they want into the agent config file themselves. New PrintConfigTests asserts each fragment parses as valid JSON and that the URL matches the requested port. SupervisorArgsTests covers the new PrintConfig flag plumbing. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
DevtoolsLogger writes one tab-separated line per tool call to
%LOCALAPPDATA%/Reactor/devtools/{pid}.log (XDG_STATE_HOME/reactor/devtools
on non-Windows): UTC ISO timestamp, tool name, selector, latency ms, ok/err
flag, JSON-RPC result code. Rotation caps files at 10 MB and keeps the
newest five archives.
McpDispatcher threads the logger through Invoke() so every tools/call
records a structured line, distinguishing successful calls from thrown
McpToolExceptions. Log level is configurable via --devtools-log-level
(off|error|call|trace); ReactorApp wires it from the CLI parser.
LoggingTests covers level filtering, line shape, rotation archive shifting,
monotonic timestamps, non-negative latencies, and end-to-end dispatcher
integration. CliFlagParsingTests picks up the new --devtools-log-level
flag.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds src/Reactor/Hosting/Devtools/README.md covering the three gates (app-level opt-in, #if DEBUG in the scaffold, 127.0.0.1-only binding), the logging contract, the --print-config flow, and the "any local process can connect" caveat. Task doc annotates each 4.5 verification with the file/line that satisfies it. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
--mcp-transport stdio switches the devtools server to newline-delimited JSON-RPC over stdin/stdout. HTTP stays the default (spec §16 question #1); stdio is additive. StdioMcpLoop shares the McpDispatcher with the HTTP path so tools, logging, and error shaping are identical across transports. On stdio, stdout is reserved for framing so banner output ([devtools] ready, MCP_TRANSPORT, MCP_ENDPOINT) routes to stderr instead — otherwise we'd corrupt the agent's message stream on the very first announce. StdioTransportTests exercises ProcessLine, Run, blank-line skipping, pre-cancelled exit, and HTTP parity. CliFlagParsingTests picks up the new --mcp-transport flag plus the safe "unknown value keeps http" fallback. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds a DevtoolsFixtures suite under the TAP selftest harness that exercises
the MCP tool surface against a real WinUI window in-process: version,
components, windows, tree (summary + full + scoped), click, type, focus,
waitFor, toggle, invoke, state, screenshot, and structured-error round-trip.
38 assertions across 16 fixtures.
Uncovered a bug in DevtoolsMcpServer.OnDispatcher where a Task.Wait fault
re-wrapped the structured McpToolException in AggregateException, losing
the `{ code, ... }` payload before it reached the JSON-RPC error envelope.
Switched to ManualResetEventSlim + ExceptionDispatchInfo so the original
exception type surfaces.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses the agent field notes in docs/specs/tasks/ai-agent-devtools-feedback.md:
- B1 node-id collisions: TreeWalker now threads the immediate parent through
as the ancestor chain; NodeIdBuilder's loop still anchors to the nearest
stable ancestor when one exists, otherwise it walks to the root — two
same-typed siblings under different parents no longer collapse to the
same id. Regression tests added.
- B3 screenshot DPI: ScreenshotCapture scales DIP crop rects via
GetDpiForWindow before stacking the client offset. Previously the crop
landed ~(35, 60) px above the target on 125%-scaled displays.
- B4 Run<T> ignored: typeof(TRoot) is now threaded through TryRunDevtools
to RunRunSubverb as the default component, matching the host developer's
intent instead of picking the first-alphabetical helper.
- B5 [name=] on Button content: SelectorResolver.NameMatches falls back to
the same text extraction the tree walker reports, so [name='Increment']
matches a Reactor Button("Increment", …) even without AutomationName set.
- B6 waitFor soft-failure logging: McpDispatcher.Invoke inspects the return
value for ok:false and records the log line as err, so the rolling log
reflects outcome rather than just handler exits.
- B7 preview: deprecation in samples: TestApp, headtrax, and
validation-showcase all migrated to devtools: true.
- U6 fire safety: DevtoolsFireTool.ForbiddenMethods refuses Render /
OnInitialized / UseState / Dispose / etc. with a structured
forbidden-method error so an agent can't accidentally corrupt hook
state.
- U7 MCP handshake: dispatcher responds to initialize / ping /
notifications/* / resources.list / prompts.list so standard MCP clients
don't bail on their first round-trip.
Self-host fixtures added for each fix: NameSelectorMatchesButtonContent,
TreeIdsUniqueAcrossSiblingsWithDifferentParents, FireRejectsLifecycleMethods,
WaitForTimeoutLoggedAsErr, InitializeHandshake. Full unit suite (3688 tests)
green. B2 was already resolved by the prior Task.Wait → ContinueWith
refactor; resolution table in the feedback doc records the status.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Wires the node-registry invalidation into the switchComponent tool so an agent holding an id from before the swap sees a structured `gone` error instead of silently reaching a stale element. - DevtoolsTools.ToolHostContext gains an optional Nodes field; when set, switchComponent calls NodeRegistry.InvalidateWindow for every active window snapshot after a successful SwitchComponent callback. - ReactorApp.TryRunDevtools threads its NodeRegistry into the host context. - Devtools_SwitchComponentInvalidatesIds self-host fixture pins the invariant end-to-end via a minimal two-component harness (AltRoot + DevtoolsFixtureRoot) with a real switch callback on the McpHarness. Also ticks off pre-existing but still-unchecked items in the phase-2 plan that the self-host + runtime-tests already cover: resolver runs on the UI dispatcher, ambiguous-selector error shape, registry id stability across walks, TreeSchemaTests + WaitForPredicateTests unit coverage. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Open-item sweep across the devtools spec checklist.
- Supervisor --component positioning: the child's DevtoolsCliParser reads
the first positional after `--devtools run` as the component name, but
the supervisor was placing --mcp-port <N> before the positional, so <N>
(which doesn't start with '-') was picked up as the component name.
Reorder so the component positional comes first, extract the argv
builder for unit testing, and pin the ordering in
SupervisorArgsTests.BuildChildArguments_*.
- NodeRegistry two-walk id stability (§2.16): the reverse map is now
typed ConditionalWeakTable<object, string>, letting unit tests exercise
the production GetOrCreate code path with a sentinel object instead of
needing a live WinUI element. New tests cover same-target -> same-id,
distinct descriptors -> distinct ids, and resolution round-trip.
- Devtools_FireInvokesNamedHandler (§3.11): self-host fixture exercising
the fire tool's happy path — asserts the handler runs on the dispatcher
(state mutates), the response tag is `via: "reactor-event-injection"`,
and unknown event names round-trip as `{ code: "unknown-event" }` on
the wire.
- Stdio/HTTP parity (§4.1): parameterized parity across every dispatcher
method class (initialize, tools/list, tools/call ok+error,
resources/list, prompts/list, direct-name invocation), plus a mixed-
sequence test that runs a realistic agent session through stdio and
asserts each line matches what HTTP would return.
- Cross-phase coverage matrix filled in to reflect present unit +
self-host coverage; E2E rows remain unchecked until Appium rigging
lands.
All 184 tests/Reactor.Tests/Devtools/ tests green.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Expand the `fire` tool's MCP description to back-reference spec §11
("Automation verbs") and enumerate the UIA-first alternatives by name.
Agents that surface tool descriptions show this guidance verbatim, so
the back-link the spec §3.8 open item asked for reaches users before
they reach for the escape hatch.
- Bump the logger self-host fixture to 100 tool calls to match the
spec §4.7 text exactly (was 25 — the structural assertions are the
same, so the test coverage is identical in spirit, but the literal
100-call claim is now pinned).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Spec §3.13 exit criterion says the state tool works for every hook type Reactor ships. `RenderContext.SnapshotHooks` names the cells for useState, useRef, useMemo, useEffect, usePersisted, useContext, and useNavigationLifecycle — but nothing was guarding that against drift. `StateShapeTests.BuildPayload_OneOfEveryHookType_AllNamesRepresented` mounts an `AllHooksComponent` that calls each hook once, drives a manual render via the shared `ContextScope` helper pattern, then asserts every `hook` name appears in the `BuildPayload` output. Adding a new hook type in the future should require adding an arm here AND in SnapshotHooks, or this test fails — keeps the "every hook" coverage claim honest. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The switchComponent tool handler was executing on the HTTP worker thread. When the host-provided `SwitchComponent` callback called `ReactorHost.Mount(new T())`, WinUI's COM thread-apartment check raised an empty-message exception that surfaced as a generic `-32603 InternalError` with `message: ""` — the selftest fixture `Devtools_SwitchComponentInvalidatesIds` saw this as a missing `result` envelope and crashed on the `Result(switchResp)!.Value` unwrap. Wrap the whole handler (switch + window snapshot + id invalidation) in `server.OnDispatcher<object>(…)` so every WinUI touchpoint runs on the UI thread. Same pattern the UIA tools already use for click / type / focus. Self-host `Devtools_SwitchComponentInvalidatesIds` now passes — was failing pre-existing at commit 14a87df (the commit that introduced the test). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…e-selector subtree prune
Three pre-existing selfhost failures; each a real bug, not a
test-threshold relaxation.
1. `select`: the `itemSelector` lands on the inner content (TextBlock
for a ListView text item). `FrameworkElementAutomationPeer.CreatePeerForElement`
on a bare ListViewItem doesn't expose `ISelectionItemProvider`
(the peer needs its parent Selector's peer to route the pattern).
Walk up the visual tree to the first `SelectorItem` ancestor
(common base for ListViewItem, ComboBoxItem, ListBoxItem,
GridViewItem, TabViewItem, …) and flip `IsSelected = true`. Falls
back to the UIA ancestor walk for non-Selector containers.
2. `scroll` by-offset: if the container's axis is unscrollable,
`HorizontalScrollPercent`/`VerticalScrollPercent` return `-1`
(UIA `ScrollPatternNoScroll` sentinel). Calling `SetScrollPercent`
with a non-sentinel value on a NoScroll axis throws a bare COM
exception ("Cannot perform the operation") that surfaced as
`-32603 InternalError` with no structured data. Detect the sentinel
up front and throw a typed `{ code: "not-scrollable", axis }`
instead; pass NoScroll through when the caller didn't ask to move
that axis so SetScrollPercent leaves it alone.
3. `[name='X']` selector: a Reactor `Button("Increment", …)` reports
text "Increment" on itself AND on the TextBlock WinUI inserts
inside the button's template. Both matched, producing
`ambiguous-selector` with candidates `["#btn-increment","TextBlock"]`.
Add a `pruneSubtreeOnMatch` mode to `SelectorResolver.Collect` and
use it for AutomationName matches — the first matching ancestor
claims its subtree, so inner ContentPresenters mirroring the text
don't get collected as separate candidates.
Also relaxed the DataGrid scroll-ratio threshold from 1.2x to 1.4x
(user edit). The fixture compares DataGrid to bare VirtualList at
single-digit-ms medians where hardware and scheduler jitter dominate;
ARM64 dev boxes land at ~1.3–1.4x, x64 CI closer to ~1.1–1.2x. The
1.4x cap still fires on structural regressions (FlexRow wrapping,
redundant Yoga passes) which the fixture's comment calls out as 2x+.
All three test types green on this branch:
- Unit: 3703 passed / 46 skipped
- Selfhost: 0 not-ok
- E2E Appium: 106 passed
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ames Addresses the second-round AI-agent field feedback. Build still compiles and 3708 unit tests pass. - #2 Stable window id: WindowIdAllocator.Reserve pins the primary devtools window to "main" so the handle survives switchComponent changing the window title. Windows payload surfaces `currentComponent`. - #4 Scroll units + readback: description explicitly calls out percentage-delta semantics; response now carries `scrollOffsetPx` and `scrollableSizePx` dug out of the underlying ScrollViewer, and the -1 sentinel is replaced with null when an axis isn't scrollable. - #5 Accessible names at mount: the reconciler now mirrors visible captions into AutomationProperties.Name for Button, HyperlinkButton, RepeatButton, ToggleButton, DropDownButton, SplitButton, ToggleSplitButton, CheckBox, RadioButton, ToggleSwitch, TextField, and TextBlock. Author-supplied .AutomationName(...) still wins; the Update path handles label changes via a provenance-aware compare so author overrides are preserved. - #6 includeReactorSource rejection: tree tool returns structured not-implemented instead of silently no-opping. - #7 ComboBox expand/collapse: new `expand` / `collapse` MCP verbs wrap IExpandCollapseProvider; `select` auto-expands a closed container so the popup items resolve. - #9 Fire lambda confusion: unknown-event payload lists reachableMethods and explains inline lambdas aren't reflectable; tool description warns upfront. - Usability: GET /mcp self-describes (schema, protocolVersion, tools, selectorGrammar, events); tools/list adds _selectorGrammar + _treeSchemaVersion extensions so POST-based agents get the grammar without a second hop; components tool returns ComponentInfo[] with isNested/isPublic/namespace; AnnounceReady emits a {"event":"devtools-ready", ...} JSON sentinel alongside the human banner; full-view tree nodes carry supportedPatterns[] probed from the UIA peer. #8 (state selector scoping) deferred — requires reconciler component registry. The resolution table previously in the feedback doc is superseded; the doc itself has been removed from the working tree. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Short sub-skill covering launch (source flag + --devtools run both required), tool catalog, selector grammar, three recipes (layout diagnosis, WCAG contrast check, state-driven verification), and the gotchas that bit during a real smoke run against TestApp.
Contributor
There was a problem hiding this comment.
Pull request overview
This PR implements Spec 024 phases 1–4 by shipping a developer-only “devtools” surface: an MCP server (HTTP loopback + optional stdio framing), UIA-driven automation tools (tree/screenshot/click/type/scroll/etc.), a mur devtools supervisor for the reload-exit-42 loop, and supporting docs/tests. It also updates the WinUI reconciler to auto-populate AutomationProperties.Name from visible captions so both agents and accessibility tooling can target the same labels.
Changes:
- Add MCP server core (JSON-RPC dispatcher, tool registry, HTTP/stdIO transport), selector parsing/resolution, tree walking, screenshot capture, logging, and “fire/state” escape-hatch tools.
- Add
mur devtoolssupervisor +--print-config, plus CLI parsing and VS Code extension migration (--preview→--devtools runwith legacy fallback). - Add extensive unit + self-host fixtures coverage, update samples/docs, and tighten UIA naming defaults in the reconciler.
Reviewed changes
Copilot reviewed 61 out of 64 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/Reactor.Tests/Devtools/WindowIdAllocatorTests.cs | Unit coverage for stable window id allocation/slugging behavior. |
| tests/Reactor.Tests/Devtools/WaitForPredicateTests.cs | Unit coverage for waitFor predicate JSON → IR parsing. |
| tests/Reactor.Tests/Devtools/TreeSchemaTests.cs | Pins tree JSON schema shape and summary/full-field contracts. |
| tests/Reactor.Tests/Devtools/TreeFullViewTests.cs | Verifies full-view tree serialization behaviors. |
| tests/Reactor.Tests/Devtools/SupervisorArgsTests.cs | Arg parsing + child argv ordering for mur devtools. |
| tests/Reactor.Tests/Devtools/StdioTransportTests.cs | Stdio framing + parity vs HTTP dispatcher response JSON. |
| tests/Reactor.Tests/Devtools/StateShapeTests.cs | State shaping privacy contract tests for reactor.state. |
| tests/Reactor.Tests/Devtools/SelectorResolverRuntimeTests.cs | Structured error contracts for resolver node-id paths. |
| tests/Reactor.Tests/Devtools/SelectorParserTests.cs | Selector grammar parsing unit tests. |
| tests/Reactor.Tests/Devtools/PrintConfigTests.cs | --print-config output validity/shape tests. |
| tests/Reactor.Tests/Devtools/NodeRegistryTests.cs | Node id bookkeeping/tombstone behavior tests. |
| tests/Reactor.Tests/Devtools/NodeIdBuilderTests.cs | Stable node-id builder invariants + collision regression tests. |
| tests/Reactor.Tests/Devtools/McpDispatcherTests.cs | Dispatcher integration tests incl. selector grammar extension. |
| tests/Reactor.Tests/Devtools/McpDispatchTests.cs | JSON-RPC envelope serialization and registry behavior tests. |
| tests/Reactor.Tests/Devtools/LoggingTests.cs | Log line shape + rotation + dispatcher integration tests. |
| tests/Reactor.Tests/Devtools/FireResolutionTests.cs | Structured error contracts for reactor.fire target resolution. |
| tests/Reactor.Tests/Devtools/DevtoolsParamCompatTests.cs | --preview deprecation compatibility tests. |
| tests/Reactor.Tests/Devtools/DevtoolsFireToolTests.cs | Helper-method unit tests for fire tool (args/handler resolution). |
| tests/Reactor.Tests/Devtools/CliFlagParsingTests.cs | --devtools/--preview flag parsing tests incl. transport/log level. |
| tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs | Registers devtools self-host fixtures in the harness. |
| tests/Reactor.AppTests.Host/SelfTest/Fixtures/DataGridScrollFixtures.cs | Loosens perf ratio threshold + adds rationale for variability. |
| tests/Reactor.AppTests.Host/SelfTest/Fixtures/CoreCoverageFixtures2.cs | Adjusts visibility of ShouldUpdate override for coverage harnessing. |
| src/vscode-reactor/src/extension.ts | VS Code extension launch now prefers --devtools run with legacy --preview fallback. |
| src/vscode-reactor/out/extension.js | Built JS update: launch fallback, safer taskkill invocation, HTML escaping, HTTP status handling. |
| src/Reactor/Reactor.csproj | Exposes internals to AppTests host for devtools harnessing. |
| src/Reactor/Hosting/ReactorHost.cs | Exposes root component internally for devtools “fire/state” tools. |
| src/Reactor/Hosting/PreviewCaptureServer.cs | Renames capture log prefix from preview → devtools. |
| src/Reactor/Hosting/Devtools/WindowRegistry.cs | Tracks windows + stable ids for windows tool and scoping. |
| src/Reactor/Hosting/Devtools/WindowIdAllocator.cs | Implements stable window id allocation/slugging rules. |
| src/Reactor/Hosting/Devtools/TreeWalker.cs | Visual tree walker emitting summary/full tree payloads. |
| src/Reactor/Hosting/Devtools/StdioMcpLoop.cs | Newline-framed stdio MCP loop using the shared dispatcher. |
| src/Reactor/Hosting/Devtools/SelectorResolver.cs | Resolves selectors to UIElements with structured error payloads. |
| src/Reactor/Hosting/Devtools/SelectorParser.cs | Selector grammar parser producing IR. |
| src/Reactor/Hosting/Devtools/ScreenshotCapture.cs | PrintWindow-based PNG capture with DPI-aware cropping. |
| src/Reactor/Hosting/Devtools/README.md | Devtools security model + observability + print-config docs. |
| src/Reactor/Hosting/Devtools/NodeRegistry.cs | Stable node-id registry w/ tombstones and test hooks. |
| src/Reactor/Hosting/Devtools/NodeIdBuilder.cs | Pure stable node-id builder per spec rules. |
| src/Reactor/Hosting/Devtools/McpToolRegistry.cs | Tool descriptor/handler registry + tool exception type. |
| src/Reactor/Hosting/Devtools/McpDispatcher.cs | JSON-RPC dispatch (initialize/tools/list/tools/call/etc.) + logging hooks. |
| src/Reactor/Hosting/Devtools/JsonRpc.cs | JSON-RPC request/response model + error code constants. |
| src/Reactor/Hosting/Devtools/DevtoolsTools.cs | Registers core MCP tools (version/components/switch/reload/windows). |
| src/Reactor/Hosting/Devtools/DevtoolsStateTool.cs | Adds reactor.state payload building + value shaping. |
| src/Reactor/Hosting/Devtools/DevtoolsMcpServer.cs | Loopback MCP server + GET /mcp schema + dispatcher marshalling. |
| src/Reactor/Hosting/Devtools/DevtoolsLogger.cs | Rolling per-call logger with rotation. |
| src/Reactor/Hosting/Devtools/DevtoolsFireTool.cs | Adds reactor.fire escape hatch with structured errors/guards. |
| src/Reactor/Hosting/Devtools/DevtoolsCliParser.cs | Parses --devtools/--preview subverbs + options. |
| src/Reactor/Core/RenderContext.cs | Adds devtools hook snapshot extraction for reactor.state. |
| src/Reactor/Core/Reconciler.cs | Adds default AutomationProperties.Name population from captions. |
| src/Reactor/Core/Reconciler.Update.cs | Keeps default AutomationName in sync across updates. |
| src/Reactor/Core/Reconciler.Mount.cs | Applies caption-derived AutomationName after mount modifiers. |
| src/Reactor.Cli/Program.cs | Adds mur devtools command entry + template guidance update. |
| src/Reactor.Cli/Devtools/DevtoolsSupervisor.cs | Supervisor for reload-exit-42 loop + print-config output. |
| skills/devtools.md | New skill doc describing how agents use Reactor devtools/MCP tools. |
| SKILL.md | Index entry for the new devtools skill doc. |
| samples/apps/validation-showcase/App.cs | Updates sample to devtools: true in DEBUG. |
| samples/apps/headtrax/HeadTrax/Program.cs | Updates sample to devtools: true. |
| samples/Reactor.TestApp/App.cs | Updates sample to devtools: true in DEBUG. |
| docs/specs/notes/024-snapshot-diff-watch.md | Notes deferral of snapshot/diff primitives. |
| .claude/scheduled_tasks.lock | Adds a local lock file (should not be committed). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Six review comments from Copilot; each addressed: - Remove the stray .claude/scheduled_tasks.lock that leaked into the PR and add .claude/scheduled_tasks.lock + settings.local.json to .gitignore so the Claude Code harness can't reintroduce it. - DevtoolsStateTool no longer forces enumeration of an arbitrary IEnumerable to compute $shape.count — a helper probes ICollection / ICollection<T>.Count via a reflective fast-path and reports count:null for sources that don't advertise size (lazy, infinite, or side-effectful sequences) instead of potentially hanging. - SelectorResolver's ambiguity payload now returns the registry's stable node id per candidate (via a new NodeRegistry.TryGetId reverse lookup) when the walker has seen the element, falling back to the prior descriptor string only for never-walked elements; the class-level doc is updated to match the actual shape. - DevtoolsLogger.LogError now writes the same 6-TSV-column shape as LogCall — the human message rides in the selector column — so downstream parsers can treat every log line uniformly. - vscode-reactor extension.ts drops the unused awaitingLegacyFallback variable and the dead clearTimeout cleanup that referenced it. Compiled extension.js regenerated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
After the rebase onto main, two self-test fixtures (FocusChild in AsyncResourceFixtures, ReaderChild in UseMutationFixtures) still overrode Component<T>.ShouldUpdate with `protected override` while the base signature is `protected internal` — CS0507 on build. Match the base modifier. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced Jun 25, 2026
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 26, 2026
Hot keyed list-diff path (grid steady state) allocated heavily and missed fast-paths even when keys were unchanged. Eliminate per-diff allocations and add the missing fast-path, preserving diff behavior exactly. ChildReconciler.cs: - Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit that the positional path has, so stable keyed rows no longer re-diff every tick (#30); cache children.Count once instead of re-reading the COM IVector.get_Size per suffix iteration (#37). - Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto filling a pooled bool mask; pool tails/tailIndices/predecessors from ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests. - Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared and returned on every exit (#33). - Filter: count-pass + single Element[] fill, no List+ToArray (#36). - GetKey: cache Type.Name via ConcurrentDictionary (#38). KeyedListDiff.cs: - Rent newKeys from ArrayPool<string>, threading explicit newCount (rented array may be larger); returned clearArray:true in a finally (#2). - Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate scan so the steady-state grid case never allocates/scans a dup set (#1). - Fold the churn-bailout decision into ApplyGeneral, computed from the same post-prefix/suffix scratch map the general walk builds (diff-range churn == full-range churn), removing the O(2n) null-marker pre-pass (#34). - Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over [0,removes), cleared+returned) (#3). - Lazy-allocate movedRows only on an actual move under an ambient (#35). - In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10). - HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh HashSet (#11); cached null-key diagnostic sample (#41). Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count, interleaved independent states, randomized stress vs oracle with survivor identity, pooled doomed removes, churn with shared prefix+suffix, Scratch reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full Reactor.Tests suite green (9693 passed); core lib Release build is warning-clean (AOT/trim). Closes #653 Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
added a commit
that referenced
this pull request
Jun 27, 2026
…ff (#657) * perf: eliminate per-diff allocations in ChildReconciler + KeyedListDiff Hot keyed list-diff path (grid steady state) allocated heavily and missed fast-paths even when keys were unchanged. Eliminate per-diff allocations and add the missing fast-path, preserving diff behavior exactly. ChildReconciler.cs: - Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit that the positional path has, so stable keyed rows no longer re-diff every tick (#30); cache children.Count once instead of re-reading the COM IVector.get_Size per suffix iteration (#37). - Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto filling a pooled bool mask; pool tails/tailIndices/predecessors from ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests. - Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared and returned on every exit (#33). - Filter: count-pass + single Element[] fill, no List+ToArray (#36). - GetKey: cache Type.Name via ConcurrentDictionary (#38). KeyedListDiff.cs: - Rent newKeys from ArrayPool<string>, threading explicit newCount (rented array may be larger); returned clearArray:true in a finally (#2). - Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate scan so the steady-state grid case never allocates/scans a dup set (#1). - Fold the churn-bailout decision into ApplyGeneral, computed from the same post-prefix/suffix scratch map the general walk builds (diff-range churn == full-range churn), removing the O(2n) null-marker pre-pass (#34). - Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over [0,removes), cleared+returned) (#3). - Lazy-allocate movedRows only on an actual move under an ambient (#35). - In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10). - HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh HashSet (#11); cached null-key diagnostic sample (#41). Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count, interleaved independent states, randomized stress vs oracle with survivor identity, pooled doomed removes, churn with shared prefix+suffix, Scratch reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full Reactor.Tests suite green (9693 passed); core lib Release build is warning-clean (AOT/trim). Closes #653 Co-authored-by: Copilot <[email protected]> * perf: address PR review on keyed-diff allocation fixes Review follow-ups on #657 (keyed list-diff allocation work): - ChildReconciler.ReconcileKeyedMiddle: return the pooled matched and inLis bool[] buffers with clearArray:false instead of true (Copilot review). Both are value-typed (no reference pinning) and have their used range fully (re)initialized before any read - matched via the Array.Clear on rent, inLis via ComputeLISInto leading clear - so the full-array wipe on return was avoidable O(rented-capacity) work on the hot path. Matches how the int[] newToOld already returns. Reference-typed pooled buffers (string[]/ReactorRow[] in KeyedListDiff) still clear. - Tests (ChildReconcilerLisIntoTests): replace the circular oracle that compared ComputeLISInto against ComputeLIS (now a thin wrapper over it) with an independent brute-force LIS-length DP that honors the -1 unmapped sentinel, asserting the mask marks a valid strictly-increasing subsequence of maximal length. - Tests (ChildReconcilerKeyedSkipTests, new): cover the #30 keyed CanSkipUpdate fast path - an identical keyed list skips every row with no ops and no child-control access, across repeated stable frames. Co-authored-by: Copilot <[email protected]> * fix: correct keyed-middle reorder identity (C1/H1) + reorder & alloc tests The keyed-middle reconciliation in ChildReconciler patched surviving controls by their FINAL panel index while the panel was only partially rearranged, so on reorders a survivor was patched against the wrong control (C1, CRITICAL): e.g. rotation [a,b,c,d]->[b,c,d,a] rendered "c" at slot 0 and scrambled keyed identity (focus/animation/state landed on the wrong row). A related stale keyToIndex (only the moved key was rewritten) left shifted siblings mis-indexed after an insert/move (H1). Fix: extract the index logic into RunKeyedMiddleCore<TSink> behind a struct-generic IKeyedMiddleSink seam (devirtualized, AOT-clean) and replace the left-to-right loop with the canonical right-to-left LIS walk. Each item is positioned immediately before its already-placed right neighbour; LIS members stay put and only out-of-LIS movers relocate (minimal moves). Every survivor is patched at its CURRENT live position, resolved from a pooled oldRelToPanel int[] that is mutated in lock-step with every Insert/Move so it stays exact -- fixing C1 and H1 together. The production RealKeyedMiddleSink drives the identical Mount/Move/ UpdateChild/Unmount/Replace + ambient enter/move behaviour as before. oldRelToPanel replaces the second pooled key->index dict (one fewer rented dict per call). Tests: - ChildReconcilerKeyedMiddleCoreTests (new): a headless SimKeyedMiddleSink drives the SAME RunKeyedMiddleCore over identity cells (exact production parity, no live-WinUI selftest wall), with a 4-invariant oracle (length, prefix/suffix untouched, per-slot identity+content, every patch hits its claimed survivor) across rotation, full reverse, scramble, block-swap, inserts/removes/duplicates and prefix/suffix offsets. A faithful pre-fix reproduction proves the rotation regression test has teeth (the buggy walk corrupts content[0] and mis-patches; the real core is clean). - KeyedListDiffPoolingTests: two GC.GetAllocatedBytesForCurrentThread budgets guarding the #1/#2/#11 pooling -- no-op steady-state diff is 0 B/iter and a 128-key reorder is 72 B/diff; reverting the pooling (a new string[128] + a 128-entry HashSet per diff) fails them. Diff correctness preserved; pooled buffers returned on every exit. Co-authored-by: Copilot <[email protected]> * fix: gate keyed no-op fast path on duplicate-free state + test hardening Address Copilot re-review of e664f9f. KeyedListDiff: the no-op fast path runs above the duplicate scan (#1), so an UNCHANGED list that already holds duplicate keys -- the state a prior duplicate bailout leaves behind, since ReactorListState.Reset preserves the dups in Source/LastKeys but collapses ByKey to first occurrences -- would match LastKeys and return Empty, silently skipping the duplicate bailout/diagnostic and leaving the diff in an invalid duplicate state. Gate the fast path on `state.ByKey.Count == oldCount`: true exactly for the duplicate-free steady state (allocation-free path preserved), false when dups were collapsed (re-takes the bailout). The check is O(1) and short-circuits before the O(n) SequenceEqualOrdinal, so the common unique-key path pays nothing. No-op steady-state allocation stays 0 B/iter. Tests: - KeyedListDiffTests: new Apply_Unchanged_Duplicate_List_Re_Bails_Instead_ Of_NoOp_FastPath -- proves an unchanged duplicate list re-bails; verified to FAIL without the guard (takes the no-op path and returns Empty). - ChildReconcilerLisIntoTests: strengthen the LIS oracle to assert selected indices are never the unmapped -1 sentinel (a buggy impl could swap a real member for a -1 and still satisfy strictly-increasing + length). - KeyedListDiffPoolingTests: drop the unused `using System.Buffers;` (fully-qualify the one ArrayPool cref) flagged by the reviewer. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
--devtools/mur devtoolssurface (renamed from--preview) with a loopback MCP server, UIA-driven automation tools, and amur devtoolssupervisor that handles the reload-exit-42 loop.version,components,switchComponent,windows,treesummary/full,screenshot,click,type,focus,waitFor,invoke,toggle,select,scroll,expand/collapse,fire,state,reload) with structured error payloads, selector-grammar publishing (GET /mcp + tools/list extension), and a machine-readabledevtools-readybanner.AutomationProperties.Namefrom the visible caption at mount/update, soclick {selector:\"[name='+ 1']\"}and screen readers both see the same label without the author saying it twice. Author-supplied.AutomationName(...)still wins.Phase coverage
preview:→devtools:rename, CLI flag parsing, VS Code extension migration, scaffoldDevtoolsMcpServer, NodeRegistry, WindowRegistry, selector parser/resolver, version/components/switchComponent/tree/screenshot/click/type/focus/waitFor/reload +mur devtoolssupervisortree view=full, state tool, invoke/toggle/select/scroll/fire (root component only — child-registry deferred)--print-config, rolling log + observability, security review (loopback-only, DEBUG-gated)Items deferred:
reactor.stateselector scoping andreactor.firechild-component traversal both depend on reconciler-level component registration; carried forward as a follow-up.Field feedback addressed
Two rounds of hands-on agent feedback informed the final cut:
Round 1 (commit
bf7315d): duplicate tree ids, screenshot DPI,Run<T>ignored,[name='…']text fallback, waitFor soft-failure logging,preview:migration in samples,firelifecycle-method guard, MCPinitialize/ping/resources/list/prompts/listhandshake.Round 2 (commit
359ebf6): stable\"main\"window id, scroll unit + pixel readback, accessible-name defaulting at UIElement creation,includeReactorSourcerejection,expand/collapseverbs +selectauto-open,firelambda-confusion error (lists reachable methods), GET /mcp schema endpoint +_selectorGrammaron tools/list,supportedPatterns[]on full-view nodes,ComponentInfo.isNestedmarker, machine-readabledevtools-readyJSON sentinel.Test plan
tests/Reactor.Tests).DevtoolsFixturesintests/Reactor.AppTests.Host/SelfTest/Fixtures).docs/specs/tasks/ai-agent-devtools-implementation.md§2.18 / §3.12 / §4.8.Reactor.TestApp.exe --devtools run --mcp-port <N>+curl -X POST http://127.0.0.1:N/mcpfor each tool;GET http://127.0.0.1:N/mcpreturns the schema document.🤖 Generated with Claude Code