@deeeed/metamask-harness 0.51.5 → 0.51.7

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/CHANGELOG.md CHANGED
@@ -1,6 +1,38 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.51.7 - 2026-09-14
4
+
5
+ ### Added
6
+
7
+ - `pr-body render <task-dir>` writes `artifacts/pr-body.md`: the worker's `artifacts/pr-description.md` with the "Validation Recipe", "Validation Logs" (and "Recipe Workflow" when `artifacts/workflow.mmd` exists) sections rendered from the task artifacts with fences that cannot break, replacing any pasted by hand. The farm publication step and the Cook evidence packaging call the same command.
8
+
9
+ ### Changed
10
+
11
+ - Extension launch focus hold polls every 80 ms instead of 20 ms, and the reopen launcher honours `MM_HARNESS_FOCUS_SETTLE_MS` like the primary launcher.
12
+
13
+ ## 0.51.6 - 2026-09-14
14
+
15
+ ### Added
16
+
17
+ - Review knowledge composition: a team library's `review/antipatterns.md`, `review/parity.md`, and `owned-paths.json` compose on top of the harness's base review; the harness never copies them.
18
+ - `review checklist [--domain <name>] [--since <sha>] [--base <ref>] [--out <file>]`: phase-structured checklist (Setup, Base review, Domain patterns, Parity, Verdict) that `checklist mark` tracks; one line per `##` section of the library's anti-patterns; the other platform's checkout named as the parity reference or "not checked" with the reason; `--since` for an incremental re-review.
19
+ A library's `review/antipatterns.<adapter>.md` adds families for that adapter only.
20
+ - `help review [--domain <name>]`: the same composition as prose; never fetches.
21
+ - `domain`: a declared `--domain` / `MM_HARNESS_DOMAIN` wins, else the changed files are matched against every reachable library's `owned-paths.json`.
22
+ - `config`: per-engineer locations outside any repo (`~/.mm-harness/config.json`): `libraries.<name>`, `references.<mobile|extension|core>`.
23
+ - Resolution order: env (`RECIPE_LIBRARY_PATH`, `MM_HARNESS_REF_<ADAPTER>`) → config → sibling directory beside the checkout → shallow fetch into `<checkout>/.skills-cache/<name>` for known libraries (excluded through the checkout's git exclude file, worktrees included).
24
+
25
+ ### Fixed
26
+
27
+ Extension fresh-launch and macOS focus fixes, first published off-main as 0.50.5 and 0.50.6 and now on main:
28
+
29
+ - Avoid disabling and re-enabling the Extension after a fresh browser launch, which could cause `No SW` storage errors in reused wallet profiles. Keep build handoff for updates in an already-running browser.
30
+ - Keep the previously focused macOS app in front while Chrome starts, instead of restoring only after CDP is up. Do not let caffeinate declare user activity during that launch.
31
+ - Keep the Extension Chrome window visible, but restore the previously focused macOS app through Launch Services while Chrome starts so the window does not come to the front or take the keyboard. System Events hangs during that activation, so osascript restore cannot hold focus.
32
+ - Reap every Chrome process that still owns the Extension profile before relaunch, and kill a macOS `open -n` browser that never exposes CDP, so repeated launches cannot stack headed Chrome instances on the same user-data-dir.
33
+ - Close extra MetaMask home tabs after an Extension browser launch. `open -n` with a start URL against a still-live profile was stacking unlock tabs.
34
+ - The macOS focus hold ends as soon as the operator brings any other app to the front, and the reopen launcher reaps a Chrome that never exposed CDP instead of leaving it behind.
35
+ - Stop every Extension Chrome whose `--user-data-dir` is under this checkout's `temp/recipe/runtime/`, including uniquely named recipe profiles and checkout paths that contain spaces. The previous allow-list of `chrome-profile`, `chrome-profile-recipe`, and `chrome-profile-pw` left leftovers that `mm-harness stop` reported as already stopped. Nested `console-tail.mjs` log paths under that runtime dir are reaped the same way. Personal Chrome and other checkouts stay untouched.
4
36
 
5
37
  ## 0.51.5 - 2026-09-14
6
38
 
package/README.md CHANGED
@@ -193,6 +193,45 @@ Teams maintain their library checkouts. Update them before starting a task;
193
193
  the harness records local revisions and recipe digests but does not fetch or
194
194
  check for upstream updates. Keep the selected library unchanged during a run.
195
195
 
196
+ ## Publish a change
197
+
198
+ ```bash
199
+ # Write artifacts/pr-description.md in the repository PR template shape (prose
200
+ # only), then render the publishable body.
201
+ mm-harness pr-body render temp/tasks/dev/TAT-1 --command 'mm-harness run artifacts/recipe.json'
202
+ ```
203
+
204
+ `pr-body render` writes `artifacts/pr-body.md`: the description with the "Validation
205
+ Recipe" and "Validation Logs" sections rendered from `artifacts/recipe.json` and
206
+ `artifacts/recipe-run/report.md` (and "Recipe Workflow" from `artifacts/workflow.mmd`
207
+ when it exists), replacing any pasted by hand. The worker never pastes artifacts
208
+ into markdown, so fences cannot break.
209
+
210
+ ## Review a change
211
+
212
+ ```bash
213
+ # Which team library owns the change (declared --domain wins, else owned-paths.json).
214
+ mm-harness domain
215
+
216
+ # The review guide: base review + the library's anti-pattern families and parity rule.
217
+ mm-harness help review --domain perps
218
+
219
+ # A checklist the mark shim can track: Setup, Base review, Domain patterns, Parity, Verdict.
220
+ mm-harness review checklist --domain perps --out temp/tasks/review/TAT-1/CHECKLIST.md
221
+ mm-harness review checklist --domain perps --since <last-reviewed-sha> # incremental re-review
222
+
223
+ # Where this machine keeps libraries and the other platform's checkout (outside any repo).
224
+ mm-harness config set references.extension ~/dev/metamask-extension
225
+ ```
226
+
227
+ A team library supplies `review/antipatterns.md` (one `##` section per family),
228
+ optional `review/antipatterns.<adapter>.md` families appended for that adapter only,
229
+ `review/parity.md`, and `owned-paths.json`; the harness composes them and never
230
+ copies them. Locations resolve env (`RECIPE_LIBRARY_PATH`, `MM_HARNESS_REF_<ADAPTER>`)
231
+ → `mm-harness config` → sibling directory beside the checkout → shallow fetch into
232
+ `<checkout>/.skills-cache/<name>`. A missing reference checkout degrades the parity
233
+ step to "not checked" with the reason.
234
+
196
235
  ## Recover
197
236
 
198
237
  ```bash
@@ -301,7 +301,8 @@ const {
301
301
  runtimeIdentityArgs,
302
302
  writeRuntimeIdentity,
303
303
  } = require(path.join('${SCRIPT_DIR}', 'lib/chrome-args.cjs'));
304
- const { captureMacFrontmostProcess, restoreMacFrontmostProcess } = require(path.join('${SCRIPT_DIR}', 'lib/macos-focus.cjs'));
304
+ const { captureMacFrontmost, macBackgroundOpenArgs, preserveMacFrontmost, startMacFocusHold, stopMacFocusHold } = require(path.join('${SCRIPT_DIR}', 'lib/macos-focus.cjs'));
305
+ const { stopProfileProcessesSync } = require(path.join('${SCRIPT_DIR}', 'lib/validation-process-ownership.cjs'));
305
306
 
306
307
  const SLOT_ID = '${SLOT_ID}';
307
308
  const AGENT_DIR = '${AGENT_DIR}';
@@ -322,6 +323,14 @@ const resumeWebpack = () => {
322
323
  if (WEBPACK_PID) { try { process.kill(-Number(WEBPACK_PID), 'SIGCONT'); } catch { try { process.kill(Number(WEBPACK_PID), 'SIGCONT'); } catch {} } }
323
324
  };
324
325
 
326
+ const previousFrontmost = captureMacFrontmost();
327
+ const chromiumApp = path.dirname(path.dirname(path.dirname(chromium.executablePath())));
328
+ let focusHold = null;
329
+ const releaseFocusHold = () => {
330
+ stopMacFocusHold(focusHold);
331
+ preserveMacFrontmost(previousFrontmost, chromiumApp);
332
+ };
333
+
325
334
  (async () => {
326
335
  const runtimeNonce = createRuntimeIdentityNonce();
327
336
  const startedAt = Date.now();
@@ -343,9 +352,8 @@ const resumeWebpack = () => {
343
352
  args.push(...remoteDebuggingArgs(CDP_PORT));
344
353
  }
345
354
 
346
- const chromiumApp = path.dirname(path.dirname(path.dirname(chromium.executablePath())));
347
- const previousFrontmostPid = captureMacFrontmostProcess();
348
- execFileSync('open', ['-g', '-n', '-a', chromiumApp, '--args', ...args], { stdio: 'ignore' });
355
+ focusHold = startMacFocusHold(previousFrontmost, chromiumApp);
356
+ execFileSync('open', macBackgroundOpenArgs(chromiumApp, args), { stdio: 'ignore' });
349
357
  for (let i = 0; i < 60; i++) {
350
358
  try {
351
359
  const version = await new Promise((resolve, reject) => {
@@ -360,7 +368,18 @@ const resumeWebpack = () => {
360
368
  } catch {}
361
369
  await new Promise(r => setTimeout(r, 1000));
362
370
  }
363
- const browser = await chromium.connectOverCDP('http://127.0.0.1:' + CDP_PORT);
371
+ let browser;
372
+ try {
373
+ browser = await chromium.connectOverCDP('http://127.0.0.1:' + CDP_PORT);
374
+ } catch (error) {
375
+ // The submitted browser never exposed CDP: reap whatever owns the profile
376
+ // so the next launch cannot stack a second Chrome on the same user-data-dir.
377
+ stopProfileProcessesSync(PROFILE, { waitForAppearanceMs: 400 });
378
+ throw new Error(
379
+ 'Reopened Chrome did not expose CDP on port ' + CDP_PORT + ': ' + (error && error.message ? error.message : String(error)) +
380
+ '. Next: inspect the slot browser process, then rerun: mm-harness launch --adapter extension --build'
381
+ );
382
+ }
364
383
  const ctx = browser.contexts()[0];
365
384
  let listenerPids;
366
385
  try {
@@ -396,6 +415,7 @@ const resumeWebpack = () => {
396
415
  } catch {}
397
416
  }
398
417
  if (!browserPid) {
418
+ stopProfileProcessesSync(PROFILE, { waitForAppearanceMs: 400 });
399
419
  throw new Error(
400
420
  'Reopened Chrome did not expose an owned CDP listener on port ' + CDP_PORT +
401
421
  '. Next: inspect the slot browser process, then rerun: mm-harness launch --adapter extension --build'
@@ -428,11 +448,12 @@ const resumeWebpack = () => {
428
448
  try {
429
449
  extId = execFileSync(RUNNER_BIN, ['resolve-extension', '--adapter', 'extension', '--target', REPO], { encoding: 'utf8' }).trim();
430
450
  } catch (err) {
451
+ releaseFocusHold();
431
452
  resumeWebpack();
432
453
  console.error('[FAIL] runner resolve-extension failed: ' + (err && err.message ? err.message : String(err)));
433
454
  process.exit(1);
434
455
  }
435
- if (!/^[a-p]{32}$/.test(extId)) { resumeWebpack(); console.error('[FAIL] runner returned invalid extension id: ' + JSON.stringify(extId)); process.exit(1); }
456
+ if (!/^[a-p]{32}$/.test(extId)) { releaseFocusHold(); resumeWebpack(); console.error('[FAIL] runner returned invalid extension id: ' + JSON.stringify(extId)); process.exit(1); }
436
457
  console.log('[reopen] Extension: ' + extId + ' (via runner resolve-extension)');
437
458
 
438
459
  // Navigate to MetaMask home
@@ -498,8 +519,12 @@ const resumeWebpack = () => {
498
519
  if (process.env.MM_HARNESS_FOCUS_BROWSER === '1') {
499
520
  await page.bringToFront().catch(() => {});
500
521
  } else {
501
- restoreMacFrontmostProcess(previousFrontmostPid);
522
+ const settleMs = Number(process.env.MM_HARNESS_FOCUS_SETTLE_MS);
523
+ const waitMs = Number.isFinite(settleMs) && settleMs >= 0 ? settleMs : 1000;
524
+ if (waitMs > 0) await new Promise(r => setTimeout(r, waitMs));
525
+ preserveMacFrontmost(previousFrontmost, chromiumApp);
502
526
  }
527
+ releaseFocusHold();
503
528
 
504
529
  fs.writeFileSync(path.join(AGENT_DIR, 'extension.id'), extId);
505
530
  console.log('[reopen] Ready \u2014 ' + SLOT_ID + (CDP_PORT ? ' CDP:' + CDP_PORT : ''));
@@ -509,6 +534,7 @@ const resumeWebpack = () => {
509
534
  if (WEBPACK_PID) console.log('[webpack] Resumed');
510
535
  process.exit(0);
511
536
  })().catch(e => {
537
+ releaseFocusHold();
512
538
  resumeWebpack();
513
539
  try { removeRuntimeIdentity(AGENT_DIR); } catch {}
514
540
  try { fs.unlinkSync(path.join(AGENT_DIR, 'browser.pid')); } catch {}
@@ -24,7 +24,7 @@ const os = require('node:os');
24
24
  const path = require('node:path');
25
25
  const { execFileSync, spawn, spawnSync } = require('node:child_process');
26
26
  const { extensionIdFromExtensionDir } = require('./lib/extension-id.cjs');
27
- const { profileProcessPids } = require('./lib/validation-process-ownership.cjs');
27
+ const { profileProcessPids, stopProfileProcessesSync } = require('./lib/validation-process-ownership.cjs');
28
28
  const { acquireBuildHandoff } = require('./build-handoff.cjs');
29
29
  const {
30
30
  automationRuntimeArgs,
@@ -42,7 +42,13 @@ const {
42
42
  validationLaunchQuarantineError,
43
43
  writeRuntimeIdentity,
44
44
  } = require('./lib/chrome-args.cjs');
45
- const { captureMacFrontmostProcess, restoreMacFrontmostProcess } = require('./lib/macos-focus.cjs');
45
+ const {
46
+ captureMacFrontmost,
47
+ macBackgroundOpenArgs,
48
+ preserveMacFrontmost,
49
+ startMacFocusHold,
50
+ stopMacFocusHold,
51
+ } = require('./lib/macos-focus.cjs');
46
52
 
47
53
  if (process.argv.includes('--help') || process.argv.includes('-h')) {
48
54
  console.log(
@@ -107,7 +113,7 @@ try {
107
113
  'Next: remove the invalid runtime identity and fix owner permissions, then rerun: mm-harness launch --adapter extension --build',
108
114
  );
109
115
  }
110
- terminatePids([...ownedPids]);
116
+ stopProfileProcessesSync(args.profile, { extraPids: [...ownedPids] });
111
117
  if (args['reset-profile'] !== undefined) {
112
118
  fs.rmSync(args.profile, { recursive: true, force: true });
113
119
  fs.mkdirSync(args.profile, { recursive: true });
@@ -164,70 +170,85 @@ const chromeArgs = [
164
170
  initialUrl,
165
171
  ];
166
172
  const logFd = fs.openSync(args['chrome-log'], 'a');
167
- const previousFrontmostPid = captureMacFrontmostProcess();
173
+ const previousFrontmost = captureMacFrontmost();
174
+ const application = process.platform === 'darwin' ? macApplicationForExecutable(args['chrome-bin']) : null;
175
+ const focusHold = startMacFocusHold(previousFrontmost, application);
168
176
  let browserPid;
169
177
  try {
170
- const application = process.platform === 'darwin' ? macApplicationForExecutable(args['chrome-bin']) : null;
171
- if (application) {
172
- beginDetachedLaunch(cdpPort, args.profile, activeValidationLease);
173
- execFileSync('open', ['-g', '-n', '-a', application, '--args', ...chromeArgs], {
174
- env: sanitizedChildEnv(),
175
- stdio: ['ignore', logFd, logFd],
178
+ try {
179
+ if (application) {
180
+ beginDetachedLaunch(cdpPort, args.profile, activeValidationLease);
181
+ execFileSync('open', macBackgroundOpenArgs(application, chromeArgs), {
182
+ env: sanitizedChildEnv(),
183
+ stdio: ['ignore', logFd, logFd],
184
+ });
185
+ browserPid = waitForOwnedCdpPid(cdpPort, args.profile, args['extension-dir']);
186
+ if (browserPid === null) {
187
+ stopProfileProcessesSync(args.profile, { waitForAppearanceMs: 400 });
188
+ throw new Error(
189
+ `Chrome launched but did not expose an owned CDP listener on 127.0.0.1:${cdpPort}. ` +
190
+ `Next: inspect ${args['chrome-log']}, then rerun: mm-harness launch --adapter extension --build`,
191
+ );
192
+ }
193
+ } else {
194
+ beginDetachedLaunch(cdpPort, args.profile, activeValidationLease);
195
+ const child = spawn(args['chrome-bin'], chromeArgs, {
196
+ detached: true,
197
+ env: sanitizedChildEnv(),
198
+ stdio: ['ignore', logFd, logFd],
199
+ });
200
+ child.unref();
201
+ browserPid = waitForOwnedCdpPid(cdpPort, args.profile, args['extension-dir']);
202
+ if (browserPid === null) {
203
+ stopProfileProcessesSync(args.profile, { extraPids: child.pid ? [child.pid] : [] });
204
+ throw new Error(
205
+ `Chrome launched but did not expose an owned CDP listener on 127.0.0.1:${cdpPort}. ` +
206
+ `Next: inspect ${args['chrome-log']}, then rerun: mm-harness launch --adapter extension --build`,
207
+ );
208
+ }
209
+ }
210
+ for (const problem of pruneExtraHomeTabs(cdpPort, args['extension-dir'])) {
211
+ process.stderr.write(`[launch] home-tab pruning: ${problem}\n`);
212
+ }
213
+ } finally {
214
+ fs.closeSync(logFd);
215
+ }
216
+ fs.writeFileSync(args['chrome-pid'], `${browserPid}\n`);
217
+ try {
218
+ writeRuntimeIdentity(runtimeDir, {
219
+ port: cdpPort,
220
+ pid: browserPid,
221
+ startedAt,
222
+ nonce: runtimeNonce,
176
223
  });
177
- browserPid = waitForOwnedCdpPid(cdpPort, args.profile, args['extension-dir']);
178
- if (browserPid === null) {
179
- throw new Error(`Chrome launched but did not expose CDP on 127.0.0.1:${cdpPort}`);
224
+ clearDetachedLaunchUnproven(args.profile);
225
+ if (!activeValidationLease) {
226
+ clearValidationPortQuarantine(cdpPort, args.profile);
180
227
  }
181
- } else {
182
- beginDetachedLaunch(cdpPort, args.profile, activeValidationLease);
183
- const child = spawn(args['chrome-bin'], chromeArgs, {
228
+ } catch (error) {
229
+ terminatePids([browserPid]);
230
+ fs.rmSync(args['chrome-pid'], { force: true });
231
+ const detail = error instanceof Error ? error.message : String(error);
232
+ throw new Error(
233
+ `Failed to persist Extension runtime identity under ${runtimeDir}: ${detail}. ` +
234
+ 'Next: fix owner write permissions for the runtime directory, then rerun: mm-harness launch --adapter extension --build',
235
+ );
236
+ }
237
+ if (process.platform === 'darwin') {
238
+ const wake = spawn('caffeinate', ['-dims', '-w', String(browserPid)], {
184
239
  detached: true,
185
- env: sanitizedChildEnv(),
186
- stdio: ['ignore', logFd, logFd],
240
+ stdio: 'ignore',
187
241
  });
188
- child.unref();
189
- browserPid = waitForOwnedCdpPid(cdpPort, args.profile, args['extension-dir']);
190
- if (browserPid === null) {
191
- if (child.pid) terminatePids([child.pid]);
192
- throw new Error(
193
- `Chrome launched but did not expose an owned CDP listener on 127.0.0.1:${cdpPort}. ` +
194
- `Next: inspect ${args['chrome-log']}, then rerun: mm-harness launch --adapter extension --build`,
195
- );
196
- }
242
+ wake.unref();
243
+ // Chrome often activates when the first window paints, which can be after CDP
244
+ // is already listening. Keep the previous app frontmost through that paint.
245
+ const settleMs = Number(process.env.MM_HARNESS_FOCUS_SETTLE_MS);
246
+ const waitSec = Number.isFinite(settleMs) && settleMs >= 0 ? settleMs / 1000 : 1;
247
+ if (waitSec > 0) spawnSync('sleep', [String(waitSec)]);
197
248
  }
198
249
  } finally {
199
- fs.closeSync(logFd);
200
- }
201
- fs.writeFileSync(args['chrome-pid'], `${browserPid}\n`);
202
- try {
203
- writeRuntimeIdentity(runtimeDir, {
204
- port: cdpPort,
205
- pid: browserPid,
206
- startedAt,
207
- nonce: runtimeNonce,
208
- });
209
- clearDetachedLaunchUnproven(args.profile);
210
- if (!activeValidationLease) {
211
- clearValidationPortQuarantine(cdpPort, args.profile);
212
- }
213
- } catch (error) {
214
- terminatePids([browserPid]);
215
- fs.rmSync(args['chrome-pid'], { force: true });
216
- const detail = error instanceof Error ? error.message : String(error);
217
- throw new Error(
218
- `Failed to persist Extension runtime identity under ${runtimeDir}: ${detail}. ` +
219
- 'Next: fix owner write permissions for the runtime directory, then rerun: mm-harness launch --adapter extension --build',
220
- );
221
- }
222
- if (process.platform === 'darwin') {
223
- const wake = spawn('caffeinate', ['-dimsu', '-w', String(browserPid)], {
224
- detached: true,
225
- stdio: 'ignore',
226
- });
227
- wake.unref();
228
- }
229
- if (process.env.MM_HARNESS_FOCUS_BROWSER !== '1') {
230
- restoreMacFrontmostProcess(previousFrontmostPid);
250
+ stopMacFocusHold(focusHold);
251
+ preserveMacFrontmost(previousFrontmost, application);
231
252
  }
232
253
 
233
254
  function sanitizedChildEnv() {
@@ -387,11 +408,11 @@ function cdpListenerPids(port) {
387
408
  function terminatePids(pids) {
388
409
  const unique = [...new Set(pids)].filter((pid) => pid !== process.pid);
389
410
  for (const pid of unique) signalPid(pid, 'SIGTERM');
390
- for (let i = 0; i < 10 && unique.some(pidAlive); i += 1) {
411
+ for (let i = 0; i < 10 && unique.some(processRespondsToSignal); i += 1) {
391
412
  spawnSync('sleep', ['0.2']);
392
413
  }
393
414
  for (const pid of unique) {
394
- if (pidAlive(pid)) signalPid(pid, 'SIGKILL');
415
+ if (processRespondsToSignal(pid)) signalPid(pid, 'SIGKILL');
395
416
  }
396
417
  }
397
418
 
@@ -405,7 +426,7 @@ function signalPid(pid, signal) {
405
426
  }
406
427
  }
407
428
 
408
- function pidAlive(pid) {
429
+ function processRespondsToSignal(pid) {
409
430
  try {
410
431
  process.kill(pid, 0);
411
432
  return true;
@@ -426,3 +447,77 @@ function extensionHomeUrl(extensionDir) {
426
447
  const id = extensionIdFromExtensionDir(extensionDir);
427
448
  return id ? `chrome-extension://${id}/home.html` : '';
428
449
  }
450
+
451
+ function cdpHttp(port, pathname) {
452
+ const result = spawnSync(process.execPath, ['-e', `
453
+ const http = require('http');
454
+ http.get('http://127.0.0.1:${Number(port)}${pathname}', (res) => {
455
+ let body = '';
456
+ res.on('data', (chunk) => { body += chunk; });
457
+ res.on('end', () => {
458
+ process.stdout.write(body);
459
+ process.exitCode = res.statusCode === 200 ? 0 : 1;
460
+ });
461
+ }).on('error', () => process.exit(1));
462
+ `], { encoding: 'utf8', timeout: 4000 });
463
+ if (result.status !== 0) return null;
464
+ return result.stdout;
465
+ }
466
+
467
+ // Best effort by design: CDP ownership is already proven and ensure-ready
468
+ // converges home tabs again during verify, so a pruning failure must not fail
469
+ // the launch. Every failure is returned so the launch log says why a duplicate
470
+ // tab survived instead of hiding it.
471
+ function pruneExtraHomeTabs(port, extensionDir) {
472
+ const id = extensionIdFromExtensionDir(extensionDir);
473
+ if (!id) return ['extension id unavailable; skipped'];
474
+ const raw = cdpHttp(port, '/json/list');
475
+ if (raw === null) return [`GET http://127.0.0.1:${port}/json/list failed`];
476
+ let targets;
477
+ try {
478
+ targets = JSON.parse(raw);
479
+ } catch (error) {
480
+ return [`/json/list returned malformed JSON: ${error.message}`];
481
+ }
482
+ if (!Array.isArray(targets)) return ['/json/list did not return a target list'];
483
+ const problems = [];
484
+ const close = (target) => {
485
+ if (cdpHttp(port, `/json/close/${target.id}`) === null) problems.push(`could not close ${target.url} (${target.id})`);
486
+ };
487
+ const homes = targets.filter((target) => (
488
+ target &&
489
+ target.type === 'page' &&
490
+ typeof target.id === 'string' &&
491
+ typeof target.url === 'string' &&
492
+ target.url.includes(`chrome-extension://${id}/`) &&
493
+ target.url.includes('/home.html')
494
+ ));
495
+ const strays = targets.filter((target) => (
496
+ target &&
497
+ target.type === 'page' &&
498
+ typeof target.id === 'string' &&
499
+ typeof target.url === 'string' &&
500
+ (
501
+ target.url === 'about:blank' ||
502
+ target.url === 'chrome://newtab/' ||
503
+ target.url.startsWith('chrome://new-tab-page')
504
+ )
505
+ ));
506
+ if (homes.length === 0) return problems;
507
+ const keeper = homes.find((target) => (
508
+ typeof target.title === 'string' &&
509
+ target.title.trim() !== '' &&
510
+ target.title.trim() !== 'MetaMask'
511
+ )) ?? homes[0];
512
+ if (homes.length > 1) {
513
+ for (const extra of homes) {
514
+ if (keeper && extra.id === keeper.id) continue;
515
+ close(extra);
516
+ }
517
+ }
518
+ for (const stray of strays) {
519
+ if (keeper && stray.id === keeper.id) continue;
520
+ close(stray);
521
+ }
522
+ return problems;
523
+ }