Docs · Architecture

Browser Lifecycle#

This document describes how Motus creates, manages, and tears down browser instances. It covers the full path from calling MotusLauncher.LaunchAsync through to disposal, including browser discovery, the object hierarchy, context and page initialization, signal handling, and the optional browser pool.


Launching a browser#

MotusLauncher.LaunchAsync in Motus.cs is the primary entry point.

IBrowser browser = await MotusLauncher.LaunchAsync(new LaunchOptions
{
    Channel = BrowserChannel.Chrome,
    Headless = true,
});

The launch sequence runs in the following order:

  1. Config merge. ConfigMerge.ApplyConfig(options) overlays values from motus.json (loaded by MotusConfigLoader) onto the caller-supplied LaunchOptions. File-level settings win only when the programmatic option is still at its default value, so explicit caller values are never overwritten.

  2. Executable resolution. BrowserFinder.Resolve(options.Channel, options.ExecutablePath) locates the binary. See Browser discovery below.

  3. Firefox detection. IsFirefoxChannel returns true when the channel is BrowserChannel.Firefox or when the resolved executable filename contains "firefox" (case-insensitive). This flag drives every subsequent branch.

  4. Transport choice. A Chromium browser on Unix is driven over a pipe: --remote-debugging-pipe tells the browser to read commands on file descriptor 3 and write on 4, and the browser exits when its end of that pipe closes, so it cannot outlive the process that started it. Firefox has no pipe mode, and Windows offers no way to hand a child arbitrary descriptors, so both keep a debugging port. When a port is needed, AllocateFreePort() binds a TcpListener on IPAddress.Loopback:0, reads the OS-assigned port from LocalEndpoint, then immediately stops the listener.

  5. Profile directory. - For Chromium channels: if options.UserDataDir is null, a temporary directory is created at {Path.GetTempPath()}/motus-profile-{8-char guid}. The ownsTempDir flag is set to true so the directory is deleted on cleanup. - For Firefox: FirefoxProfileManager.CreateTempProfile creates a minimal profile directory unconditionally when no UserDataDir is supplied.

  6. Process start. A ProcessStartInfo is built with UseShellExecute = false, RedirectStandardOutput = true, and RedirectStandardError = true. Arguments are added via ArgumentList (not Arguments) so that paths with spaces are handled correctly without manual quoting. For Firefox, environment variables from FirefoxArgs.Build are also applied.

A browser on the pipe transport is started through /bin/sh -c 'exec "$0" "$@" 3<&0 4>&1 1>/dev/null', because the process API offers no way to give a child an arbitrary file descriptor. The shell copies this process's end of the redirected standard input onto descriptor 3 and of the redirected standard output onto descriptor 4, points standard output at nothing so the browser's own logging cannot be mistaken for protocol traffic, and then replaces itself with the browser, so the process handle still refers to the browser. Standard output then carries CDP rather than diagnostics, and only standard error is drained.

  1. Transport connection. - Chromium on a pipe: a CdpTransport wraps a CdpPipeSocket over the redirected streams and is started rather than connected, since the pipes are already open. Each message is a JSON document followed by a NUL byte in both directions. There is no endpoint to discover and nothing to poll. - Chromium on a port: CdpEndpointPoller.WaitForEndpointAsync polls the /json/version HTTP endpoint on the allocated port until the browser is ready, then returns a WebSocket URL. A CdpTransport wraps a CdpSocket and connects to that URL. An optional SlowMo delay (milliseconds) is wired into the transport. - Firefox: FirefoxEndpointReader.WaitForEndpointAsync reads the process's stderr stream to discover the WebSocket BiDi endpoint. A BiDiTransport connects and negotiates an initial session.

  2. Browser object construction. A Browser instance is created with the transport, session registry, process handle, temp dir path (if owned), signal-handler flags, and on Windows a job object that ends the browser when this process's handles close. InitializeAsync then sends Browser.getVersion over the browser-level CDP/BiDi session to populate IBrowser.Version and sets IsConnected = true.

Error handling: if any step after process start throws, the process is killed with entireProcessTree: true, disposed, and the temp directory deleted before the exception propagates.


Connecting to an existing browser#

MotusLauncher.ConnectAsync attaches to a browser that is already running and listening for CDP connections. For the task-focused version of this, including how to start such a browser and what attaching is good for, see Attaching to a Running Browser.

IBrowser browser = await MotusLauncher.ConnectAsync("http://127.0.0.1:9222");
IBrowser browser = await MotusLauncher.ConnectAsync("ws://localhost:9222/devtools/browser/...");

Either endpoint form is accepted. ResolveWebSocketEndpointAsync passes a ws/wss URI straight through, and for an http/https endpoint fetches /json/version and reads webSocketDebuggerUrl from it. Both forms exist because the HTTP endpoint is the one a caller who chose the port already knows.

The sequence is simpler than a launch:

  1. A CdpSocket and CdpTransport are created, with the SlowMo delay from ConnectOptions if one was set.
  2. The transport connects to the resolved WebSocket URI.
  3. A CdpSessionRegistry wraps the transport.
  4. A Browser is constructed with process: null and tempUserDataDir: null. Signal handlers are not registered (handleSigint: false, handleSigterm: false) because Motus does not own the process.
  5. InitializeAsync runs identically to the launch path, and additionally adopts existing targets when ConnectOptions.AdoptExistingTargets is true, which is the default.

The whole connect is bounded by ConnectOptions.Timeout (default 30 seconds). Neither the WebSocket handshake nor target adoption carries a bound of its own, so an endpoint that accepts a connection and then answers nothing would otherwise hold the caller for good.

Each stage is bounded separately out of that one budget, so running out of time says which stage was still waiting rather than only how long the caller waited. The timeout error names one of three: the debugging endpoint never answered with a WebSocket URL, and what the last attempt to reach it said; it named a URL and that WebSocket never finished opening; or the WebSocket opened and the browser never finished reporting its version and taking over the tabs already open. A refused connection, a name that will not resolve and an answer from something else listening on that port all look identical from the outside and call for different next steps, which is why the first of the three carries the last failure's own message with it.

Target adoption#

Adoption is what makes browser.Contexts and context.Pages reflect the browser as it actually is, with no further call. Target.setDiscoverTargets switches discovery on, Target.getTargets is read on the browser-level session, and for each page target:

  • The browser context it belongs to is created as an adopted BrowserContext, or reused if already seen. A context with no browserContextId is the browser's default context. An adopted context gets a plugin host of its own, since selector strategies are registered by the built-in plugins and a context without them cannot resolve a single locator.
  • Target.attachToTarget with flatten: true opens a session for the page, and a Page is built around it and initialized the way a created page is, including Page.setInterceptFileChooserDialog. A tab that was already open has already navigated, so enabling the Page domain replays nothing and the frame map would stay empty; the frame tree is read once instead.
  • None of the context's own options are applied. The viewport, locale, timezone and user agent of a tab that was already open belong to whoever opened it, and overriding them would change a browser Motus does not own.

The file chooser interception has a consequence worth knowing: while Motus is attached, a file picker opened by the person using the browser is intercepted and does not appear.

A page that will not answer is reported on standard error and skipped, rather than failing the whole connect or dropping every other page in the browser along with it.

Only once every existing target has been wrapped does the event pump start, so it cannot race the enumeration over the same target. From then on, targets appearing and disappearing are tracked through Target.targetCreated and Target.targetDestroyed, so a long-lived session stays accurate rather than describing a snapshot taken at connect time. A target the browser announces is claimed by its context only if that context does not already hold it and is not in the middle of building it, which is what keeps a page opened by a call from also being wrapped a second time by the pump.

Ownership#

IBrowser.OwnsProcess reports whether Motus started the browser. It is the flag every teardown path keys off.

Call OwnsProcess: true OwnsProcess: false
CloseAsync Closes contexts, sends Browser.close, waits for the process, kills it if it overstays Closes contexts Motus created, then drops the transport. Browser.close is never sent
DisconnectAsync Drops the transport and leaves the process running Drops the transport
DisposeAsync Kills the process without the grace period, deletes an owned temp profile Drops the transport

An adopted BrowserContext carries the same distinction one level down. Closing one releases its pages from Motus and unloads its plugins, but Target.disposeBrowserContext is not sent, so windows belonging to whoever is using the browser survive. Page disposal is likewise local: Page.DisposeAsync tears down Motus's own state and does not send Target.closeTarget.

DisconnectAsync exists so intent is visible at the call site. For an attached browser it does what CloseAsync does; for a launched one it is the only way to walk away from a browser without ending it.

When the connection drops#

IBrowser.IsConnected goes false and the Disconnected event fires, exactly as for a launched browser. Handles taken before that point are not silently wrong: operations on them fail with a disconnection error rather than appearing to succeed.

For an attached browser, a dropped connection says nothing about whether the browser is still running, so reconnecting to the same endpoint is the correct recovery and fails cleanly if the browser really is gone. This is what the MCP server's session manager does; see Health detection below.


Browser discovery#

BrowserFinder.Resolve determines the executable path using the following precedence:

  1. Explicit path. If options.ExecutablePath is set, it is validated with File.Exists and returned directly. A FileNotFoundException is thrown if the file does not exist.

  2. Channel-specific candidates. If options.Channel is set, CandidatesForChannel builds an ordered list of paths for the current platform and returns the first one that exists.

  3. Auto-detect. If neither option is set, Resolve iterates over Chrome, Edge, and Chromium in that order, returning the first match found.

InstalledBinariesPath#

When the Motus install system downloads a browser, it sets BrowserFinder.InstalledBinariesPath. This path is prepended to every channel's candidate list, ahead of system-installed locations.

Pinning a specific binary#

Steps 2 and 3 above resolve to whichever build is installed, which is why a CI run can change behavior without a commit: the channel moved. Step 1 is the escape from that. motus install --revision <n> downloads an exact Chromium revision, constructing the download URL for that revision rather than resolving through the stable listing, and launch.executablePath or MOTUS_EXECUTABLE_PATH then points options.ExecutablePath at it. A path set in code still wins over both, so the precedence above is unchanged.

On Windows, a browser unzipped into a user directory does not necessarily carry the file-system permissions its sandbox requires. The installer grants them during install and when repairing an existing install. A failure there is reported rather than fatal, since the browser can still run where those permissions are not needed.

See Configuration for the settings, and Sharding for why reproducibility matters more once a suite is spread across agents.

Platform candidate paths#

Channel macOS Linux Windows
Chrome /Applications/Google Chrome.app/Contents/MacOS/Google Chrome /usr/bin/google-chrome-stable, /usr/bin/google-chrome %ProgramFiles%\Google\Chrome\Application\chrome.exe, %ProgramFiles(x86)%\..., %LocalAppData%\...
Edge /Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge /usr/bin/microsoft-edge-stable, /usr/bin/microsoft-edge %ProgramFiles%\Microsoft\Edge\Application\msedge.exe, %ProgramFiles(x86)%\...
Chromium /Applications/Chromium.app/Contents/MacOS/Chromium /usr/bin/chromium-browser, /usr/bin/chromium %LocalAppData%\Chromium\Application\chrome.exe
Firefox /Applications/Firefox.app/Contents/MacOS/firefox, /Applications/Firefox Nightly.app/... /usr/bin/firefox, /usr/bin/firefox-esr, /usr/local/bin/firefox, /snap/bin/firefox %ProgramFiles%\Mozilla Firefox\firefox.exe, %ProgramFiles(x86)%\...

Object hierarchy#

IBrowser
  └─ IBrowserContext  (one or more)
       └─ IPage       (one or more)

Ownership and lifetime rules:

  • IBrowser owns all IBrowserContext instances. CloseAsync on the browser closes all contexts in order before sending Browser.close.
  • IBrowserContext owns all IPage instances. Closing a context closes all its pages, then sends Target.disposeBrowserContext.
  • IPage is owned by the context that created it. A page closed independently (via IPage.CloseAsync) removes itself from the context's page list and sends Target.closeTarget, but does not close the context.
  • IBrowser also owns the OS process (when launched) and the temp profile directory (when UserDataDir was not supplied by the caller).

The IBrowserContext.Browser property provides upward navigation. IPage.Context provides upward navigation from a page to its owning context.


Context creation#

IBrowser.NewContextAsync creates an isolated browsing context.

IBrowserContext context = await browser.NewContextAsync(new ContextOptions
{
    Viewport = new ViewportSize(1280, 720),
    Locale = "en-US",
});

Internally, Browser.NewContextAsync runs these steps:

  1. ConfigMerge.ApplyConfig(options) merges motus.json context defaults.

  2. The CDP command Target.createBrowserContext is sent on the browser-level session with DisposeOnDetach: true. This creates a new isolated context in the browser process and returns a browserContextId.

  3. A BrowserContext is instantiated with the registry, the context ID, and the resolved options. It does not yet contain any pages.

  4. Plugin loading. A PluginHost is created and LoadAsync is called: - Built-in plugins (BuiltinSelectorsPlugin, AccessibilityRulesPlugin, AccessibilityAuditHook) are loaded unconditionally. Failures propagate and abort context creation. - Auto-discovered plugins registered via PluginDiscovery.Factory are merged with any plugins supplied in LaunchOptions.Plugins. Manual registrations take precedence in deduplication by PluginId. - User and discovered plugins are loaded with per-plugin failure isolation: a plugin that throws OnLoadedAsync is silently skipped. - Plugins are loaded in registration order; they are unloaded in reverse order when the context closes.

  5. The context is added to Browser._contexts.

  6. If ContextOptions.Permissions contains entries, Browser.grantPermissions is sent immediately.

The convenience method IBrowser.NewPageAsync calls NewContextAsync followed by context.NewPageAsync, creating a page in a fresh isolated context.


Page creation#

IBrowserContext.NewPageAsync creates a new tab within the context.

IPage page = await context.NewPageAsync();

The sequence:

  1. Target.createTarget is sent with url: "about:blank" and the parent BrowserContextId. The browser returns a targetId.

  2. Target.attachToTarget is sent with flatten: true. The browser returns a sessionId for the new page's CDP session.

  3. A Page object is constructed around the new session and target ID, then Page.InitializeAsync runs:

a. The event pump is started before any CDP domain is enabled. This is necessary because Chrome fires Runtime.executionContextCreated immediately when Runtime.enable is sent. If the pump were not already listening, that first event and the main-frame context ID would be dropped.

b. Page.enable is sent to enable page lifecycle events.

c. Runtime.enable is sent to enable JavaScript context tracking.

d. Page.setInterceptFileChooserDialog is sent with enabled: true to capture file chooser dialogs.

e. Any init scripts registered on the context via AddInitScriptAsync are installed with Page.addScriptToEvaluateOnNewDocument.

f. Any bindings registered on the context via ExposeBindingAsync are applied with Runtime.addBinding.

g. Network monitoring and interception are initialized via InitializeNetworkAsync.

  1. Context options are applied to the new page: viewport (Emulation.setDeviceMetricsOverride), locale, timezone, color scheme, user agent, HTTPS error handling, and geolocation are each sent if the corresponding option is set.

  2. Context-level extra HTTP headers and offline state are propagated to the page.

  3. If ContextOptions.StorageState is set and this is the first page created in the context, cookies and localStorage entries are restored.

  4. If ContextOptions.RecordVideo is set, a VideoRecorder is started.

  5. The page is added to BrowserContext._pages, lifecycle hooks fire OnPageCreated, and the IBrowserContext.Page event is raised.

Popups and new tabs#

A tab the page opens for itself, through window.open or a link with target="_blank", is a page of the context its opener belongs to. Every browser Motus drives watches for new targets, whoever started it, because a tab one of Motus's own pages opens belongs to Motus wherever the browser came from. Without that, such a tab would load a document no caller could see, address, or close.

When one appears, the owning context takes it in much the way it takes in a page it was asked for: a session is attached, the page is initialized, it is added to context.Pages, OnPageCreated and the IBrowserContext.Page event fire, and then the page that opened it is handed the new one through IPage.Popup. The event argument is that IPage itself, so there is nothing to unwrap:

var opened = new TaskCompletionSource<IPage>(TaskCreationOptions.RunContinuationsAsynchronously);
page.Popup += (_, popup) => opened.TrySetResult(popup);

await page.Locator("a[target=_blank]").ClickAsync();

IPage receipt = await opened.Task;
await receipt.WaitForURLAsync("**/receipt.html");

A Chromium window with two tabs: Checkout, the page that was clicked, and Receipt, the tab that page opened, whose text has been rewritten through the page handle the Popup event handed over.

Subscribe before the action that opens the tab, since the browser can announce the tab before that action returns. The page handed over is ready to be driven: its domains are enabled and its frame tree has been read, so a handler can navigate it, wait on it, or close it with no further step. It may still be on about:blank at that moment, because the browser opens the tab before the document it was asked for arrives, which is why the example above waits on the page rather than reading Url straight away.

A popup adds a page, never a context. It belongs to the opener's context and, where that is a context Motus created, is given that context's viewport, locale, timezone and user agent, so one tab does not sit at the browser default while the rest are emulated. A popup that closes leaves context.Pages right away either way: IPage.CloseAsync drops it from the list before Target.closeTarget is sent, and a tab the page closed itself is dropped when the browser's Target.targetDestroyed report arrives. The handle then says closed rather than failing obscurely on the next call. Closing the context takes the popup with the rest of its pages: for a context Motus created, Target.disposeBrowserContext ends every tab in it, the one the page opened included.

Attaching narrows this rather than switching it off. ConnectOptions.AdoptExistingTargets decides what is taken over, not what is watched, so a popup from a context you created is tracked either way; see Attaching to a Running Browser for that carve-out and what it is for.

All of this rests on CDP target discovery, which only a transport that multiplexes targets offers. Firefox over WebDriver BiDi models browsing contexts its own way and reports nothing through this path.


Cleanup and disposal#

IBrowser.CloseAsync#

CloseAsync is the graceful shutdown path:

  1. IsConnected is set to false.
  2. The BrowserHeartbeat (if running) is disposed, stopping background health pings.
  3. Signal handlers and the Process.Exited handler are unregistered.
  4. All contexts are closed in sequence by calling context.CloseAsync().
  5. Browser.close is sent over the browser-level CDP session. A CdpDisconnectedException is expected and caught because the browser closes the WebSocket as part of its shutdown.
  6. The transport is disposed.
  7. The owned OS process (if any) is awaited for up to 5 seconds. If it has not exited within that window, process.Kill(entireProcessTree: true) is called.

IBrowserContext.CloseAsync#

  1. PluginHost.UnloadAsync is called first, unloading plugins in reverse registration order. Individual plugin failures are swallowed so all plugins receive OnUnloadedAsync.
  2. Each page has lifecycle hooks fired (OnPageClosed), then page.DisposeAsync is called. The CDP session and its event channels are cleaned up.
  3. Target.disposeBrowserContext is sent to the browser.
  4. The IBrowserContext.Close event is raised.

IBrowser.DisposeAsync#

DisposeAsync is the non-graceful teardown path, used when an exception occurs during launch or when the pool discards a disconnected browser:

  1. The BrowserHeartbeat (if running) is disposed.
  2. Signal handlers and the Process.Exited handler are unregistered.
  3. IsConnected is set to false.
  4. The transport is disposed asynchronously.
  5. If the process has not exited, process.Kill(entireProcessTree: true) is called immediately, without the 5-second grace period.
  6. The process handle is disposed.
  7. If a temp user data directory is owned, Directory.Delete(path, recursive: true) is attempted. Failures are silently ignored (best-effort cleanup).

Health detection#

When a browser is launched (not connected via ConnectAsync), Motus monitors the browser process for two failure modes: crashes and freezes.

Crash detection via Process.Exited. The Browser constructor subscribes to _process.Exited. When Chrome crashes or is killed externally, the handler fires immediately, sets IsConnected = false, disposes the transport (which faults all pending CDP commands with CdpDisconnectedException), and raises the Disconnected event. This is faster than waiting for the WebSocket receive loop to detect the broken connection.

Freeze detection via BrowserHeartbeat. After InitializeAsync completes, a background BrowserHeartbeat is started for launched browsers. The heartbeat sends Browser.getVersion every 5 seconds with a 10-second timeout. If the ping times out or fails (and the browser has not been intentionally shut down), the OnHeartbeatFailed callback triggers the same disconnect path as Process.Exited. This catches cases where Chrome becomes unresponsive without closing the WebSocket, such as GPU process hangs or runaway JavaScript.

Both handlers are guarded by an Interlocked.CompareExchange on _disconnectedFlag so that only one path fires the Disconnected event, regardless of which detection mechanism triggers first.

IBrowser.IsHealthy. The IsHealthy property (defined as a default interface member on IBrowser) returns true when the browser is connected. The Browser implementation overrides this with a process-aware check: _isConnected && (_process is null || !_process.HasExited). For browsers obtained via ConnectAsync (no process ownership), IsHealthy is equivalent to IsConnected.

Recovery built on health detection. IsHealthy and the Disconnected event are the primitives consumers use to survive a dead browser rather than fail for good. The browser pool relaunches replacements proactively (see Browser pooling below). A single-browser holder, such as the MCP server's session manager, instead checks IsHealthy lazily on the next use: finding the cached browser unhealthy, it disposes it and acquires another in its place, so a crash costs one failed operation rather than the whole session. Where that replacement comes from follows ownership. A browser the holder started is started again; one it connected to is connected to again at the same endpoint, since a browser it did not start is not one it can start.

Signal handlers#

When a browser is launched (not connected), signal handlers are registered if the corresponding LaunchOptions flags are set:

  • HandleSIGINT (default true): registers for SIGINT on Unix, and hooks Console.CancelKeyPress on Windows, where Ctrl+C arrives as a console control event instead.
  • HandleSIGTERM (default true): registers for SIGTERM and SIGHUP on Unix. A closed terminal ends a process the same way a kill does and leaves the same browser behind, so it is covered by the same flag. Windows has neither signal, so this flag does nothing there.

The handler closes the browser and waits for it, up to five seconds, then ends the browser process outright if the close has not finished. The wait is the point: a handler that starts the close and returns would let the process end with the close half sent, and the browser would keep running with nothing left that knows about it.

None of the signals is cancelled, so each keeps its ordinary meaning and the process still ends on it. What the handler changes is the order, closing the browser first while there is still something running that knows about it.

Signals rather than AppDomain.CurrentDomain.ProcessExit, because that event does not fire for a signal on Unix at all. A process sent SIGTERM or SIGINT is ended by the operating system and nothing managed runs on the way out, so a browser left to that event is a browser left running.

Handlers are released in CloseAsync, DisconnectAsync and DisposeAsync via UnregisterSignalHandlers. Signal handlers are never registered for browsers obtained via ConnectAsync, because a browser Motus did not start is not Motus's to end.

SIGKILL cannot be caught by anything, so none of the above applies to it. What covers that case is the transport: a browser driven over a pipe sees its end close when this process dies, however it died, and exits. That is also why a browser context Motus creates in a browser it started is not marked disposeOnDetach. A browser that answers a detach by disposing contexts does not also act on the connection having closed, and would keep running with nothing left in it.


Browser pooling#

MotusBrowserPool manages a pool of reusable browser instances for concurrent workloads such as parallel test execution.

await using IBrowserPool pool = await MotusBrowserPool.CreateAsync(new BrowserPoolOptions
{
    MinInstances = 2,
    MaxInstances = 8,
    AcquireTimeout = TimeSpan.FromSeconds(30),
    LaunchOptions = new LaunchOptions { Headless = true },
});

await using IBrowserLease lease = await pool.AcquireAsync();
IPage page = await lease.Browser.NewPageAsync();
// ... use page ...
// Lease returns browser to pool on DisposeAsync

BrowserPoolOptions#

Property Default Description
MinInstances 1 Number of browsers launched eagerly during WarmUpAsync.
MaxInstances Environment.ProcessorCount Hard cap on concurrent browser instances.
AcquireTimeout 30s How long AcquireAsync waits when all instances are busy.
LaunchOptions null Launch settings applied to every browser in the pool.

Internals#

BrowserPool uses two concurrency primitives:

  • A SemaphoreSlim initialized to MaxInstances tracks total capacity.
  • An unbounded Channel<IBrowser> acts as the idle queue.

MotusBrowserPool.CreateAsync constructs the pool and calls WarmUpAsync, which launches MinInstances browsers in parallel, each acquiring a semaphore slot before launching.

AcquireAsync flow:

  1. Attempt to dequeue an idle browser immediately without blocking.
  2. If no idle browser is available and capacity remains, launch a new browser.
  3. If at capacity, wait for up to AcquireTimeout for a browser to be returned.
  4. Any idle browser that is found to be disconnected is disposed and its semaphore slot released.

The returned IBrowserLease holds the browser and a return callback. Disposing the lease returns the browser to the idle channel if it is still connected and the pool has not been disposed. A disconnected or post-dispose browser is discarded and the semaphore slot is released.

Proactive replenishment. The pool subscribes to each browser's Disconnected event. When a browser crashes or becomes unresponsive, OnBrowserDisconnected disposes the dead browser, releases its capacity semaphore slot, and (if the idle count has dropped below MinInstances) launches a replacement in the background. A ConcurrentDictionary<IBrowser, byte> deduplicates the disconnect and lease-return paths to prevent double-dispose when both fire for the same browser.

IBrowserPool.ActiveCount and IdleCount expose live counters for observability.

DisposeAsync on the pool drains and disposes all idle browsers. Browsers that are currently leased out are not forcibly recalled; callers must dispose their leases before the pool can be fully cleaned up.


See Also#

  • src/Motus/Motus.cs - MotusLauncher source
  • src/Motus/Browser/BrowserFinder.cs - platform executable discovery
  • src/Motus/Context/BrowserContext.cs - context and page creation
  • src/Motus/Page/Page.cs - page initialization and CDP domain enablement
  • src/Motus/Pool/MotusBrowserPool.cs and BrowserPool.cs - pool implementation
  • src/Motus/Plugins/PluginHost.cs - plugin loading and unloading
  • src/Motus.Abstractions/IBrowser.cs, IBrowserContext.cs, IPage.cs - public contracts
  • src/Motus.Abstractions/IBrowserPool.cs - pool and lease contracts
  • src/Motus.Abstractions/Options/LaunchOptions.cs - launch configuration reference
  • src/Motus.Abstractions/Options/ConnectOptions.cs - attach configuration reference
  • src/Motus.Abstractions/Options/BrowserPoolOptions.cs - pool configuration reference
  • docs/architecture/overview.md - high-level architecture overview
  • Attaching to a Running Browser - the task-focused guide to connecting