Skip to content

[Feature]: Run and automate apps in persistent Windows execution targets #769

Closed

Description

Is your feature request related to a problem? Please describe.

Windows UI automation currently runs on the user's interactive desktop. Agent workflows can steal focus, move the cursor, type into the wrong application, or require the user to stop using their machine while testing runs. Manually orchestrating Windows Sandbox also requires callers to start/connect the environment, provision runtimes, transfer files, launch guest processes, route UI commands, and retrieve artifacts.

We want winapp to make isolated execution nearly invisible while preserving fast local builds and the existing run/UI command model.

Describe the solution you'd like

Winapp Windows Sandbox Execution

Status

Proposed specification for review.

This document covers transparent Windows Sandbox execution in winapp.
Opt-in unique package identity generation is intentionally specified separately.

Summary

Winapp will allow applications to be built on the host and run, debugged, and
automated inside a persistent Windows Sandbox.

Windows Sandbox is the only public execution environment in v1. Internally,
environment acquisition and transport are isolated behind a narrow execution
target boundary so future Hyper-V, Dev Box, or remote-machine implementations
can reuse deployment, runtime, UI, and artifact orchestration without rewriting
the feature.

The common workflow is:

winapp run . --sandbox
winapp ui inspect --sandbox -a MyApp
winapp ui invoke --sandbox SubmitButton -a MyApp

Winapp automatically:

  1. Builds and resolves the application on the host.
  2. Starts or reuses the single Windows Sandbox instance managed by winapp.
  3. Prepares the interactive Sandbox session without taking host focus.
  4. Installs or verifies supported shared runtimes.
  5. Synchronizes the application into guest-local storage.
  6. Registers and launches the application using guest winapp.
  7. Routes Sandbox UI commands to guest winapp.
  8. Copies generated artifacts back to host paths.

The Sandbox remains active across application exit and subsequent builds. Users
manage its lifecycle through the existing Windows Sandbox CLI:

wsb list
wsb connect --id <id>
wsb stop --id <id>

Goals

  • Make running a Windows application in Sandbox a one-flag operation.
  • Keep Sandbox applications and real input automation from disrupting the host
    user's desktop.
  • Reuse Sandbox across rebuilds to make iterative development fast.
  • Allow multiple trusted applications and workflows to share the Sandbox.
  • Preserve Cooperative UI Turns semantics when UI commands are forwarded through
    the persistent guest agent.
  • Preserve existing winapp run and winapp ui behavior where practical.
  • Guarantee the WinUI/.NET development and UI testing workflow.
  • Allow other application frameworks to work when their artifacts and guest
    prerequisites are sufficient.
  • Give agents generic command and file-transfer escape hatches for additional
    setup, diagnostics, and workflows.
  • Keep the guest protocol and application orchestration independent of Windows
    Sandbox so another Windows execution target can be added later.

Non-goals

  • Isolating the host from restore or build scripts. Builds still run on the host.
  • Isolation between applications or workflows sharing the same Sandbox.
  • Multiple simultaneous Windows Sandbox instances.
  • Hyper-V, Dev Box, cloud, or other execution providers.
  • Building source inside Sandbox.
  • Visual Studio remote debugging.
  • Full terminal or ConPTY fidelity for forwarded commands.
  • Public arbitrary SYSTEM-context command execution in v1.
  • Automatic Sandbox shutdown or idle timeout in v1.
  • General Sandbox lifecycle management in winapp.
  • A public multi-target model, provider plugin system, target configuration
    files, target discovery, or automatic provider selection in v1.
  • Package identity rewriting. That is covered by a separate specification.

Platform requirements

Sandbox execution requires:

  • Windows 11 24H2 or newer.
  • A supported Windows edition.
  • Hardware virtualization enabled.
  • The Windows Sandbox optional feature installed.
  • A compatible wsb.exe command-line interface.
  • An unlocked interactive host session while foreground-sensitive automation is
    required.

Winapp does not enable Windows features, change firmware settings, or reboot the
host. Missing prerequisites fail before application build or Sandbox mutation
when they can be detected cheaply.

There is no silent fallback to local execution.

Security and trust model

--sandbox provides runtime isolation for the launched application. It does not
make an untrusted project safe to restore or build because project evaluation,
package restore, and compilation occur on the host.

All applications inside the shared Sandbox are trusted as the same host user.
They share:

  • The Sandbox user account.
  • Processes and the interactive desktop.
  • Registry and package registration state.
  • Installed runtimes.
  • Guest filesystem permissions.
  • Network access.

Applications can observe or interfere with one another. Mutual workflow
isolation requires separate machines or a future provider.

The host/guest connection and file exchange are treated as untrusted:

  • Every Sandbox generation receives a random connection identity and
    authentication secret.
  • The guest accepts commands only after an authenticated and encrypted
    handshake.
  • Requests use structured executable and argument arrays, never shell
    interpolation.
  • Message framing, protocol versions, operation IDs, sequence numbers, sizes,
    and payload types are validated before dispatch.
  • Paths are canonicalized and restricted to managed roots.
  • Reparse-point and path-traversal escapes are rejected.
  • Guest-provided paths never directly select arbitrary host destinations.
  • Authoritative host state remains outside guest-writable staging.

Authentication and encryption protect the command channel from unrelated host
or network callers. They do not isolate the agent from applications running as
the same Sandbox user. Co-resident guest applications remain mutually trusted
for v1 and may be able to inspect, terminate, or interfere with the guest agent
and other guest processes.

Public CLI

Run

winapp run <input> --sandbox [existing run options]

Examples:

winapp run . --sandbox
winapp run .\MyApp.csproj --sandbox --detach --json
winapp run .\publish --sandbox --debug-output

--sandbox selects the deployment and execution environment. Host-side build
options continue to apply on the host; launch and debug behavior occurs inside
Sandbox.

UI automation

Every winapp ui verb accepts a recursive --sandbox option:

winapp ui inspect --sandbox -a MyApp
winapp ui inspect --sandbox -a 4212
winapp ui inspect --sandbox -w 123456
winapp ui screenshot --sandbox -a MyApp -o .\result.png
winapp ui record --sandbox -a MyApp --duration-sec 5 -o .\result.mp4

When --sandbox is present, the complete UI command is forwarded to guest
winapp. The host does not perform UI Automation, window discovery, capture, or
input injection.

String application targets may also opt into Sandbox routing:

winapp ui inspect -a sandbox:MyApp
winapp ui inspect -a sandbox:4212

The prefix is removed before guest execution.

Numeric --window remains unchanged and requires --sandbox for guest
routing:

winapp ui inspect --sandbox -w 123456

Sandbox UI commands preserve the existing explicit targeting contract. If
neither --app nor --window is provided, the command fails and lists
copyable guest targets. winapp ui list-windows --sandbox is the discovery
path; action commands never silently infer the most recent or only managed
launch.

Unregister

winapp unregister --sandbox [existing unregister options]

This unregisters only the exact managed guest package associated with the
resolved input/manifest. It never unregisters by package name alone and never
removes an unmanaged package.

Generic command execution

winapp sandbox exec [options] -- <executable> [arguments...]

Examples:

winapp sandbox exec -- dotnet --info
winapp sandbox exec --cwd C:\Work -- powershell -File .\test.ps1

Behavior:

  • Ensures or reuses the managed Sandbox.
  • Runs as the interactive Sandbox user.
  • Preserves argument boundaries.
  • Streams stdin, stdout, and stderr.
  • Returns the guest process exit code when transport succeeds.
  • Distinguishes host, transport, guest-winapp, and application failures.
  • Ctrl+C first requests graceful termination, then force-kills the process Job
    Object after a timeout.
  • Does not provide a full TTY or ConPTY. Interactive console applications may
    observe redirected pipes.

Generic command arguments, paths, stdin, stdout, and stderr are excluded from
telemetry.

V1 does not expose arbitrary SYSTEM-context execution. Fixed privileged setup
operations required by winapp, such as enabling guest development
prerequisites, use narrowly scoped internal helpers with fixed executable and
argument contracts.

sandbox exec forwards the caller's Cooperative UI Turns owner context into
the guest environment. This allows a script executed through sandbox exec to
invoke guest winapp ui commands without losing workflow ownership.

File copy

winapp sandbox cp <source> <destination>

Exactly one endpoint must use a sandbox: prefix:

winapp sandbox cp .\setup.ps1 sandbox:C:\Setup\setup.ps1
winapp sandbox cp .\build sandbox:C:\Work\build
winapp sandbox cp sandbox:C:\Results .\results

Copy supports files and directories, preserves directory structure and useful
timestamps, skips unchanged files, and atomically replaces changed destination
files. It does not expose arbitrary mapped host folders to guest applications.

The sandbox namespace is limited to exec and cp. Lifecycle, images,
snapshots, ports, providers, shells, and package-manager commands are not added.

Framework support

Guaranteed v1 workflow

The supported and tested profile is WinUI/.NET:

  • Packaged .NET WinUI project mode.
  • Framework-dependent .NET WinUI applications.
  • Self-contained .NET/WinUI applications.
  • Packaged and unpackaged forms already supported by winapp run.
  • Prebuilt .NET outputs with sufficient runtime and package metadata.

Winapp automatically provisions the required:

  • .NET runtime.
  • .NET Desktop Runtime.
  • Windows App Runtime framework packages.
  • Required VC runtime packages.
  • Developer Mode and loose-registration guest prerequisites.

Other frameworks

Other frameworks are not rejected merely because they are not WinUI/.NET.

They should work when:

  • The application is self-contained or its runtime is already present.
  • Existing winapp run can resolve and launch its artifact.
  • The required guest dependencies have been installed.

Agents can use winapp sandbox exec and winapp sandbox cp to prepare
self-contained application layouts and supported user-scoped dependencies:

winapp sandbox cp .\dist sandbox:C:\Work\MyElectronApp
winapp run .\dist --sandbox

Winapp does not guarantee automatic runtime inference or provisioning for other
frameworks in v1. Failures should identify the missing dependency or setup step
when possible.

Existing run option semantics

Sandbox mode preserves the existing run option matrix.

Option Sandbox behavior
--detach Return after guest launch; app and Sandbox remain running.
--debug-output Run debugging inside guest winapp and stream output.
--no-launch Deploy/register in Sandbox without launching.
--clean Clear only the target guest package's application data.
--unregister-on-exit Unregister that guest package after its tracked process exits; Sandbox remains running.
--with-alias Launch the guest execution alias with forwarded stdin/stdout/stderr. Full terminal/TTY semantics are not guaranteed.
--json Keep stdout machine-readable; progress and diagnostics use stderr.

Host-only build options retain their current meanings before guest deployment.

Output and JSON

Without --sandbox, existing output and JSON schemas remain unchanged.

Sandbox mode may add optional fields:

{
  "processId": 4212,
  "processScope": "sandbox",
  "appTarget": "sandbox:4212",
  "aumid": "Contoso.MyApp_...!App",
  "sandbox": true,
  "executionTarget": {
    "kind": "windows-sandbox",
    "id": "windows-sandbox:default",
    "architecture": "arm64",
    "epoch": "opaque-generation-id"
  }
}

UI results retain existing numeric guest PID/HWND fields and add scope metadata
or copyable commands. Numeric guest HWND values are meaningful only with
--sandbox and within the exact executionTarget.epoch that produced them.
Process-bearing results also include process start metadata. Commands reject
handles or process IDs from a stale epoch rather than allowing them to resolve
against a recreated guest.

executionTarget is additive and provider-neutral. Future explicit target
selection can populate the same object without changing existing process,
package, or artifact fields.

Infrastructure failures use stable error codes distinct from guest application
exit codes. Generic command payloads and outputs are never included in
telemetry.

Internal execution target model

V1 does not expose a public provider system. It introduces only the internal
seams needed to prevent Windows Sandbox lifecycle details from leaking into app
orchestration.

Target reference

Host orchestration uses a provider-neutral target reference:

{
  "kind": "windows-sandbox",
  "id": "windows-sandbox:default"
}

--sandbox resolves to that target. A future target selector may resolve values
such as hyperv:winui-test or devbox:my-devbox, but those values and that
public CLI are outside v1.

Target backend

A target backend is responsible only for:

  • Capability probing.
  • Ensuring the Windows environment is running.
  • Ensuring an interactive desktop is available.
  • Installing or connecting the matching guest winapp agent.
  • Returning a provider-neutral guest transport.
  • Reporting provider-specific diagnostics and epoch identity.

The Windows Sandbox backend owns:

  • wsb start, list, share, connect, exec, and stop integration.
  • Singleton ownership checks.
  • The off-screen, non-minimized interactive client.
  • Read-only bootstrap sharing, guest IP discovery, and authenticated TCP
    transport connection.
  • WSB-specific prerequisite and policy errors.

Future backends may use Hyper-V lifecycle, network transport, Hyper-V sockets,
or remote APIs without changing the shared command-channel semantics.

Transport and command channel

Target backends implement a narrow IGuestTransport that provides framed
message and binary-stream reads/writes, timeouts, and connection closure. A
single target-neutral GuestCommandChannel owns:

  • Capability and version negotiation.
  • Structured execution and stream forwarding.
  • Cancellation and process liveness.
  • File reconciliation and transfer.
  • Artifact manifests.
  • Target epoch and operation fencing.
  • Guest-agent update negotiation.
  • Output-path rewriting and failure envelopes.

The protocol uses provider-neutral targetId and targetEpoch fields. For
Windows Sandbox, the backend derives the epoch from the WSB ID plus the random
guest boot nonce.

Windows Sandbox v1 uses an authenticated and encrypted framed TCP connection to
the guest IP returned by wsb ip. A read-only mapped bootstrap folder carries
the architecture-matched guest binary and per-boot connection material. A
separate narrowly scoped writable bootstrap-result folder carries only
startup diagnostics and readiness output. The result folder has a fixed size
and file-count limit, is treated as untrusted input, and is removed after the
host consumes the bootstrap result.
wsb exec is used only for fixed bootstrap operations because it returns a
guest exit code but does not relay guest stdout or stderr.

The bootstrap command writes its stdout, stderr, and structured status to the
managed bootstrap folder. If the agent cannot start, the host reports those
guest diagnostics rather than reducing the failure to a generic transport
error.

Capabilities

The guest reports supported capabilities rather than requiring orchestration to
infer them from the provider name:

{
  "architecture": "arm64",
  "supportsInteractiveDesktop": true,
  "supportsRealInput": true,
  "supportsScreenCapture": true,
  "cooperativeUiTurnsVersion": 1,
  "supportsInternalSystemSetup": true,
  "persistentStorage": false
}

Commands validate required capabilities before deployment or execution.
Capability support does not imply current readiness. Before foreground-sensitive
UI commands, the guest dynamically verifies that the agent is running in the
interactive user session, the input desktop is available, the target window is
live and visible, foreground can be established, and the required input APIs
are available. These checks do not claim to prove generic input delivery.
Commands verify a bounded command-specific postcondition when one exists;
otherwise they report successful API submission while preserving the current
delivery warnings. Readiness failures return structured diagnostics and never
report successful input delivery.

Shared orchestration

The following remain above the target backend and must not reference WSB APIs,
paths, IDs, or window titles:

  • Host build and materialization.
  • Deployment ownership and desired-state reconciliation.
  • Runtime requirement resolution and provisioning.
  • Package registration/launch requests.
  • UI argv forwarding and target selection.
  • Artifact copy-back and JSON rewriting.

This is an internal architectural boundary, not a provider SDK. Add a general
plugin model only after a second backend demonstrates the need. Contract tests
exercise orchestration against a fake IGuestTransport, proving that handshake,
streaming, cancellation, artifacts, and errors do not depend on WSB APIs.

Sandbox lifecycle

Ownership

Winapp persists the exact Sandbox ID and a random boot nonce. If another
Sandbox is running and is not provably owned by winapp:

  • Winapp does not adopt it.
  • Winapp does not stop it.
  • The command reports the running ID, explains that Windows permits only one
    Sandbox, and leaves termination to an explicit user decision.
  • A wsb stop --id command may be shown as an optional user action, never run
    automatically or presented as a safe default.

Ensure and reuse

Every Sandbox invocation:

  1. Acquires the global mutation lock when guest mutation is required.
  2. Reconciles the persisted ID with wsb list, the remote-session client, the
    guest connection, boot nonce, and agent heartbeat.
  3. Classifies the target as starting, interactive-ready, running,
    tearing-down, stale-client, or terminated.
  4. Waits for singleton teardown to complete before attempting another start.
  5. Verifies protocol and guest winapp compatibility.
  6. Repairs or restarts only the stale layer.
  7. Releases the mutation lock after mutation and state commit.

Read-only guest operations do not hold the mutation lock.

Interactive client requirement

The Windows Sandbox RDP client must remain connected and non-minimized whenever
real input or Windows Graphics Capture is required. Winapp keeps the owned
client off-screen and at the bottom of the host window order without activating
it.

An empirical ARM64 Windows 11 build 28000 spike established:

  • The Sandbox guest has no active console session
    (WTSGetActiveConsoleSessionId == 0xFFFFFFFF).
  • tscon <interactive-session> /dest:console fails with
    Sessionname console not found.
  • Closing the WSB client leaves the guest user session, application process,
    UI Automation, UIA mutations, and fallback window screenshot operational.
  • A disconnected client makes the guest session non-interactive: SendInput
    and real mouse input fail.
  • Windows Graphics Capture recording is unavailable while disconnected.
  • wsb connect reconnects to the same guest session and application state and
    restores real input and recording.

Therefore tscon is not used. Client disconnection may be considered only as a
future read-only/UIA optimization; it is never used while a command requires
real input or WGC-based screen capture.

If the user closes the client during active foreground-sensitive work, the
command fails with sandbox_no_interactive_session. A later Sandbox command may
reconnect the owned client and retry only when retry is safe and cannot repeat
an already-observed UI side effect.

Winapp prints concise progress:

Preparing Windows Sandbox...

or:

Reusing Windows Sandbox...

No Sandbox ID or lifecycle guidance is printed during successful normal use.

External termination

If the user closes Sandbox or runs wsb stop:

  • Active commands fail with sandbox_terminated.
  • Late events from the old epoch are ignored.
  • The next Sandbox invocation invalidates old process/deployment state and
    waits for teardown before creating a new managed Sandbox.

Automatic shutdown

Winapp does not automatically stop Sandbox in v1. The user may close it or use
the Windows Sandbox CLI.

Host coordination and state

There is no persistent host coordinator process.

Host winapp processes coordinate through:

  • One per-target named mutation mutex.
  • Per-deployment atomic state files with revisions.
  • Target epoch fields on every request, result, and state commit.
  • Guest-side fencing of mutation operations.

V1 stores the Windows Sandbox target under
%LOCALAPPDATA%\Microsoft\WinApp\Targets\windows-sandbox-default. Future
targets receive separate state roots and mutation locks, allowing independent
environments to mutate concurrently.

The mutation lock covers:

  • Sandbox creation and repair.
  • Guest winapp replacement.
  • Shared runtime installation.
  • Deployment synchronization.
  • Package registration and unregistration.

It does not cover:

  • Host restore or build.
  • Running applications.
  • Read-only UI Automation operations.

When a host process dies, the next owner treats an abandoned mutex as a recovery
signal, verifies the epoch and dirty state, and reconciles before further
mutation.

The Sandbox mutation mutex is unrelated to UI turn coordination. It protects
guest environment and deployment mutations, not the interactive desktop.

Guest winapp agent mode

The architecture-matched guest winapp.exe runs a private persistent mode that
is not included in normal public help.

The guest agent is always started as ExistingLogin after wsb connect
establishes the interactive Sandbox user session. At startup it verifies that
it is not in session 0 and that its window station and input desktop are
interactive. It does not publish a ready heartbeat or serve UI commands until
those checks pass.

Responsibilities:

  • Publish heartbeat, version, protocol capabilities, architecture, and binary
    hash.
  • Receive structured operation requests.
  • Run multiple child processes concurrently.
  • Report started PID and process creation information.
  • Stream stdin/EOF, stdout, and stderr.
  • Return exact result and failure domain.
  • Track process trees with Job Objects.
  • Request graceful cancellation and enforce a timeout before Job termination.
  • Reconcile files between exchange staging and managed guest-local roots.
  • Track process liveness and deployment ownership.
  • Stage artifact manifests and files.
  • Fence mutation operations by target epoch and operation generation.
  • Inject the forwarded Cooperative UI Turns owner context into guest child
    winapp processes.

The agent does not implement separate app semantics. It invokes ordinary guest
winapp child commands for run, unregister, debugging, and UI Automation.

Agent versioning and upgrades

  • Same version and hash: reuse.
  • Host newer: stage the new guest binary, verify its hash, run its self-test,
    stop admitting new operations, drain or cancel active operations according to
    command semantics, and activate through an atomic process handoff.
  • Guest newer with compatible protocol: reuse the newer guest.
  • Guest newer with incompatible protocol: fail and require updating the host
    winapp.
  • Never downgrade guest winapp.

The previous working guest binary remains available as last-known-good until
the replacement reports ready and serves a health probe. Failed activation
automatically rolls back without reporting the target healthy. A force-repair
path can reinstall the host's matching guest only when doing so is not a
downgrade.

All comparisons use one stamped Winapp version source plus the binary hash.
Protocol envelopes declare minimum and maximum compatible versions, state
schema migrations are monotonic, and request pipelining cannot cross an update
handoff.

Deployment model

Each resolved input receives an internal deployment ID derived from:

  • Canonical resolved input/project path.
  • Original package identity when present.

It is used only for:

  • Guest directories.
  • State files.
  • Ownership.
  • Artifacts.
  • Relaunching the deployment's previous app.

It is not a public target and is never inferred from the current directory for
UI selection.

Host snapshot

After build/materialization, winapp creates an immutable desired-state manifest
containing relative paths, sizes, timestamps, and hashes. If source files change
during snapshot creation, deployment aborts and requests another build.

Exact in-place reconciliation

For a rerun:

  1. Acquire the mutation mutex.
  2. Stop only processes proven owned by the deployment.
  3. Mark the deployment dirty and persist the desired-state manifest.
  4. Copy added/changed files.
  5. Delete files absent from the desired state.
  6. Verify final hashes.
  7. Mark the deployment clean.
  8. Register and launch according to run options.
  9. Commit package/process state.

A dirty deployment never launches or reports healthy. The next run performs a
complete desired-state reconciliation. There is no rollback guarantee.

Package ownership

Original package identity is preserved.

The package ownership record includes:

  • Target ID and epoch.
  • Deployment ID.
  • Original package name and publisher.
  • Effective package full name and family.
  • Registered guest location.
  • AUMID.
  • Managed process metadata.

Registration/unregistration removes only an exact managed development package
whose registered location matches the deployment. It never adopts or removes an
external guest package.

If another active deployment owns the same original identity, run --sandbox
fails. Concurrent identity rewriting is specified separately.

Package deployment preserves per-user application state by default. The
existing run --clean option is the explicit clean-reinstall operation in
Sandbox mode and may clear only the selected managed package's state. If an
inbox or provisioned package blocks development registration, winapp fails with
the exact package identity and a dedicated conflict code. It never removes a
provisioned package automatically.

Runtime provisioning

Runtime requirements are derived from the resolved project and build artifacts.
Requirements are modeled as compatible constraints, not a complete machine
snapshot.

Provisioning:

  1. Inspect host project/build metadata.
  2. Resolve official payloads from existing host caches.
  3. If missing, acquire them through existing official winapp download paths and
    cache them on the host.
  4. Stage required payloads into Sandbox.
  5. Install under the mutation mutex with the correct machine/user scope.
  6. Verify the complete required package/runtime graph.

Winapp never downgrades or removes a shared runtime while Sandbox is active.

Partial installation is journaled and verified/repaired before application
launch.

Provisioning records per-phase timings for requirement discovery, cache
resolution, transfer, installation, and verification. If compatible constraints
cannot be satisfied without removing or downgrading a shared runtime, the
operation fails with the unsatisfied requirement rather than mutating the
environment destructively.

UI command routing

Sandbox routing is handled at one pre-dispatch interception point rather than in
every UI handler.

The host:

  1. Detects recursive --sandbox or an --app sandbox: target before local UI
    services execute.
  2. Ensures the managed Sandbox and guest agent.
  3. Rewrites only routing-specific arguments.
  4. Forwards the remaining argv to guest winapp.
  5. Resolves and forwards Cooperative UI Turns owner context.
  6. Relays stdout, stderr, exit code, stdin, and cancellation.
  7. Copies and rewrites declared output artifacts.

Guest winapp parses and executes the normal UI command unchanged.

Cooperative UI Turns

Sandbox UI forwarding depends on the Cooperative UI Turns implementation used
by ordinary local winapp ui commands.

The interaction resource is scoped to the OS desktop where the UI command
executes:

  • Local UI commands coordinate through the local signed-in Windows session.
  • Sandbox UI commands coordinate through the Sandbox interactive session.
  • Future execution targets coordinate through their own guest Windows session.

There is no host-side Sandbox UI mutex or Sandbox-specific scheduler. Guest
winapp classifies and coordinates the forwarded command using the normal
Observe, TurnShared, and DesktopExclusive rules. Existing post-wait target
resolution, foreground validation, element-stability checks, cancellation, and
recording behavior remain authoritative.

Owner-context forwarding

The guest agent is the immediate parent of every guest child winapp process.
Without forwarding, parent-derived owner identity would incorrectly group all
host workflows under the one agent parent.

Before forwarding a UI command, host winapp resolves the logical owner using the
same precedence as Cooperative UI Turns:

  1. Explicit WINAPP_UI_OWNER_ID.
  2. Immediate host parent PID plus process start time.
  3. A unique one-command anonymous owner.

The router derives an opaque, target-and-epoch-scoped owner token and carries it
as a normal field in the guest operation envelope. The guest agent sets the
existing WINAPP_UI_OWNER_ID variable for the child command, and the normal
Cooperative UI Turns owner resolution and hashing behavior remains unchanged.

Requirements:

  • The raw explicit owner ID is never written to state, output, logs, protocol
    events, or telemetry.
  • The forwarded context is scoped to the target ID and target epoch so it cannot
    accidentally group commands across recreated or different environments.
  • Two host commands that would cooperate locally must cooperate in the guest.
  • Two host workflows with different owners must remain different guest owners,
    even though their child commands share the same guest agent parent.
  • Anonymous host invocations remain one-command guest owners.
  • sandbox exec forwards the same owner context so nested guest winapp UI
    commands behave consistently.

The owner token is versioned with the guest protocol and is never exposed in
public output.

UI turn state

Cooperative UI Turns state remains guest-local under the guest user's
session-scoped lock directory. It is not stored in host Sandbox deployment
state and is not reconstructed by the host.

During an agent activation handoff:

  1. Stop admitting new guest commands.
  2. Allow active commands to complete or cancel them according to their existing
    semantics.
  3. Wait for participant leases to close or become provably stale.
  4. Activate the self-tested compatible guest agent, retaining last-known-good
    rollback until the new agent reports ready.
  5. Let Cooperative UI Turns perform its normal state normalization and stale
    participant pruning.

An unknown newer Cooperative UI Turns state version fails safely; it is never
reset over potentially live participants.

Artifact handling

File-producing commands use host-created operation staging.

The guest returns an artifact manifest:

{
  "artifacts": [
    {
      "relativePath": "result.mp4",
      "type": "video",
      "size": 123456,
      "sha256": "...",
      "complete": true
    }
  ]
}

The host:

  1. Validates the manifest and operation quota.
  2. Streams artifacts in bounded chunks to temporary host destinations.
  3. Verifies size and hash.
  4. Atomically publishes requested output paths.
  5. Rewrites guest JSON paths to host paths.

Recording receives EOF/graceful cancellation first, waits for Media Foundation
finalization, and force-kills only after timeout. Partial/recovery artifacts are
reported rather than presented as successful output.

V1 transfers restart from the beginning rather than resuming. If the connection
closes, cancellation occurs, ownership is lost, or the Sandbox terminates, the
host does not publish the requested destination. The error reports the artifact
name, expected size, received byte count, and failing transfer phase. Temporary
partial files are deleted best-effort; cleanup failure never converts an
interrupted transfer into success.

Cleanup

V1 performs minimal cleanup:

  • Successful acknowledged request/event files are removed.
  • Successful transfer staging is removed.
  • Active deployments and shared runtimes remain for reuse.
  • Dirty deployment state remains until repaired.
  • Failed transfers, logs, partial artifacts, and caches may remain until
    Sandbox is stopped or manually cleaned.

Existing command-specific limits continue to apply. Disk exhaustion fails
explicitly rather than silently corrupting state.

Telemetry

Existing telemetry behavior remains for modeled winapp commands.

The following are never collected from winapp sandbox exec or cp:

  • Executable and argument values.
  • Environment variables.
  • Host or guest paths.
  • stdin, stdout, or stderr.
  • File names or contents.
  • Registry commands or values.

Allowed telemetry is limited to coarse command name, success/failure domain,
duration bucket, architecture, and anonymized capability/error categories.

npm, schema, and packaging

  • --sandbox is added to run, unregister, and recursively to the ui
    command group.
  • sandbox exec and sandbox cp are included in CLI schema and generated npm
    APIs intentionally.
  • npm APIs preserve existing numeric window types because Sandbox HWND routing
    uses --sandbox.
  • Interactive stdin forwarding is guaranteed for terminal CLI invocation. npm
    capture APIs remain non-interactive unless a later streaming API is added.
  • Host and guest winapp are built, signed, packaged, and versioned together for
    x64 and ARM64.

Failure model

Sandbox failures extend the existing command's JSON error contract. Routing
through Sandbox does not move an existing command's success or error payload
between stdout and stderr. Progress and diagnostics never mix with a
machine-readable payload.

The following is the common Sandbox error shape; its output channel follows the
invoked command's existing --json behavior:

{
  "error": {
    "code": "sandbox_unmanaged_instance",
    "message": "Another Windows Sandbox instance is already running.",
    "context": {
      "sandboxId": "..."
    },
    "userAction": "Close the existing Sandbox if it is safe to do so, then retry.",
    "nextCommand": {
      "command": "wsb stop --id ...",
      "advisory": true
    },
    "validValues": null,
    "example": "winapp run . --sandbox",
    "recoveredFrom": null
  }
}

code values are stable once released. Optional fields provide structured
context, exact user action, one recovery command, valid alternatives, a working
example, and the original failure when an automatic non-destructive recovery
succeeds. Recovery commands that require user judgment are advisory and are
never run automatically. Snapshot tests pin the released code set and envelope
shape.

Initial Sandbox codes include:

  • sandbox_unsupported
  • sandbox_unmanaged_instance
  • sandbox_start_failed
  • sandbox_no_interactive_session
  • sandbox_input_not_ready
  • sandbox_terminated
  • sandbox_agent_incompatible
  • sandbox_agent_upgrade_failed
  • sandbox_transport_failed
  • sandbox_transfer_interrupted
  • sandbox_runtime_provision_failed
  • sandbox_deployment_dirty
  • sandbox_package_conflict
  • sandbox_provisioned_package_conflict
  • sandbox_target_ambiguous
  • sandbox_target_stale
  • sandbox_stale_handle
  • sandbox_artifact_failed

Under --json, each command preserves its existing stdout/stderr payload
contract. Progress and diagnostics use the command's existing diagnostic
channel and never corrupt the machine-readable result. Guest application exit
codes remain distinguishable from infrastructure failures.

Implementation organization

New code should not enlarge existing oversized services.

Suggested internal organization:

WinApp.Cli/
  ExecutionTargets/
    Abstractions/
      ExecutionTargetRef
      ExecutionTargetCapabilities
      IExecutionTargetBackend
      IGuestTransport
    Orchestration/
      ExecutionTargetOrchestrator
      TargetStateStore
      GuestProtocol
      GuestCommandChannel
      TargetDeploymentService
      TargetRuntimeService
      TargetArtifactService
      TargetCommandRouter
    WindowsSandbox/
      WindowsSandboxBackend
      WindowsSandboxClient
      WindowsSandboxTransport
      WindowsSandboxWindowController

Agent-mode and protocol code must be NativeAOT/trim-safe and use source-generated
serialization.

Only WindowsSandboxBackend may directly invoke wsb.exe or manipulate the
Windows Sandbox client window.

Validation plan

Unit and integration

  • Transport framing and target-neutral command-channel behavior.
  • Version negotiation, staged update, self-test, activation handoff, and
    last-known-good rollback.
  • Bootstrap diagnostics when wsb exec returns only an exit code.
  • Cooperative UI Turns owner-context forwarding and target/epoch scoping.
  • Separate host workflows remain separate guest owners despite sharing one
    persistent agent parent.
  • Same-owner guest record/input commands cooperate using TurnShared and
    DesktopExclusive semantics.
  • Argument fidelity, Unicode, stdin/EOF, stdout/stderr ordering, large output.
  • Named mutex abandonment and epoch fencing.
  • Fake-transport contract tests proving handshake, execution, cancellation,
    artifacts, path rewriting, and errors do not depend on WSB paths or commands.
  • Atomic revised state updates.
  • Exact copy add/change/delete and dirty repair.
  • Path canonicalization and reparse-point rejection.
  • Package ownership and unmanaged-package protection.
  • Provisioned-package conflict and non-destructive default behavior.
  • Runtime compatibility and partial-install repair.
  • UI argv routing and no local handler execution.
  • Explicit target requirements and stale PID/HWND rejection across epochs.
  • Structured error recovery fields and stable-code snapshot.
  • JSON purity and telemetry exclusion.

Windows Sandbox E2E

  • Cold start and warm reuse.
  • Connected-client requirement; deliberate disconnect preserves UIA but rejects
    real input/WGC, and reconnect restores the same guest session.
  • Unmanaged Sandbox refusal.
  • Starting/running/teardown/stale-client state transitions and singleton teardown
    wait.
  • External stop and epoch recovery.
  • Guest agent launch in the interactive user session and refusal to serve UI
    from session 0.
  • Dynamic input readiness across lock/unlock, RDP transition, foreground loss,
    stale HWND, and client reconnect.
  • Guest agent staged upgrade, failed self-test, failed activation, rollback, and
    no downgrade.
  • Packaged framework-dependent WinUI application.
  • Self-contained packaged and unpackaged .NET applications.
  • Two distinct applications running concurrently.
  • Local and guest UI automation simultaneously.
  • Two independent host workflows queue guest DesktopExclusive operations without
    overlap or wrong-window input.
  • One host workflow records while same-owner input commands continue in guest.
  • Every UI verb, including playable MP4 recording and artifact copy-back.
  • Full run option matrix.
  • Generic exec/cp as the interactive user.
  • Agent-bootstrap failure with guest stdout/stderr surfaced from bootstrap
    staging.
  • Interrupted and oversized artifact transfer with no partial destination
    publication.
  • Host crash during sync, registration, command execution, and state commit.
  • x64 and ARM64.
  • Host lock/unlock, RDP transition, localization, and user closing Sandbox.

Live Sandbox tests require self-hosted Windows runners or a gated manual release
environment with nested virtualization and supported Windows editions.

Acceptance criteria

  1. winapp run . --sandbox starts or reuses Sandbox without changing host
    foreground.
  2. A warm rerun transfers only changed state, deletes stale files, and relaunches
    without affecting another app.
  3. winapp ui ... --sandbox executes entirely in guest and preserves current
    verb output/exit semantics.
  4. Sandbox UI action commands require an explicit app/window target, dynamically
    verify input readiness, and never report successful delivery when readiness
    or a bounded postcondition fails.
  5. Screenshots and recordings appear at requested host paths only after complete
    size/hash verification; interrupted artifacts are never published as success.
  6. Guest PID/HWND values are scoped to a target epoch and stale values are
    rejected after recreation.
  7. Two distinct applications run concurrently.
  8. External Sandbox termination is detected and recovered on the next command
    after singleton teardown completes.
  9. Unmanaged Sandbox, unmanaged package registrations, and provisioned packages
    are never modified.
  10. Guest agent update is staged, verified, self-tested, rollback-safe,
    compatible, and never downgraded.
  11. Generic exec/cp preserve argument/file semantics and exclude sensitive
    telemetry.
  12. Unsupported platforms and application forms fail with structured recovery
    guidance and without local fallback.
  13. Application deployment, UI forwarding, and artifact tests run against a
    fake guest transport without invoking Windows Sandbox.
  14. Cooperative UI Turns owner identity and scheduling remain correct across
    host-to-guest forwarding.

Delivery phases

Implementation may proceed in phases while preserving this public design:

  1. Sandbox lifecycle, transport/command-channel protocol, safe agent bootstrap
    and updates, state/epoch, deployment, and WinUI run.
  2. After Cooperative UI Turns ([Feature]: Cooperative UI turns for concurrent winapp UI agents #764) is available, UI routing, owner forwarding,
    dynamic readiness, artifacts, and recording.
  3. Generic sandbox exec and sandbox cp.
  4. Additional application-framework provisioning and compatibility validation.
  5. A second execution target, only after its concrete lifecycle and transport
    requirements are known.

Package identity rewriting remains a separate specification.

Additional context

A working exploratory spike validated the central Windows Sandbox mechanics on ARM64:

  • wsb start/share/connect/exec/stop lifecycle.
  • Background/off-screen non-minimized Sandbox connection without host focus changes.
  • Real guest UI Automation, SendInput typing, mouse clicking, screenshots, and packaged WinUI execution.
  • Self-contained guest winapp execution.
  • Host-side portable layout materialization and differential transfer.
  • Guest-side winapp run --debug-output with concurrent UI commands.

The current proposal deliberately keeps Windows Sandbox as the only v1 public target while isolating lifecycle/transport internally for future Hyper-V, Dev Box, or remote-machine implementations.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions