Skip to content

End winapp's Windows Sandbox when its window is closed - #978

Closed
Nikola Metulev (nmetulev) wants to merge 11 commits into
mainfrom
nmetulev-sandbox-window-close-watcher
Closed

Nikola Metulev (nmetulev) wants to merge 11 commits into
mainfrom
nmetulev-sandbox-window-close-watcher

Conversation

@nmetulev

@nmetulev Nikola Metulev (nmetulev) commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

Description

Stacked on #964. Merge #964 first; this PR's base is #964's branch, so the diff shows only the window-close watcher.

Problem. winapp starts its Windows Sandbox with wsb start, which has no window and only ends with wsb stop. It shows the Sandbox with wsb connect, which is only a viewer. So closing that window leaves the Sandbox running out of sight, unlike a Sandbox opened from Start. If you then open Windows Sandbox from Start, it fails with "Only one running instance of Windows Sandbox is allowed". wsb has no option to tie a Sandbox's lifetime to its window.

Change. When winapp opens the window for a Sandbox it started, it also starts a hidden winapp __sandbox-window-watch process. When that window closes, the watcher:

  1. Waits for any winapp command that is changing or connecting to the Sandbox to finish (the mutation lock, then the connection lock).
  2. Confirms the closed window is still the one winapp recorded, and that no other Sandbox window is shown.
  3. Ends the closed window's lingering process, then runs wsb stop.

It never stops a Sandbox winapp didn't start (an adopted one). The watcher opts out of telemetry and does not use up the one-time first-run notice.

A closed window hides within 0.1 s, but its process can linger hidden for 15 s to over 60 s, so a hidden window counts as closed.

Usage Example

winapp run . --on sandbox --detach
# Close the "Windows Sandbox" window.
wsb list
# Before: the Sandbox winapp started is still listed (running, no window).
# After:  it is gone about 1.5 s after the window closes. The next --on sandbox command starts a fresh one.

Related Issue

Follow-up to #964, which was split so this behaviour can be decided separately.

Type of Change

  • ✨ New feature
  • 📝 Documentation
  • 🧪 Test update

Checklist

  • New tests added for new functionality (if applicable)
  • Tested locally on Windows
  • Shipped skills updated in plugins/winapp/skills/ (if CLI commands/workflows changed)

docs/sandbox-execution.md and the winapp-sandbox skill now say that closing winapp's Sandbox window ends a Sandbox winapp started and discards its guest state. The version-mismatch advice from #964 still says to stop the Sandbox with wsb stop --id <id>, and now notes that closing the window does not stop a Sandbox another winapp version or tool started. The new command is hidden, so docs/usage.md and the CLI schema do not change.

Screenshots / Demo

No new UI. Measured live on a real Windows Sandbox before this was split out of #964:

Interaction Result
Close the Sandbox window Sandbox gone 1.5–1.6 s after close in 4 of 4 runs; no leftover windows or watcher processes
The client's own Close button No confirmation dialog appeared; Sandbox stopped about 1 s later
Maximize, restore, resize, minimize, enter/leave the client's full-screen mode Same window kept; watcher did not fire
A second --on sandbox command Reused the running Sandbox; still exactly one watcher

Local validation on this branch (no live Sandbox commands were run for this PR):

  • dotnet build src/winapp-CLI/winapp.sln -c Debug and dotnet build src/winapp-CLI/WinApp.Cli.Tests/WinApp.Cli.Tests.csproj -c Release: 0 warnings, 0 errors.
  • Sandbox, InteractiveDesktop, ExecutionTarget, WindowsSandboxWindow, Program, FirstRun and Telemetry tests: 744 total, 721 passed, 0 failed, 23 skipped (live Sandbox E2E tests gated behind WINAPP_SANDBOX_E2E=1, plus a test that needs wsb.exe absent).
  • The 9 new tests pass: SandboxClientWatcherTests (stops a Sandbox winapp created or recovered, ending the lingering client first; never stops an adopted Sandbox; does nothing when a newer window was recorded, another Sandbox window is shown, or another command holds the connection lock; ignores a window winapp didn't record) and SandboxUxRegressionTests.WindowOpenedForASandboxWinappStarted_IsWatchedForClose.
  • .\scripts\build-cli.ps1 -SkipTests -SkipNpm -SkipMsix: NativeAOT x64 and arm64 publish, CLI schema regeneration and NuGet packing succeeded; no generated files changed. This ran on an earlier base; the build and test results above are from the current base.

Additional Notes

Open questions for the product owner (why this is a separate PR):

  1. Should close-to-stop exist, and should it confirm first? Closing the window silently discards the whole guest, including other workflows' state and any unsaved evidence.
  2. Is a background process per connect acceptable? It is the only mechanism found. An independent review found no smaller alternative: wsb and .wsb files have no lifetime option, and launching the classic WindowsSandbox.exe instead loses the instance ID winapp assigns.
  3. Not verified: whether a Sandbox opened from Start asks for confirmation before discarding. If it does, matching it would argue for a confirmation here too.

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build Metrics Report

Validation passed. All required build and validation jobs succeeded.

Binary Sizes

Artifact Baseline Current Delta
CLI (ARM64) 57.42 MB 57.45 MB 📈 +29.0 KB (+0.05%)
CLI (x64) 57.46 MB 57.48 MB 📈 +26.5 KB (+0.05%)
MSIX (ARM64) 23.86 MB 23.86 MB 📈 +5.4 KB (+0.02%)
MSIX (x64) 25.32 MB 25.33 MB 📈 +6.1 KB (+0.02%)
NPM Package 49.76 MB 49.78 MB 📈 +27.8 KB (+0.05%)
NuGet Package 49.86 MB 49.89 MB 📈 +28.9 KB (+0.06%)

.NET Test Results (TRX reports)

Other suites are reflected in the overall validation status above.

✅ 8091 passed, 37 skipped out of 8128 tests in 1209.8s (+29 tests, -373.9s vs. baseline)

Test Coverage

✅ 86.4% line coverage, 81% branch coverage · ✅ no change vs. baseline

CLI Startup Time

65ms median (x64, winapp --version) · ✅ no change vs. baseline

Try This Build

Installs 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))) 978
Switching between builds often?

Put the tool on your PATH once:

& ([scriptblock]::Create((irm https://raw.githubusercontent.com/microsoft/winappCli/main/scripts/winapp-pr.ps1))) -AddToPath

Then this build is just:

winapp-pr 978

Run winapp-pr with no arguments to pick from a list of open PRs.


Updated 2026-10-07 05:03:57 UTC · commit 07ab4d6 · workflow run

@nmetulev
Nikola Metulev (nmetulev) marked this pull request as draft October 5, 2026 19:53
@nmetulev
Nikola Metulev (nmetulev) force-pushed the nmetulev-sandbox-window-close-watcher branch 2 times, most recently from 766dcd5 to e3c1cb2 Compare October 5, 2026 21:36
@nmetulev
Nikola Metulev (nmetulev) force-pushed the nmetulev-sandbox-window-close-watcher branch 2 times, most recently from 674e57a to 891d673 Compare October 6, 2026 20:37
`winapp target exec sandbox` (and every command that prepares the Sandbox
guest agent) failed with "The Windows Sandbox command line failed: Access
is denied ... restart the host" while the Sandbox itself was healthy.

The failing call was `wsb share`. UI coordination created
%USERPROFILE%\.winapp\state\ui with DirectoryInfo.Create(DirectorySecurity),
which also stamps the protected current-user-only DACL onto every missing
ancestor, including the shared state root. Bootstrap folders under
state\targets then had no SYSTEM access, and Windows Sandbox's host
service cannot share a folder SYSTEM cannot open.

- Create missing ancestors with normal inherited permissions before
  creating the restricted coordination directory.
- Grant SYSTEM on the two bootstrap folders before sharing them, which
  also repairs machines whose state root was already locked down.
- Report share failures with the folder and, for access denied, the
  account that needs access; never suggest restarting the host.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- When no Windows Sandbox client process is running on the host, connect
  before starting the guest agent instead of waiting for the agent to
  fail with NoInputDesktop. Windows runs one Sandbox at a time, so no
  client process means nothing is attached; any client process keeps the
  existing conservative path.
- Replacing a staged agent binary that the Sandbox still holds could
  throw UnauthorizedAccessException and crash the command. Report it as
  sandbox_agent_incompatible with the existing recovery guidance.
- Verify the coordination directory DACL even after creating it, so a
  directory another process created first is repaired or rejected.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
winapp parked the Sandbox client it opens 32,000 pixels off-screen, so a
running Sandbox looked closed, and opening Windows Sandbox from Start then
failed with "Only one running instance of Windows Sandbox is allowed".

Place the client directly behind the window the user was working in,
without activating it, instead. Real input and capture keep working
while it is covered. A client on no monitor at all, such as one parked by
0.7.0, is moved back onto the nearest monitor. Document the Start-menu
error and how to get back to the running Sandbox.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- A minimized Sandbox client cannot be verified (its remote-desktop
  renderer leaves the UI tree), so real-input commands failed with "its
  remote desktop could not be verified" instead of restoring winapp's own
  window. Restore it first, then verify. A minimized client the user
  opened now gets restore guidance instead.
- Bring winapp's own client back on screen when it is on no monitor, as
  winapp 0.7.0 left it. A client the user opened is never moved.
- Remove the up-front reconnect when no client process exists. Measured
  live, it made closed-window recovery slower (median 58 s vs 34 s): the
  guest re-attaching its session slowed the firewall step by ~16 s, far
  more than the one agent launch it saved.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
`wsb start` creates a Sandbox with no window and only `wsb stop` ends it;
the window `wsb connect` opens is just a viewer. Closing it left the
Sandbox running out of sight, and opening Windows Sandbox from Start then
failed with "Only one running instance of Windows Sandbox is allowed".

When winapp opens the window for a Sandbox it started, it now starts a
hidden `winapp __sandbox-window-watch` process. Once the window closes
(it hides within 0.1 s; its process can linger for over a minute), the
watcher waits for any winapp command that is changing or connecting to
the Sandbox, confirms the window is still the one winapp recorded and no
other Sandbox window is shown, ends the lingering window process, and
runs `wsb stop`. Measured: the Sandbox is gone about 1.5 s after the
window closes. Minimizing or moving the window does not end it. A
Sandbox winapp adopted is never stopped. The watcher opts out of
telemetry and skips the first-run notice, like the guest agent.

Restoring a minimized or off-screen Sandbox window no longer depends on
whether winapp opened it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Closing winapp's Sandbox window and having the Sandbox shut down needs a
background process, and whether closing the window should discard the
guest is a product decision of its own. Keep this PR to the access
fixes and window placement, and document the current behaviour: the
Sandbox keeps running after its window closes, `wsb connect` shows it
again, and `wsb stop` ends it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Placing the Sandbox window behind the foreground window passed that
window as SetWindowPos' insert-after. When the foreground window is
always-on-top (for example a terminal pinned with PowerToys), Windows
makes the inserted window always-on-top too, so the Sandbox window stayed
above every normal window. Leave the z-order alone in that case.

The version-conflict error told users to close Windows Sandbox, but
closing the window leaves a Sandbox winapp started running and its files
in use. It now says to save any work and stop it, and suggests
`wsb stop --id <id>`; `wsb stop` alone is rejected because --id is
required.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
winapp starts its Sandbox with `wsb start`, which has no window and ends
only with `wsb stop`, and shows it with `wsb connect`, which is only a
viewer. Closing that window left the Sandbox running out of sight, so
opening Windows Sandbox from Start then failed with "Only one running
instance of Windows Sandbox is allowed". `wsb` has no option to tie the
Sandbox's lifetime to its window.

When winapp opens the window for a Sandbox it started, it now starts a
hidden `winapp __sandbox-window-watch` process. When the window closes
(or is hidden, since a closed client can linger hidden for over a
minute), the watcher waits for any winapp command changing or connecting
to the Sandbox, confirms the closed window is still the one winapp
recorded and no other Sandbox window is shown, ends the lingering client
process, and runs `wsb stop`. It never stops a Sandbox winapp adopted,
opts out of telemetry, and skips the first-run notice.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@nmetulev
Nikola Metulev (nmetulev) force-pushed the nmetulev-sandbox-window-close-watcher branch from 891d673 to 07ab4d6 Compare October 7, 2026 04:37
Base automatically changed from nmetulev-sandbox-target-exec-access-denied to main October 8, 2026 01:42
@nmetulev

Copy link
Copy Markdown
Member Author

Closing in favour of a different approach. Instead of a hidden watcher that runs wsb stop with no prompt, winapp will start its Sandbox the way Windows Sandbox does from Start, so the Sandbox belongs to its own window. Closing that window shows Windows' confirmation ("all of its content will be discarded") before ending the Sandbox. That removes the background process, the polling and the lock waits. A follow-up PR will link here.

Zach Teutsch (zateutsch) pushed a commit that referenced this pull request Oct 9, 2026
…sks (#1047)

## Description

**Problem.** winapp started its Windows Sandbox with `wsb start`. That
Sandbox has no window, and only `wsb stop` ends it. winapp then showed
it with `wsb connect`, which only views it. So closing the Sandbox
window left the Sandbox running out of sight. One left on a dev machine
this way had about 3.9 GB of memory committed three days later. Opening
Windows Sandbox from Start then failed with "Only one running instance
of Windows Sandbox is allowed".

**Change.** winapp now opens a new Sandbox the same way Start does: it
launches the Windows Sandbox app, with no arguments. That window owns
the Sandbox. Closing it shows Windows' own confirmation, *"Are you sure
you want to close Windows Sandbox? Once Windows Sandbox is closed all of
its content will be discarded and permanently lost."*:

- **Ok** ends the Sandbox. The next `--on sandbox` command starts a
fresh one.
- **Cancel** keeps it, and winapp keeps using it.

There is still exactly one Sandbox window. winapp still moves it behind
your window.

winapp records the Sandbox as one it created only when the window it
launched reaches a session. In any other case it uses the Sandbox as
adopted, meaning started by something else, which winapp never ends. One
example is opening Windows Sandbox from Start at the same moment.

## Usage Example

```powershell
winapp run . --on sandbox --detach
# Close the "Windows Sandbox" window.
# Before: no prompt; `wsb list` still shows the Sandbox, running with no window.
# After:  Windows asks to confirm. Ok ends it (`wsb list` is empty). Cancel keeps it.
```

## Related Issue

Replaces #978, which ended the Sandbox from a hidden background process
with no confirmation.

## Type of Change

- 🐛 Bug fix
- 📝 Documentation
- 🧪 Test update

## Checklist

- [x] New tests added for new functionality (if applicable)
- [x] Tested locally on Windows
- [x] Shipped skills updated in `plugins/winapp/skills/` (if CLI
commands/workflows changed)

`docs/sandbox-execution.md` and the `winapp-sandbox` skill now say that
closing the window of a Sandbox winapp started asks for confirmation and
then ends it. No commands or options change, so `docs/usage.md` does
not.

## Screenshots / Demo

Measured on a real Windows Sandbox (Windows build 28000, Arm64, Windows
Sandbox 0.8.107.0), with a NativeAOT build of this branch:

| What I did | What happened |
|---|---|
| `winapp target exec sandbox -- cmd /c echo hello` with nothing running
| Exit 0 in 25–41 s. One Sandbox window, recorded as created by winapp.
Focus returned to my window. |
| The same command again | Exit 0 in 0.2 s, same Sandbox and window |
| Closed the window, clicked **Cancel** | Sandbox still listed; the next
command reused it (1 s) |
| `winapp ui list-windows --on sandbox`, `winapp ui screenshot --on
sandbox -w <hwnd>` | Both worked through the window winapp opened |
| Closed the window, clicked **Ok** | `wsb list` empty; the next command
started a fresh Sandbox (35 s) |
| Killed winapp 8 s into a cold start | The Sandbox kept running; the
next command used it (25 s), still one window |
| Ran `wsb start` 0.7 s after winapp began a cold start, so the headless
Sandbox won | winapp's window showed "Only one running instance…".
winapp used the headless Sandbox, connected one window to it, and exited
0 in 20 s |

Before this change, closing the window showed no prompt and `wsb list`
still listed the Sandbox.

## Additional Notes

- **Only Sandboxes winapp opens change.** A Sandbox started with `wsb
start`, for example by another tool or by winapp 0.7.1 or earlier, still
keeps running after its window is closed. The docs point those users to
`wsb stop --id <id>`. If winapp 0.7.1 crashed mid-start and left a
pending-start record, newer winapp still recovers it.
- **Ending the window's process ends the Sandbox.** That is how Windows
Sandbox works when started from Start. winapp never ends that process:
it stops tracking it when a command is cancelled, and a winapp killed
mid-start leaves the Sandbox running.
- **One window, even when winapp can't identify its own.** If winapp's
window takes over 30 s to show a session, winapp uses the Sandbox as
adopted and doesn't connect a second window. If winapp's window instead
shows Windows' "Only one running instance" error, another Sandbox won.
winapp then treats that Sandbox like any other it adopts, and connects a
window only if nobody is signed in.

---------

Co-authored-by: Nikola Metulev <711864+nmetulev@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant