|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2025 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import crypto from 'node:crypto'; |
| 8 | + |
| 9 | +import type {Channel} from './browser.js'; |
| 10 | +import {launch} from './browser.js'; |
| 11 | +import {logger} from './logger.js'; |
| 12 | +import {McpContext} from './McpContext.js'; |
| 13 | +import {Mutex} from './Mutex.js'; |
| 14 | +import type {Browser} from './third_party/index.js'; |
| 15 | + |
| 16 | +export interface SessionInfo { |
| 17 | + sessionId: string; |
| 18 | + browser: Browser; |
| 19 | + context: McpContext; |
| 20 | + mutex: Mutex; |
| 21 | + createdAt: Date; |
| 22 | + label?: string; |
| 23 | +} |
| 24 | + |
| 25 | +export interface CreateSessionOptions { |
| 26 | + headless?: boolean; |
| 27 | + executablePath?: string; |
| 28 | + channel?: Channel; |
| 29 | + userDataDir?: string; |
| 30 | + viewport?: {width: number; height: number}; |
| 31 | + chromeArgs?: string[]; |
| 32 | + ignoreDefaultChromeArgs?: string[]; |
| 33 | + acceptInsecureCerts?: boolean; |
| 34 | + devtools?: boolean; |
| 35 | + enableExtensions?: boolean; |
| 36 | + label?: string; |
| 37 | +} |
| 38 | + |
| 39 | +export interface McpContextOptions { |
| 40 | + experimentalDevToolsDebugging: boolean; |
| 41 | + experimentalIncludeAllPages?: boolean; |
| 42 | + performanceCrux: boolean; |
| 43 | +} |
| 44 | + |
| 45 | +export class SessionManager { |
| 46 | + readonly #sessions = new Map<string, SessionInfo>(); |
| 47 | + readonly #contextOptions: McpContextOptions; |
| 48 | + #shuttingDown = false; |
| 49 | + |
| 50 | + constructor(contextOptions: McpContextOptions) { |
| 51 | + this.#contextOptions = contextOptions; |
| 52 | + } |
| 53 | + |
| 54 | + async createSession(options: CreateSessionOptions): Promise<SessionInfo> { |
| 55 | + if (this.#shuttingDown) { |
| 56 | + throw new Error('Server is shutting down. Cannot create new sessions.'); |
| 57 | + } |
| 58 | + |
| 59 | + const sessionId = crypto.randomUUID().slice(0, 8); |
| 60 | + logger(`Creating session ${sessionId}`); |
| 61 | + |
| 62 | + let browser: Browser | undefined; |
| 63 | + try { |
| 64 | + browser = await launch({ |
| 65 | + headless: options.headless ?? false, |
| 66 | + executablePath: options.executablePath, |
| 67 | + channel: options.channel, |
| 68 | + userDataDir: options.userDataDir, |
| 69 | + // Always isolated to avoid profile conflicts between concurrent sessions |
| 70 | + isolated: true, |
| 71 | + viewport: options.viewport, |
| 72 | + chromeArgs: options.chromeArgs ?? [], |
| 73 | + ignoreDefaultChromeArgs: options.ignoreDefaultChromeArgs ?? [], |
| 74 | + acceptInsecureCerts: options.acceptInsecureCerts, |
| 75 | + devtools: options.devtools ?? false, |
| 76 | + enableExtensions: options.enableExtensions, |
| 77 | + }); |
| 78 | + |
| 79 | + const context = await McpContext.from( |
| 80 | + browser, |
| 81 | + logger, |
| 82 | + this.#contextOptions, |
| 83 | + ); |
| 84 | + const mutex = new Mutex(); |
| 85 | + |
| 86 | + const session: SessionInfo = { |
| 87 | + sessionId, |
| 88 | + browser, |
| 89 | + context, |
| 90 | + mutex, |
| 91 | + createdAt: new Date(), |
| 92 | + label: options.label, |
| 93 | + }; |
| 94 | + |
| 95 | + browser.on('disconnected', () => { |
| 96 | + logger(`Session ${sessionId} browser disconnected unexpectedly`); |
| 97 | + this.#purgeDisconnectedSession(sessionId); |
| 98 | + }); |
| 99 | + |
| 100 | + this.#sessions.set(sessionId, session); |
| 101 | + logger(`Session ${sessionId} created`); |
| 102 | + return session; |
| 103 | + } catch (err) { |
| 104 | + if (browser?.connected) { |
| 105 | + try { |
| 106 | + await browser.close(); |
| 107 | + } catch (closeErr) { |
| 108 | + logger(`Failed to close browser after creation failure:`, closeErr); |
| 109 | + } |
| 110 | + } |
| 111 | + throw err; |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + getSession(sessionId: string): SessionInfo { |
| 116 | + const session = this.#sessions.get(sessionId); |
| 117 | + if (!session) { |
| 118 | + const available = [...this.#sessions.keys()].join(', '); |
| 119 | + throw new Error( |
| 120 | + `Session "${sessionId}" not found. Available sessions: ${available || 'none. Create one with create_session.'}`, |
| 121 | + ); |
| 122 | + } |
| 123 | + if (!session.browser.connected) { |
| 124 | + this.#purgeDisconnectedSession(sessionId); |
| 125 | + throw new Error( |
| 126 | + `Session "${sessionId}" browser is disconnected. Create a new session.`, |
| 127 | + ); |
| 128 | + } |
| 129 | + return session; |
| 130 | + } |
| 131 | + |
| 132 | + listSessions(): Array<{ |
| 133 | + sessionId: string; |
| 134 | + createdAt: string; |
| 135 | + label?: string; |
| 136 | + connected: boolean; |
| 137 | + }> { |
| 138 | + const result: Array<{ |
| 139 | + sessionId: string; |
| 140 | + createdAt: string; |
| 141 | + label?: string; |
| 142 | + connected: boolean; |
| 143 | + }> = []; |
| 144 | + |
| 145 | + for (const [, session] of this.#sessions) { |
| 146 | + result.push({ |
| 147 | + sessionId: session.sessionId, |
| 148 | + createdAt: session.createdAt.toISOString(), |
| 149 | + label: session.label, |
| 150 | + connected: session.browser.connected, |
| 151 | + }); |
| 152 | + } |
| 153 | + return result; |
| 154 | + } |
| 155 | + |
| 156 | + async closeSession(sessionId: string): Promise<void> { |
| 157 | + const session = this.#sessions.get(sessionId); |
| 158 | + if (!session) { |
| 159 | + throw new Error(`Session "${sessionId}" not found.`); |
| 160 | + } |
| 161 | + |
| 162 | + logger(`Closing session ${sessionId} (acquiring mutex)`); |
| 163 | + const guard = await session.mutex.acquire(); |
| 164 | + try { |
| 165 | + session.context.dispose(); |
| 166 | + if (session.browser.connected) { |
| 167 | + await session.browser.close(); |
| 168 | + } |
| 169 | + } catch (err) { |
| 170 | + logger(`Error closing session ${sessionId}:`, err); |
| 171 | + } finally { |
| 172 | + guard.dispose(); |
| 173 | + this.#sessions.delete(sessionId); |
| 174 | + logger(`Session ${sessionId} closed`); |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + async closeAllSessions(): Promise<void> { |
| 179 | + this.#shuttingDown = true; |
| 180 | + const ids = [...this.#sessions.keys()]; |
| 181 | + await Promise.allSettled(ids.map(id => this.closeSession(id))); |
| 182 | + } |
| 183 | + |
| 184 | + get sessionCount(): number { |
| 185 | + return this.#sessions.size; |
| 186 | + } |
| 187 | + |
| 188 | + get isShuttingDown(): boolean { |
| 189 | + return this.#shuttingDown; |
| 190 | + } |
| 191 | + |
| 192 | + #purgeDisconnectedSession(sessionId: string): void { |
| 193 | + const session = this.#sessions.get(sessionId); |
| 194 | + if (!session) { |
| 195 | + return; |
| 196 | + } |
| 197 | + try { |
| 198 | + session.context.dispose(); |
| 199 | + } catch (err) { |
| 200 | + logger(`Error disposing context for disconnected session ${sessionId}:`, err); |
| 201 | + } |
| 202 | + this.#sessions.delete(sessionId); |
| 203 | + logger(`Purged disconnected session ${sessionId}`); |
| 204 | + } |
| 205 | +} |
0 commit comments