oira666_pi-browser-agent 0.0.14 → 0.0.15
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/package.json +1 -1
- package/src/broker/remote.ts +31 -2
- package/src/broker/server.ts +23 -7
- package/src/index.ts +80 -19
- package/tests/broker.test.ts +114 -0
- package/tests/index.test.ts +199 -0
package/package.json
CHANGED
package/src/broker/remote.ts
CHANGED
|
@@ -114,6 +114,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
114
114
|
* none is listening) compete to become the new primary. Idempotent and safe
|
|
115
115
|
* to call concurrently — `promoteOrReconnect()` dedupes the bind race. */
|
|
116
116
|
async ensureReady(options: EnsureReadyOptions = {}): Promise<void> {
|
|
117
|
+
if (this.stopped) return;
|
|
117
118
|
if (this.promotedBroker) {
|
|
118
119
|
await this.promotedBroker.ensureReady(options);
|
|
119
120
|
return;
|
|
@@ -240,12 +241,28 @@ export class RemoteBrowserAgentBroker {
|
|
|
240
241
|
this.stopped = true;
|
|
241
242
|
this.cancelHealTimer();
|
|
242
243
|
this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
|
|
244
|
+
const connecting = this.connectPromise;
|
|
243
245
|
const socket = this.socket;
|
|
244
246
|
this.socket = null;
|
|
245
|
-
this.connectPromise = null;
|
|
246
247
|
if (socket) {
|
|
247
248
|
try { socket.close(); } catch { /* ignore */ }
|
|
248
249
|
}
|
|
250
|
+
// A connect or promotion already in flight can otherwise publish a socket
|
|
251
|
+
// or listener after stop() returns. Their completion paths observe
|
|
252
|
+
// `stopped` and tear down instead of publishing.
|
|
253
|
+
if (connecting) {
|
|
254
|
+
try { await connecting; } catch { /* expected during shutdown */ }
|
|
255
|
+
}
|
|
256
|
+
this.connectPromise = null;
|
|
257
|
+
const promotion = this.promotionPromise;
|
|
258
|
+
if (promotion) {
|
|
259
|
+
try { await promotion; } catch { /* promotion failure is already logged */ }
|
|
260
|
+
}
|
|
261
|
+
const lateSocket = this.socket;
|
|
262
|
+
this.socket = null;
|
|
263
|
+
if (lateSocket) {
|
|
264
|
+
try { lateSocket.close(); } catch { /* ignore */ }
|
|
265
|
+
}
|
|
249
266
|
this.unsubscribePromoted?.();
|
|
250
267
|
this.unsubscribePromoted = null;
|
|
251
268
|
this.bridgeStateListeners.clear();
|
|
@@ -258,6 +275,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
258
275
|
}
|
|
259
276
|
|
|
260
277
|
async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
|
|
278
|
+
if (this.stopped) throw new Error('E_BRIDGE_DISCONNECTED');
|
|
261
279
|
if (this.promotedBroker) {
|
|
262
280
|
return await this.promotedBroker.request(type, params, options);
|
|
263
281
|
}
|
|
@@ -366,6 +384,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
366
384
|
}
|
|
367
385
|
|
|
368
386
|
private async ensureConnected(): Promise<void> {
|
|
387
|
+
if (this.stopped) throw new Error('Browser broker is stopped');
|
|
369
388
|
if (this.socket?.readyState === WebSocket.OPEN) return;
|
|
370
389
|
if (this.connectPromise) return await this.connectPromise;
|
|
371
390
|
|
|
@@ -397,6 +416,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
397
416
|
};
|
|
398
417
|
|
|
399
418
|
socket.once('open', () => {
|
|
419
|
+
if (this.stopped) {
|
|
420
|
+
fail(new Error('Browser broker is stopped'));
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
400
423
|
settled = true;
|
|
401
424
|
clearTimeout(connectTimeout);
|
|
402
425
|
this.socket = socket;
|
|
@@ -475,6 +498,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
475
498
|
}
|
|
476
499
|
|
|
477
500
|
private async promoteOrReconnect(): Promise<BrowserAgentBroker | null> {
|
|
501
|
+
if (this.stopped) return null;
|
|
478
502
|
if (this.promotedBroker) return this.promotedBroker;
|
|
479
503
|
if (this.promotionPromise) return await this.promotionPromise;
|
|
480
504
|
|
|
@@ -492,6 +516,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
492
516
|
});
|
|
493
517
|
try {
|
|
494
518
|
await candidate.start();
|
|
519
|
+
if (this.stopped) {
|
|
520
|
+
await candidate.stop();
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
495
523
|
this.unsubscribePromoted?.();
|
|
496
524
|
this.unsubscribePromoted = candidate.addBridgeStateListener((state) => this.emitBridgeState(state));
|
|
497
525
|
this.promotedBroker = candidate;
|
|
@@ -515,7 +543,8 @@ export class RemoteBrowserAgentBroker {
|
|
|
515
543
|
return null;
|
|
516
544
|
}
|
|
517
545
|
// Someone else won the race. Reconnect to the new primary and refresh
|
|
518
|
-
// our probe snapshot.
|
|
546
|
+
// our probe snapshot, unless shutdown won the race first.
|
|
547
|
+
if (this.stopped) return null;
|
|
519
548
|
try {
|
|
520
549
|
await this.ensureConnected();
|
|
521
550
|
this.remoteProbe = await this.probePrimary();
|
package/src/broker/server.ts
CHANGED
|
@@ -113,6 +113,10 @@ export class BrowserAgentBroker {
|
|
|
113
113
|
private listenerEpoch = 0;
|
|
114
114
|
private coldBridgeMisses = 0;
|
|
115
115
|
private coldBridgeSince: number | null = null;
|
|
116
|
+
/** Serializes listener lifecycle transitions. In particular, a stop requested
|
|
117
|
+
* while start() is still binding must run after that bind and tear it down,
|
|
118
|
+
* rather than observing `server === null` and letting the late bind escape. */
|
|
119
|
+
private lifecycleTail: Promise<void> = Promise.resolve();
|
|
116
120
|
|
|
117
121
|
constructor({
|
|
118
122
|
host = process.env.PI_BA_HOST || '127.0.0.1',
|
|
@@ -150,12 +154,13 @@ export class BrowserAgentBroker {
|
|
|
150
154
|
return `ws://${this.host}:${this.port}`;
|
|
151
155
|
}
|
|
152
156
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
+
start(): Promise<void> {
|
|
158
|
+
return this.serializeLifecycle(async () => {
|
|
159
|
+
if (this.server) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
157
162
|
|
|
158
|
-
|
|
163
|
+
this.startupError = null;
|
|
159
164
|
|
|
160
165
|
// A previous listener generation may still have a heartbeat running (e.g.
|
|
161
166
|
// ensureReady() rebinding without stop()). Two intervals would race each
|
|
@@ -206,6 +211,15 @@ export class BrowserAgentBroker {
|
|
|
206
211
|
}
|
|
207
212
|
throw this.startupError;
|
|
208
213
|
}
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
private serializeLifecycle(operation: () => Promise<void>): Promise<void> {
|
|
218
|
+
const result = this.lifecycleTail.then(operation, operation);
|
|
219
|
+
// Keep the queue usable after a failed bind; callers still receive the
|
|
220
|
+
// original rejection through `result`.
|
|
221
|
+
this.lifecycleTail = result.then(() => undefined, () => undefined);
|
|
222
|
+
return result;
|
|
209
223
|
}
|
|
210
224
|
|
|
211
225
|
/** Lazily (re)acquire the broker listener on demand. Tools call this at the
|
|
@@ -426,8 +440,9 @@ export class BrowserAgentBroker {
|
|
|
426
440
|
});
|
|
427
441
|
}
|
|
428
442
|
|
|
429
|
-
|
|
430
|
-
|
|
443
|
+
stop(): Promise<void> {
|
|
444
|
+
return this.serializeLifecycle(async () => {
|
|
445
|
+
const closeErrors: Error[] = [];
|
|
431
446
|
|
|
432
447
|
if (this.pingTimer) {
|
|
433
448
|
clearInterval(this.pingTimer);
|
|
@@ -492,6 +507,7 @@ export class BrowserAgentBroker {
|
|
|
492
507
|
this.logger.error?.('[pi-browser-agent] broker shutdown failed', this.shutdownError);
|
|
493
508
|
throw new AggregateError(closeErrors, 'Broker shutdown failed');
|
|
494
509
|
}
|
|
510
|
+
});
|
|
495
511
|
}
|
|
496
512
|
|
|
497
513
|
async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
|
package/src/index.ts
CHANGED
|
@@ -18,6 +18,12 @@ type ExtensionContextLike = { ui?: ExtensionUi };
|
|
|
18
18
|
|
|
19
19
|
let brokerSingleton: BrowserAgentBrokerLike | null = null;
|
|
20
20
|
let brokerStartup: Promise<BrowserAgentBrokerLike> | null = null;
|
|
21
|
+
/** Invalidates an acquisition that was already in flight when shutdown began. */
|
|
22
|
+
let brokerLifecycleGeneration = 0;
|
|
23
|
+
/** Separately invalidates session setup. Suspend must not do this: tools still
|
|
24
|
+
* need to finish registering while broker acquisition is paused. */
|
|
25
|
+
let sessionLifecycleGeneration = 0;
|
|
26
|
+
let brokerShuttingDown = false;
|
|
21
27
|
let startupMessage: string | null = null;
|
|
22
28
|
/** Handles handed to the browser_* tools. They outlive the broker, so shutdown
|
|
23
29
|
* has to disarm them explicitly or a late tool call re-binds the port. */
|
|
@@ -34,9 +40,18 @@ export function getStartupMessage(): string | null {
|
|
|
34
40
|
}
|
|
35
41
|
|
|
36
42
|
export async function resetForTests(): Promise<void> {
|
|
37
|
-
|
|
43
|
+
brokerShuttingDown = true;
|
|
44
|
+
brokerLifecycleGeneration += 1;
|
|
45
|
+
sessionLifecycleGeneration += 1;
|
|
46
|
+
const startup = brokerStartup;
|
|
47
|
+
if (startup) {
|
|
48
|
+
try { await startup; } catch { /* invalidated startup stops itself */ }
|
|
49
|
+
}
|
|
50
|
+
const broker = brokerSingleton;
|
|
51
|
+
brokerSingleton = null;
|
|
52
|
+
if (broker) {
|
|
38
53
|
try {
|
|
39
|
-
await
|
|
54
|
+
await broker.stop();
|
|
40
55
|
} catch {
|
|
41
56
|
// ignore in tests; callers are resetting state intentionally
|
|
42
57
|
}
|
|
@@ -49,9 +64,9 @@ export async function resetForTests(): Promise<void> {
|
|
|
49
64
|
handle.dispose();
|
|
50
65
|
}
|
|
51
66
|
activeHandles.clear();
|
|
52
|
-
brokerSingleton = null;
|
|
53
67
|
brokerStartup = null;
|
|
54
68
|
startupMessage = null;
|
|
69
|
+
brokerShuttingDown = false;
|
|
55
70
|
}
|
|
56
71
|
|
|
57
72
|
function formatLogArg(value: unknown): string {
|
|
@@ -176,11 +191,16 @@ function installSuspendResumeHandlers(): void {
|
|
|
176
191
|
process.on('SIGTSTP', () => {
|
|
177
192
|
if (suspending) return;
|
|
178
193
|
suspending = true;
|
|
194
|
+
brokerShuttingDown = true;
|
|
195
|
+
brokerLifecycleGeneration += 1;
|
|
196
|
+
const startup = brokerStartup;
|
|
179
197
|
const broker = brokerSingleton;
|
|
180
198
|
void (async () => {
|
|
181
199
|
try {
|
|
182
|
-
//
|
|
183
|
-
|
|
200
|
+
// Invalidate and await any in-flight startup before releasing the port.
|
|
201
|
+
if (startup) {
|
|
202
|
+
try { await startup; } catch { /* cancelled/failed startup */ }
|
|
203
|
+
}
|
|
184
204
|
if (broker) {
|
|
185
205
|
await broker.stop();
|
|
186
206
|
try { await removeInstanceFile(process.pid); } catch { /* ignore */ }
|
|
@@ -198,6 +218,7 @@ function installSuspendResumeHandlers(): void {
|
|
|
198
218
|
process.on('SIGCONT', () => {
|
|
199
219
|
if (!suspending) return;
|
|
200
220
|
suspending = false;
|
|
221
|
+
brokerShuttingDown = false;
|
|
201
222
|
const broker = brokerSingleton;
|
|
202
223
|
if (!broker) return;
|
|
203
224
|
void (async () => {
|
|
@@ -282,6 +303,10 @@ function attachPromotionReporter(broker: BrowserAgentBrokerLike, logger: BrokerL
|
|
|
282
303
|
}
|
|
283
304
|
|
|
284
305
|
async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrokerLike> {
|
|
306
|
+
if (brokerShuttingDown) {
|
|
307
|
+
throw new Error('Browser broker is shutting down');
|
|
308
|
+
}
|
|
309
|
+
|
|
285
310
|
// If an existing broker is healthy, reuse it.
|
|
286
311
|
if (brokerSingleton) {
|
|
287
312
|
const probe = brokerSingleton.probeConnectivity();
|
|
@@ -291,29 +316,53 @@ async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrok
|
|
|
291
316
|
// Non-listening singleton (e.g. after a prior failure). Stop it before
|
|
292
317
|
// dropping the reference: an abandoned broker keeps its heal timers and can
|
|
293
318
|
// still bind the port, giving this process two competing brokers.
|
|
294
|
-
const stale = brokerSingleton;
|
|
295
|
-
brokerSingleton = null;
|
|
296
|
-
void stale.stop().catch(() => {});
|
|
297
319
|
}
|
|
298
320
|
|
|
299
|
-
// Serialize startup: at most one
|
|
321
|
+
// Serialize startup (including stale teardown): at most one replacement can
|
|
322
|
+
// stop/bind/publish at a time.
|
|
300
323
|
if (brokerStartup) {
|
|
301
324
|
return await brokerStartup;
|
|
302
325
|
}
|
|
303
326
|
|
|
304
|
-
|
|
327
|
+
const generation = brokerLifecycleGeneration;
|
|
328
|
+
let startup!: Promise<BrowserAgentBrokerLike>;
|
|
329
|
+
startup = (async () => {
|
|
305
330
|
try {
|
|
331
|
+
const stale = brokerSingleton;
|
|
332
|
+
if (stale && !stale.probeConnectivity().brokerListening) {
|
|
333
|
+
brokerSingleton = null;
|
|
334
|
+
try {
|
|
335
|
+
await stale.stop();
|
|
336
|
+
} catch (error) {
|
|
337
|
+
logger.warn?.('[pi-browser-agent] stale broker cleanup failed', error);
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (brokerShuttingDown || generation !== brokerLifecycleGeneration) {
|
|
343
|
+
throw new Error('Browser broker startup was cancelled by shutdown');
|
|
344
|
+
}
|
|
345
|
+
|
|
306
346
|
const broker = await createAndStartBroker(logger);
|
|
307
|
-
//
|
|
347
|
+
// Shutdown may have begun while task-store setup or the socket bind was
|
|
348
|
+
// in flight. Never publish that late broker, and await its teardown so it
|
|
349
|
+
// cannot reclaim the port after shutdown returns.
|
|
350
|
+
if (brokerShuttingDown || generation !== brokerLifecycleGeneration) {
|
|
351
|
+
await broker.stop();
|
|
352
|
+
throw new Error('Browser broker startup was cancelled by shutdown');
|
|
353
|
+
}
|
|
308
354
|
brokerSingleton = broker;
|
|
309
355
|
return broker;
|
|
310
356
|
} finally {
|
|
311
|
-
//
|
|
312
|
-
brokerStartup
|
|
357
|
+
// Do not let an older attempt clear a newer attempt's promise.
|
|
358
|
+
if (brokerStartup === startup) {
|
|
359
|
+
brokerStartup = null;
|
|
360
|
+
}
|
|
313
361
|
}
|
|
314
362
|
})();
|
|
363
|
+
brokerStartup = startup;
|
|
315
364
|
|
|
316
|
-
return await
|
|
365
|
+
return await startup;
|
|
317
366
|
}
|
|
318
367
|
|
|
319
368
|
export default async function piBrowserAgentExtension(pi: {
|
|
@@ -321,6 +370,7 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
321
370
|
registerTool: (tool: any) => void;
|
|
322
371
|
}) {
|
|
323
372
|
const registerSessionTool = async (ctx?: ExtensionContextLike) => {
|
|
373
|
+
const sessionGeneration = sessionLifecycleGeneration;
|
|
324
374
|
resetBrowserAgentToolState();
|
|
325
375
|
resetRegisteredBrowserTools();
|
|
326
376
|
const logger = createUiLogger(ctx);
|
|
@@ -350,6 +400,12 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
350
400
|
// initialised here — it is a different instance from the broker's.
|
|
351
401
|
const taskStore = new TaskStore({ dir: join(await ensureStateDir('tasks')) });
|
|
352
402
|
await taskStore.init();
|
|
403
|
+
// session_shutdown may have completed while the per-session task store was
|
|
404
|
+
// being prepared, before this session had a handle or brokerStartup for it
|
|
405
|
+
// to invalidate. Do not let that delayed setup rebind after shutdown.
|
|
406
|
+
if (sessionGeneration !== sessionLifecycleGeneration) {
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
353
409
|
const handle = new LazyBrokerHandle(async () => {
|
|
354
410
|
const broker = await getOrCreateBroker(logger);
|
|
355
411
|
attachReporters(broker);
|
|
@@ -391,7 +447,10 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
391
447
|
});
|
|
392
448
|
|
|
393
449
|
pi.on('session_shutdown', async (_event, ctx) => {
|
|
394
|
-
|
|
450
|
+
brokerShuttingDown = true;
|
|
451
|
+
brokerLifecycleGeneration += 1;
|
|
452
|
+
sessionLifecycleGeneration += 1;
|
|
453
|
+
const startup = brokerStartup;
|
|
395
454
|
for (const cleanup of [...sessionCleanups]) {
|
|
396
455
|
try { cleanup(); } catch { /* ignore */ }
|
|
397
456
|
}
|
|
@@ -402,15 +461,16 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
402
461
|
handle.dispose();
|
|
403
462
|
}
|
|
404
463
|
activeHandles.clear();
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
464
|
+
// Await an in-flight acquisition. Its generation check tears down any
|
|
465
|
+
// broker that finished binding after shutdown started.
|
|
466
|
+
if (startup) {
|
|
467
|
+
try { await startup; } catch { /* cancelled/failed startup */ }
|
|
408
468
|
}
|
|
409
469
|
const broker = brokerSingleton;
|
|
410
470
|
brokerSingleton = null;
|
|
411
471
|
startupMessage = null;
|
|
412
472
|
try {
|
|
413
|
-
await broker.stop();
|
|
473
|
+
if (broker) await broker.stop();
|
|
414
474
|
} catch (error) {
|
|
415
475
|
const message = error instanceof Error ? error.message : String(error);
|
|
416
476
|
ctx?.ui?.notify?.(`pi-browser-agent shutdown failed: ${message}`, 'warning');
|
|
@@ -421,6 +481,7 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
421
481
|
const message = error instanceof Error ? error.message : String(error);
|
|
422
482
|
ctx?.ui?.notify?.(`pi-browser-agent instance cleanup failed: ${message}`, 'warning');
|
|
423
483
|
}
|
|
484
|
+
brokerShuttingDown = false;
|
|
424
485
|
}
|
|
425
486
|
});
|
|
426
487
|
}
|
package/tests/broker.test.ts
CHANGED
|
@@ -71,6 +71,43 @@ async function createBroker(port: number, opts: { portRange?: number; fallbackTo
|
|
|
71
71
|
});
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
test('concurrent start() calls share one listener lifecycle', async () => {
|
|
75
|
+
const port = await getFreePort();
|
|
76
|
+
const broker = await createBroker(port);
|
|
77
|
+
|
|
78
|
+
await Promise.all(Array.from({ length: 12 }, () => broker.start()));
|
|
79
|
+
|
|
80
|
+
assert.equal(broker.probeConnectivity().brokerListening, true);
|
|
81
|
+
assert.equal(broker.port, port);
|
|
82
|
+
await broker.stop();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('stop() racing an in-flight start() tears down the late listener', async () => {
|
|
86
|
+
const port = await getFreePort();
|
|
87
|
+
const broker = await createBroker(port);
|
|
88
|
+
let releaseInit!: () => void;
|
|
89
|
+
let initEntered!: () => void;
|
|
90
|
+
const entered = new Promise<void>((resolve) => { initEntered = resolve; });
|
|
91
|
+
const release = new Promise<void>((resolve) => { releaseInit = resolve; });
|
|
92
|
+
const originalInit = broker.taskStore.init.bind(broker.taskStore);
|
|
93
|
+
(broker.taskStore as any).init = async () => {
|
|
94
|
+
initEntered();
|
|
95
|
+
await release;
|
|
96
|
+
await originalInit();
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const starting = broker.start();
|
|
100
|
+
await entered;
|
|
101
|
+
const stopping = broker.stop();
|
|
102
|
+
releaseInit();
|
|
103
|
+
await Promise.all([starting, stopping]);
|
|
104
|
+
|
|
105
|
+
assert.equal(broker.probeConnectivity().brokerListening, false);
|
|
106
|
+
const successor = await createBroker(port);
|
|
107
|
+
await successor.start();
|
|
108
|
+
await successor.stop();
|
|
109
|
+
});
|
|
110
|
+
|
|
74
111
|
test('broker probe reports server-only and bridge-connected states', async () => {
|
|
75
112
|
const port = await getFreePort();
|
|
76
113
|
const broker = await createBroker(port);
|
|
@@ -834,6 +871,83 @@ test('ensureReady() rebind leaves exactly one heartbeat interval running', async
|
|
|
834
871
|
}
|
|
835
872
|
});
|
|
836
873
|
|
|
874
|
+
test('remote stop() awaits an in-flight promotion and prevents a late bind', async () => {
|
|
875
|
+
const port = await getFreePort();
|
|
876
|
+
const primary = await createBroker(port);
|
|
877
|
+
await primary.start();
|
|
878
|
+
|
|
879
|
+
const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-stop-promotion-'));
|
|
880
|
+
const remote = new RemoteBrowserAgentBroker({
|
|
881
|
+
host: '127.0.0.1',
|
|
882
|
+
port,
|
|
883
|
+
logger: { info() {}, warn() {}, error() {} },
|
|
884
|
+
requestTimeoutMs: 2_000,
|
|
885
|
+
taskStore: new TaskStore({ dir: join(root, 'tasks') }),
|
|
886
|
+
});
|
|
887
|
+
await remote.start();
|
|
888
|
+
await primary.stop();
|
|
889
|
+
|
|
890
|
+
let initEntered!: () => void;
|
|
891
|
+
let releaseInit!: () => void;
|
|
892
|
+
const entered = new Promise<void>((resolve) => { initEntered = resolve; });
|
|
893
|
+
const release = new Promise<void>((resolve) => { releaseInit = resolve; });
|
|
894
|
+
const originalInit = remote.taskStore.init.bind(remote.taskStore);
|
|
895
|
+
(remote.taskStore as any).init = async () => {
|
|
896
|
+
initEntered();
|
|
897
|
+
await release;
|
|
898
|
+
await originalInit();
|
|
899
|
+
};
|
|
900
|
+
|
|
901
|
+
const promotion = (remote as any).promoteOrReconnect() as Promise<BrowserAgentBroker | null>;
|
|
902
|
+
await entered;
|
|
903
|
+
const stopping = remote.stop();
|
|
904
|
+
releaseInit();
|
|
905
|
+
await Promise.all([promotion, stopping]);
|
|
906
|
+
|
|
907
|
+
assert.equal(remote.probeConnectivity().brokerListening, false);
|
|
908
|
+
const successor = await createBroker(port);
|
|
909
|
+
await successor.start();
|
|
910
|
+
await successor.stop();
|
|
911
|
+
});
|
|
912
|
+
|
|
913
|
+
test('an operation resuming after remote stop() cannot start a new promotion', async () => {
|
|
914
|
+
const port = await getFreePort();
|
|
915
|
+
const primary = await createBroker(port);
|
|
916
|
+
await primary.start();
|
|
917
|
+
|
|
918
|
+
const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-late-promotion-'));
|
|
919
|
+
const remote = new RemoteBrowserAgentBroker({
|
|
920
|
+
host: '127.0.0.1',
|
|
921
|
+
port,
|
|
922
|
+
logger: { info() {}, warn() {}, error() {} },
|
|
923
|
+
requestTimeoutMs: 2_000,
|
|
924
|
+
taskStore: new TaskStore({ dir: join(root, 'tasks') }),
|
|
925
|
+
});
|
|
926
|
+
await remote.start();
|
|
927
|
+
|
|
928
|
+
let probeEntered!: () => void;
|
|
929
|
+
let releaseProbe!: () => void;
|
|
930
|
+
const entered = new Promise<void>((resolve) => { probeEntered = resolve; });
|
|
931
|
+
const release = new Promise<void>((resolve) => { releaseProbe = resolve; });
|
|
932
|
+
const originalProbe = (remote as any).probePrimary.bind(remote);
|
|
933
|
+
(remote as any).probePrimary = async () => {
|
|
934
|
+
probeEntered();
|
|
935
|
+
await release;
|
|
936
|
+
return await originalProbe();
|
|
937
|
+
};
|
|
938
|
+
|
|
939
|
+
const ensuring = remote.ensureReady({ waitForBridgeMs: 0 });
|
|
940
|
+
await entered;
|
|
941
|
+
await remote.stop();
|
|
942
|
+
await primary.stop();
|
|
943
|
+
releaseProbe();
|
|
944
|
+
await ensuring;
|
|
945
|
+
|
|
946
|
+
const successor = await createBroker(port);
|
|
947
|
+
await successor.start();
|
|
948
|
+
await successor.stop();
|
|
949
|
+
});
|
|
950
|
+
|
|
837
951
|
test('a remote broker restarted after stop() resumes background healing', async () => {
|
|
838
952
|
// Ctrl+Z stops the broker and SIGCONT start()s the same instance. If stop()'s
|
|
839
953
|
// `stopped` flag is never cleared, every heal path is dead for the rest of the
|
package/tests/index.test.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
3
|
import net from 'node:net';
|
|
4
|
+
import { mkdtemp } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
4
7
|
|
|
5
8
|
import extension, { getBroker, resetForTests } from '../src/index.ts';
|
|
9
|
+
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
10
|
+
import { TaskStore } from '../src/broker/task-store.ts';
|
|
6
11
|
|
|
7
12
|
async function getFreePort(): Promise<number> {
|
|
8
13
|
return await new Promise((resolve, reject) => {
|
|
@@ -191,6 +196,200 @@ test('broker startup diagnostics are routed through the extension UI context', a
|
|
|
191
196
|
}
|
|
192
197
|
});
|
|
193
198
|
|
|
199
|
+
test('suspend during task-store setup still registers browser tools without acquiring a broker', async () => {
|
|
200
|
+
await resetForTests();
|
|
201
|
+
const originalPort = process.env.PI_BA_PORT;
|
|
202
|
+
const originalInit = TaskStore.prototype.init;
|
|
203
|
+
const originalKill = process.kill;
|
|
204
|
+
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
|
|
205
|
+
let releaseInit!: () => void;
|
|
206
|
+
let initEntered!: () => void;
|
|
207
|
+
let stopAttempted!: () => void;
|
|
208
|
+
const entered = new Promise<void>((resolve) => { initEntered = resolve; });
|
|
209
|
+
const release = new Promise<void>((resolve) => { releaseInit = resolve; });
|
|
210
|
+
const attempted = new Promise<void>((resolve) => { stopAttempted = resolve; });
|
|
211
|
+
let delayed = false;
|
|
212
|
+
|
|
213
|
+
try {
|
|
214
|
+
process.env.PI_BA_PORT = String(await getFreePort());
|
|
215
|
+
TaskStore.prototype.init = async function (...args: Parameters<typeof originalInit>) {
|
|
216
|
+
if (!delayed) {
|
|
217
|
+
delayed = true;
|
|
218
|
+
initEntered();
|
|
219
|
+
await release;
|
|
220
|
+
}
|
|
221
|
+
return await originalInit.apply(this, args);
|
|
222
|
+
};
|
|
223
|
+
// Install the POSIX suspend handlers even though the test suite runs on
|
|
224
|
+
// Windows, and intercept SIGSTOP so the test process is not suspended.
|
|
225
|
+
Object.defineProperty(process, 'platform', { ...platformDescriptor, value: 'linux' });
|
|
226
|
+
(process as any).kill = (_pid: number, signal?: string | number) => {
|
|
227
|
+
if (signal === 'SIGSTOP') stopAttempted();
|
|
228
|
+
return true;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const pi = createPiHarness();
|
|
232
|
+
await extension(pi as any);
|
|
233
|
+
Object.defineProperty(process, 'platform', platformDescriptor!);
|
|
234
|
+
const starting = pi.handlers.get('session_start')({}, {});
|
|
235
|
+
await entered;
|
|
236
|
+
(process as any).emit('SIGTSTP');
|
|
237
|
+
await attempted;
|
|
238
|
+
releaseInit();
|
|
239
|
+
await starting;
|
|
240
|
+
|
|
241
|
+
assert.equal(getBroker(), null, 'suspend must still block eager broker acquisition');
|
|
242
|
+
assert.equal(pi.tools.has('activate_browser_agent_tools'), true);
|
|
243
|
+
assert.equal(pi.tools.has('browser_run_task'), true);
|
|
244
|
+
|
|
245
|
+
(process as any).emit('SIGCONT');
|
|
246
|
+
await pi.handlers.get('session_shutdown')({}, {});
|
|
247
|
+
} finally {
|
|
248
|
+
releaseInit?.();
|
|
249
|
+
(process as any).emit('SIGCONT');
|
|
250
|
+
TaskStore.prototype.init = originalInit;
|
|
251
|
+
(process as any).kill = originalKill;
|
|
252
|
+
if (platformDescriptor) Object.defineProperty(process, 'platform', platformDescriptor);
|
|
253
|
+
await resetForTests();
|
|
254
|
+
if (originalPort === undefined) delete process.env.PI_BA_PORT;
|
|
255
|
+
else process.env.PI_BA_PORT = originalPort;
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test('session shutdown invalidates setup that has not reached broker startup yet', async () => {
|
|
260
|
+
await resetForTests();
|
|
261
|
+
const originalPort = process.env.PI_BA_PORT;
|
|
262
|
+
const originalInit = TaskStore.prototype.init;
|
|
263
|
+
let releaseInit!: () => void;
|
|
264
|
+
let initEntered!: () => void;
|
|
265
|
+
const entered = new Promise<void>((resolve) => { initEntered = resolve; });
|
|
266
|
+
const release = new Promise<void>((resolve) => { releaseInit = resolve; });
|
|
267
|
+
let delayed = false;
|
|
268
|
+
|
|
269
|
+
try {
|
|
270
|
+
process.env.PI_BA_PORT = String(await getFreePort());
|
|
271
|
+
TaskStore.prototype.init = async function (...args: Parameters<typeof originalInit>) {
|
|
272
|
+
if (!delayed) {
|
|
273
|
+
delayed = true;
|
|
274
|
+
initEntered();
|
|
275
|
+
await release;
|
|
276
|
+
}
|
|
277
|
+
return await originalInit.apply(this, args);
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
const pi = createPiHarness();
|
|
281
|
+
await extension(pi as any);
|
|
282
|
+
const starting = pi.handlers.get('session_start')({}, {});
|
|
283
|
+
await entered;
|
|
284
|
+
await pi.handlers.get('session_shutdown')({}, {});
|
|
285
|
+
releaseInit();
|
|
286
|
+
await starting;
|
|
287
|
+
|
|
288
|
+
assert.equal(getBroker(), null);
|
|
289
|
+
assert.equal(pi.tools.size, 0, 'a session invalidated before registration must stay torn down');
|
|
290
|
+
} finally {
|
|
291
|
+
releaseInit?.();
|
|
292
|
+
TaskStore.prototype.init = originalInit;
|
|
293
|
+
await resetForTests();
|
|
294
|
+
if (originalPort === undefined) delete process.env.PI_BA_PORT;
|
|
295
|
+
else process.env.PI_BA_PORT = originalPort;
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
test('session shutdown invalidates and awaits an in-flight broker startup', async () => {
|
|
300
|
+
await resetForTests();
|
|
301
|
+
const originalPort = process.env.PI_BA_PORT;
|
|
302
|
+
const originalGc = TaskStore.prototype.gc;
|
|
303
|
+
let releaseGc!: () => void;
|
|
304
|
+
let gcEntered!: () => void;
|
|
305
|
+
const entered = new Promise<void>((resolve) => { gcEntered = resolve; });
|
|
306
|
+
const release = new Promise<void>((resolve) => { releaseGc = resolve; });
|
|
307
|
+
let delayed = false;
|
|
308
|
+
|
|
309
|
+
try {
|
|
310
|
+
process.env.PI_BA_PORT = String(await getFreePort());
|
|
311
|
+
TaskStore.prototype.gc = async function (...args: Parameters<typeof originalGc>) {
|
|
312
|
+
if (!delayed) {
|
|
313
|
+
delayed = true;
|
|
314
|
+
gcEntered();
|
|
315
|
+
await release;
|
|
316
|
+
}
|
|
317
|
+
return await originalGc.apply(this, args);
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
const pi = createPiHarness();
|
|
321
|
+
await extension(pi as any);
|
|
322
|
+
const starting = pi.handlers.get('session_start')({}, {});
|
|
323
|
+
await entered;
|
|
324
|
+
const shuttingDown = pi.handlers.get('session_shutdown')({}, {});
|
|
325
|
+
releaseGc();
|
|
326
|
+
await Promise.all([starting, shuttingDown]);
|
|
327
|
+
|
|
328
|
+
assert.equal(getBroker(), null, 'late startup must not publish after shutdown');
|
|
329
|
+
const successor = new BrowserAgentBroker({
|
|
330
|
+
host: '127.0.0.1',
|
|
331
|
+
port: Number(process.env.PI_BA_PORT),
|
|
332
|
+
portRange: 1,
|
|
333
|
+
fallbackToEphemeral: false,
|
|
334
|
+
logger: { info() {}, warn() {}, error() {} },
|
|
335
|
+
taskStore: new TaskStore({ dir: join(await mkdtemp(join(tmpdir(), 'pi-browser-agent-successor-')), 'tasks') }),
|
|
336
|
+
});
|
|
337
|
+
await successor.start();
|
|
338
|
+
await successor.stop();
|
|
339
|
+
} finally {
|
|
340
|
+
releaseGc?.();
|
|
341
|
+
TaskStore.prototype.gc = originalGc;
|
|
342
|
+
await resetForTests();
|
|
343
|
+
if (originalPort === undefined) delete process.env.PI_BA_PORT;
|
|
344
|
+
else process.env.PI_BA_PORT = originalPort;
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
test('replacement waits for a stale broker to stop before binding', async () => {
|
|
349
|
+
await resetForTests();
|
|
350
|
+
const originalPort = process.env.PI_BA_PORT;
|
|
351
|
+
let releaseStop!: () => void;
|
|
352
|
+
const release = new Promise<void>((resolve) => { releaseStop = resolve; });
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
process.env.PI_BA_PORT = String(await getFreePort());
|
|
356
|
+
const pi = createPiHarness();
|
|
357
|
+
await extension(pi as any);
|
|
358
|
+
const sessionStart = pi.handlers.get('session_start');
|
|
359
|
+
const sessionShutdown = pi.handlers.get('session_shutdown');
|
|
360
|
+
await sessionStart({}, {});
|
|
361
|
+
|
|
362
|
+
const stale = getBroker();
|
|
363
|
+
assert.ok(stale);
|
|
364
|
+
await stale.stop();
|
|
365
|
+
const originalStop = stale.stop.bind(stale);
|
|
366
|
+
let stopEntered!: () => void;
|
|
367
|
+
const entered = new Promise<void>((resolve) => { stopEntered = resolve; });
|
|
368
|
+
(stale as any).stop = async () => {
|
|
369
|
+
stopEntered();
|
|
370
|
+
await release;
|
|
371
|
+
await originalStop();
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
let replacementSettled = false;
|
|
375
|
+
const replacing = sessionStart({}, {}).finally(() => { replacementSettled = true; });
|
|
376
|
+
await entered;
|
|
377
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
378
|
+
assert.equal(replacementSettled, false, 'replacement must await stale stop');
|
|
379
|
+
assert.equal(getBroker(), null);
|
|
380
|
+
|
|
381
|
+
releaseStop();
|
|
382
|
+
await replacing;
|
|
383
|
+
assert.equal(getBroker()?.probeConnectivity().brokerListening, true);
|
|
384
|
+
await sessionShutdown({}, {});
|
|
385
|
+
} finally {
|
|
386
|
+
releaseStop?.();
|
|
387
|
+
await resetForTests();
|
|
388
|
+
if (originalPort === undefined) delete process.env.PI_BA_PORT;
|
|
389
|
+
else process.env.PI_BA_PORT = originalPort;
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
|
|
194
393
|
test('overlapping session_start calls yield a single shared broker instance', async () => {
|
|
195
394
|
await resetForTests();
|
|
196
395
|
const originalPort = process.env.PI_BA_PORT;
|