dsh-web-fetch-playwright 0.2.12 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cdp-pool.ts CHANGED
@@ -1,211 +1,396 @@
1
- /**
2
- * The CDP backend's shared connection: one `connectOverCDP` session reused by
3
- * every fetch, each fetch leasing a page (a tab in the remote browser) that
4
- * it closes when done — in an isolated throwaway context (`isolated` mode),
5
- * or in the remote browser's default context (`profile` mode, whose cookies
6
- * and localStorage are the real profile's, so its persistent logins apply;
7
- * that context is never closed, only the tab is). The connection itself
8
- * outlives fetches — reconnecting per fetch would spend 100–500ms per call
9
- * and open one socket per concurrent tab for no benefit.
10
- *
11
- * Liveness is handled three ways: `isConnected()` is checked before reuse, a
12
- * `disconnected` event (when the backend emits it) drops the reference
13
- * immediately, and an open-lease failure against a dead connection triggers
14
- * exactly one reconnect-and-retry before the error surfaces. A changed
15
- * endpoint (settings edit) replaces the connection.
16
- *
1
+ /** Session-dedicated or global/profile-shared CDP connections and page leases.
2
+ * Retired generations drain
3
+ * before disconnecting; named contexts belong to a generation, never a profile.
17
4
  * @module dsh-web-fetch-playwright/cdp-pool
18
5
  */
19
-
20
6
  import type { PlaywrightBrowser, PlaywrightContext, PlaywrightPage } from './types.ts'
7
+ import { createSessionPage } from './session-window.ts'
21
8
 
22
- /** Opens the shared connection; injected so tests can substitute a fake. */
23
- export type CdpConnect = (endpoint: string, timeoutMs: number) => Promise<PlaywrightBrowser>
24
-
25
- /** How a lease scopes its fetch: throwaway context or the remote profile. */
26
- export type CdpAcquireMode = 'isolated' | 'profile'
9
+ export type SessionPageFactory = (context: PlaywrightContext, browser: PlaywrightBrowser, timeoutMs: number) => Promise<PlaywrightPage>
27
10
 
28
- /** One fetch's lease: the shared browser, a context, and the tab it owns. */
11
+ export type CdpConnect = (endpoint: string, timeoutMs: number) => Promise<PlaywrightBrowser>
12
+ export type CdpAcquireMode = 'isolated' | 'profile' | { scope: 'session' | 'global'; name: string }
29
13
  export interface CdpLease {
30
- /** The shared connection — close only what the lease owns, never this. */
31
14
  browser: PlaywrightBrowser
32
- /**
33
- * The context the page lives in: fetch-owned (`isolated`) or the remote
34
- * browser's default context (`profile`). NEVER close the latter — closing
35
- * it tears down the whole shared connection (playwright-core maps a
36
- * default-context close to "close browser" for this connection).
37
- */
38
15
  context: PlaywrightContext
39
- /** The fetch-owned tab; {@link CdpConnectionPool.release} always closes it. */
40
16
  page: PlaywrightPage
41
- /** True when `context` is the remote default context: release must not close it. */
17
+ /** Retained context: never close it directly on fetch completion. */
42
18
  persistent: boolean
19
+ /** Idempotent, bounded cleanup; use this rather than closing context/browser. */
20
+ release(): Promise<void>
21
+ }
22
+ interface ContextEntry {
23
+ context: PlaywrightContext
24
+ closed: boolean
25
+ /** Named leases, including acquisitions still creating their page. */
26
+ active: number
27
+ }
28
+ interface Generation {
29
+ endpoint: string
30
+ /** Session-isolated connections must never be shared across DSH sessions. */
31
+ sessionKey?: string
32
+ browser?: PlaywrightBrowser
33
+ connecting?: Promise<PlaywrightBrowser>
34
+ retired: boolean
35
+ disposed: boolean
36
+ /** Includes pending acquisitions so retirement cannot race page creation. */
37
+ active: number
38
+ named: Map<string, Promise<ContextEntry>>
39
+ owned: Set<PlaywrightContext>
40
+ cleanup?: Promise<void>
41
+ /** FIFO lifecycle mutex per named context, never held while fetching content. */
42
+ locks: Map<string, Promise<void>>
43
+ }
44
+
45
+ const CLOSE_GRACE_MS = 2_000
46
+
47
+ /** Thrown when a policy/connection change retired the generation mid-acquisition.
48
+ * A dedicated class lets acquire() recognise it without matching message text.
49
+ */
50
+ class AcquisitionAbandonedError extends Error {
51
+ constructor() { super('cdp acquisition abandoned after policy or connection change') }
52
+ }
53
+
54
+ /** Chromium does not notify other CDP clients when a browser context is
55
+ * disposed externally. Only this explicit createTarget error proves that the
56
+ * context used by newPage no longer exists; generic "Target closed" errors do
57
+ * not justify discarding shared state. Kept private to the newPage path.
58
+ */
59
+ function isMissingBrowserContext(error: unknown): boolean {
60
+ return error instanceof Error && /Protocol error \(Target\.createTarget\): Failed to find browser context with id [A-Za-z0-9_-]+(?:\r?\n|$)/.test(error.message)
43
61
  }
44
62
 
45
- /** A reusable `connectOverCDP` session handing out per-fetch pages. */
46
63
  export class CdpConnectionPool {
47
- private browser: PlaywrightBrowser | undefined
48
- private endpoint = ''
49
- private connecting: Promise<PlaywrightBrowser> | undefined
50
- private connectingEndpoint = ''
51
- /** Bumped by dispose/replace so a settling connect knows it was abandoned. */
52
- private generation = 0
53
-
54
- /**
55
- * @param connect - opens a connection to an endpoint (the provider's real
56
- * one resolves the bundled playwright-core; tests inject fakes).
64
+ private current?: Generation
65
+ private readonly sessionConnections = new Map<string, Generation>()
66
+ private policy?: string
67
+ private epoch = 0
68
+ private readonly generations = new Set<Generation>()
69
+ private readonly closes = new WeakMap<object, Promise<void>>()
70
+
71
+ constructor(
72
+ private readonly connect: CdpConnect,
73
+ private readonly sessionPageFactory: SessionPageFactory = createSessionPage,
74
+ ) {}
75
+
76
+ /** Serialize create/reuse/new-tab and tab-close/empty-check/context-close as
77
+ * whole transactions. Different session keys never wait for each other.
78
+ * A failed operation cannot poison the queue, and the map only drops the
79
+ * exact tail it owns (a queued acquisition may already have replaced it).
57
80
  */
58
- constructor(private readonly connect: CdpConnect) {}
59
-
60
- /**
61
- * Lease a fetch's page on the shared connection, connecting (or
62
- * reconnecting) first if needed. Concurrent first fetches share one
63
- * connect attempt.
64
- *
65
- * @param endpoint - normalized CDP endpoint URL.
66
- * @param timeoutMs - connect timeout budget.
67
- * @param mode - `isolated` (default): a fresh throwaway context plus a page
68
- * in it; `profile`: a page in the remote browser's default context — the
69
- * real profile — which is never closed, only the page is.
70
- * @returns the shared browser, the page's context, and the page the caller
71
- * must release.
72
- * @throws whatever the connect function throws when no connection can be
73
- * established (the provider wraps it in a structured WebError), or a
74
- * diagnostic error when `profile` mode finds no default context.
81
+ private async withLock<T>(generation: Generation, key: string, operation: () => Promise<T>): Promise<T> {
82
+ const previous = generation.locks.get(key) ?? Promise.resolve()
83
+ let unlock!: () => void
84
+ const tail = new Promise<void>(resolve => { unlock = resolve })
85
+ generation.locks.set(key, tail)
86
+ await previous
87
+ try { return await operation() } finally {
88
+ unlock()
89
+ if (generation.locks.get(key) === tail) generation.locks.delete(key)
90
+ }
91
+ }
92
+
93
+ /** Call synchronously for every fetch, including local-backend fetches.
94
+ * Keys must encode backend, endpoint and effective context policy. A change
95
+ * prevents new leases on the old generation but preserves existing pages.
75
96
  */
97
+ setPolicy(key: string): void {
98
+ if (this.policy === key) return
99
+ this.policy = key
100
+ this.epoch++
101
+ for (const generation of this.generations) this.retire(generation)
102
+ }
103
+
76
104
  async acquire(endpoint: string, timeoutMs: number, mode: CdpAcquireMode = 'isolated'): Promise<CdpLease> {
77
- const browser = await this.ensure(endpoint, timeoutMs)
78
- try {
79
- return await this.openLease(browser, mode)
80
- } catch (error: unknown) {
81
- // The connection may have died between ensure() and opening the lease;
82
- // one fresh connection attempt, then the error propagates as-is.
83
- if (this.isLive(browser)) throw error
84
- this.drop(browser)
85
- const fresh = await this.ensure(endpoint, timeoutMs)
86
- return await this.openLease(fresh, mode)
105
+ for (let attempt = 0; ; attempt++) {
106
+ const generation = this.ensure(endpoint, mode)
107
+ const epoch = this.epoch
108
+ generation.active++
109
+ try {
110
+ const browser = await this.attach(generation, timeoutMs)
111
+ this.assertCurrent(generation)
112
+ const open = async () => {
113
+ this.assertCurrent(generation)
114
+ return await this.openLease(generation, browser, mode, timeoutMs)
115
+ }
116
+ return typeof mode === 'object'
117
+ ? await this.withLock(generation, JSON.stringify([mode.scope, mode.name]), open)
118
+ : await open()
119
+ } catch (error: unknown) {
120
+ generation.active--
121
+ const idleSessionRetired = generation.sessionKey !== undefined && generation.retired && epoch === this.epoch
122
+ && error instanceof AcquisitionAbandonedError
123
+ // A failed acquisition must not leave a per-session socket stranded, nor
124
+ // an idle context kept open for it as a pending same-session fetch.
125
+ if (generation.sessionKey !== undefined && generation.active === 0) this.retire(generation)
126
+ void this.drain(generation)
127
+ // A queued acquisition may have waited behind the last tab's close;
128
+ // take a fresh session connection rather than reuse a closing gateway.
129
+ if (attempt === 0 && idleSessionRetired) continue
130
+ // Otherwise retry only a confirmed dead connection, never arbitrary
131
+ // target errors or a policy-superseded acquisition.
132
+ if (attempt > 0 || epoch !== this.epoch || !generation.browser || this.isLive(generation.browser)) throw error
133
+ this.retire(generation)
134
+ }
87
135
  }
88
136
  }
89
137
 
90
- /**
91
- * Open one lease's page on a live connection. The profile-mode handle is
92
- * taken fresh every call (never cached across connections): a reconnect
93
- * yields a new Browser object whose `contexts()[0]` must be re-read.
138
+ release(lease: CdpLease): Promise<void> { return lease.release() }
139
+
140
+ /** Teardown is stronger than policy retirement: close owned contexts and
141
+ * disconnect even with active leases. Pending creations clean up on arrival.
142
+ * The remote default context is NEVER explicitly closed.
94
143
  */
95
- private async openLease(browser: PlaywrightBrowser, mode: CdpAcquireMode): Promise<CdpLease> {
96
- if (mode === 'profile') {
97
- // [0] is the default context: playwright-core's BrowserDispatcher
98
- // always dispatches it first, and contexts created outside this
99
- // connection never appear here — so the pick is deterministic.
100
- const context = browser.contexts?.()[0]
101
- if (context === undefined) {
102
- throw new Error('the CDP endpoint exposed no default browser context (profile mode requires a real browser profile)')
144
+ async dispose(): Promise<void> {
145
+ const generations = [...this.generations]
146
+ this.epoch++
147
+ this.current = undefined
148
+ this.sessionConnections.clear()
149
+ for (const generation of generations) {
150
+ generation.retired = true
151
+ generation.disposed = true
152
+ }
153
+ await Promise.all(generations.map(generation => this.drain(generation)))
154
+ }
155
+
156
+ private ensure(endpoint: string, mode: CdpAcquireMode): Generation {
157
+ if (typeof mode === 'object' && mode.scope === 'session') {
158
+ const key = JSON.stringify([endpoint, mode.name])
159
+ let generation = this.sessionConnections.get(key)
160
+ if (generation?.browser && !this.isLive(generation.browser)) {
161
+ this.retire(generation)
162
+ generation = undefined
103
163
  }
104
- // A failed newPage leaves nothing behind (the default context is not
105
- // ours to clean), so the acquire-level retry can simply try again.
106
- return { browser, context, page: await context.newPage(), persistent: true }
164
+ if (!generation) {
165
+ generation = { endpoint, sessionKey: key, retired: false, disposed: false, active: 0, named: new Map(), owned: new Set(), locks: new Map() }
166
+ this.sessionConnections.set(key, generation)
167
+ this.generations.add(generation)
168
+ }
169
+ return generation
107
170
  }
108
- const context = await browser.newContext()
109
- try {
110
- return { browser, context, page: await context.newPage(), persistent: false }
111
- } catch (error: unknown) {
112
- // The context exists but its page does not: close it now, or a
113
- // transient newPage failure on a live connection strands the context
114
- // until the whole connection goes away.
115
- await context.close().catch(() => {})
116
- throw error
171
+ if (this.current && (this.current.endpoint !== endpoint || (this.current.browser && !this.isLive(this.current.browser)))) {
172
+ if (this.current.endpoint !== endpoint) this.epoch++
173
+ this.retire(this.current)
117
174
  }
175
+ if (!this.current) {
176
+ this.current = { endpoint, retired: false, disposed: false, active: 0, named: new Map(), owned: new Set(), locks: new Map() }
177
+ this.generations.add(this.current)
178
+ }
179
+ return this.current
118
180
  }
119
181
 
120
- /**
121
- * Close a fetch-owned page, plus its context when the lease owns one. The
122
- * remote default context (persistent leases) and the shared connection
123
- * stay for the next fetch.
124
- * @param lease - the lease whose page (and, when isolated, context) goes away.
125
- */
126
- async release(lease: CdpLease): Promise<void> {
127
- await lease.page.close().catch(() => {})
128
- if (!lease.persistent) await lease.context.close().catch(() => {})
182
+ private async attach(generation: Generation, timeoutMs: number): Promise<PlaywrightBrowser> {
183
+ if (generation.browser) return generation.browser
184
+ if (!generation.connecting) {
185
+ generation.connecting = (async () => {
186
+ const browser = await this.connect(generation.endpoint, timeoutMs)
187
+ generation.browser = browser
188
+ if (generation.retired) {
189
+ await this.close(browser)
190
+ throw new Error('cdp connection abandoned before it attached')
191
+ }
192
+ try {
193
+ browser.on?.('disconnected', () => {
194
+ // Keep the record for draining leases but do not reuse it.
195
+ this.retire(generation)
196
+ })
197
+ } catch { /* optional event support */ }
198
+ return browser
199
+ })()
200
+ }
201
+ try { return await generation.connecting } catch (error) {
202
+ generation.connecting = undefined
203
+ throw error
204
+ }
129
205
  }
130
206
 
131
- /**
132
- * Drop the shared connection (plugin teardown or endpoint change). Fetches
133
- * holding leases keep their contexts until they release them. A connect
134
- * still in flight is abandoned — its own continuation closes the stray
135
- * browser (nothing here waits on it, so teardown cannot deadlock).
136
- */
137
- async dispose(): Promise<void> {
138
- const browser = this.browser
139
- this.browser = undefined
140
- this.endpoint = ''
141
- this.connecting = undefined
142
- this.connectingEndpoint = ''
143
- this.generation++
144
- await browser?.close().catch(() => {})
207
+ private assertCurrent(generation: Generation): void {
208
+ if (generation.retired) throw new AcquisitionAbandonedError()
145
209
  }
146
210
 
147
- /** The shared connection for `endpoint`, connecting or reconnecting as needed. */
148
- private async ensure(endpoint: string, timeoutMs: number): Promise<PlaywrightBrowser> {
149
- if (this.browser !== undefined && this.endpoint === endpoint && this.isLive(this.browser)) return this.browser
150
- if (this.connecting !== undefined && this.connectingEndpoint === endpoint) return this.connecting
151
- // Dead connection or different endpoint: (re)connect. An in-flight connect
152
- // to another endpoint is abandoned by the generation bump below — its own
153
- // continuation closes the stray browser and rejects to its waiter.
154
- return await this.connectFresh(endpoint, timeoutMs)
211
+ private async createContext(generation: Generation, browser: PlaywrightBrowser): Promise<ContextEntry> {
212
+ const context = await browser.newContext()
213
+ // Fail closed on adapters/proxies that return a profile or another lease's
214
+ // context instead of a fresh isolated context. Never take ownership of it.
215
+ if (browser.contexts?.()[0] === context || [...this.generations].some(item => item.owned.has(context))) {
216
+ throw new Error('CDP backend did not create a distinct isolated browser context')
217
+ }
218
+ if (generation.retired) {
219
+ await this.close(context)
220
+ throw new Error('cdp context abandoned after policy or connection change')
221
+ }
222
+ const entry = { context, closed: false, active: 0 }
223
+ generation.owned.add(context)
224
+ try {
225
+ context.on?.('close', () => {
226
+ entry.closed = true
227
+ generation.owned.delete(context)
228
+ })
229
+ } catch { /* optional event support */ }
230
+ return entry
155
231
  }
156
232
 
157
- /** Start a connection to `endpoint`, superseding whatever was there. */
158
- private connectFresh(endpoint: string, timeoutMs: number): Promise<PlaywrightBrowser> {
159
- const stale = this.browser
160
- this.browser = undefined
161
- this.endpoint = ''
162
- const generation = ++this.generation
163
- const attempt = (async () => {
164
- const browser = await this.connect(endpoint, timeoutMs)
165
- // A dispose/replace won the race while we were connecting: this
166
- // connection is unwanted — close it and surface the abandonment.
167
- if (generation !== this.generation) {
168
- await browser.close().catch(() => {})
169
- throw new Error('cdp connection abandoned before it attached')
233
+ private async namedContext(generation: Generation, browser: PlaywrightBrowser, key: string): Promise<ContextEntry> {
234
+ let pending = generation.named.get(key)
235
+ if (!pending) {
236
+ pending = this.createContext(generation, browser)
237
+ generation.named.set(key, pending)
238
+ }
239
+ try {
240
+ const entry = await pending
241
+ if (!entry.closed) {
242
+ // Reserve before returning across an await boundary: the last release
243
+ // must not close a context that another acquisition is about to use.
244
+ entry.active++
245
+ return entry
170
246
  }
171
- this.browser = browser
172
- this.endpoint = endpoint
173
- this.watch(browser)
174
- return browser
175
- })()
176
- this.connecting = attempt
177
- this.connectingEndpoint = endpoint
178
- void attempt.then(
179
- () => { if (this.connecting === attempt) this.connecting = undefined },
180
- () => { if (this.connecting === attempt) this.connecting = undefined },
181
- )
182
- void stale?.close().catch(() => {})
183
- return attempt
247
+ if (generation.named.get(key) === pending) generation.named.delete(key)
248
+ this.assertCurrent(generation)
249
+ return await this.namedContext(generation, browser, key)
250
+ } catch (error) {
251
+ if (generation.named.get(key) === pending) generation.named.delete(key)
252
+ throw error
253
+ }
254
+ }
255
+
256
+ /** Invalidate the exact entry, not its key: a concurrent request may already
257
+ * have installed a replacement. namedContext removes only the Promise it read.
258
+ * Best-effort close attempts to release Playwright's local handle after an
259
+ * external CDP deletion (some versions retain it until disconnect); it never
260
+ * touches a sibling context or the default profile.
261
+ */
262
+ private invalidateContext(generation: Generation, entry: ContextEntry): void {
263
+ entry.closed = true
264
+ generation.owned.delete(entry.context)
265
+ void this.close(entry.context)
184
266
  }
185
267
 
186
- /** Clear the reference when this exact connection reports it went away. */
187
- private watch(browser: PlaywrightBrowser): void {
268
+ private async releaseNamedContext(generation: Generation, entry: ContextEntry, mode: CdpAcquireMode): Promise<void> {
269
+ entry.active--
270
+ if (typeof mode !== 'object' || mode.scope !== 'session' || entry.active > 0 || entry.closed) return
271
+ // Same-session acquisitions already inside the pool (queued on the lock or
272
+ // still attaching) count as pending: keep the context so they inherit its
273
+ // cookies instead of reconnecting. The caller's own lease is still counted
274
+ // in generation.active here; the last one out closes the context (or, if it
275
+ // fails before reaching the lock, acquire() retires the idle generation).
276
+ if (generation.active > 1) return
277
+ // Count real tabs too, not just leases: never tear down an unrelated tab
278
+ // or a page whose close failed/timed out. Minimal backends use lease count.
279
+ if ((entry.context.pages?.().length ?? 0) > 0) return
280
+ // Mark unavailable synchronously before awaiting close. New acquisitions
281
+ // replace this exact entry rather than racing its asynchronous teardown.
282
+ entry.closed = true
283
+ generation.named.delete(JSON.stringify([mode.scope, mode.name]))
284
+ await this.close(entry.context)
285
+ generation.owned.delete(entry.context)
286
+ // Some CDP gateways map a connection's first context to a whole browser.
287
+ // Discard that socket too: never create nested contexts for another session
288
+ // or race a new context against an asynchronously destroyed gateway browser.
289
+ if (generation.sessionKey !== undefined) this.retire(generation)
290
+ }
291
+
292
+ private async openLease(generation: Generation, browser: PlaywrightBrowser, mode: CdpAcquireMode, timeoutMs: number): Promise<CdpLease> {
293
+ const namedKey = typeof mode === 'object' ? JSON.stringify([mode.scope, mode.name]) : undefined
294
+ let entry: ContextEntry
295
+ if (mode === 'profile') {
296
+ const context = browser.contexts?.()[0]
297
+ if (!context) throw new Error('the CDP endpoint exposed no default browser context (profile mode requires a real browser profile)')
298
+ entry = { context, closed: false, active: 0 }
299
+ } else {
300
+ entry = namedKey === undefined ? await this.createContext(generation, browser) : await this.namedContext(generation, browser, namedKey)
301
+ }
302
+ let page: PlaywrightPage
188
303
  try {
189
- browser.on?.('disconnected', () => {
190
- if (this.browser === browser) {
191
- this.browser = undefined
192
- this.endpoint = ''
304
+ for (let attempt = 0; ; attempt++) {
305
+ this.assertCurrent(generation)
306
+ try {
307
+ page = typeof mode === 'object' && mode.scope === 'session'
308
+ ? await this.sessionPageFactory(entry.context, browser, timeoutMs)
309
+ : await entry.context.newPage()
310
+ break
311
+ } catch (error) {
312
+ if (!namedKey || (!entry.closed && !isMissingBrowserContext(error))) throw error
313
+ this.invalidateContext(generation, entry)
314
+ // Also invalidate an unsuccessful replacement so a later request can
315
+ // recover, but this acquisition gets at most ONE newPage retry.
316
+ if (attempt >= 1 || !this.isLive(browser)) throw error
317
+ this.assertCurrent(generation)
318
+ const replacement = await this.namedContext(generation, browser, namedKey)
319
+ entry.active--
320
+ entry = replacement
193
321
  }
194
- })
195
- } catch {
196
- // a backend that refuses listeners just loses proactive detection
322
+ }
323
+ if (generation.retired) {
324
+ await this.close(page)
325
+ this.assertCurrent(generation)
326
+ }
327
+ } catch (error) {
328
+ if (mode === 'isolated') {
329
+ await this.close(entry.context)
330
+ generation.owned.delete(entry.context)
331
+ }
332
+ if (namedKey !== undefined) await this.releaseNamedContext(generation, entry, mode)
333
+ throw error
197
334
  }
335
+ const context = entry.context
336
+ let released: Promise<void> | undefined
337
+ const release = (): Promise<void> => {
338
+ const cleanup = async () => {
339
+ await this.close(page)
340
+ if (mode === 'isolated') {
341
+ await this.close(context)
342
+ generation.owned.delete(context)
343
+ }
344
+ if (namedKey !== undefined) await this.releaseNamedContext(generation, entry, mode)
345
+ generation.active--
346
+ await this.drain(generation)
347
+ }
348
+ // Global release only decrements a counter and closes its own tab: it
349
+ // never touches the shared context, so it need not queue behind creation.
350
+ released ??= namedKey === undefined || (typeof mode === 'object' && mode.scope === 'global')
351
+ ? cleanup()
352
+ : this.withLock(generation, namedKey, cleanup)
353
+ return released
354
+ }
355
+ return { browser, context, page, persistent: mode !== 'isolated', release }
198
356
  }
199
357
 
200
- /** Forget a connection known to be dead (absent probe = assume dead here). */
201
- private drop(browser: PlaywrightBrowser): void {
202
- if (this.browser === browser) {
203
- this.browser = undefined
204
- this.endpoint = ''
358
+ private retire(generation: Generation): void {
359
+ generation.retired = true
360
+ if (this.current === generation) this.current = undefined
361
+ if (generation.sessionKey !== undefined && this.sessionConnections.get(generation.sessionKey) === generation) {
362
+ this.sessionConnections.delete(generation.sessionKey)
205
363
  }
364
+ void this.drain(generation)
206
365
  }
207
366
 
208
- private isLive(browser: PlaywrightBrowser): boolean {
209
- return browser.isConnected?.() !== false
367
+ private async drain(generation: Generation): Promise<void> {
368
+ if (!generation.retired || (!generation.disposed && generation.active > 0)) return
369
+ generation.cleanup ??= (async () => {
370
+ await Promise.all([...generation.owned].map(context => this.close(context)))
371
+ generation.owned.clear()
372
+ generation.named.clear()
373
+ if (generation.browser) await this.close(generation.browser)
374
+ this.generations.delete(generation)
375
+ })()
376
+ await generation.cleanup
210
377
  }
378
+
379
+ /** Bound cleanup and deduplicate close calls, including release/dispose races. */
380
+ private close(value: { close(): Promise<void> }): Promise<void> {
381
+ let pending = this.closes.get(value)
382
+ if (!pending) {
383
+ pending = new Promise<void>(resolve => {
384
+ const timer = setTimeout(resolve, CLOSE_GRACE_MS)
385
+ void Promise.resolve().then(() => value.close()).catch(() => {}).then(() => {
386
+ clearTimeout(timer)
387
+ resolve()
388
+ })
389
+ })
390
+ this.closes.set(value, pending)
391
+ }
392
+ return pending
393
+ }
394
+
395
+ private isLive(browser: PlaywrightBrowser): boolean { return browser.isConnected?.() !== false }
211
396
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The Playwright plugin-configuration card: backend radio group (each option
3
3
  * carrying its backend-specific inputs nested inside — local path under Local
4
- * Playwright, CDP endpoint and shared-context checkbox under Remote CDP) plus
4
+ * Playwright, CDP endpoint and context-mode radios under Remote CDP) plus
5
5
  * the denoise checkbox, staged and saved through the card form like the
6
6
  * built-in plugin cards.
7
7
  *
@@ -39,6 +39,8 @@ export function PlaywrightCard(props: PlaywrightCardProps) {
39
39
  const state = props.usePlaywrightCard(snapshot => snapshot)
40
40
  if (!state.available) return null
41
41
  const disabled = !state.writable
42
+ const isolated = state.shareBrowserContext.text === 'false'
43
+ const scope = state.contextIsolationScope.text === 'session' ? 'session' : 'global'
42
44
  const backend = state.backend.text === 'cdp' ? 'cdp' : 'local'
43
45
  return (
44
46
  <CardForm
@@ -97,12 +99,40 @@ export function PlaywrightCard(props: PlaywrightCardProps) {
97
99
  onEdit={(text) => { props.edit('cdpEndpoint', text) }}
98
100
  onReset={() => { props.resetField('cdpEndpoint') }}
99
101
  />
100
- <CheckboxField
102
+ <RadioGroupField
101
103
  embedded
102
- id="plugin-config-playwright-share-context"
103
- label={t('shareBrowserContext')}
104
- hint={t('shareBrowserContextHint')}
105
- checked={state.shareBrowserContext.text !== 'false'}
104
+ label={t('contextMode')}
105
+ text={isolated ? 'false' : 'true'}
106
+ options={[
107
+ { value: 'true', label: t('shareBrowserContext'), hint: t('shareBrowserContextHint') },
108
+ {
109
+ value: 'false',
110
+ label: t('isolateBrowserContext'),
111
+ hint: t('isolateBrowserContextHint'),
112
+ content: isolated ? (
113
+ <RadioGroupField
114
+ embedded
115
+ plainOptions
116
+ label={t('contextIsolationScope')}
117
+ text={scope}
118
+ options={[
119
+ {
120
+ value: 'global',
121
+ label: t('contextScopeGlobal'),
122
+ hint: t('contextScopeGlobalHint'),
123
+ },
124
+ { value: 'session', label: t('contextScopeSession'), hint: t('contextScopeSessionHint') },
125
+ ]}
126
+ overridden={state.contextIsolationScope.overridden}
127
+ overriddenLabel={t('overridden')}
128
+ resetLabel={t('reset')}
129
+ disabled={disabled || backend !== 'cdp'}
130
+ onEdit={(text) => { props.edit('contextIsolationScope', text) }}
131
+ onReset={() => { props.resetField('contextIsolationScope') }}
132
+ />
133
+ ) : undefined,
134
+ },
135
+ ]}
106
136
  overridden={state.shareBrowserContext.overridden}
107
137
  overriddenLabel={t('overridden')}
108
138
  resetLabel={t('reset')}
@@ -114,7 +144,7 @@ export function PlaywrightCard(props: PlaywrightCardProps) {
114
144
  ),
115
145
  },
116
146
  ]}
117
- text={state.backend.text}
147
+ text={backend}
118
148
  overridden={state.backend.overridden}
119
149
  overriddenLabel={t('overridden')}
120
150
  resetLabel={t('reset')}