From eea337a742b95a053cc8c02421e9cfb432a4f1c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:22:21 +0000 Subject: [PATCH 1/3] Close the host on SIGINT, SIGTERM, and SIGHUP (core-signals, upstream #1734) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e21jov6Swn2Aj93SnF7 --- docs-site/src/content/docs/docs/core.mdx | 1 + skills/e2e-dotnet/SKILL.md | 2 +- skills/e2e-dotnet/references/host.md | 2 +- src/E2E/Core/Launch.cs | 18 +- src/E2E/Core/Signals.cs | 189 ++++++++++++++++++ tests/E2E.Tests.App/E2E.Tests.App.csproj | 4 + tests/E2E.Tests.App/Program.cs | 50 +++++ .../CoreSignals/CoreOnASignalTests.cs | 112 +++++++++++ 8 files changed, 375 insertions(+), 3 deletions(-) create mode 100644 src/E2E/Core/Signals.cs create mode 100644 tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs diff --git a/docs-site/src/content/docs/docs/core.mdx b/docs-site/src/content/docs/docs/core.mdx index 0be5229c7..56fa4e3ec 100644 --- a/docs-site/src/content/docs/docs/core.mdx +++ b/docs-site/src/content/docs/docs/core.mdx @@ -34,6 +34,7 @@ foreach (var sku in new[] { "A-1001", "B-2040" }) | Sessions | One session at a time on a host. Close it before `NewSessionAsync()`. For parallel work, launch more hosts. | | Timeouts | An action, a wait, or a read gets 30 seconds. `App.OpenAsync()` and `App.RestartAsync()` get 120 seconds. `LaunchOptions.Timeout` or `session.SetDefaultTimeout(timeout)` sets one value for all of them, for the operations that start from then on. There is no session deadline. | | Cancellation | The token passed to `LaunchAsync` and `NewSessionAsync` stops what is running. | +| Ctrl-C | The host closes on SIGINT, SIGTERM, and SIGHUP, so its browser or device session does not stay behind. Then the program ends by the signal, unless it listens for the signal itself (`PosixSignalRegistration`), which then sees it again and decides. Turn it off with `LaunchOptions.HandleSignals = false`. A close that fails is said on stderr first. | | Files | Screenshots and downloads go to a temp directory that is deleted when the host closes. Set `ArtifactsDir` to keep them; a relative path resolves from `Cwd`. | | Closing | `CloseAsync` is idempotent and throws an `AggregateException` of the failures closing found. | diff --git a/skills/e2e-dotnet/SKILL.md b/skills/e2e-dotnet/SKILL.md index 7b30675e2..dff470b07 100644 --- a/skills/e2e-dotnet/SKILL.md +++ b/skills/e2e-dotnet/SKILL.md @@ -36,7 +36,7 @@ trip. The installed tool prints the same text with `e2e guide ` | Running tests: `dotnet test` filters, the `e2e` tool (`e2e doctor` checks that `e2e explore` and `e2e mcp` can start; `--json` prints the `doctor-1` report for a host, `--check-model` calls each model once; `e2e cache ls|stats|clear` lists, sizes, or empties the replay cache), `report.json` for scripts, exit codes, CI, test filters (NUnit, xUnit v3, and TUnit, mobile and Windows adapters included: `E2ERunFixture.Filters` and `ChangedSince`, or `E2E_CHANGED_SINCE`; `run.changes`, `run.filters`, and `filtered` skips in `report.json`), `--last-failed` reruns (`E2ERunFixture.LastFailed` or `E2E_LAST_FAILED=1`; `run.carried` in `report.json`, `FinishedRun.LastRun` for reporters, folded into the GitHub comment) | `running` | [references/running.md](references/running.md) | | Handling a failed run: the trace page, `report.json` for scripts, `E2ESession.Report()` for a session you run yourself, error codes and their fixes, a visible browser, replay misses, phase timings, the agent step table, every model call | `debugging` | [references/debugging.md](references/debugging.md) | | Exploring an app toward a goal without a test file, with `e2e explore` or `Explore.ExploreAsync` | `explore` | [references/explore.md](references/explore.md) | -| Driving an app from plain code with no test framework (`Launch.LaunchAsync(engine, new LaunchOptions { App, Secrets, Timeout, ArtifactsDir, Cwd })`, `Host.NewSessionAsync`, `Host.Secret`, `Session.SaveStateAsync`, and `SessionState.ExportAsync`/`ImportAsync` with a 32-byte key you keep), or running isolated per-test sessions from your own runner: `E2EHost.OpenAsync`, `OpenHostOptions` (config value or file, target, `EngineFactory`), `host.OpenSessionAsync`, `E2ESession.CloseAsync` and the failures it returns, `Steps()` | `host` | [references/host.md](references/host.md) | +| Driving an app from plain code with no test framework (`Launch.LaunchAsync(engine, new LaunchOptions { App, Secrets, Timeout, HandleSignals, ArtifactsDir, Cwd })`, `Host.NewSessionAsync`, `Host.Secret`, `Session.SaveStateAsync`, and `SessionState.ExportAsync`/`ImportAsync` with a 32-byte key you keep), or running isolated per-test sessions from your own runner: `E2EHost.OpenAsync`, `OpenHostOptions` (config value or file, target, `EngineFactory`), `host.OpenSessionAsync`, `E2ESession.CloseAsync` and the failures it returns, `Steps()` | `host` | [references/host.md](references/host.md) | | Testing an iOS or Android app: `MobileEngine`, the `Device` fixture, picking a simulator (without `MobileOptions.Device`, `MobileEngine` skips booted devices another agent-device session holds, and `prepare` fails with `ENGINE_FAILURE` when every booted one is held, and with none booted agent-device boots a shut-down one: on iOS an iPhone over an iPad over an Apple TV, on Android a phone or tablet over a TV, then newest OS, then name order, and a reachable paired iPhone or iPad counts as booted; `prepare` logs a per-device timing line), video of the device screen, `Device.SetPermissionAsync` (the enums, or wire-name strings such as `"camera"` and `"grant"`; an unknown name or state is `INVALID_ARGUMENT` before any device command), `Device.UnstableRaw` (the test's agent-device session: name, device id and name, selection, and a raw `IDeviceClient` whose calls are not steps, replayed, or redacted, and that throws `NotSupportedException` for the `text-size` and `animations` settings, `apps.uninstall`, and `command.hardwareButton`; unstable; `INVALID_STATE` after the session is disposed; a custom agent tool gets the running attempt's from `MobileTools.UnstableDeviceSession(engines)`), a NativeScript `testID` or `accessibilityIdentifier` as the test id `GetByTestId` reads (an Android `accessibilityLabel` is put before the text), Limrun and BrowserStack hosted devices, a MAUI app through the DevFlow agent, known limits, `Locator.PressAsync("Enter")` tapping an unfocused field first, and the agent's `open_app` returning to the app under test when it names no app, a Compose Multiplatform field on iOS (for an empty (no value), editable, non-secure iOS field that reports no placeholder of its own, whose only child is a `StaticText` with no children, and whose label is a non-empty name, then `, `, then that child's text, that text is the field's `Placeholder`, the child is left out, and the name is the label before `, `; a non-empty `ContentDescription` stays the name, and that label is then the `Text`; any other field keeps its label and children), and `FillAsync` and `ClearAsync` refusing a node that is not an editable field with `UNSUPPORTED_CAPABILITY` (an iOS `other` that holds a value or only text is typed into), reading the field again before typing (a field the new capture no longer lists, an incomplete capture, or a changed input purpose or secure, disabled, or hidden state is a retryable `NODE_STALE` before anything is typed), looking at the screen again after the keyboard opens or closes (an unmoved control is acted on at once only when keyboard visibility is unchanged, else it waits out `TransitionMilliseconds`; a test's screen swipe waits out the remaining budget before it scrolls), and a `target_still_moving` refusal with `dispatched: no` being a retryable `NODE_STALE` | `mobile` | [references/mobile.md](references/mobile.md) | | Testing a Windows desktop app: `WinAppEngine`, `WinAppTest`, the `Window` fixture, the `windows` target in `e2e explore` and `e2e mcp`, the interactive-desktop requirement, known limits | `windows` | [references/windows.md](references/windows.md) | | Asked to bug bash or hunt for bugs: the bug-bash config, many `e2e explore` runs at once, proving each bug with a repro test | `bug-bash` | [references/bug-bash.md](references/bug-bash.md) | diff --git a/skills/e2e-dotnet/references/host.md b/skills/e2e-dotnet/references/host.md index 7d075ca82..a05ead9a9 100644 --- a/skills/e2e-dotnet/references/host.md +++ b/skills/e2e-dotnet/references/host.md @@ -97,6 +97,6 @@ await session.Screen.GetByLabel("Password").FillAsync(shop.Secret("SHOP_PASSWORD - A second `LaunchAsync` on an engine instance another host owns, and a second open session on a host, fail with `WORKER_PROTOCOL`. Parallel work is more hosts. - A secret value is at least 6 characters, and is redacted from the errors a session throws and from `Screen.TreeAsync()`. `Host.Secret(name)` with another name is `SECRET_UNAVAILABLE`. -- `LaunchOptions.Timeout` bounds an action, a wait, a read, and `App.OpenAsync()` or `App.RestartAsync()` (30 seconds for the first three and 120 seconds for the last two without it). `session.SetDefaultTimeout(timeout)` moves all of them for the operations that start from then on; a zero or infinite span is `INVALID_ARGUMENT`. There is no session deadline. `ArtifactsDir` keeps screenshots and downloads (a relative path resolves from `Cwd`); without it they go to a temp directory deleted when the host closes. +- `LaunchOptions.Timeout` bounds an action, a wait, a read, and `App.OpenAsync()` or `App.RestartAsync()` (30 seconds for the first three and 120 seconds for the last two without it). `session.SetDefaultTimeout(timeout)` moves all of them for the operations that start from then on; a zero or infinite span is `INVALID_ARGUMENT`. There is no session deadline. On SIGINT, SIGTERM, and SIGHUP the host closes, then the program ends by the signal unless it listens for it itself with `PosixSignalRegistration` (it sees the signal again and decides); `LaunchOptions.HandleSignals = false` turns that off, and a failed close is said on stderr. `ArtifactsDir` keeps screenshots and downloads (a relative path resolves from `Cwd`); without it they go to a temp directory deleted when the host closes. - `await session.SaveStateAsync()` captures cookies and storage in memory. Pass it to `shop.NewSessionAsync(new NewSessionOptions { State = state })`. To keep it between runs, `state.ExportAsync(new SessionStateKeyOptions { Key = key })` with a 32-byte key you keep, and `SessionState.ImportAsync(bytes, options)`. A state restores only on the same engine, platform, and app (`SESSION_MISMATCH`; give two addresses of one app the same `LaunchApp.Identity`), a wrong key or changed byte is `SESSION_INVALID`, and an old one `SESSION_EXPIRED`. - Not ported yet: closing on signals, `app.linkBase`, and `createAgent` (issues 1675 to 1678). diff --git a/src/E2E/Core/Launch.cs b/src/E2E/Core/Launch.cs index 4577bdf99..234388174 100644 --- a/src/E2E/Core/Launch.cs +++ b/src/E2E/Core/Launch.cs @@ -60,6 +60,12 @@ public sealed record LaunchOptions /// The environment the engine reads; default the process environment. public IReadOnlyDictionary? Env { get; init; } + /// + /// Closes the host on SIGINT, SIGTERM, and SIGHUP, so the browsers and devices it launched do not outlive the program; the signal is raised again + /// afterwards unless the program listens for it itself. Default true. A closing that fails is said on stderr. Upstream's handleSignals. + /// + public bool HandleSignals { get; init; } = true; + /// Progress outside operations: provisioning, downloads, device leases. Must not throw. public Action? OnNotice { get; init; } } @@ -165,6 +171,7 @@ public sealed class Host : IAsyncDisposable private readonly LaunchApp? _app; private readonly Lock _gate = new(); private readonly Lazy _closing; + private Action _unregister = () => { }; private Session? _open; internal Host(StandaloneHost host, IEngine engine, string target, string projectRoot, string output, bool ownsArtifacts, IReadOnlyDictionary secrets, StateIdentity identity, TimeSpan? timeout, LaunchApp? app) @@ -199,6 +206,8 @@ public Secret Secret(string name) return E2E.Secret.Create(name, value); } + internal void CloseOnSignals() => _unregister = Signals.CloseOnSignals(CloseAsync); + /// Opens a session. One at a time: the previous one must be closed. public Task NewSessionAsync(NewSessionOptions? options = null, CancellationToken cancellationToken = default) => OpenSession.RedactOpening(async () => @@ -258,6 +267,7 @@ private void Release(StandaloneAttempt attempt) private async Task CloseOnceAsync() { + _unregister(); var errors = new List(); Session? open; lock (_gate) @@ -401,7 +411,13 @@ public static async Task LaunchAsync(IEngine engine, LaunchOptions? option CancellationToken = cancellationToken, Notice = options.OnNotice is { } notice ? (_, message) => OpenSession.Notify(notice, message) : null, }).ConfigureAwait(false); - return new Host(worker, engine, target, projectRoot, output, ownsArtifacts, secrets, identity, options.Timeout, app); + var opened = new Host(worker, engine, target, projectRoot, output, ownsArtifacts, secrets, identity, options.Timeout, app); + if (options.HandleSignals) + { + opened.CloseOnSignals(); + } + + return opened; } catch { diff --git a/src/E2E/Core/Signals.cs b/src/E2E/Core/Signals.cs new file mode 100644 index 000000000..c8415186f --- /dev/null +++ b/src/E2E/Core/Signals.cs @@ -0,0 +1,189 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Runtime.InteropServices; + +namespace E2E; + +/// +/// Ctrl-C for hosts: on SIGINT, SIGTERM, or SIGHUP every host that asked for it (, on by default) closes, so +/// the browsers and device sessions it launched do not outlive the program. The signal is then raised again for the process's own disposition. A +/// program that listens for the signal itself () sees it again and decides. Upstream's core/signals.ts. +/// +/// +/// Upstream marks the listeners an engine registers while it opens (engineListeners) and removes them before it raises the signal again. .NET +/// cannot list the registrations of a process, so an engine's listener that cancels a signal is not told apart from a program's. +/// +internal static class Signals +{ + private static readonly PosixSignal[] SignalList = [PosixSignal.SIGINT, PosixSignal.SIGTERM, PosixSignal.SIGHUP]; + + // How long the program's registrations get to cancel a signal raised again. + private static readonly TimeSpan HandlersWait = TimeSpan.FromMilliseconds(500); + + private static readonly Lock Gate = new(); + + private static readonly HashSet> Closers = []; + + private static List? s_registrations; + + /// Registers a host's close for the process signals; the returned action unregisters it. Upstream's closeOnSignals. + internal static Action CloseOnSignals(Func close) + { + lock (Gate) + { + Closers.Add(close); + Install(); + } + + return () => + { + lock (Gate) + { + Closers.Remove(close); + if (Closers.Count == 0) + { + Uninstall(); + } + } + }; + } + + // Closes every registered host once, then hands the signal back to the process. + private static void OnSignal(PosixSignalContext context) + { + context.Cancel = true; + var signal = context.Signal; + List> closers; + lock (Gate) + { + Uninstall(); + closers = [.. Closers]; + Closers.Clear(); + } + + _ = Task.Run(async () => + { + // The process ends right after, so a close that failed is said on stderr or nowhere; its message is already redacted. + await Task.WhenAll(closers.Select(close => CloseAsync(close, signal))).ConfigureAwait(false); + Raise(signal); + }); + } + + private static async Task CloseAsync(Func close, PosixSignal signal) + { + try + { + await close().ConfigureAwait(false); + } + catch (Exception cause) + { + await Console.Error.WriteAsync($"E2E: closing a host on {signal} failed: {cause.Message}\n").ConfigureAwait(false); + } + } + + private static void Raise(PosixSignal signal) + { + if (OperatingSystem.IsWindows()) + { + Environment.Exit(128 + Number(signal)); + return; + } + + // Our registration is gone: the signal goes through the program's own registrations. A probe keeps the context they all share; when none + // of them cancelled it by the time they ran, the process takes the signal's default disposition and ends by it. + var seen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var probe = PosixSignalRegistration.Create(signal, context => seen.TrySetResult(context)); + try + { + Send(Number(signal)); + if (seen.Task.Wait(HandlersWait) && seen.Task.Result.Cancel) + { + return; + } + + Terminate(signal); + } + catch (Exception cause) when (cause is DllNotFoundException or EntryPointNotFoundException) + { + Environment.Exit(128 + Number(signal)); + } + } + + private static void Terminate(PosixSignal signal) + { + try + { + ResetToDefault(Number(signal)); + Send(Number(signal)); + } + catch (Exception cause) when (cause is DllNotFoundException or EntryPointNotFoundException) + { + Environment.Exit(128 + Number(signal)); + } + } + + // PosixSignal values are the runtime's own constants, not the POSIX numbers the C library takes. + private static int Number(PosixSignal signal) => signal switch + { + PosixSignal.SIGHUP => 1, + PosixSignal.SIGINT => 2, + _ => 15, + }; + + private static void Send(int signal) => + _ = OperatingSystem.IsLinux() ? KillLinux(Environment.ProcessId, signal) : Kill(Environment.ProcessId, signal); + + private static void ResetToDefault(int signal) => + _ = OperatingSystem.IsLinux() ? SignalLinux(signal, 0) : SignalDefault(signal, 0); + + [DllImport("libc", EntryPoint = "kill", SetLastError = true)] + private static extern int Kill(int pid, int signal); + + // "libc" is a linker script on Linux, not a library the loader opens. + [DllImport("libc.so.6", EntryPoint = "kill", SetLastError = true)] + private static extern int KillLinux(int pid, int signal); + + [DllImport("libc", EntryPoint = "signal", SetLastError = true)] + private static extern nint SignalDefault(int signal, nint handler); + + [DllImport("libc.so.6", EntryPoint = "signal", SetLastError = true)] + private static extern nint SignalLinux(int signal, nint handler); + + private static void Install() + { + if (s_registrations is not null) + { + return; + } + + s_registrations = []; + foreach (var signal in SignalList) + { + try + { + s_registrations.Add(PosixSignalRegistration.Create(signal, OnSignal)); + } + catch (PlatformNotSupportedException) + { + // The platform has no such signal; the others still close the host. + } + } + } + + private static void Uninstall() + { + if (s_registrations is null) + { + return; + } + + foreach (var registration in s_registrations) + { + registration.Dispose(); + } + + s_registrations = null; + } +} diff --git a/tests/E2E.Tests.App/E2E.Tests.App.csproj b/tests/E2E.Tests.App/E2E.Tests.App.csproj index b2a54c081..bb1cdcfd4 100644 --- a/tests/E2E.Tests.App/E2E.Tests.App.csproj +++ b/tests/E2E.Tests.App/E2E.Tests.App.csproj @@ -5,4 +5,8 @@ E2E.Tests.App false + + + + diff --git a/tests/E2E.Tests.App/Program.cs b/tests/E2E.Tests.App/Program.cs index 1090806ef..a4351068b 100644 --- a/tests/E2E.Tests.App/Program.cs +++ b/tests/E2E.Tests.App/Program.cs @@ -16,6 +16,7 @@ // serve-hold serves; on SIGTERM it writes `stopping` to the working directory, then exits 0 once `release-stop` exists there // serve-receipt serves; on SIGTERM it writes {"projectExists":} to the file 100 ms later and exits 0 // wrap ... starts ` ...` as a child, writes its pid to the file, and exits 0 on SIGTERM, staying up until then +// signal-host launches a host and a session on a fake engine, prints READY, and waits to be signalled; the engine writes `disposed` to the directory // idle stays up and answers nothing // exit exits with the code // chatter prints a line to stdout and one to stderr, then exits with the code @@ -54,6 +55,8 @@ return await ServeReceipt(int.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture), args[2], args[3]); case "wrap": return await Wrap(args[1], args.Skip(2).ToArray()); + case "signal-host": + return await SignalHost(args[1], args[2] == "fail-close", args[3] == "listens"); case "idle": await Task.Delay(Timeout.Infinite); return 0; @@ -210,3 +213,50 @@ static async Task Wrap(string pidFile, string[] childArgs) await Task.Delay(Timeout.Infinite); return 0; } + +static async Task SignalHost(string dir, bool failClose, bool listens) +{ + // A browser driver listens for a hangup to close its browsers, and its listener stays after they are closed. + using var engineListener = PosixSignalRegistration.Create(PosixSignal.SIGHUP, _ => { }); + // A program that listens for the signal itself decides when it ends: here it never does. + using var programListener = listens ? PosixSignalRegistration.Create(PosixSignal.SIGHUP, context => context.Cancel = true) : null; + var host = await E2E.Launch.LaunchAsync( + new SignalEngine(Path.Combine(dir, "disposed"), failClose), + new E2E.LaunchOptions { App = new E2E.LaunchApp { Url = "http://127.0.0.1:4500" }, Cwd = dir, Env = new Dictionary() }); + await host.NewSessionAsync(); + Console.Out.WriteLine("READY"); + Console.Out.Flush(); + await Task.Delay(Timeout.Infinite); + return 0; +} + +internal sealed class SignalEngine(string marker, bool failClose) : E2E.Engine.IEngine +{ + public string Platform => "fake"; + + public string Version => "1"; + + public E2E.Engine.EngineCapabilities Capabilities => E2E.Engine.EngineCapabilities.Observation | E2E.Engine.EngineCapabilities.Actions; + + public Task StartAsync(E2E.Engine.EngineStartOptions options, CancellationToken cancellationToken) => + Task.FromResult(new SignalSession(marker, failClose)); + + private sealed class SignalSession(string marker, bool failClose) : E2E.Engine.IEngineSession + { + public string Route => "/"; + + public Task OpenAsync(string url, CancellationToken cancellationToken) => Task.CompletedTask; + + public Task ObserveAsync(CancellationToken cancellationToken) => Task.FromResult(new E2E.Engine.Observation { Route = "/", Roots = [] }); + + public Task PerformAsync(E2E.Engine.SemanticNode node, E2E.Engine.LocatorAction action, CancellationToken cancellationToken) => Task.CompletedTask; + + public Task PressAsync(string key, CancellationToken cancellationToken) => Task.CompletedTask; + + public ValueTask DisposeAsync() + { + File.WriteAllText(marker, "disposed"); + return failClose ? throw new InvalidOperationException("the device would not let go") : ValueTask.CompletedTask; + } + } +} diff --git a/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs b/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs new file mode 100644 index 000000000..3aa3a04f2 --- /dev/null +++ b/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs @@ -0,0 +1,112 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using E2E.Tests.ManagedProcess; + +namespace E2E.Tests.CoreSignals; + +/// +/// Upstream's describe('@e2e-dev/core on a signal') (tests/integration/core-signals.test.ts): a program that holds a host and gets SIGINT or SIGHUP +/// closes the host, and the engine with it, then ends by the signal, whatever the engine listens for; a close that fails says so on stderr before the process goes. +/// +public sealed class CoreOnASignalTests +{ + private const int SigHup = 1; + private const int SigInt = 2; + + [DllImport("libc", EntryPoint = "kill", SetLastError = true)] + private static extern int Kill(int pid, int signal); + + [DllImport("libc.so.6", EntryPoint = "kill", SetLastError = true)] + private static extern int KillLinux(int pid, int signal); + + // Runs a program that opens a host and a session, sends it the signal once it is ready, and reports how it ended. + private static async Task<(int? Signal, int Code, string Stderr, bool Disposed)> Interrupt(bool failClose, int signal = SigInt, bool listens = false) + { + var dir = Directory.CreateTempSubdirectory("core-signals-").FullName; + try + { + var info = new ProcessStartInfo(AppProgram.Executable) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = dir, + }; + foreach (var arg in new[] { "signal-host", dir, failClose ? "fail-close" : "close", listens ? "listens" : "alone" }) + { + info.ArgumentList.Add(arg); + } + + using var child = Process.Start(info)!; + var stderr = new StringBuilder(); + child.ErrorDataReceived += (_, line) => + { + lock (stderr) + { + stderr.AppendLine(line.Data); + } + }; + child.BeginErrorReadLine(); + using var ready = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + while (await child.StandardOutput.ReadLineAsync(ready.Token) is { } line && !line.Contains("READY", StringComparison.Ordinal)) + { + } + + Assert.False(child.HasExited, $"the program exited before it was ready:\n{stderr}"); + Assert.Equal(0, OperatingSystem.IsLinux() ? KillLinux(child.Id, signal) : Kill(child.Id, signal)); + + // A program that listens for the signal itself decides when it ends: here it never does. + using var stays = new CancellationTokenSource(TimeSpan.FromSeconds(listens ? 3 : 30)); + try + { + await child.WaitForExitAsync(stays.Token); + } + catch (OperationCanceledException) when (listens) + { + child.Kill(); + await child.WaitForExitAsync(); + } + + child.WaitForExit(); + var killed = child.ExitCode == 128 + 9; + lock (stderr) + { + return (killed ? 9 : child.ExitCode > 128 ? child.ExitCode - 128 : null, child.ExitCode, stderr.ToString(), File.Exists(Path.Combine(dir, "disposed"))); + } + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + [Fact] + public async Task ClosesTheHostDisposingItsEngineThenEndsByTheSignal() + { + var ended = await Interrupt(false); + Assert.True(ended.Signal == SigInt && ended.Disposed, ended.Stderr); + Assert.DoesNotContain("failed", ended.Stderr, StringComparison.Ordinal); + } + + [Fact] + public async Task EndsBySighupThoughTheEngineListensForItAndLeavesAProgramThatListensItselfToDecide() + { + var alone = await Interrupt(false, SigHup); + Assert.True(alone.Signal == SigHup && alone.Disposed, alone.Stderr); + var listening = await Interrupt(false, SigHup, listens: true); + Assert.True(listening.Signal == 9 && listening.Disposed, listening.Stderr); + } + + [Fact] + public async Task SaysOnStderrThatACloseFailedAndStillEndsByTheSignal() + { + var ended = await Interrupt(true); + Assert.Equal(SigInt, ended.Signal); + Assert.Contains("closing a host on SIGINT failed", ended.Stderr, StringComparison.Ordinal); + } +} From bbc26608d680af9ed031272fed56d953b86d061a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 18:41:46 +0000 Subject: [PATCH 2/3] Address review: settle before reading Cancel, leave unhandled signals alone, update stale docs Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e21jov6Swn2Aj93SnF7 --- COMPATIBILITY.md | 2 +- .../src/content/docs/api/E2E/LaunchOptions.md | 15 +++++++++++++++ skills/e2e-dotnet/references/host.md | 2 +- src/E2E/Core/Signals.cs | 19 ++++++++++++++++--- .../CoreSignals/CoreOnASignalTests.cs | 15 +++++++++++++++ 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 7b87c7f3c..6838e0fe1 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -168,7 +168,7 @@ Differences: Differences: - A session is one `Session` class with `Screen`, `App`, `Platform`, `Browser`, `SaveStateAsync`, `SetDefaultTimeout`, `CloseAsync`, and `DisposeAsync`, where upstream's is a flat object typed by the engine's fixtures (`Host`). There is no `Device` member on it yet (#1678). It has no `agent`: `createAgent` is not ported (#1676). -- `LaunchOptions` has no `Headed` (the web engine takes its window mode through its own options), no `Signal` or `HandleSignals` (the token passed to `LaunchAsync` and `NewSessionAsync` is the signal; closing on SIGINT, SIGTERM, and SIGHUP is #1677), and `Timeout` is a `TimeSpan`. `Env` is a dictionary and `OnNotice` takes the line only. +- `LaunchOptions` has no `Headed` (the web engine takes its window mode through its own options), no `Signal` (the token passed to `LaunchAsync` and `NewSessionAsync` is the signal). `HandleSignals` closes the host on SIGINT, SIGTERM, and SIGHUP (`Core/Signals.cs` is `core/signals.ts`, `Signals.CloseOnSignals` is `closeOnSignals`); `engineListeners` is not ported, because .NET cannot list a process's signal registrations (#1693), so a program's listener is told from an engine's by whether it cancels the signal raised again, and on Windows the process exits with 128 plus the signal number without asking the program, and `Timeout` is a `TimeSpan`. `Env` is a dictionary and `OnNotice` takes the line only. - `RedactThrown` rebuilds an error that carries a secret value (type and code kept, causes redacted) where upstream edits the thrown error in place, which a .NET exception's read-only message does not allow. An error with no secret is thrown as it is. - `SessionState.ExportAsync` and `ImportAsync` are `Task`-returning like upstream's `async` methods, so a bad key rejects instead of throwing. The key is `SessionStateKeyOptions.Key`, a `byte[]` of 32 bytes; there is no unknown-option check (`plaintext: true` cannot be passed). - `app.linkBase` (`AppConfig.LinkBase`, `ResolvedApp.LinkBase`, `LaunchApp.LinkBase`, checked by `TargetApps.CheckLinkBase`, upstream's `checkLinkBase`) and the engine `openLink` hook (`IEngineSession.OpenLinkAsync`, `EngineSessionSpec.OpenLink`, `ISessionApp.OpenLinkAsync`, `session/openLink` in the manifest schema) are ported, with `App.OpenAsync(path)` joining and opening the link as upstream's `launchPinnedApp` does. `EngineCapabilities.OpenLink` is .NET-only: C# has no optional member to test, so an engine declares the hook the way it declares `Resize`. `TargetApps.JoinLink`, `TargetApps.RefusesLink`, and `Urls.IsRefusedLinkScheme` (upstream's `joinLink`, `refusesLink`, `isRefusedLinkScheme`) are shared with `DeviceLinks`. Not ported: the unknown-key message of a `defineEngine` session, which a typed `EngineSessionSpec` cannot receive (`engine.test.ts`). diff --git a/docs-site/src/content/docs/api/E2E/LaunchOptions.md b/docs-site/src/content/docs/api/E2E/LaunchOptions.md index 91304fa48..f678c4f2a 100644 --- a/docs-site/src/content/docs/api/E2E/LaunchOptions.md +++ b/docs-site/src/content/docs/api/E2E/LaunchOptions.md @@ -90,6 +90,21 @@ The environment the engine reads; default the process environment. **Value:** [IReadOnlyDictionary<string, string>](https://learn.microsoft.com/dotnet/api/system.collections.generic.ireadonlydictionary-2) + + + +### HandleSignals + + +```csharp +public bool HandleSignals { get; init; } +``` + + +Closes the host on SIGINT, SIGTERM, and SIGHUP, so the browsers and devices it launched do not outlive the program; the signal is raised again afterwards unless the program listens for it itself. Default `true`. A closing that fails is said on stderr. Upstream's `handleSignals`. + +**Value:** [bool](https://learn.microsoft.com/dotnet/api/system.boolean) + diff --git a/skills/e2e-dotnet/references/host.md b/skills/e2e-dotnet/references/host.md index 29f67ea9b..5e7976d6d 100644 --- a/skills/e2e-dotnet/references/host.md +++ b/skills/e2e-dotnet/references/host.md @@ -100,4 +100,4 @@ await session.Screen.GetByLabel("Password").FillAsync(shop.Secret("SHOP_PASSWORD - `LaunchOptions.Timeout` bounds an action, a wait, a read, and `App.OpenAsync()` or `App.RestartAsync()` (30 seconds for the first three and 120 seconds for the last two without it). `session.SetDefaultTimeout(timeout)` moves all of them for the operations that start from then on; a zero or infinite span is `INVALID_ARGUMENT`. There is no session deadline. On SIGINT, SIGTERM, and SIGHUP the host closes, then the program ends by the signal unless it listens for it itself with `PosixSignalRegistration` (it sees the signal again and decides); `LaunchOptions.HandleSignals = false` turns that off, and a failed close is said on stderr. `ArtifactsDir` keeps screenshots and downloads (a relative path resolves from `Cwd`); without it they go to a temp directory deleted when the host closes. - `await session.SaveStateAsync()` captures cookies and storage in memory. Pass it to `shop.NewSessionAsync(new NewSessionOptions { State = state })`. To keep it between runs, `state.ExportAsync(new SessionStateKeyOptions { Key = key })` with a 32-byte key you keep, and `SessionState.ImportAsync(bytes, options)`. A state restores only on the same engine, platform, and app (`SESSION_MISMATCH`; give two addresses of one app the same `LaunchApp.Identity`), a wrong key or changed byte is `SESSION_INVALID`, and an old one `SESSION_EXPIRED`. - `LaunchApp.LinkBase` (an absolute URL or a scheme such as `shopapp://`, with no query or fragment) makes `session.App.OpenAsync("/orders/42")` open `shopapp://orders/42` in the pinned app of a device engine. An absolute link opens as given; `file:`, `data:`, `javascript:`, `view-source:`, `blob:`, and `filesystem:` are `POLICY_DENIED`; an engine without a link hook, or a bad value, is `INVALID_CONFIG` at launch. -- Not ported yet: closing on signals and `createAgent` (issues 1676 to 1678). +- Not ported yet: `createAgent`, and an engine's own signal listeners (issues 1676, 1678, and 1693). On Windows, the host closes on a signal and the process then exits with 128 plus the signal number, whether or not the program listens for it. diff --git a/src/E2E/Core/Signals.cs b/src/E2E/Core/Signals.cs index c8415186f..54581856f 100644 --- a/src/E2E/Core/Signals.cs +++ b/src/E2E/Core/Signals.cs @@ -22,6 +22,8 @@ internal static class Signals // How long the program's registrations get to cancel a signal raised again. private static readonly TimeSpan HandlersWait = TimeSpan.FromMilliseconds(500); + private static readonly TimeSpan SettleWait = TimeSpan.FromMilliseconds(200); + private static readonly Lock Gate = new(); private static readonly HashSet> Closers = []; @@ -53,11 +55,17 @@ internal static Action CloseOnSignals(Func close) // Closes every registered host once, then hands the signal back to the process. private static void OnSignal(PosixSignalContext context) { - context.Cancel = true; var signal = context.Signal; List> closers; lock (Gate) { + // No host is left to close: the signal is the program's own. + if (Closers.Count == 0) + { + return; + } + + context.Cancel = true; Uninstall(); closers = [.. Closers]; Closers.Clear(); @@ -98,9 +106,14 @@ private static void Raise(PosixSignal signal) try { Send(Number(signal)); - if (seen.Task.Wait(HandlersWait) && seen.Task.Result.Cancel) + // Handlers run in no set order, so the context is read once they have all had a moment to run. + if (seen.Task.Wait(HandlersWait)) { - return; + Thread.Sleep(SettleWait); + if (seen.Task.Result.Cancel) + { + return; + } } Terminate(signal); diff --git a/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs b/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs index 3aa3a04f2..e5dad5516 100644 --- a/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs +++ b/tests/E2E.Tests/CoreSignals/CoreOnASignalTests.cs @@ -88,6 +88,11 @@ public sealed class CoreOnASignalTests [Fact] public async Task ClosesTheHostDisposingItsEngineThenEndsByTheSignal() { + if (OperatingSystem.IsWindows()) + { + return; // The signals are POSIX; Windows has no `kill`. + } + var ended = await Interrupt(false); Assert.True(ended.Signal == SigInt && ended.Disposed, ended.Stderr); Assert.DoesNotContain("failed", ended.Stderr, StringComparison.Ordinal); @@ -96,6 +101,11 @@ public async Task ClosesTheHostDisposingItsEngineThenEndsByTheSignal() [Fact] public async Task EndsBySighupThoughTheEngineListensForItAndLeavesAProgramThatListensItselfToDecide() { + if (OperatingSystem.IsWindows()) + { + return; // The signals are POSIX; Windows has no `kill`. + } + var alone = await Interrupt(false, SigHup); Assert.True(alone.Signal == SigHup && alone.Disposed, alone.Stderr); var listening = await Interrupt(false, SigHup, listens: true); @@ -105,6 +115,11 @@ public async Task EndsBySighupThoughTheEngineListensForItAndLeavesAProgramThatLi [Fact] public async Task SaysOnStderrThatACloseFailedAndStillEndsByTheSignal() { + if (OperatingSystem.IsWindows()) + { + return; // The signals are POSIX; Windows has no `kill`. + } + var ended = await Interrupt(true); Assert.Equal(SigInt, ended.Signal); Assert.Contains("closing a host on SIGINT failed", ended.Stderr, StringComparison.Ordinal); From fc03570872cb0a81ce00f00450dba45ebc877783 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 18:48:36 +0000 Subject: [PATCH 3/3] Inline the close in Signals.OnSignal like upstream; update COMPATIBILITY Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Ls2e21jov6Swn2Aj93SnF7 --- COMPATIBILITY.md | 2 +- src/E2E/Core/Signals.cs | 25 ++++++++++++------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 6838e0fe1..998b6387e 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -172,7 +172,7 @@ Differences: - `RedactThrown` rebuilds an error that carries a secret value (type and code kept, causes redacted) where upstream edits the thrown error in place, which a .NET exception's read-only message does not allow. An error with no secret is thrown as it is. - `SessionState.ExportAsync` and `ImportAsync` are `Task`-returning like upstream's `async` methods, so a bad key rejects instead of throwing. The key is `SessionStateKeyOptions.Key`, a `byte[]` of 32 bytes; there is no unknown-option check (`plaintext: true` cannot be passed). - `app.linkBase` (`AppConfig.LinkBase`, `ResolvedApp.LinkBase`, `LaunchApp.LinkBase`, checked by `TargetApps.CheckLinkBase`, upstream's `checkLinkBase`) and the engine `openLink` hook (`IEngineSession.OpenLinkAsync`, `EngineSessionSpec.OpenLink`, `ISessionApp.OpenLinkAsync`, `session/openLink` in the manifest schema) are ported, with `App.OpenAsync(path)` joining and opening the link as upstream's `launchPinnedApp` does. `EngineCapabilities.OpenLink` is .NET-only: C# has no optional member to test, so an engine declares the hook the way it declares `Resize`. `TargetApps.JoinLink`, `TargetApps.RefusesLink`, and `Urls.IsRefusedLinkScheme` (upstream's `joinLink`, `refusesLink`, `isRefusedLinkScheme`) are shared with `DeviceLinks`. Not ported: the unknown-key message of a `defineEngine` session, which a typed `EngineSessionSpec` cannot receive (`engine.test.ts`). -- Tests: `Core/CoreSessionStateTests` is `core-state.test.ts`; `Core/CoreTests` is the ported part of `core.test.ts` (partial, and renamed `Partial_...`: 'opens sessions one at a time' (no `gadget` fixture or key list), 'refuses what is not an engine' (no non-engine or unknown app key to pass), 'says a closed session is closed' (the redaction half only), 'bounds each operation by its default timeout' (no agent step, which needs `createAgent`, #1676)); `AppLinkBase/` is `app-link-base.test.ts`; `Core/CoreTests` also holds 'opens a path as a link in the pinned app on a device target with a link base' (`Opens_a_path_as_a_link_...`); `SchemaFixtures/SessionStateV1SchemaTests`; `StepVerification/StepRecorderLastVerifiedStepIndexTests` has the two new `it` (`RedactThrown` is partial: the caught error is checked, not the original in place); `TraceCache/Trace1EntryTests` has the space-press `it`. Not ported: the `it` of `createAgent`, the link-base `it` of `core.test.ts`, `core-signals.test.ts`, and the `engine.test.ts` fixture-name check (#1676 to #1678). +- Tests: `Core/CoreSessionStateTests` is `core-state.test.ts`; `Core/CoreTests` is the ported part of `core.test.ts` (partial, and renamed `Partial_...`: 'opens sessions one at a time' (no `gadget` fixture or key list), 'refuses what is not an engine' (no non-engine or unknown app key to pass), 'says a closed session is closed' (the redaction half only), 'bounds each operation by its default timeout' (no agent step, which needs `createAgent`, #1676)); `AppLinkBase/` is `app-link-base.test.ts`; `Core/CoreTests` also holds 'opens a path as a link in the pinned app on a device target with a link base' (`Opens_a_path_as_a_link_...`); `SchemaFixtures/SessionStateV1SchemaTests`; `StepVerification/StepRecorderLastVerifiedStepIndexTests` has the two new `it` (`RedactThrown` is partial: the caught error is checked, not the original in place); `TraceCache/Trace1EntryTests` has the space-press `it`. Not ported: the `it` of `createAgent`, the link-base `it` of `core.test.ts`, and the `engine.test.ts` fixture-name check (#1676 to #1678). `CoreSignals/CoreOnASignalTests` ports the three `it` of `core-signals.test.ts` whole, apart from the engine-listener removal (#1693). ## Not ported diff --git a/src/E2E/Core/Signals.cs b/src/E2E/Core/Signals.cs index 54581856f..d52cee04b 100644 --- a/src/E2E/Core/Signals.cs +++ b/src/E2E/Core/Signals.cs @@ -74,23 +74,22 @@ private static void OnSignal(PosixSignalContext context) _ = Task.Run(async () => { // The process ends right after, so a close that failed is said on stderr or nowhere; its message is already redacted. - await Task.WhenAll(closers.Select(close => CloseAsync(close, signal))).ConfigureAwait(false); + var pending = closers.Select(async close => + { + try + { + await close().ConfigureAwait(false); + } + catch (Exception cause) + { + await Console.Error.WriteAsync($"E2E: closing a host on {signal} failed: {cause.Message}\n").ConfigureAwait(false); + } + }); + await Task.WhenAll(pending).ConfigureAwait(false); Raise(signal); }); } - private static async Task CloseAsync(Func close, PosixSignal signal) - { - try - { - await close().ConfigureAwait(false); - } - catch (Exception cause) - { - await Console.Error.WriteAsync($"E2E: closing a host on {signal} failed: {cause.Message}\n").ConfigureAwait(false); - } - } - private static void Raise(PosixSignal signal) { if (OperatingSystem.IsWindows())