oira666_pi-browser-agent 0.0.17 → 0.0.18
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/README.md +5 -1
- package/package.json +1 -1
- package/src/broker/health-reporter.ts +59 -0
- package/src/broker/remote.ts +28 -6
- package/src/index.ts +58 -95
- package/tests/broker.test.ts +59 -1
- package/tests/health-reporter.test.ts +76 -0
- package/tests/index.test.ts +65 -7
package/README.md
CHANGED
|
@@ -78,7 +78,11 @@ Environment variables:
|
|
|
78
78
|
- `PI_BA_PORT` — broker port, default `7878`
|
|
79
79
|
- `PI_BA_TASK_TTL_DAYS` — task-history retention
|
|
80
80
|
|
|
81
|
-
If port `7878
|
|
81
|
+
If another pi instance owns port `7878`, this session connects through it. If acquisition fails, the extension retries in the background.
|
|
82
|
+
|
|
83
|
+
## Connection status
|
|
84
|
+
|
|
85
|
+
The status line shows `browser: connected`, `browser: recovering`, or `browser: disconnected`. Transient disconnects and successful recovery do not produce notifications. After 60 seconds without a connection, the extension shows one short warning for that outage and continues retrying quietly. Broker logs and stack traces are not forwarded to the TUI. Use `activate_browser_agent_tools` for on-demand diagnostics.
|
|
82
86
|
|
|
83
87
|
## WSL → Windows Chrome
|
|
84
88
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { BrokerLogger } from './server.ts';
|
|
2
|
+
|
|
3
|
+
export type BrowserHealthUi = {
|
|
4
|
+
notify?: (message: string, type?: 'info' | 'warning' | 'error') => void;
|
|
5
|
+
setStatus?: (key: string, text: string | undefined) => void;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// Broker logs describe individual attempts, not the outcome of recovery. Never
|
|
9
|
+
// forward them (or Error objects) into pi's notifications or runtime console.
|
|
10
|
+
export const quietBrokerLogger: BrokerLogger = { info() {}, warn() {}, error() {} };
|
|
11
|
+
export const RECOVERY_GRACE_MS = 60_000;
|
|
12
|
+
|
|
13
|
+
/** One reporter per session, retained across broker replacements. */
|
|
14
|
+
export class BrowserHealthReporter {
|
|
15
|
+
private disconnectedSince: number | null = null;
|
|
16
|
+
private warned = false;
|
|
17
|
+
private status: string | undefined;
|
|
18
|
+
private disposed = false;
|
|
19
|
+
|
|
20
|
+
private readonly ui?: BrowserHealthUi;
|
|
21
|
+
|
|
22
|
+
constructor(ui?: BrowserHealthUi) {
|
|
23
|
+
this.ui = ui;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
observe(connected: boolean, now = Date.now()): void {
|
|
27
|
+
if (this.disposed) return;
|
|
28
|
+
if (connected) {
|
|
29
|
+
this.disconnectedSince = null;
|
|
30
|
+
this.warned = false;
|
|
31
|
+
this.setStatus('browser: connected');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
this.disconnectedSince ??= now;
|
|
35
|
+
const expired = now - this.disconnectedSince >= RECOVERY_GRACE_MS;
|
|
36
|
+
this.setStatus(expired ? 'browser: disconnected' : 'browser: recovering');
|
|
37
|
+
if (expired && !this.warned) {
|
|
38
|
+
this.warned = true;
|
|
39
|
+
this.ui?.notify?.('Browser unavailable. Check Chrome and the Browser Agent extension; retrying quietly.', 'warning');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Time spent suspended is not a failed recovery attempt. Keep the warning
|
|
44
|
+
* latch, but give an unfinished recovery a fresh grace period on resume. */
|
|
45
|
+
resume(): void {
|
|
46
|
+
this.disconnectedSince = null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
dispose(): void {
|
|
50
|
+
this.disposed = true;
|
|
51
|
+
this.ui?.setStatus?.('browser-bridge', undefined);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private setStatus(status: string): void {
|
|
55
|
+
if (this.status === status) return;
|
|
56
|
+
this.status = status;
|
|
57
|
+
this.ui?.setStatus?.('browser-bridge', status);
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/broker/remote.ts
CHANGED
|
@@ -44,6 +44,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
44
44
|
readonly taskStore: TaskStore;
|
|
45
45
|
|
|
46
46
|
private socket: WebSocket | null = null;
|
|
47
|
+
private validatedSocket: WebSocket | null = null;
|
|
47
48
|
private connectPromise: Promise<void> | null = null;
|
|
48
49
|
private pendingRequests = new Map<string, PendingRequest>();
|
|
49
50
|
private startupError: Error | null = null;
|
|
@@ -237,11 +238,15 @@ export class RemoteBrowserAgentBroker {
|
|
|
237
238
|
}
|
|
238
239
|
}
|
|
239
240
|
|
|
240
|
-
private closeSocket(): void {
|
|
241
|
+
private closeSocket(terminate = false): void {
|
|
241
242
|
const socket = this.socket;
|
|
242
243
|
this.socket = null;
|
|
244
|
+
this.validatedSocket = null;
|
|
243
245
|
if (socket) {
|
|
244
|
-
try {
|
|
246
|
+
try {
|
|
247
|
+
if (terminate) socket.terminate();
|
|
248
|
+
else socket.close();
|
|
249
|
+
} catch { /* ignore */ }
|
|
245
250
|
}
|
|
246
251
|
}
|
|
247
252
|
|
|
@@ -327,7 +332,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
327
332
|
// socket to the primary is gone; otherwise tools happily send requests
|
|
328
333
|
// into a dead proxy and only fail on timeout, and callers cannot tell
|
|
329
334
|
// "healed" from "still using a stale snapshot".
|
|
330
|
-
const proxyAlive =
|
|
335
|
+
const proxyAlive = this.hasValidatedConnection();
|
|
331
336
|
return {
|
|
332
337
|
...primary,
|
|
333
338
|
brokerReachable: proxyAlive && primary.brokerReachable,
|
|
@@ -339,8 +344,8 @@ export class RemoteBrowserAgentBroker {
|
|
|
339
344
|
};
|
|
340
345
|
}
|
|
341
346
|
return {
|
|
342
|
-
brokerReachable:
|
|
343
|
-
brokerListening:
|
|
347
|
+
brokerReachable: this.hasValidatedConnection(),
|
|
348
|
+
brokerListening: this.hasValidatedConnection(),
|
|
344
349
|
bridgeConnected: false,
|
|
345
350
|
startupError: this.startupError?.message,
|
|
346
351
|
url: this.url,
|
|
@@ -349,7 +354,14 @@ export class RemoteBrowserAgentBroker {
|
|
|
349
354
|
};
|
|
350
355
|
}
|
|
351
356
|
|
|
357
|
+
private hasValidatedConnection(): boolean {
|
|
358
|
+
return !!this.socket && this.socket === this.validatedSocket
|
|
359
|
+
&& this.socket.readyState === WebSocket.OPEN && !this.startupError;
|
|
360
|
+
}
|
|
361
|
+
|
|
352
362
|
private async probePrimary(): Promise<ProbeResult> {
|
|
363
|
+
await this.ensureConnected();
|
|
364
|
+
const socket = this.socket;
|
|
353
365
|
const response = await this.sendControlRequest('probe');
|
|
354
366
|
if (!response.ok) {
|
|
355
367
|
throw new Error(response.error?.message || 'Primary broker probe failed');
|
|
@@ -361,6 +373,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
361
373
|
if (data.supportsBrokerProxy !== true) {
|
|
362
374
|
throw new Error(`Port ${this.port} has an old pi-browser-agent broker; restart the first pi instance`);
|
|
363
375
|
}
|
|
376
|
+
if (this.stopped || this.socket !== socket || socket?.readyState !== WebSocket.OPEN) {
|
|
377
|
+
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
378
|
+
}
|
|
379
|
+
this.validatedSocket = socket;
|
|
364
380
|
return data as ProbeResult;
|
|
365
381
|
}
|
|
366
382
|
|
|
@@ -471,7 +487,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
471
487
|
if (this.stopped) return;
|
|
472
488
|
this.logger.warn?.('[pi-browser-agent] lost primary broker; healing', { reason });
|
|
473
489
|
const promoted = await this.promoteOrReconnect();
|
|
474
|
-
if (promoted || this.
|
|
490
|
+
if (promoted || this.hasValidatedConnection()) {
|
|
475
491
|
this.healAttempt = 0;
|
|
476
492
|
this.cancelHealTimer();
|
|
477
493
|
return;
|
|
@@ -551,6 +567,12 @@ export class RemoteBrowserAgentBroker {
|
|
|
551
567
|
this.remoteProbe = await this.probePrimary();
|
|
552
568
|
this.startupError = null;
|
|
553
569
|
} catch (reconnectError) {
|
|
570
|
+
this.startupError = reconnectError instanceof Error ? reconnectError : new Error(String(reconnectError));
|
|
571
|
+
// A WebSocket handshake alone does not identify a broker. Discard
|
|
572
|
+
// failed probes immediately rather than waiting for a close handshake.
|
|
573
|
+
this.closeSocket(true);
|
|
574
|
+
this.rejectPendingRequests(this.startupError);
|
|
575
|
+
this.scheduleHeal();
|
|
554
576
|
this.logger.warn?.('[pi-browser-agent] failed to reconnect to promoted primary broker', reconnectError);
|
|
555
577
|
}
|
|
556
578
|
return null;
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { join } from 'node:path';
|
|
|
3
3
|
import { BrowserAgentBroker, type BrokerLogger } from './broker/server.ts';
|
|
4
4
|
import { RemoteBrowserAgentBroker } from './broker/remote.ts';
|
|
5
5
|
import { TaskStore } from './broker/task-store.ts';
|
|
6
|
+
import { BrowserHealthReporter, quietBrokerLogger } from './broker/health-reporter.ts';
|
|
6
7
|
import { ensureStateDir } from './util/paths.ts';
|
|
7
8
|
import { listInstances, removeInstanceFile, writeInstanceFile } from './util/instances.ts';
|
|
8
9
|
import { LazyBrokerHandle, type BrokerLike } from './broker/lazy.ts';
|
|
@@ -69,40 +70,6 @@ export async function resetForTests(): Promise<void> {
|
|
|
69
70
|
brokerShuttingDown = false;
|
|
70
71
|
}
|
|
71
72
|
|
|
72
|
-
function formatLogArg(value: unknown): string {
|
|
73
|
-
if (value instanceof Error) {
|
|
74
|
-
return value.stack || value.message;
|
|
75
|
-
}
|
|
76
|
-
if (typeof value === 'string') {
|
|
77
|
-
return value;
|
|
78
|
-
}
|
|
79
|
-
try {
|
|
80
|
-
return JSON.stringify(value);
|
|
81
|
-
} catch {
|
|
82
|
-
return String(value);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
function createUiLogger(ctx?: ExtensionContextLike): BrokerLogger {
|
|
87
|
-
const notify = ctx?.ui?.notify;
|
|
88
|
-
if (typeof notify !== 'function') {
|
|
89
|
-
return { info() {}, warn() {}, error() {} };
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const emit = (type: 'info' | 'warning' | 'error', args: unknown[]) => {
|
|
93
|
-
const message = args.map(formatLogArg).filter(Boolean).join(' ');
|
|
94
|
-
if (message) {
|
|
95
|
-
notify(message, type);
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
return {
|
|
100
|
-
info: (...args: unknown[]) => emit('info', args),
|
|
101
|
-
warn: (...args: unknown[]) => emit('warning', args),
|
|
102
|
-
error: (...args: unknown[]) => emit('error', args),
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
|
|
106
73
|
async function createAndStartBroker(logger: BrokerLogger): Promise<BrowserAgentBrokerLike> {
|
|
107
74
|
const tasksDir = await ensureStateDir('tasks');
|
|
108
75
|
const preferredPort = Number(process.env.PI_BA_PORT || 7878);
|
|
@@ -154,6 +121,9 @@ async function createAndStartBroker(logger: BrokerLogger): Promise<BrowserAgentB
|
|
|
154
121
|
try {
|
|
155
122
|
await remoteBroker.start();
|
|
156
123
|
} catch (remoteError) {
|
|
124
|
+
// A failed handshake can leave an open socket and a background heal loop.
|
|
125
|
+
// Retire this candidate before a later acquisition tries again.
|
|
126
|
+
await remoteBroker.stop();
|
|
157
127
|
const message = remoteError instanceof Error ? remoteError.message : String(remoteError);
|
|
158
128
|
if (message.includes('not a pi-browser-agent broker')) {
|
|
159
129
|
throw new Error(`Port ${preferredPort} is busy, but it is not pi-browser-agent`);
|
|
@@ -169,6 +139,7 @@ async function createAndStartBroker(logger: BrokerLogger): Promise<BrowserAgentB
|
|
|
169
139
|
|
|
170
140
|
let signalHandlersInstalled = false;
|
|
171
141
|
let suspending = false;
|
|
142
|
+
let resumeGeneration = 0;
|
|
172
143
|
|
|
173
144
|
/**
|
|
174
145
|
* Make Ctrl+Z (SIGTSTP) graceful.
|
|
@@ -205,8 +176,8 @@ function installSuspendResumeHandlers(): void {
|
|
|
205
176
|
await broker.stop();
|
|
206
177
|
try { await removeInstanceFile(process.pid); } catch { /* ignore */ }
|
|
207
178
|
}
|
|
208
|
-
} catch
|
|
209
|
-
|
|
179
|
+
} catch {
|
|
180
|
+
// Resume and the session recovery loop will retry quietly.
|
|
210
181
|
} finally {
|
|
211
182
|
// Now actually suspend. SIGSTOP is uncatchable, so this reliably stops
|
|
212
183
|
// the process just like the default Ctrl+Z behaviour would have.
|
|
@@ -218,6 +189,7 @@ function installSuspendResumeHandlers(): void {
|
|
|
218
189
|
process.on('SIGCONT', () => {
|
|
219
190
|
if (!suspending) return;
|
|
220
191
|
suspending = false;
|
|
192
|
+
resumeGeneration += 1;
|
|
221
193
|
brokerShuttingDown = false;
|
|
222
194
|
const broker = brokerSingleton;
|
|
223
195
|
if (!broker) return;
|
|
@@ -239,51 +211,14 @@ function installSuspendResumeHandlers(): void {
|
|
|
239
211
|
});
|
|
240
212
|
} catch { /* ignore */ }
|
|
241
213
|
}
|
|
242
|
-
} catch
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
// Another pi process became primary while we were suspended. That is
|
|
246
|
-
// fine: the lazy handle re-resolves this session into a proxy of the
|
|
247
|
-
// new primary on the next tool call, so no restart is needed.
|
|
248
|
-
console.warn('[pi-browser-agent] another pi instance owns the broker port after resume; this session re-resolves into a proxy of the new primary automatically');
|
|
249
|
-
} else {
|
|
250
|
-
console.warn('[pi-browser-agent] broker restart after resume failed', error);
|
|
251
|
-
}
|
|
214
|
+
} catch {
|
|
215
|
+
// Another process may own the port now. The session recovery loop
|
|
216
|
+
// re-resolves the lazy handle; the health reporter owns any warning.
|
|
252
217
|
}
|
|
253
218
|
})();
|
|
254
219
|
});
|
|
255
220
|
}
|
|
256
221
|
|
|
257
|
-
/**
|
|
258
|
-
* Surface bridge health to the human running pi.
|
|
259
|
-
*
|
|
260
|
-
* The failure mode this guards against: the broker keeps listening, Chrome keeps
|
|
261
|
-
* running, but the extension's service worker socket is gone — so every agent
|
|
262
|
-
* reports "the connection is down" while the user sees nothing wrong. Now the
|
|
263
|
-
* transition is announced in the UI the moment it happens.
|
|
264
|
-
*/
|
|
265
|
-
function attachBridgeStateReporter(broker: BrowserAgentBrokerLike, ctx?: ExtensionContextLike): () => void {
|
|
266
|
-
const notify = ctx?.ui?.notify;
|
|
267
|
-
const setStatus = ctx?.ui?.setStatus;
|
|
268
|
-
// Per-subscription, not per-process: with a module global one session's
|
|
269
|
-
// transition suppressed every other session's notification.
|
|
270
|
-
let lastReportedBridgeState: boolean | null = null;
|
|
271
|
-
return broker.addBridgeStateListener(({ connected, probe }) => {
|
|
272
|
-
if (lastReportedBridgeState === connected) return;
|
|
273
|
-
lastReportedBridgeState = connected;
|
|
274
|
-
setStatus?.('browser-bridge', connected ? 'browser: connected' : 'browser: DISCONNECTED');
|
|
275
|
-
if (connected) {
|
|
276
|
-
notify?.(`Browser extension bridge reconnected (${probe.url || 'ws://127.0.0.1:7878'}).`, 'info');
|
|
277
|
-
} else {
|
|
278
|
-
notify?.(
|
|
279
|
-
`Browser extension bridge disconnected${probe.lastBridgeDisconnectReason ? `: ${probe.lastBridgeDisconnectReason}` : ''}. `
|
|
280
|
-
+ 'pi keeps retrying automatically; if browser tools stay unavailable, reload the "Browser Agent" extension at chrome://extensions.',
|
|
281
|
-
'warning',
|
|
282
|
-
);
|
|
283
|
-
}
|
|
284
|
-
});
|
|
285
|
-
}
|
|
286
|
-
|
|
287
222
|
/** Republish instance discovery when a secondary wins the bind race. Without
|
|
288
223
|
* this, discovery keeps advertising the dead primary's pid/port forever. */
|
|
289
224
|
function attachPromotionReporter(broker: BrowserAgentBrokerLike, logger: BrokerLogger): () => void {
|
|
@@ -370,24 +305,24 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
370
305
|
registerTool: (tool: any) => void;
|
|
371
306
|
}) {
|
|
372
307
|
const registerSessionTool = async (ctx?: ExtensionContextLike) => {
|
|
373
|
-
const sessionGeneration = sessionLifecycleGeneration;
|
|
308
|
+
const sessionGeneration = ++sessionLifecycleGeneration;
|
|
309
|
+
for (const cleanup of [...sessionCleanups]) cleanup();
|
|
310
|
+
sessionCleanups.clear();
|
|
311
|
+
for (const handle of activeHandles) handle.dispose();
|
|
312
|
+
activeHandles.clear();
|
|
374
313
|
resetBrowserAgentToolState();
|
|
375
314
|
resetRegisteredBrowserTools();
|
|
376
|
-
const logger =
|
|
315
|
+
const logger = quietBrokerLogger;
|
|
316
|
+
const health = new BrowserHealthReporter(ctx?.ui);
|
|
377
317
|
|
|
378
318
|
// One subscription per (session, broker instance). Re-resolving the broker
|
|
379
319
|
// must not stack duplicate reporters, and the previous broker's must go.
|
|
380
320
|
let attachedBroker: BrowserAgentBrokerLike | null = null;
|
|
381
321
|
let detachReporters: (() => void) | null = null;
|
|
382
322
|
const attachReporters = (broker: BrowserAgentBrokerLike) => {
|
|
383
|
-
if (attachedBroker === broker) return;
|
|
323
|
+
if (disposed || attachedBroker === broker) return;
|
|
384
324
|
detachReporters?.();
|
|
385
|
-
|
|
386
|
-
const detachPromotion = attachPromotionReporter(broker, logger);
|
|
387
|
-
detachReporters = () => {
|
|
388
|
-
detachBridge();
|
|
389
|
-
detachPromotion();
|
|
390
|
-
};
|
|
325
|
+
detachReporters = attachPromotionReporter(broker, logger);
|
|
391
326
|
attachedBroker = broker;
|
|
392
327
|
};
|
|
393
328
|
|
|
@@ -412,7 +347,40 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
412
347
|
return broker as unknown as BrokerLike;
|
|
413
348
|
}, taskStore);
|
|
414
349
|
activeHandles.add(handle);
|
|
350
|
+
let disposed = false;
|
|
351
|
+
let recovering = false;
|
|
352
|
+
let observedResumeGeneration = resumeGeneration;
|
|
353
|
+
// Polling also covers initial state, lost proxy transports and stop/start
|
|
354
|
+
// cycles, none of which reliably emit bridge-state events.
|
|
355
|
+
const observeHealth = () => {
|
|
356
|
+
if (disposed || suspending) return;
|
|
357
|
+
if (observedResumeGeneration !== resumeGeneration) {
|
|
358
|
+
observedResumeGeneration = resumeGeneration;
|
|
359
|
+
health.resume();
|
|
360
|
+
// stop() clears broker listeners. Resume may reuse that same object.
|
|
361
|
+
const previousBroker = attachedBroker;
|
|
362
|
+
attachedBroker = null;
|
|
363
|
+
if (previousBroker) attachReporters(previousBroker);
|
|
364
|
+
}
|
|
365
|
+
health.observe(handle.probeConnectivity().bridgeConnected);
|
|
366
|
+
};
|
|
367
|
+
const recoveryTimer = setInterval(() => {
|
|
368
|
+
if (disposed || suspending || brokerShuttingDown) return;
|
|
369
|
+
observeHealth();
|
|
370
|
+
if (recovering) return;
|
|
371
|
+
recovering = true;
|
|
372
|
+
void handle.ensureReady({ waitForBridgeMs: 0 }).catch(() => {
|
|
373
|
+
// Tool diagnostics retain the cause; no raw exception reaches the UI.
|
|
374
|
+
}).finally(() => {
|
|
375
|
+
recovering = false;
|
|
376
|
+
observeHealth();
|
|
377
|
+
});
|
|
378
|
+
}, 2_000);
|
|
379
|
+
recoveryTimer.unref();
|
|
415
380
|
sessionCleanups.add(() => {
|
|
381
|
+
disposed = true;
|
|
382
|
+
clearInterval(recoveryTimer);
|
|
383
|
+
health.dispose();
|
|
416
384
|
detachReporters?.();
|
|
417
385
|
detachReporters = null;
|
|
418
386
|
attachedBroker = null;
|
|
@@ -431,11 +399,8 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
431
399
|
startupMessage = null;
|
|
432
400
|
} catch (error) {
|
|
433
401
|
startupMessage = error instanceof Error ? error.message : String(error);
|
|
434
|
-
ctx?.ui?.notify?.(
|
|
435
|
-
`Browser agent broker not acquired yet: ${startupMessage}. Browser tools are registered and will retry automatically.`,
|
|
436
|
-
'warning',
|
|
437
|
-
);
|
|
438
402
|
}
|
|
403
|
+
observeHealth();
|
|
439
404
|
};
|
|
440
405
|
|
|
441
406
|
// Install once per process so Ctrl+Z releases the broker port instead of
|
|
@@ -471,15 +436,13 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
471
436
|
startupMessage = null;
|
|
472
437
|
try {
|
|
473
438
|
if (broker) await broker.stop();
|
|
474
|
-
} catch
|
|
475
|
-
|
|
476
|
-
ctx?.ui?.notify?.(`pi-browser-agent shutdown failed: ${message}`, 'warning');
|
|
439
|
+
} catch {
|
|
440
|
+
ctx?.ui?.notify?.('Browser broker cleanup failed.', 'warning');
|
|
477
441
|
} finally {
|
|
478
442
|
try {
|
|
479
443
|
await removeInstanceFile(process.pid);
|
|
480
|
-
} catch
|
|
481
|
-
|
|
482
|
-
ctx?.ui?.notify?.(`pi-browser-agent instance cleanup failed: ${message}`, 'warning');
|
|
444
|
+
} catch {
|
|
445
|
+
ctx?.ui?.notify?.('Browser discovery cleanup failed.', 'warning');
|
|
483
446
|
}
|
|
484
447
|
brokerShuttingDown = false;
|
|
485
448
|
}
|
package/tests/broker.test.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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';
|
|
4
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
5
5
|
import { tmpdir } from 'node:os';
|
|
6
6
|
import { join } from 'node:path';
|
|
7
7
|
|
|
@@ -792,6 +792,64 @@ test('a secondary heals itself in the background when the primary dies, with no
|
|
|
792
792
|
await remote.stop();
|
|
793
793
|
});
|
|
794
794
|
|
|
795
|
+
for (const failure of ['invalid', 'silent'] as const) {
|
|
796
|
+
test(`background recovery closes connections with ${failure} probes and keeps retrying`, async () => {
|
|
797
|
+
const port = await getFreePort();
|
|
798
|
+
const server = new WebSocketServer({ host: '127.0.0.1', port });
|
|
799
|
+
await new Promise<void>((resolve) => server.once('listening', resolve));
|
|
800
|
+
let valid = true;
|
|
801
|
+
let failedProbes = 0;
|
|
802
|
+
server.on('connection', (socket) => {
|
|
803
|
+
socket.on('message', (raw) => {
|
|
804
|
+
const frame = JSON.parse(raw.toString());
|
|
805
|
+
if (frame.kind !== 'probe') return;
|
|
806
|
+
if (!valid) {
|
|
807
|
+
failedProbes += 1;
|
|
808
|
+
if (failure === 'silent') return;
|
|
809
|
+
}
|
|
810
|
+
socket.send(JSON.stringify({
|
|
811
|
+
v: 1, kind: 'response', id: frame.id, ok: true,
|
|
812
|
+
data: valid ? {
|
|
813
|
+
brokerReachable: true, brokerListening: true, bridgeConnected: true,
|
|
814
|
+
supportsBrokerProxy: true, bridgeSessionSerial: 1,
|
|
815
|
+
} : { notABroker: true },
|
|
816
|
+
}));
|
|
817
|
+
});
|
|
818
|
+
});
|
|
819
|
+
const tmp = join(process.cwd(), 'tmp');
|
|
820
|
+
await mkdir(tmp, { recursive: true });
|
|
821
|
+
const root = await mkdtemp(join(tmp, 'broker-invalid-probe-'));
|
|
822
|
+
const remote = new RemoteBrowserAgentBroker({
|
|
823
|
+
host: '127.0.0.1', port,
|
|
824
|
+
logger: { info() {}, warn() {}, error() {} },
|
|
825
|
+
requestTimeoutMs: 100,
|
|
826
|
+
taskStore: new TaskStore({ dir: join(root, 'tasks') }),
|
|
827
|
+
});
|
|
828
|
+
try {
|
|
829
|
+
await remote.start();
|
|
830
|
+
assert.equal(remote.probeConnectivity().bridgeConnected, true);
|
|
831
|
+
valid = false;
|
|
832
|
+
for (const socket of server.clients) socket.terminate();
|
|
833
|
+
|
|
834
|
+
await waitFor(() => failedProbes >= 1 && server.clients.size === 0, 2_000, 'failed connection cleanup');
|
|
835
|
+
assert.equal(remote.probeConnectivity().brokerListening, false);
|
|
836
|
+
assert.equal(remote.probeConnectivity().bridgeConnected, false);
|
|
837
|
+
await waitFor(() => failedProbes >= 2 && server.clients.size === 0, 3_000, 'background retry cleanup');
|
|
838
|
+
|
|
839
|
+
// No foreground call should be needed once a valid primary is available.
|
|
840
|
+
valid = true;
|
|
841
|
+
await waitFor(() => remote.probeConnectivity().bridgeConnected, 4_000, 'validated reconnect');
|
|
842
|
+
assert.equal(remote.probeConnectivity().role, 'proxy');
|
|
843
|
+
assert.equal(remote.probeConnectivity().startupError, undefined);
|
|
844
|
+
} finally {
|
|
845
|
+
await remote.stop();
|
|
846
|
+
for (const socket of server.clients) socket.terminate();
|
|
847
|
+
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
848
|
+
await rm(root, { recursive: true, force: true });
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
|
|
795
853
|
test('a proxy secondary never claims a live bridge once its socket to the primary is gone', async () => {
|
|
796
854
|
const port = await getFreePort();
|
|
797
855
|
const primary = await createBroker(port);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { BrowserHealthReporter, quietBrokerLogger, RECOVERY_GRACE_MS } from '../src/broker/health-reporter.ts';
|
|
4
|
+
|
|
5
|
+
function harness() {
|
|
6
|
+
const statuses: Array<string | undefined> = [];
|
|
7
|
+
const notifications: string[] = [];
|
|
8
|
+
const reporter = new BrowserHealthReporter({
|
|
9
|
+
setStatus(key, value) { assert.equal(key, 'browser-bridge'); statuses.push(value); },
|
|
10
|
+
notify(message, type) { assert.equal(type, 'warning'); notifications.push(message); },
|
|
11
|
+
});
|
|
12
|
+
return { reporter, statuses, notifications };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
test('initial state and transient disconnects only update the status line', () => {
|
|
16
|
+
const { reporter, statuses, notifications } = harness();
|
|
17
|
+
reporter.observe(true, 0);
|
|
18
|
+
reporter.observe(true, 1);
|
|
19
|
+
reporter.observe(false, 2);
|
|
20
|
+
reporter.observe(false, RECOVERY_GRACE_MS);
|
|
21
|
+
reporter.observe(true, RECOVERY_GRACE_MS + 1);
|
|
22
|
+
assert.deepEqual(statuses, ['browser: connected', 'browser: recovering', 'browser: connected']);
|
|
23
|
+
assert.deepEqual(notifications, []);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('sustained failure warns once, regardless of repeated recovery attempts', () => {
|
|
27
|
+
const { reporter, statuses, notifications } = harness();
|
|
28
|
+
reporter.observe(false, 0);
|
|
29
|
+
reporter.observe(false, RECOVERY_GRACE_MS - 1);
|
|
30
|
+
assert.equal(notifications.length, 0);
|
|
31
|
+
reporter.observe(false, RECOVERY_GRACE_MS);
|
|
32
|
+
for (let i = 1; i <= 100; i++) reporter.observe(false, RECOVERY_GRACE_MS + i * 2_000);
|
|
33
|
+
assert.deepEqual(statuses, ['browser: recovering', 'browser: disconnected']);
|
|
34
|
+
assert.equal(notifications.length, 1);
|
|
35
|
+
assert.ok(notifications[0].length < 120);
|
|
36
|
+
assert.ok(!notifications[0].includes('\n'));
|
|
37
|
+
reporter.observe(true, 300_000);
|
|
38
|
+
reporter.observe(false, 300_001);
|
|
39
|
+
reporter.observe(false, 300_001 + RECOVERY_GRACE_MS);
|
|
40
|
+
assert.equal(notifications.length, 2, 'a separate outage gets its own warning');
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('resume gives recovery time without repeating an existing warning', () => {
|
|
44
|
+
const { reporter, notifications } = harness();
|
|
45
|
+
reporter.observe(false, 0);
|
|
46
|
+
reporter.resume();
|
|
47
|
+
reporter.observe(false, 300_000);
|
|
48
|
+
reporter.observe(true, 300_001);
|
|
49
|
+
assert.deepEqual(notifications, []);
|
|
50
|
+
reporter.observe(false, 300_002);
|
|
51
|
+
reporter.observe(false, 300_002 + RECOVERY_GRACE_MS);
|
|
52
|
+
assert.equal(notifications.length, 1);
|
|
53
|
+
reporter.resume();
|
|
54
|
+
reporter.observe(false, 600_000);
|
|
55
|
+
reporter.observe(false, 600_000 + RECOVERY_GRACE_MS);
|
|
56
|
+
assert.equal(notifications.length, 1);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('shutdown clears status and ignores late recovery completions', () => {
|
|
60
|
+
const { reporter, statuses, notifications } = harness();
|
|
61
|
+
reporter.observe(false, 0);
|
|
62
|
+
reporter.dispose();
|
|
63
|
+
reporter.observe(false, RECOVERY_GRACE_MS);
|
|
64
|
+
reporter.observe(true, RECOVERY_GRACE_MS + 1);
|
|
65
|
+
assert.deepEqual(statuses, ['browser: recovering', undefined]);
|
|
66
|
+
assert.deepEqual(notifications, []);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('low-level logs never reach the runtime console, even with stack traces', (t) => {
|
|
70
|
+
const spies = ['info', 'warn', 'error'].map((method) => t.mock.method(console, method as 'warn', () => {}));
|
|
71
|
+
const error = new Error('failure\n at internal-frame.ts:123');
|
|
72
|
+
quietBrokerLogger.info?.('connected', error);
|
|
73
|
+
quietBrokerLogger.warn?.('retrying', error);
|
|
74
|
+
quietBrokerLogger.error?.('failed', error);
|
|
75
|
+
for (const spy of spies) assert.equal(spy.mock.callCount(), 0);
|
|
76
|
+
});
|
package/tests/index.test.ts
CHANGED
|
@@ -145,7 +145,7 @@ test('extension retries broker startup on a later session after a transient bind
|
|
|
145
145
|
}
|
|
146
146
|
});
|
|
147
147
|
|
|
148
|
-
test('
|
|
148
|
+
test('startup failure stays quiet and retries without a tool call', async () => {
|
|
149
149
|
await resetForTests();
|
|
150
150
|
const originalPort = process.env.PI_BA_PORT;
|
|
151
151
|
const originalRange = process.env.PI_BA_PORT_RANGE;
|
|
@@ -153,6 +153,7 @@ test('broker startup diagnostics are routed through the extension UI context', a
|
|
|
153
153
|
const blockedPort = await getFreePort();
|
|
154
154
|
const blocker = net.createServer();
|
|
155
155
|
const notifications: Array<{ message: string; type?: string }> = [];
|
|
156
|
+
const statuses: Array<string | undefined> = [];
|
|
156
157
|
|
|
157
158
|
try {
|
|
158
159
|
await new Promise<void>((resolve, reject) => blocker.listen(blockedPort, '127.0.0.1', () => resolve()).once('error', reject));
|
|
@@ -164,17 +165,26 @@ test('broker startup diagnostics are routed through the extension UI context', a
|
|
|
164
165
|
await extension(pi as any);
|
|
165
166
|
const sessionStart = pi.handlers.get('session_start');
|
|
166
167
|
|
|
167
|
-
await sessionStart({}, { ui: {
|
|
168
|
+
await sessionStart({}, { ui: {
|
|
169
|
+
notify: (message: string, type?: string) => notifications.push({ message, type }),
|
|
170
|
+
setStatus: (_key: string, status: string | undefined) => statuses.push(status),
|
|
171
|
+
} });
|
|
168
172
|
|
|
169
173
|
assert.equal(getBroker(), null);
|
|
170
|
-
assert.
|
|
171
|
-
|
|
172
|
-
// and the full browser_* suite is still registered behind a lazy handle so
|
|
173
|
-
// the integration can heal itself on a later tool call without restarting pi.
|
|
174
|
-
assert.ok(notifications.some((entry) => entry.type === 'warning' && entry.message.includes('Browser agent broker not acquired yet')));
|
|
174
|
+
assert.deepEqual(notifications, []);
|
|
175
|
+
assert.deepEqual(statuses, ['browser: recovering']);
|
|
175
176
|
assert.ok(pi.tools.has('activate_browser_agent_tools'));
|
|
176
177
|
assert.ok(pi.tools.has('browser_get_html'));
|
|
177
178
|
assert.ok(pi.tools.has('browser_run_task'));
|
|
179
|
+
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
|
180
|
+
const deadline = Date.now() + 5_000;
|
|
181
|
+
while (!getBroker() && Date.now() < deadline) {
|
|
182
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
183
|
+
}
|
|
184
|
+
assert.equal(getBroker()?.probeConnectivity().brokerListening, true);
|
|
185
|
+
assert.deepEqual(notifications, []);
|
|
186
|
+
await pi.handlers.get('session_shutdown')({}, {});
|
|
187
|
+
assert.equal(statuses.at(-1), undefined);
|
|
178
188
|
} finally {
|
|
179
189
|
await resetForTests();
|
|
180
190
|
await new Promise<void>((resolve) => blocker.close(() => resolve()));
|
|
@@ -196,6 +206,54 @@ test('broker startup diagnostics are routed through the extension UI context', a
|
|
|
196
206
|
}
|
|
197
207
|
});
|
|
198
208
|
|
|
209
|
+
test('session monitor reports one warning per outage and stops on shutdown', async (t) => {
|
|
210
|
+
await resetForTests();
|
|
211
|
+
const originalPort = process.env.PI_BA_PORT;
|
|
212
|
+
const notifications: string[] = [];
|
|
213
|
+
const statuses: Array<string | undefined> = [];
|
|
214
|
+
try {
|
|
215
|
+
process.env.PI_BA_PORT = String(await getFreePort());
|
|
216
|
+
t.mock.timers.enable({ apis: ['setInterval', 'Date'], now: 0 });
|
|
217
|
+
const pi = createPiHarness();
|
|
218
|
+
await extension(pi as any);
|
|
219
|
+
await pi.handlers.get('session_start')({}, { ui: {
|
|
220
|
+
notify: (message: string) => notifications.push(message),
|
|
221
|
+
setStatus: (_key: string, status: string | undefined) => statuses.push(status),
|
|
222
|
+
} });
|
|
223
|
+
const broker = getBroker()!;
|
|
224
|
+
const initial = broker.probeConnectivity();
|
|
225
|
+
let connected = false;
|
|
226
|
+
t.mock.method(broker, 'probeConnectivity', () => ({ ...initial, bridgeConnected: connected }));
|
|
227
|
+
const ready = t.mock.method(broker, 'ensureReady', async () => {});
|
|
228
|
+
t.mock.timers.tick(60_000);
|
|
229
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
230
|
+
assert.equal(notifications.length, 1);
|
|
231
|
+
assert.equal(statuses.at(-1), 'browser: disconnected');
|
|
232
|
+
t.mock.timers.tick(60_000);
|
|
233
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
234
|
+
assert.equal(notifications.length, 1);
|
|
235
|
+
connected = true;
|
|
236
|
+
t.mock.timers.tick(2_000);
|
|
237
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
238
|
+
assert.equal(statuses.at(-1), 'browser: connected');
|
|
239
|
+
assert.equal(notifications.length, 1, 'recovery is silent');
|
|
240
|
+
const calls = ready.mock.callCount();
|
|
241
|
+
t.mock.timers.tick(2_000);
|
|
242
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
243
|
+
assert.ok(ready.mock.callCount() > calls, 'healthy connections are still validated');
|
|
244
|
+
await pi.handlers.get('session_shutdown')({}, {});
|
|
245
|
+
const stoppedCalls = ready.mock.callCount();
|
|
246
|
+
t.mock.timers.tick(120_000);
|
|
247
|
+
assert.equal(ready.mock.callCount(), stoppedCalls);
|
|
248
|
+
assert.equal(statuses.at(-1), undefined);
|
|
249
|
+
assert.equal(notifications.length, 1);
|
|
250
|
+
} finally {
|
|
251
|
+
await resetForTests();
|
|
252
|
+
if (originalPort === undefined) delete process.env.PI_BA_PORT;
|
|
253
|
+
else process.env.PI_BA_PORT = originalPort;
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
|
|
199
257
|
test('suspend during task-store setup still registers browser tools without acquiring a broker', async () => {
|
|
200
258
|
await resetForTests();
|
|
201
259
|
const originalPort = process.env.PI_BA_PORT;
|