|
| 1 | +using Microsoft.Extensions.Logging; |
| 2 | +using Microsoft.Extensions.Logging.Abstractions; |
| 3 | +using Motus; |
| 4 | +using Motus.Abstractions; |
| 5 | + |
| 6 | +namespace Motus.Mcp; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Owns the live browser for the lifetime of an MCP server session. Tool calls |
| 10 | +/// arrive as individually stateless messages, so this holder keeps the browser, |
| 11 | +/// its isolated contexts, and the active selection between calls. |
| 12 | +/// </summary> |
| 13 | +/// <remarks> |
| 14 | +/// The model is intentionally multi-context from the start: one browser holds |
| 15 | +/// several named, isolated contexts (each with its own cookies and storage), and |
| 16 | +/// one of them is active at any time. An implicit <see cref="DefaultContextName"/> |
| 17 | +/// context is created on first use, so a caller that never touches named contexts |
| 18 | +/// sees a plain single-session model. Element-addressing and per-tab state are |
| 19 | +/// layered on later by the components that consume them. |
| 20 | +/// </remarks> |
| 21 | +public sealed class BrowserSessionManager : IAsyncDisposable |
| 22 | +{ |
| 23 | + /// <summary>The name of the context created implicitly on first use.</summary> |
| 24 | + public const string DefaultContextName = "default"; |
| 25 | + |
| 26 | + private readonly McpServerLaunchOptions _options; |
| 27 | + private readonly ILogger<BrowserSessionManager> _logger; |
| 28 | + private readonly SemaphoreSlim _gate = new(1, 1); |
| 29 | + private readonly Dictionary<string, IBrowserContext> _contexts = new(StringComparer.Ordinal); |
| 30 | + |
| 31 | + private IBrowser? _browser; |
| 32 | + private int _disposed; |
| 33 | + |
| 34 | + public BrowserSessionManager(McpServerLaunchOptions options, ILogger<BrowserSessionManager>? logger = null) |
| 35 | + { |
| 36 | + _options = options; |
| 37 | + _logger = logger ?? NullLogger<BrowserSessionManager>.Instance; |
| 38 | + } |
| 39 | + |
| 40 | + /// <summary>The name of the context that unscoped tool calls act on.</summary> |
| 41 | + public string ActiveContextName { get; private set; } = DefaultContextName; |
| 42 | + |
| 43 | + /// <summary>Whether the browser process has been launched.</summary> |
| 44 | + public bool IsBrowserLaunched => _browser is not null; |
| 45 | + |
| 46 | + /// <summary>A snapshot of the currently open context names.</summary> |
| 47 | + public IReadOnlyCollection<string> ContextNames => _contexts.Keys.ToArray(); |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Returns the live browser, launching it lazily on first use. Concurrent |
| 51 | + /// first callers share a single launch. |
| 52 | + /// </summary> |
| 53 | + public async Task<IBrowser> EnsureBrowserAsync(CancellationToken cancellationToken = default) |
| 54 | + { |
| 55 | + if (_browser is not null) |
| 56 | + { |
| 57 | + return _browser; |
| 58 | + } |
| 59 | + |
| 60 | + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 61 | + try |
| 62 | + { |
| 63 | + ThrowIfDisposed(); |
| 64 | + if (_browser is null) |
| 65 | + { |
| 66 | + _logger.LogInformation( |
| 67 | + "Launching browser (headless={Headless}, channel={Channel}).", |
| 68 | + _options.Headless, |
| 69 | + _options.Channel); |
| 70 | + _browser = await MotusLauncher.LaunchAsync(_options.ToLaunchOptions(), cancellationToken) |
| 71 | + .ConfigureAwait(false); |
| 72 | + } |
| 73 | + |
| 74 | + return _browser; |
| 75 | + } |
| 76 | + finally |
| 77 | + { |
| 78 | + _gate.Release(); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /// <summary> |
| 83 | + /// Returns the active context, creating it (and launching the browser) on |
| 84 | + /// first use. |
| 85 | + /// </summary> |
| 86 | + public Task<IBrowserContext> GetOrCreateActiveContextAsync(CancellationToken cancellationToken = default) |
| 87 | + => GetOrCreateContextAsync(ActiveContextName, cancellationToken); |
| 88 | + |
| 89 | + /// <summary> |
| 90 | + /// Creates a new isolated context with the given name and makes it active. |
| 91 | + /// </summary> |
| 92 | + /// <exception cref="InvalidOperationException">A context with that name already exists.</exception> |
| 93 | + public async Task<IBrowserContext> CreateContextAsync(string name, CancellationToken cancellationToken = default) |
| 94 | + { |
| 95 | + ArgumentException.ThrowIfNullOrEmpty(name); |
| 96 | + var browser = await EnsureBrowserAsync(cancellationToken).ConfigureAwait(false); |
| 97 | + |
| 98 | + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 99 | + try |
| 100 | + { |
| 101 | + ThrowIfDisposed(); |
| 102 | + if (_contexts.ContainsKey(name)) |
| 103 | + { |
| 104 | + throw new InvalidOperationException($"A context named '{name}' already exists."); |
| 105 | + } |
| 106 | + |
| 107 | + var context = await browser.NewContextAsync().ConfigureAwait(false); |
| 108 | + _contexts[name] = context; |
| 109 | + ActiveContextName = name; |
| 110 | + return context; |
| 111 | + } |
| 112 | + finally |
| 113 | + { |
| 114 | + _gate.Release(); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /// <summary>Makes an existing context active.</summary> |
| 119 | + /// <exception cref="InvalidOperationException">No context with that name is open.</exception> |
| 120 | + public void SelectContext(string name) |
| 121 | + { |
| 122 | + ArgumentException.ThrowIfNullOrEmpty(name); |
| 123 | + if (!_contexts.ContainsKey(name)) |
| 124 | + { |
| 125 | + throw new InvalidOperationException($"No open context named '{name}'."); |
| 126 | + } |
| 127 | + |
| 128 | + ActiveContextName = name; |
| 129 | + } |
| 130 | + |
| 131 | + /// <summary> |
| 132 | + /// Closes the named context and its pages. If the active context is closed, |
| 133 | + /// the active selection falls back to <see cref="DefaultContextName"/>. |
| 134 | + /// </summary> |
| 135 | + public async Task CloseContextAsync(string name, CancellationToken cancellationToken = default) |
| 136 | + { |
| 137 | + ArgumentException.ThrowIfNullOrEmpty(name); |
| 138 | + |
| 139 | + IBrowserContext? context; |
| 140 | + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 141 | + try |
| 142 | + { |
| 143 | + if (!_contexts.Remove(name, out context)) |
| 144 | + { |
| 145 | + return; |
| 146 | + } |
| 147 | + |
| 148 | + if (ActiveContextName == name) |
| 149 | + { |
| 150 | + ActiveContextName = DefaultContextName; |
| 151 | + } |
| 152 | + } |
| 153 | + finally |
| 154 | + { |
| 155 | + _gate.Release(); |
| 156 | + } |
| 157 | + |
| 158 | + await context.CloseAsync().ConfigureAwait(false); |
| 159 | + } |
| 160 | + |
| 161 | + private async Task<IBrowserContext> GetOrCreateContextAsync(string name, CancellationToken cancellationToken) |
| 162 | + { |
| 163 | + var browser = await EnsureBrowserAsync(cancellationToken).ConfigureAwait(false); |
| 164 | + |
| 165 | + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| 166 | + try |
| 167 | + { |
| 168 | + ThrowIfDisposed(); |
| 169 | + if (_contexts.TryGetValue(name, out var existing)) |
| 170 | + { |
| 171 | + return existing; |
| 172 | + } |
| 173 | + |
| 174 | + var context = await browser.NewContextAsync().ConfigureAwait(false); |
| 175 | + _contexts[name] = context; |
| 176 | + return context; |
| 177 | + } |
| 178 | + finally |
| 179 | + { |
| 180 | + _gate.Release(); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + private void ThrowIfDisposed() |
| 185 | + { |
| 186 | + ObjectDisposedException.ThrowIf(_disposed != 0, this); |
| 187 | + } |
| 188 | + |
| 189 | + /// <summary> |
| 190 | + /// Tears the session down: closes every context, then the browser. Safe to |
| 191 | + /// call more than once. |
| 192 | + /// </summary> |
| 193 | + public async ValueTask DisposeAsync() |
| 194 | + { |
| 195 | + if (Interlocked.Exchange(ref _disposed, 1) != 0) |
| 196 | + { |
| 197 | + return; |
| 198 | + } |
| 199 | + |
| 200 | + await _gate.WaitAsync().ConfigureAwait(false); |
| 201 | + try |
| 202 | + { |
| 203 | + foreach (var context in _contexts.Values) |
| 204 | + { |
| 205 | + try |
| 206 | + { |
| 207 | + await context.CloseAsync().ConfigureAwait(false); |
| 208 | + } |
| 209 | + catch (Exception ex) |
| 210 | + { |
| 211 | + _logger.LogWarning(ex, "Failed to close a browser context during shutdown."); |
| 212 | + } |
| 213 | + } |
| 214 | + |
| 215 | + _contexts.Clear(); |
| 216 | + |
| 217 | + if (_browser is not null) |
| 218 | + { |
| 219 | + try |
| 220 | + { |
| 221 | + await _browser.CloseAsync().ConfigureAwait(false); |
| 222 | + } |
| 223 | + catch (Exception ex) |
| 224 | + { |
| 225 | + _logger.LogWarning(ex, "Failed to close the browser cleanly; forcing disposal."); |
| 226 | + await _browser.DisposeAsync().ConfigureAwait(false); |
| 227 | + } |
| 228 | + |
| 229 | + _browser = null; |
| 230 | + } |
| 231 | + } |
| 232 | + finally |
| 233 | + { |
| 234 | + _gate.Release(); |
| 235 | + _gate.Dispose(); |
| 236 | + } |
| 237 | + } |
| 238 | +} |
0 commit comments