Repository navigation
Cooperative UI turns for concurrent winapp ui agents - #767
Conversation
Concurrent winapp.exe processes share one Windows desktop, so a command could steal focus or dismiss another workflow's transient UI even though the existing foreground guards stopped wrong-window injection. Add an owner-aware coordination service so desktop-driving commands take turns. Coordinator (Services/InteractiveDesktop): - Owner identity: WINAPP_UI_OWNER_ID, else the immediate parent process, else a one-command anonymous owner. Only a domain-separated SHA-256 key is persisted; the raw value never reaches disk, logs, or telemetry. - state.lock, atomically published state.json with schema versioning and unknown-field preservation, active.lock, and DeleteOnClose participant leases scoped per user and Windows session. - A pure, clock-injected scheduler implementing the forward barrier, FIFO promotion, four-second idle grace, and handoff. - Liveness is proven only by a held lease plus PID/start match: there are no heartbeats, so a suspended process keeps its place in the queue. Command integration: - New two-phase UiCoordinatedAction: all local validation runs in Preflight, so a malformed command never opens a lease, takes a ticket, or joins the queue. - All 21 ui commands declare a mode. active.lock is held only across the desktop-sensitive section, never across output formatting, PNG encoding or file publication. - Every DesktopExclusive command resolves and validates the HWND, PID and element it acts on inside that section, so nothing acts on state captured before an unbounded queue wait. - IDesktopForegroundService is now the only path to SetForegroundWindow and window restore. - send-keys no longer focuses its --target before foreground validation. - record is TurnShared so same-owner input interleaves; screenshot starts observational and escalates the whole invocation, discarding buffered captures and recapturing from the beginning. Also: privacy-minimized bucketed coordination telemetry, npm AbortSignal threaded through both spawn helpers, and documentation across the UI guide, usage, telemetry, JSON envelope reference, shipped skill, agent guidance, sample, and npm README. Refs #764
…ce tests Review round 2 findings, each with a regression test proven to fail without the fix: 1. Prior-boot idle deadline stranded the turn. Environment.TickCount64 resets on reboot, so a persisted deadline from a long-uptime session could hold the desktop for days. Normalize now clamps a deadline beyond now + IdleGraceMs, and the UTC diagnostic is overflow-safe. 2. Screenshot escalation swallowed OperationCanceledException and UiCoordinationException in its catch-all, reporting internal_error while the coordinator saw a normal completion and renewed the grace. All ten UI handlers now filter their catch-all with UiCoordinatedAction.IsCoordinationFault, and the coordinator no longer treats a cancelled token as a normal completion. 3. CompleteCommand rewrote the idle deadline without checking that the completing owner is the current owner, letting a foreign completion revoke or extend a stranger's grace. It now takes the full UiOwnerIdentity and mutates the deadline only on a match. 4. RegisterObserve ignored a Detached admission, leaving the lease open and completing against a foreign owner when ownership lapsed mid-registration. 5. IDesktopSection.EnterAsync documented reentrancy the implementation deliberately does not provide. 6. Missing state.json was treated as fresh unconditionally, so an external deletion while a participant was live could mint a second owner. It is fresh only with no live participant and a free active.lock. Also adds spec 18.3 real-app acceptance coverage: a tight burst protecting transient menu UI, a >4s reasoning gap forcing handover and replay, and a recording pinning its owner while same-owner input continues and another owner waits - driven by real separate winapp.exe processes against a real window. Co-authored-by: Copilot App <[email protected]>
…daries Recording/cancellation correction (reviewer): - bodyCompletedNormally now means "the body returned rather than threw", not "the token is unset". `ui record` observes Ctrl+C deliberately, finalizes the MP4 and returns success; per spec that is a completed command and must renew the owner's grace. The earlier generic token check wrongly denied renewal. Commands that must not renew let cancellation propagate instead, which is what the handler catch-all filters are for. - Added coverage on both sides: a queued screenshot escalation that is cancelled removes its ticket and renews nothing, while an active recording that finalizes on cancellation does renew. - Added handler-level coverage that UiScreenshotCommand lets a cancelled or refused escalation escape instead of flattening it to internal_error. Additional hardening: 1. InteractiveDesktopPaths.IsCurrentUserOnly now also requires the directory owner to be the current user: an owner implicitly holds WRITE_DAC and can rewrite even a protected, current-user-only DACL. The repair path re-reads and fails closed if ownership could not actually be taken. 2. UiSendKeysCommand now runs the same in-section HWND/PID validation as click and invoke. Without --target it could act on a recycled session handle; with --target the re-resolved element is verified to still belong to the session process before foreground, focus, post or send. 3. Lock acquisition no longer retries every IOException. Only ERROR_SHARING_VIOLATION (32) and ERROR_LOCK_VIOLATION (33) are contention; anything else fails desktop_coordination_unavailable instead of spinning forever on a failure that will never clear. ParticipantRegistry keeps its fail-safe-as-live probe (documented why it differs) but no longer reports a vanished lease as held. 4. Screenshot blank-retry foreground now goes through IDesktopForegroundService rather than a direct PInvoke.SetForegroundWindow seam, so every foreground change has one choke point. Added a guard test that scans production sources for direct SetForegroundWindow/ShowWindow calls outside that service, plus a self-check that the guard's pattern still matches. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds owner-aware cooperative turns so concurrent winapp ui workflows safely share the Windows desktop.
Changes:
- Adds lease-backed scheduling, desktop locking, recovery, cancellation, and telemetry.
- Coordinates all UI commands with post-wait target revalidation.
- Adds npm
AbortSignalsupport, documentation, and extensive tests.
Reviewed changes
Copilot reviewed 87 out of 87 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
src/winapp-npm/test/abort-signal.test.ts |
Tests abort propagation. |
src/winapp-npm/src/winapp-commands.ts |
Adds generated signal support. |
src/winapp-npm/src/winapp-cli-utils.ts |
Forwards abort signals. |
src/winapp-npm/src/ui-record-guard.ts |
Forwards recording signals. |
src/winapp-npm/scripts/generate-commands.mjs |
Generates signal options. |
src/winapp-npm/README.md |
Documents cancellation and ownership. |
docs/npm-usage.md |
Adds generated signal documentation. |
src/winapp-CLI/WinApp.Cli/Services/InteractiveDesktop/* |
Implements coordination state, scheduling, leases, locking, recovery, output, and telemetry. |
src/winapp-CLI/WinApp.Cli/Services/UiAutomationService.cs |
Injects foreground coordination. |
src/winapp-CLI/WinApp.Cli/Services/UiAutomationService.Screenshot.cs |
Coordinates screenshot escalation. |
src/winapp-CLI/WinApp.Cli/Services/UiAutomationService.Record.cs |
Coordinates recording operations. |
src/winapp-CLI/WinApp.Cli/Services/IUiAutomationService.cs |
Extends capture contracts. |
src/winapp-CLI/WinApp.Cli/Helpers/UiCoordinatedAction.cs |
Adds coordinated command lifecycle. |
src/winapp-CLI/WinApp.Cli/Helpers/IDesktopForegroundService.cs |
Centralizes foreground operations. |
src/winapp-CLI/WinApp.Cli/Helpers/DesktopTargetValidation.cs |
Validates targets after waiting. |
src/winapp-CLI/WinApp.Cli/Helpers/PointerCommandSupport.cs |
Routes foreground requests safely. |
src/winapp-CLI/WinApp.Cli/Helpers/UiJsonError.cs |
Adds coordination errors. |
src/winapp-CLI/WinApp.Cli/Helpers/UiJsonContext.cs |
Serializes coordination details. |
src/winapp-CLI/WinApp.Cli/Helpers/HostBuilderExtensions.cs |
Registers coordination services. |
src/winapp-CLI/WinApp.Cli/Commands/Ui*Command.cs |
Classifies and coordinates UI commands. |
src/winapp-CLI/WinApp.Cli/Program.cs |
Opens telemetry scope. |
src/winapp-CLI/WinApp.Cli/NativeMethods.txt |
Adds process-enumeration APIs. |
src/winapp-CLI/WinApp.Cli/Telemetry/Events/CommandCompletedEvent.cs |
Reports coordination telemetry. |
src/winapp-CLI/WinApp.Cli.Tests/InteractiveDesktopSchedulerTests.cs |
Tests scheduler semantics. |
src/winapp-CLI/WinApp.Cli.Tests/InteractiveDesktopStoreTests.cs |
Tests storage and recovery. |
src/winapp-CLI/WinApp.Cli.Tests/InteractiveDesktopLockTests.cs |
Tests lock lifecycle. |
src/winapp-CLI/WinApp.Cli.Tests/InteractiveDesktopMultiprocessTests.cs |
Tests cross-process coordination. |
src/winapp-CLI/WinApp.Cli.Tests/InteractiveDesktopRealAppTests.cs |
Tests real desktop workflows. |
src/winapp-CLI/WinApp.Cli.Tests/UiCommandTests.Coordination.cs |
Tests command classifications. |
src/winapp-CLI/WinApp.Cli.Tests/FakeInteractiveDesktopLock.cs |
Provides fake turns. |
src/winapp-CLI/WinApp.Cli.Tests/FakeDesktopForegroundService.cs |
Provides fake foreground operations. |
src/winapp-CLI/WinApp.Cli.Tests/DesktopPrimitiveGuardTests.cs |
Guards foreground-call conventions. |
src/winapp-CLI/WinApp.Cli.Tests/FakeUiServices.cs |
Extends UI test fakes. |
src/winapp-CLI/WinApp.Cli.Tests/UiCommandTests.cs |
Registers coordination fakes. |
src/winapp-CLI/WinApp.Cli.Tests/UiCommandTests.Record.Stdin.cs |
Updates handler construction. |
src/winapp-CLI/WinApp.Cli.Tests/UiAutomationServicePureTests.cs |
Tests coordinated blank retries. |
src/winapp-CLI/WinApp.Cli.Tests/RealUiAutomationTests*.cs |
Updates capture and recording tests. |
src/winapp-CLI/WinApp.Cli.Tests/GestureTargetingTests.cs |
Updates service test contract. |
src/winapp-CLI/WinApp.Cli.Tests/UiaTestFixture.cs |
Adds transient-menu fixtures. |
docs/ui-automation.md |
Documents cooperative turns. |
docs/usage.md |
Documents workflow identity. |
docs/telemetry.md |
Documents coordination telemetry. |
plugins/winapp/skills/winapp-ui-automation/SKILL.md |
Updates agent UI guidance. |
plugins/winapp/skills/winapp-ui-automation/references/ui-json-envelope.md |
Documents coordination errors. |
plugins/winapp/agents/winapp.agent.md |
Adds ownership guidance. |
samples/winui-app/README.md |
Demonstrates owner setup. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Build Metrics ReportBinary Sizes
Test Results✅ 5079 passed, 18 skipped out of 5097 tests in 888.9s (+277 tests, +93.9s vs. baseline) Test Coverage✅ 88.4% line coverage, 81.9% branch coverage · CLI Startup Time52ms median (x64, Try This BuildInstalls the MSIX for your architecture, replacing any previously installed build. Needs the GitHub CLI — the command offers to install it and sign you in if it is missing. & ([scriptblock]::Create((irm https://raw.githubusercontent.com/microsoft/winappCli/main/scripts/winapp-pr.ps1))) 767Switching between builds often?Put the tool on your PATH once: & ([scriptblock]::Create((irm https://raw.githubusercontent.com/microsoft/winappCli/main/scripts/winapp-pr.ps1))) -AddToPathThen this build is just: winapp-pr 767Run Updated 2026-09-09 06:56:05 UTC · commit |
… npm docs Fixes the five substantive review findings on the cooperative UI turns PR: - UiTurnAgeBucket was populated from the queue-wait stopwatch, so it duplicated the wait bucket and was always 0 for an immediate acquisition. The turn's claim tick is now persisted in state (TurnStartedTick64, written only by ClaimTurn alongside TurnId) so the bucket reports how long the owning workflow has held the desktop across all of its commands. - UiTurnAction.HandoffAfterIdle was unreachable: BeginParticipating normalized an expired owner away and then reported New. The previous owner key is now captured before normalization, so taking over a lapsed turn is distinguishable from finding a genuinely free desktop. - ui record's catch-all swallowed coordination faults, turning an active.lock failure into internal_error and letting the coordinator renew the owner's grace on a command that never ran. It is now filtered with IsCoordinationFault like the other eleven desktop-sensitive handlers. - The ui-json-envelope reference claimed an npm AbortSignal produces the native cancelled envelope and exit 130. Node force-terminates the child and rejects with AbortError; that row is now native Ctrl+C only. - CommonOptions.signal has a multi-paragraph JSDoc that was emitted verbatim into every generated Markdown table, terminating the row at its first newline. Table cells are now flattened, and signal is treated as a common option so it is documented once instead of in all 43 command tables. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 8ff5ec0b-09ea-4a4e-baef-2e5d807feb1e
H1 CI gating. InteractiveDesktopMultiprocessTests and InteractiveDesktopRealAppTests are gated on WINAPP_UI_MULTIPROCESS_TESTS=1, but no workflow ever set it, so all 11 skipped everywhere and the coordination protocol was effectively unverified in CI. They now run in the existing interactive e2e-test-ui job, after the CLI artifacts are downloaded, with the gate set explicitly. The step asserts against the TRX counters rather than the exit code, because a run that skips everything still exits 0: zero matched tests, any skip, or any failure fails the job. Verified both ways locally - 11/11 pass with the gate set, and with it unset the guard trips on 11 skips. The existing WinUI E2E step is untouched. H2 recording pre-start cancellation. The catch at UiRecordCommand ~400 swallowed a native Ctrl+C that arrived before capture started and returned 1. The coordinator decides whether to renew the owner's idle grace from whether the body returned or threw, so a recording that produced nothing looked like a completed command and kept the desktop reserved. It now propagates when the caller's token is cancelled, and InteractiveDesktopLock handles post-acquisition cancellation with the documented contract - exit 130, the `cancelled` envelope, no grace renewal - instead of letting it escape as "an unexpected error occurred". The established behaviour is preserved and pinned by its own test: an ACTIVE recording that observes cancellation, finalizes its MP4 and returns success is a completed command and still renews. H3 send-input focus drift. The foreground was verified before an awaited FocusAsync and never rechecked before injection. Setting focus can itself change the foreground - a focus handler activating another window, or any app stealing focus during the await - and the published repro exited 0 while HELLO landed in a decoy window. send-input now re-verifies after focusing; nothing between that check and keyboardInput.Send awaits. post-message posts straight to the target HWND's queue and is deliberately unaffected. H4 legitimate cross-process owned windows. DesktopTargetValidation rejected any target HWND whose PID differed from the session's, but GetAllAppWindows intentionally discovers cross-process windows the app OWNS - common-item file pickers and system dialogs - and tags elements with those foreign HWNDs, so every such target became unreachable after a queue wait. Validation now accepts a live target whose GW_OWNER chain reaches a live window belonging to the expected PID, mirroring the exact association discovery uses. Recycled-handle protection is preserved: each owner link is checked for liveness AND for belonging to the expected process, so a dead or reused owner cannot launder an unrelated window in. The walk is depth-capped and cycle-guarded. H5 future state version. InteractiveDesktopStateStore deserialized strongly before checking the version, so a newer schema that changes field SHAPES rather than merely adding fields threw JsonException and was classified as corruption - quarantined and replaced with a v1 document. The published repro had `owner` as a string and `ui list-windows` silently downgraded the file. The root version is now read with JsonDocument first and an unknown newer version returns UnknownNewerVersion before any typed deserialization, leaving the bytes untouched. Malformed JSON and a non-numeric version still take the existing corruption-recovery path. H6 foreground capture verification. screenshot --capture-screen and record --capture-screen requested the foreground and then BitBlt'd the screen without confirming activation took. SetForegroundWindow is advisory, so a refusal produced a PNG/MP4 of whatever window was actually in front while the command exited 0 - the repro captured a magenta decoy for a green target. Both paths now verify after the activation delay and immediately before capture, through one shared helper, and report the existing foreground_not_target contract rather than internal_error. No artifact is written on refusal. Window-targeted capture (WGC/PrintWindow) is unaffected. Regression tests fail before their fix and pass after: 10 for the owner chain, 3 for the version probe, 3 for focus drift, 2 for pre-start cancellation plus the positive finalized-recording case, 1 for post-acquisition cancellation, and 2 service-level plus 2 command-level for capture verification. Co-authored-by: Copilot App <[email protected]>
…ot loop Follow-up to H6, caught by self-review. CaptureForegroundNotTargetException derives from InvalidOperationException and is therefore not a coordination fault, so the per-window catch-all in CaptureMultipleWindows swallowed it, recorded it as a per-window failure, and ended with 'No windows could be captured' as internal_error - exactly the outcome H6 exists to replace. The path is reachable with plain --capture-screen whenever discovery finds more than one top-level window, or any owned dialog for a single-window session, which is the common case the flag is used for. The foreground is a property of the desktop rather than of one window, so a refused activation is not a per-window condition; it now propagates out of the loop the way DesktopEscalationRequiredException already does, and lands on the handler that reports foreground_not_target. Co-authored-by: Copilot App <[email protected]>
This comment was marked as outdated.
This comment was marked as outdated.
The canonical build publishes both win-x64 and win-arm64, and the CI lane downloads
the whole cli-binaries artifact, so BOTH runtime identifiers are on disk when the
newly enabled gated step runs. Both InteractiveDesktopMultiprocessTests and
InteractiveDesktopRealAppTests resolved the executable by probing a fixed
{ win-arm64, win-x64 } order and taking the first hit, which is a choice by luck
rather than by architecture: on the x64 windows-latest runner they would
deterministically pick the ARM64 binary and every child Process.Start would fail.
The bug was invisible locally because this dev box is arm64, where the wrong-order
probe happens to land on the right file - the same reason the gated suite passed
11/11 here while being broken for CI.
Resolution now lives in one shared WinappTestBinary helper rather than being
duplicated in both suites, and is driven by RuntimeInformation.OSArchitecture: an
arm64 host runs arm64 natively (x64 only under emulation) and an x64 host cannot run
arm64 at all, so the OS architecture is the one that is always executable. It is
fail-closed - only the matching RID is ever returned, never a different one. A build
that produced only the other architecture now fails with a message naming both the
required and the found RIDs, instead of skipping and reporting the suite as merely
"not run"; no build at all stays inconclusive, which is the ordinary local-dev state
and which the CI step's skip guard already turns into a job failure.
The RID choice is a pure function so both architectures are asserted from one
machine, which is what makes this regression testable at all: WinappTestBinaryTests
covers x64, arm64, that the two differ, that an unpublished architecture throws
rather than guessing, and that resolution never hands back a binary built for the
other architecture.
Also corrects a comment on the H4 owner-chain walk. It claimed to mirror "the exact
association" used by discovery, but GetAllAppWindows checks a single GW_OWNER hop
while the validator follows up to eight. The walk is a deliberate superset - a picker
can parent a nested dialog - and is safe because every hop enforces the same
property: the link must resolve to a live window whose PID equals the expected
process. Depth changes how far the chain is followed, never what qualifies as a
match.
Co-authored-by: Copilot App <[email protected]>
The agent half of the protocol was missing, so the command channel had nothing real to talk to and the update rules the spec requires had no implementation at all. Guest agent mode. A hidden `guest-agent` verb runs winapp as the persistent agent, and `GuestCommandServer` serves the same `IGuestTransport` the host channel consumes. Because both halves depend only on that interface, they are now run against each other in one process over an in-memory pair -- which proves the two implementations agree rather than each agreeing separately with a fixture. The agent implements no application semantics; every operation becomes an ordinary guest winapp child process, which is what keeps guest behaviour identical to local behaviour instead of a second implementation that drifts. Readiness is verified rather than assumed. `GuestSessionProbe` reads the real session, window station, and input desktop. Opening the input desktop is the load-bearing check: a closed Sandbox client leaves the guest session and UI Automation working while real input and Windows Graphics Capture stop, so capabilities report inspection as available in exactly the state where input must be refused. Agent versioning. `GuestAgentUpdatePlanner` decides reuse, stage, install, or fail using the stamped version *and* the binary hash: version alone cannot separate two builds of the same version, and the hash alone carries no ordering, so neither can tell an upgrade from a downgrade. A newer guest is never moved backwards -- it is reused when protocols overlap and reported incompatible when they do not, even under an explicit force-repair. `GuestAgentInstaller` stages, verifies the hash of what actually landed, self-tests the candidate in its own process, then activates by rename with the previous binary retained as last-known-good. The self-test runs before anything is swapped, so the common failure never leaves a target needing recovery. Owner-context forwarding. The guest agent is the parent of every guest child, so parent-derived owner identity would collapse every host workflow into one owner and let two workflows drive the same desktop at once. The host now resolves its owner with Cooperative UI Turns precedence and forwards an opaque token scoped to target and epoch; the raw explicit owner never leaves the host. This is only the forwarding contract -- the feature itself remains #767. 346 execution-target tests pass, up from 306. Verified against the real binary: `guest-agent --self-test` reports ready on an interactive host and the verb stays out of `--help`. Co-authored-by: Copilot App <[email protected]>
An independent review raised ten findings against the guest agent and deployment work. Nine were valid; each is fixed with a regression test that states the rule rather than covering a line. Readiness is a property of the moment, not of the connection. The capability handshake happened when the channel opened; a user can close the Sandbox window at any point after that, which silently removes real input while leaving UI Automation working. Requests now declare whether they inject input, and the guest re-probes immediately before starting one -- refusing rather than launching a process that would report input it never delivered. A cancelled upload left the guest holding the destination open. The host never sent a cancel for a file transfer at all: only execution had that path. It does now, and the guest disposes the partial write on receipt. The test that proves it cancels mid-transfer and immediately retries the same file, which is exactly what failed before. The no-downgrade rule had an architecture-shaped hole. Architecture was compared first, so a *newer* guest reporting a different architecture -- running emulated, for instance -- was replaced with an older host binary, a downgrade reached without ever comparing versions. Version ordering now comes first and has no exceptions, including under force-repair. An unorderable version also fails closed rather than being replaced: it cannot be proven older, so replacing it might be a downgrade. A forwarded owner must never be silently altered. The resolver trimmed whitespace and truncated oversized values; #767 preserves valid values byte for byte and rejects the rest. Trimming would merge two locally distinct workflows into one guest owner, and truncating would merge two distinct long ones -- both breaking the property forwarding exists to preserve. Invalid values are now refused, and the value itself never appears in the failure. Managed roots were walked and written through links. Enumeration skipped reparse *files* but recursed through reparse *directories*, so a junction made an entire outside subtree look like managed content. Enumeration no longer descends through any reparse point, and writes verify every ancestor, creating missing ones as they go so nothing can introduce a link between the check and the write. Reconciliation had two ordering bugs. A clean wipe ran before the dirty commit, so a crash between them left state claiming a complete deployment over an empty folder. And writes ran before deletes, which cannot work for a path that changed between file and directory -- the case reconciliation exists to handle. Dirty is now committed first, and removals precede writes. Job containment is layered. `Process.Start` cannot create a process already inside a job, so assigning afterwards leaves a window. The agent now places *itself* in a job at startup, and Windows puts every descendant of a job member into that job at creation with no window at all -- so nothing can escape the agent under any timing. The per-operation job still provides the finer-grained kill. The test now captures a spawned grandchild's own process ID and asserts on that. Also: the self-test never drained its candidate's output, so a candidate printing more than a pipe buffer would deadlock and look like a hang; it is now drained and the tree killed on timeout, which also releases the staged file. And standard input could overtake the request it belonged to, because the operation ID was published before the request was sent. Finding 1 was superseded: the hidden verb now constructs and serves a real agent through `GuestAgentRunner`. With the fixes in place, `sandbox exec` and `sandbox cp` land on top of them. Both are built on the primitives deployment already uses, so hashing, verification, atomic replacement, and containment behave identically however a file arrived -- a second transfer path would be a second set of bugs. Two of my own earlier tests asserted the pre-fix behaviour and were rewritten to state the corrected rules; leaving them would have pinned the bugs in place. 397 execution-target tests pass, up from 373. CLI schema regenerated for the new public commands, plus reference and concept documentation. Co-authored-by: Copilot App <[email protected]>
…perative UI turns Takes latest main as the baseline for every conflicting file - all 21 command handlers, the extracted WinApp.UIAutomation / .Recording packages and their tests, the shared test support fakes, and HostBuilderExtensions - and keeps the CLI-internal coordination infrastructure to be re-applied on top. WinApp.Cli/Services/IUiAutomationService.cs stays deleted; the CLI now consumes the package's IUiAutomation, IUiTargetResolver, IUiSelectorParser, UiTarget and UiSelector. The package surface is intentionally left coordination-blind, so this commit drops the IDesktopSection / observeOnly plumbing the branch had threaded through it. This resolves the merge only. The coordination layer is ported onto the new APIs in the commits that follow. Co-authored-by: Copilot App <[email protected]>
Two tiers replace three owner kinds. Collision arbitration stays unconditional for every desktop-sensitive mutation; continuity between commands is now opt-in. WINAPP_UI_OWNER_ID becomes WINAPP_UI_WORKFLOW_ID, because the value names one logical workflow rather than an agent, an app or a process. When it is absent the command gets a unique anonymous one-command owner: it queues and arbitrates like anyone else, but banks no idle grace and hands the desktop off the instant it finishes, so a one-shot can never strand the desktop waiting for a follow-up that is never coming. The parent-derived owner is deleted outright - UiOwnerKind.Parent, the parent PID/start fields on OwnerRecord and WaiterEntry, ReleaseDeadParentReservation, ICoordinationLivenessProbe.IsParentAlive, IProcessInspector.TryGetParentProcessId/TryGetProcessStartTicksUtc, the Toolhelp snapshot walk and its five NativeMethods entries, and the diagnostic parent PID in --verbose waiting output. Inferring a workflow from process ancestry silently grouped unrelated commands that merely shared a shell and just as silently split commands of one workflow that did not; continuity you cannot see is worse than none. The grace rule now reads off UiOwnerIdentity.HasContinuity, so the two-tier decision lives in one place instead of being re-derived per call site. Also restores IsIconic/ShowWindow to the CLI's NativeMethods after PR #799 moved the window P/Invokes into the package, and reads foreground state through the package's public ForegroundGuard.ForegroundBelongsTo. Both keep coordination CLI-side without adding anything to the package surface. Co-authored-by: Copilot App <[email protected]>
Re-applies cooperative-turn integration on top of main's package-based handlers, which the merge had reset. Every handler regains the two-phase shape: Preflight does local-only validation so a malformed command never opens a lease or joins a queue, and ExecuteAsync runs under the workflow turn. Mutating handlers take one desktop section around the work that touches the shared desktop, re-resolve their target inside it, and validate the HWND with DesktopTargetValidation before acting - a queued command may have waited an unbounded time, so anything resolved before the wait is advisory. Screenshot is now unconditionally DesktopExclusive and the entire Observe-to-exclusive escalation mechanism is gone: IUiTurn.EscalateToDesktopExclusiveAsync, the scheduler's EscalateObserveToExclusive transition, the observeOnly plumbing, the discard-and-recapture loop and DesktopEscalationRequiredException. Every capture path restores or foregrounds a window, so a screenshot was desktop-sensitive whatever its arguments; escalation bought a non-blocking start for a command that virtually always ended up blocking anyway, at the cost of a whole second capture pass and a mode that could change mid-command. The capture pass now runs under ONE section spanning discovery, revalidation and every window's pixels - compositing several windows only means something if they were captured against the same desktop state, and a per-window section would let another workflow foreground something between two frames. Encoding, PNG compression and the disk write sit outside the section: they are the slowest part of the command and touch no shared state. Recording holds the desktop only for as long as its capture mode needs it. For WGC and screen-DC it acquires the section before RecordAsync and releases it once the first frame is committed, so a workflow can record itself typing. The started callback only completes a TaskCompletionSource created with RunContinuationsAsynchronously - it never disposes the section, because disposal is async and would otherwise run on the engine's capture thread inside its own callback. Task.WhenAny races the started signal against the recording task so a run that faults, cancels or produces no frame still releases, and release is idempotent. PrintWindow is different: any frame there can trigger the engine's blank-frame foreground retry, so the section is held for the whole recording and the caller gets an actionable text + JSON warning. The predicted mode is asserted against the reported one so future engine drift surfaces instead of silently releasing the desktop mid-recording. Package-internal capture safety (not coordination): both ScreenshotAsync and RecordAsync now verify the target actually reached the foreground before a screen-DC capture and throw the package's existing ForegroundLostException if not. SetForegroundWindow is advisory, so without this a refused activation returned a valid-looking image of the wrong window while reporting success. Commands map it to the established foreground_not_target contract and write no artifact. No coordination type crosses into either package. Co-authored-by: Copilot App <[email protected]>
CommonOptions gains workflowId, applied to the spawned child's environment only. The wrapper never touches process.env: mutating it would silently enrol every later call in the process - including unrelated ones - into a workflow the caller meant for a single command, and would race across concurrent calls. Two tests pin that, one for an explicit id and one for an id inherited from the environment. Arbitration does not depend on this. Every desktop-sensitive winapp ui command takes a turn whether or not an id is set; what the id buys is continuity between invocations - a shared idle grace, permission to overlap (a recording and the clicks it records), and never being interleaved with another workflow's input. Documented that way in the README rather than as a switch that turns coordination on. Co-authored-by: Copilot App <[email protected]>
…y-opt-in The old docs led with 'set this variable so the CLI can tell your commands apart', which read like coordination was something you switch on. It never was: arbitration is unconditional and a workflow id only buys continuity between commands. Every surface now says that in the same order - arbitration first, then the opt-in. Also corrected across all surfaces: - WINAPP_UI_OWNER_ID -> WINAPP_UI_WORKFLOW_ID, invalid_ui_owner_id -> invalid_ui_workflow_id, telemetry identity values Explicit/Parent/Anonymous -> Workflow/Anonymous. - Dropped the claim that direct scripts are grouped automatically. There is no process-ancestry fallback any more, so without an id every command is its own one-shot - including several launched from one shell. - Ordering is described honestly as owner affinity first, then FIFO among the remaining workflows once the owner yields or its grace expires. It was previously implied to be strict FIFO, which it has never been. - screenshot is documented as always exclusive, with the escalation story removed, plus the fact that a multi-window composite is captured under one turn and encoded after the desktop is released. - record: a no-id recording blocks every other workflow for its duration, and PrintWindow hosts hold the desktop for the whole recording. - Both package READMEs state plainly that direct NuGet consumers are outside the CLI's coordination guarantee and must serialize themselves. Co-authored-by: Copilot App <[email protected]>
Retargets every coordination test onto the two-tier owner model and the package APIs, and deletes the tests for concepts that no longer exist rather than adapting them: parent-derived owner identity and liveness, and the screenshot observe-to-exclusive escalation including its cancellation and unknown-version paths. New coverage for the semantics the redesign actually promises: a named workflow banks the four-second grace while an anonymous one banks none; two no-id resolutions produce different owners; an anonymous completion hands off on the next normalization; a no-id recording blocks a no-id click while the same workflow id lets a recording and a click overlap; owner affinity lets the current owner continue ahead of waiting foreign owners, with FIFO applying among those waiters only after it yields; and a persisted grace survives with no live participant lease. Screenshot tests assert it is always DesktopExclusive, that a multi-window composite is captured under exactly one desktop section, that the section is released before encoding and writing, and that a foreground refusal writes no artifact. Record tests cover the first-frame release, release on failure or cancellation before the callback, a late or duplicate callback, the PrintWindow full-duration hold and its warning, and predicted-versus-actual mode disagreement. Package foreground-loss safety is tested in WinApp.UIAutomation.Tests using no coordination type, and PublicApiSurfaceTests proves neither package exports one. Co-authored-by: Copilot App <[email protected]>
…cording test RecordAsync_CaptureScreen_UsesConsentedScreenPath drives the real recording service against a real fixture window, so the engine's new pre-capture foreground check applies to it. The test now brings the fixture to the foreground the way a user would, via the existing DesktopTestHelpers.ForceForeground, and reports inconclusive only if the session refuses activation outright - the refusal path itself is covered directly by CaptureForegroundSafetyTests. The foreground question is asked through the shipped ForegroundGuard rather than a private P/Invoke so the test asks exactly what the engine asks. Co-authored-by: Copilot App <[email protected]>
An independent review of the integrated feature found six defects that all share a shape: something is checked once, and then acted on later as if the check still held. Each is fixed at the point of use, and each fix has a test that fails without it. A blocked "recording started" write no longer holds the desktop. The engine raises its first-frame callback on the capture thread, and the CLI both signalled its own "the desktop is free" gate and wrote the liveness JSON from inside it. Writing first meant a caller slow to drain stderr — a full pipe, a paused consumer — pinned the capture thread in the callback, so the gate never fired and the section stayed open for every other winapp ui command on the machine. The signal now goes first, which is what makes the release independent of the reader. Recording revalidates its target inside the section. The target is resolved before the command queues; by the time the turn is granted the window may have closed and Windows may have reused its handle. Without the check the command recorded the new occupant and exited 0 — a video of the wrong application is indistinguishable from a correct one. The multi-window screenshot composite had the same hole and never validated any handle, because it branches to the composite path above the single-window check; each handle is now classified before capture and a recycled one is reported as not captured instead of being spliced into the image. ui wait-for propagates cancellation. Its dedicated catch returned an exit code, and the coordinator decides whether to renew the owner's idle grace from whether the body returned or threw — so an interrupted wait renewed grace for a workflow that had already stopped. Worse, the inner polling catch swallowed cancellation too, so --gone could report the element as gone: a success, invented from a Ctrl+C. Screen recording checks the foreground once more before any file exists. The existing check ran right after the activation delay, with selector resolution still to come; it now sits immediately above encoder creation, which is the last moment a refusal leaves no MP4 behind — the contract the foreground_not_target path states. npm uiRecord forwards workflowId. Both wrappers passed only cwd and signal, so a recording started through the SDK became an anonymous one-shot and blocked its own workflow's clicks for the whole recording, which is the exact scenario workflow ids exist for. Also removes the last two references to the deleted owner-id contract — a sample that still set WINAPP_UI_OWNER_ID and an unused error constant mirroring it — and states on WINAPP_UI_LOCK_DIRECTORY that cooperating processes must agree on it, since the recovery hints that mention it previously did not say so. Co-authored-by: Copilot App <[email protected]>
…ation Both readmes already told direct consumers they are outside the CLI's cooperative desktop turns. Two gaps remained against what a reader needs to act on. Neither said the words a reader is looking for - that package calls do not participate in the CLI's workflow arbitration - so the boundary read as a general caution rather than a specific one. And only the UIAutomation readme offered the alternative to serializing yourself: running somewhere nothing else is driving the desktop. That advice is most useful to the recording package, which is the one that can capture a whole screen, where another workflow's clicks and menus land in the video rather than merely racing it. The UIAutomation note points at its own 'Input injection drives the real mouse and keyboard' section instead of restating the desktop guidance, so the advice stays on one canonical surface. No API, behavior, or package contents change: readme text only. Co-authored-by: Copilot App <[email protected]>
Closes #764.
Multiple
winapp.exeprocesses share one signed-in Windows desktop but Windows exposes only one foreground window, keyboard focus, cursor, andSendInputstream. Without coordination, concurrent agents can steal focus, dismiss transient UI, invalidate resolved targets, or act on the wrong app.This PR adds cooperative UI turns with two deliberately separate guarantees:
winapp uicommand participates automatically.WINAPP_UI_WORKFLOW_ID(or npmworkflowId) form one logical workflow and retain the turn for a four-second tight-burst grace, or release it early withwinapp ui yield.A command without a workflow ID is a unique anonymous one-shot. It still waits safely, but receives no post-command grace and hands off immediately. There is no parent-process inference.
Command model
Observestatus,list-windows,inspect,search,get-*,wait-forTurnSharedactive.lock. Compatible same-workflow work may overlap; an earlier same-workflowDesktopExclusivecommand still orders itrecord,set-value,scroll-into-view, UIA scroll (--direction/--to)DesktopExclusiveactive.lockaround physical desktop workinvoke,click,drag,hover, wheel scroll,touch,pen,focus,send-keys,screenshotset-value,scroll-into-viewandscroll --direction/--todrive UIA patterns rather than the foreground, so they never takeactive.lockand stay headless/locked-session friendly. But they change what the app shows, so they wait behind a foreign workflow rather than editing a field or scrolling a list out from under another agent'ssend-keysorhover.scroll --wheelsynthesizes real mouse input and remainsDesktopExclusive.Releasing the turn early:
winapp ui yieldThe four-second grace is a fallback for when a workflow cannot say it is finished. When it can,
winapp ui yieldends the grace immediately and hands the desktop to whoever was waiting.It is deliberately not a coordinated command: registering it as a participant would make it the very live command that stops a turn being idle. It takes
state.lockonly — no lease, no owner-command entry, noactive.lock, no grace-renewing teardown — ends the grace, promotes the next waiter and signals it in one transaction, and reportsreleased: trueonly after that reaches disk.WINAPP_UI_WORKFLOW_ID. Absent isinvalid_arguments, decided before state is read; present-but-malformed still reportsinvalid_ui_workflow_id.{"released": false}and exit 0.ui_turn_busywhen this workflow still has a command running or queued. The running command is unaffected.Ordering is owner affinity first, then FIFO among live foreign waiters. Continuous activity by one explicit workflow can delay others indefinitely. Anonymous commands receive zero grace; explicit workflows receive four seconds after normal completion. There is no hard live-command duration limit.
Runtime protocol
Per current user and Windows session:
state.lockprotects short metadata transitions only.state.jsonstores the current owner, commands, grace deadline, tickets, and foreign FIFO.active.lockcovers only restore, foreground, focus, cursor, input, live-screen capture, or equivalent physical-desktop work.FileShare.None + DeleteOnCloselease as crash-safe liveness proof.Waiting is push-based. A transaction that makes commands runnable publishes authoritative state and signals exactly those participants. A signal is only a doorbell: every wake reacquires
state.lockand verifies that the participant isRunningbefore executing.Sparse recovery deadlines cover cases where nobody can signal:
The foreign FIFO admits at most 64 live commands from other workflows. The cap does not count processes that have not registered or commands waiting behind their own current workflow. Dead lease entries are pruned before capacity is evaluated.
Safety and recovery
{}or incomplete nested command/waiter is corruption, not a fresh desktop; with any live lease oractive.lock, recovery fails closed and leaves the bytes untouched.WINAPP_UI_LOCK_DIRECTORYoverride are never touched.Screenshot and recording
Every CLI screenshot is conservatively
DesktopExclusive. One active section spans rediscovery, validation, and the complete multi-window pixel-capture pass; composition, PNG encoding, disk writes, and output occur after release. Foreground refusal writes no artifact. If-amatches several top-level or owned windows,--capture-screenfails withinvalid_argumentsbefore foregrounding or capturing anything and points atlist-windows+-w <hwnd>: live-screen capture records whatever is in front, and only one window can be, so compositing several is unsatisfiable. An explicit-w <hwnd>is not ambiguous — it names one screen region, including anything visibly on top of it — so it does not expand to owned windows. Window-content capture is unaffected and still composites.Live-screen capture uses a capture-specific foreground predicate. Input injection stays strict — a dialog in front would swallow the keystrokes — but capture also accepts a foreground window whose bounded
GW_OWNERchain reaches the target, because a modal dialog the target owns is part of that app's UI and is sitting on the pixels being read. An unrelated window is still refused, so a capture never returns somebody else's window labelled as yours. Screenrecorduses the same predicate at both of its pre-frame checks, and a refusal still writes no artifact.recordisTurnSharedfor its full lifetime:active.lockthrough the first committed frame and then releases it;active.lockfor the full recording because any frame may need foreground recovery.Package and npm boundary
Coordination remains entirely in
WinApp.Cli. The reusable UI Automation and Recording NuGet packages expose no workflow, owner, turn, queue, lock, or signal API — no coordination concept or type was added to either package. Direct package consumers retain ordinary behavior and remain outside thewinapp.exearbitration guarantee.One additive public member was needed:
ForegroundGuard.ForegroundIsCapturableFor(long), the capture-only foreground predicate shared by screenshot and screen recording.InternalsVisibleTocannot be used between these assemblies — both run the CsWin32 generator, so sharing internals makesWindows.Win32.PInvokeambiguous (CS0436, fatal under Release warnings-as-errors), a constraintPublicApiSurfaceTestsalready documents — and the alternative was a second copy of a safety check in the Recording package, which is how these two paths came to disagree in the first place. It adds no type, sits beside the existingForegroundBelongsToon the same already-public guard class, and is documented inWinApp.UIAutomation/PACKAGE.md.Generated npm options add
signal?: AbortSignalandworkflowId?: string.workflowIdis copied only into the spawned child's environment; globalprocess.envis never mutated.uiYield({ workflowId })follows the same rule. Abort force-terminates the child on Windows, while leases let other coordinators recover stale state.Regular-command overhead versus pre-feature main
A dedicated ARM64 NativeAOT A/B compared coordination head
fc9ef956with pre-feature main1567b08a, which has no coordination implementation. Both direct binaries and disposablepackagedClassicApp/mediumILidentities used the same real WinForms fixture and successfulInvokePatterncommand.ui invokeAcross repeated packaged runs, measured overhead was 7.7–15.3 ms (7–15%), not the separately reported 2.3–2.5 seconds. The fixed cost breaks down to roughly 4 ms of added service construction, 7 ms of turn admission/state publication, and 5 ms of deliberate post-wait target revalidation. A lazy event-creation variant saved less than 1 ms and did not improve queue throughput, so it was not adopted.
The same harness drained 64 final-head commands in 3.89 seconds with 64/64 success and no lost wakes. Raw samples, exit codes, interleaved A/B scripts, and the full report are retained in the session artifact
files/perf-767-final/.Queue performance
Measured A/B with NativeAOT binaries, identical harness/commands, and isolated lock directories:
At 70 processes, targeted wakes delivered a 9.3× faster drain and 17.7× less CPU, with no stranded process. Admission and promotion also reuse already-normalized state instead of repeatedly reopening every participant lease.
Validation
Final head
c33f7f2c, with currentorigin/main(e3c1449b) merged in — the branch is not behind.GetLatestVersionAsync/GetPackageDependenciesAsync/AnalyzeDumpAsync, which resolve packages from a live NuGet feed that is unreachable from this machine; none are in any file this PR touches.format:checkandeslintclean.scripts/build-cli.ps1green; Release solution build clean; fresh x64 + ARM64 NativeAOT publish; all four NuGet packages produced; zero generated-doc drift.scripts/validate-plugin-package.ps1: Agent Plugins 1.0 conformant.Runtime evidence on published binaries
Real
winapp.exechild processes, isolated coordination namespaces, same harness for each A/B.ui yieldui yieldduring a same-workflow recordingui_turn_busy, exit 1; recording still exited 0set-valuewhile another workflow holds the turnObserve)set-valueafter its own commandset-valueduring its ownrecordactive.lockprobed 40× while aTurnSharedscroll ranPer-command latency on the same binary, cold run discarded:
--version(no coordination)ui inspect(Observe)ui set-value(TurnShared)ui click(DesktopExclusive)ui yield(rejected, no workflow id)Reclassifying
set-valuecosts ~9 ms on a solo command — the same admission cost an exclusive command already paid.Documentation covers the workflow contract, the three-mode command model,
ui yield, targeted wake/recovery protocol, exact queue-capacity semantics, JSON errors, npm behavior, package guarantee boundary, and shipped agent guidance.