glidercli 0.4.0 → 0.4.3

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.
Files changed (3) hide show
  1. package/README.md +1 -0
  2. package/bin/glider.js +199 -25
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -172,6 +172,7 @@ Copy `config/domains.template.json` into `~/.glider/config/domains.json` to seed
172
172
  | `glider connect` | attach relay to browser |
173
173
  | `glider status` | server, extension, tabs |
174
174
  | `glider goto` / `eval` / `click` / `type` | page ops |
175
+ | `glider frozen` / `thaw` | detect / un-throttle a hidden (macrotask-frozen) tab in place |
175
176
  | `glider screenshot` | PNG capture |
176
177
  | `glider explore` | crawl + HAR |
177
178
  | `glider resolve` | host → local warch intel (`--json`) |
package/bin/glider.js CHANGED
@@ -1546,6 +1546,83 @@ async function cmdFrozen(opts = []) {
1546
1546
  }
1547
1547
  }
1548
1548
 
1549
+ // Thaw a macrotask-frozen tab WITHOUT touching the OS window.
1550
+ //
1551
+ // Chrome throttles/pauses macrotasks (setTimeout, fetch, XHR, workers, and MSAL
1552
+ // token refresh) on any tab whose window is minimized or fully occluded --
1553
+ // document.visibilityState reports 'hidden' and `glider frozen` exits 1. Neither
1554
+ // Page.bringToFront nor Target.activateTarget un-hide a minimized window, so the
1555
+ // tab stays frozen. Emulation.setFocusEmulationEnabled + Page.setWebLifecycleState
1556
+ // ('active') flip the renderer to a focused/active lifecycle state and un-throttle
1557
+ // it in place -- async fires again within a couple hundred ms, no window restore
1558
+ // needed. Reverse of `glider frozen` (which only detects). Idempotent.
1559
+ async function cmdThaw(opts = []) {
1560
+ let sessionId = null;
1561
+ let all = false;
1562
+ let verify = false;
1563
+ for (let i = 0; i < opts.length; i++) {
1564
+ const a = opts[i];
1565
+ if (a === '--session' || a === '--sessionId') sessionId = opts[++i];
1566
+ else if (a === '--all') all = true;
1567
+ else if (a === '--verify') verify = true;
1568
+ else if (a === '--help') {
1569
+ console.log('Usage: glider thaw [--session <id>] [--all] [--verify]');
1570
+ console.log(' Un-throttle a macrotask-frozen (hidden/minimized) tab in place so');
1571
+ console.log(' setTimeout/fetch/XHR/workers + token refresh resume -- no window restore.');
1572
+ console.log(' --all thaw every attached tab');
1573
+ console.log(' --verify re-check visibility + async liveness after thawing');
1574
+ console.log(' Reverse of `glider frozen` (detect). Idempotent.');
1575
+ return;
1576
+ }
1577
+ }
1578
+ if (!await ensureConnected()) process.exit(1);
1579
+
1580
+ let sessions;
1581
+ if (all) {
1582
+ const raw = await httpGet('/targets');
1583
+ sessions = (Array.isArray(raw) ? raw : []).map((t) => t.sessionId).filter(Boolean);
1584
+ if (!sessions.length) { log.warn('No targets to thaw'); return; }
1585
+ } else {
1586
+ sessions = [sessionId || activeSessionId || null];
1587
+ }
1588
+
1589
+ const results = [];
1590
+ for (const sid of sessions) {
1591
+ const p1 = { method: 'Emulation.setFocusEmulationEnabled', params: { enabled: true } };
1592
+ const p2 = { method: 'Page.setWebLifecycleState', params: { state: 'active' } };
1593
+ if (sid) { p1.sessionId = sid; p2.sessionId = sid; }
1594
+ try {
1595
+ await httpPost('/cdp', p1);
1596
+ await httpPost('/cdp', p2);
1597
+ const entry = { sessionId: sid || activeSessionId || '(pinned)', thawed: true };
1598
+ if (verify) {
1599
+ const vp = { method: 'Runtime.evaluate', params: { expression: `document.visibilityState`, returnByValue: true } };
1600
+ if (sid) vp.sessionId = sid;
1601
+ const vr = await httpPost('/cdp', vp);
1602
+ entry.visibilityState = vr?.result?.value;
1603
+ const ap = { method: 'Runtime.evaluate', params: { expression: `new Promise(r=>setTimeout(()=>r('ALIVE'),250))`, returnByValue: true, awaitPromise: true } };
1604
+ if (sid) ap.sessionId = sid;
1605
+ const ar = await httpPost('/cdp', ap);
1606
+ entry.asyncAlive = ar?.result?.value === 'ALIVE';
1607
+ }
1608
+ results.push(entry);
1609
+ } catch (e) {
1610
+ results.push({ sessionId: sid || '(pinned)', thawed: false, error: e.message });
1611
+ }
1612
+ }
1613
+
1614
+ if (jsonOutput) {
1615
+ emitJson(true, all ? { thawed: results } : results[0]);
1616
+ } else {
1617
+ for (const r of results) {
1618
+ if (!r.thawed) { log.fail(`thaw failed (${r.sessionId}): ${r.error}`); continue; }
1619
+ let extra = '';
1620
+ if (verify) extra = ` - visibilityState=${r.visibilityState} asyncAlive=${r.asyncAlive}`;
1621
+ log.ok(`thawed ${r.sessionId}${extra}`);
1622
+ }
1623
+ }
1624
+ }
1625
+
1549
1626
  // List cookies for a URL (including HttpOnly) via extension chrome.cookies.getAll bridge.
1550
1627
  // Primitive: extension_ws_bridge (background.js exposes method:'getCookies').
1551
1628
  // Note: this reads via the CRX cookies API - HttpOnly cookies (ESTSAUTH, s.SessID etc.)
@@ -1939,14 +2016,18 @@ async function cmdExplore(url, opts = []) {
1939
2016
  let outputDir = '/tmp/glider-explore';
1940
2017
  let harFile = null;
1941
2018
  let sessionId = null;
2019
+ let freshTab = false;
2020
+ let closeOnDone = false;
1942
2021
 
1943
2022
  for (let i = 0; i < opts.length; i++) {
1944
2023
  if (opts[i] === '--depth' || opts[i] === '-d') depth = parseInt(opts[++i], 10);
1945
2024
  else if (opts[i] === '--output' || opts[i] === '-o') outputDir = opts[++i];
1946
2025
  else if (opts[i] === '--har') harFile = opts[++i];
1947
2026
  else if (opts[i] === '--session-id' || opts[i] === '--session') sessionId = opts[++i];
2027
+ else if (opts[i] === '--fresh-tab') freshTab = true;
2028
+ else if (opts[i] === '--close-on-done') closeOnDone = true;
1948
2029
  }
1949
- if (!sessionId && activeSessionId) sessionId = activeSessionId;
2030
+ if (!sessionId && !freshTab && activeSessionId) sessionId = activeSessionId;
1950
2031
 
1951
2032
  try {
1952
2033
  assertUrlAllowed(url, allowedDomainList, 'explore');
@@ -1956,6 +2037,29 @@ async function cmdExplore(url, opts = []) {
1956
2037
  process.exit(1);
1957
2038
  }
1958
2039
 
2040
+ // v0.4.2: --fresh-tab sidesteps H4 (CSS.enable forwardCDPCommand timeout
2041
+ // on long-lived session reuse). Opens a new tab, waits for target attach,
2042
+ // uses the new session-id, and optionally closes on done.
2043
+ let freshTargetId = null;
2044
+ if (freshTab) {
2045
+ const { WindowManager } = require(path.join(LIB_DIR, 'bwindow.js'));
2046
+ const wm = new WindowManager();
2047
+ await wm.connect();
2048
+ await wm.init();
2049
+ log.info(`[explore] Opening fresh tab for capture...`);
2050
+ const result = await wm.createTab(url);
2051
+ freshTargetId = result.targetId;
2052
+ await new Promise(r => setTimeout(r, 2500));
2053
+ try {
2054
+ const targetsRes = await httpGet('/targets');
2055
+ const targets = (targetsRes && targetsRes.targets) || targetsRes || [];
2056
+ const t = (Array.isArray(targets) ? targets : []).find(x => x.targetId === freshTargetId);
2057
+ if (t && t.sessionId) sessionId = t.sessionId;
2058
+ } catch {}
2059
+ if (!sessionId) log.info('[explore] fresh-tab created but sessionId not resolved (bexplore will auto-pin)');
2060
+ else log.ok(`[explore] fresh-tab session: ${sessionId}`);
2061
+ }
2062
+
1959
2063
  log.info(`Exploring: ${url} (depth: ${depth})`);
1960
2064
 
1961
2065
  // Use the bexplore.js library
@@ -1969,9 +2073,24 @@ async function cmdExplore(url, opts = []) {
1969
2073
  const child = spawn('node', spawnArgs, {
1970
2074
  stdio: 'inherit'
1971
2075
  });
1972
- await new Promise((resolve, reject) => {
1973
- child.on('close', code => code === 0 ? resolve() : reject(new Error(`Exit code: ${code}`)));
1974
- });
2076
+ try {
2077
+ await new Promise((resolve, reject) => {
2078
+ child.on('close', code => code === 0 ? resolve() : reject(new Error(`Exit code: ${code}`)));
2079
+ });
2080
+ } finally {
2081
+ if (freshTab && closeOnDone && freshTargetId) {
2082
+ try {
2083
+ const { WindowManager } = require(path.join(LIB_DIR, 'bwindow.js'));
2084
+ const wm = new WindowManager();
2085
+ await wm.connect();
2086
+ await wm.init();
2087
+ await wm.closeTarget(freshTargetId);
2088
+ log.ok(`[explore] fresh-tab closed: ${freshTargetId}`);
2089
+ } catch (e) {
2090
+ log.info(`[explore] fresh-tab close failed: ${e.message}`);
2091
+ }
2092
+ }
2093
+ }
1975
2094
  } else {
1976
2095
  // Fallback: simple exploration
1977
2096
  await cmdGoto(url);
@@ -2441,7 +2560,8 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
2441
2560
  console.log(` ${GREEN}${'pdf'.padEnd(16)}${NC} ${DIM}[PATH] [--landscape] [--margin N] [--scale F]${NC}`);
2442
2561
  console.log(` ${GREEN}${'mock'.padEnd(16)}${NC} ${DIM}<url-glob> --status N --body FILE | mock clear${NC}`);
2443
2562
  console.log(` ${GREEN}${'a11y'.padEnd(16)}${NC} ${DIM}Accessibility.getFullAXTree (snapshot --a11y flag equivalent)${NC}`);
2444
- console.log(` ${GREEN}${'frozen'.padEnd(16)}${NC} ${DIM}freeze/restore page state${NC}`);
2563
+ console.log(` ${GREEN}${'frozen'.padEnd(16)}${NC} ${DIM}detect if tab is macrotask-frozen (hidden); exit 1 = frozen${NC}`);
2564
+ console.log(` ${GREEN}${'thaw'.padEnd(16)}${NC} ${DIM}un-throttle a frozen/hidden tab in place (--all --verify); aka unfreeze/wake${NC}`);
2445
2565
  console.log('');
2446
2566
  }
2447
2567
 
@@ -3447,33 +3567,82 @@ async function cmdUpload(argv) {
3447
3567
  } catch (e) { log.fail(`upload failed: ${e.message}`); process.exit(1); }
3448
3568
  }
3449
3569
 
3450
- // --- WAVE 3: cmdHar (start/stop/dump/replay) ---
3451
- let HAR_BUFFER = null;
3570
+ // --- WAVE 3: cmdHar (start/stop/dump/status) ---
3571
+ // v0.4.1: rewired to bexplore subprocess (was Potemkin stub - help advertised
3572
+ // the verb but dump always returned 0 entries; "server-side subscription
3573
+ // not implemented"). Now delegates to the same code path `explore --har` uses.
3452
3574
  async function cmdHar(argv) {
3453
3575
  const sub = argv[0];
3454
- await _guardAndConnect('har');
3455
- const HAR_STATE = path.join(os.homedir(), '.glider', 'har-buffer.json');
3576
+ const STATE_PATH = path.join(os.homedir(), '.glider', 'har-state.json');
3577
+ const BUF_HAR = path.join(os.homedir(), '.glider', 'har-buffer.har');
3578
+ const BUF_OUT = path.join(os.homedir(), '.glider', 'har-buffer-out');
3579
+ const readState = () => { try { return JSON.parse(fs.readFileSync(STATE_PATH, 'utf8')); } catch { return null; } };
3580
+ const writeState = (st) => { try { fs.mkdirSync(path.dirname(STATE_PATH), { recursive: true }); } catch {} fs.writeFileSync(STATE_PATH, JSON.stringify(st, null, 2)); };
3581
+ const pidAlive = (pid) => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch { return false; } };
3582
+
3456
3583
  if (sub === 'start') {
3457
- await httpPost('/cdp', { method: 'Network.enable', params: {} });
3458
- HAR_BUFFER = { started: new Date().toISOString(), entries: [] };
3459
- try { fs.mkdirSync(path.dirname(HAR_STATE), { recursive: true }); } catch {}
3460
- fs.writeFileSync(HAR_STATE, JSON.stringify(HAR_BUFFER));
3461
- // Note: full HAR requires event subscription (persistent server); here we mark state; user can dump devtools separately if needed.
3462
- if (jsonOutput) emitJson(true, { started: true, state_file: HAR_STATE });
3463
- else log.ok(`HAR capture started; state at ${HAR_STATE} (server-side subscription not implemented - stub)`);
3584
+ const url = argv[1];
3585
+ if (!url) { log.fail('Usage: glider har start <url> [--session-id id]'); process.exit(1); }
3586
+ const existing = readState();
3587
+ if (existing && pidAlive(existing.pid)) {
3588
+ log.fail(`HAR capture already running (pid=${existing.pid}, url=${existing.url}). Run 'glider har stop' first.`);
3589
+ process.exit(1);
3590
+ }
3591
+ let sessionId = null;
3592
+ for (let i = 2; i < argv.length; i++) {
3593
+ if (argv[i] === '--session-id' || argv[i] === '--session') sessionId = argv[++i];
3594
+ }
3595
+ if (!sessionId && activeSessionId) sessionId = activeSessionId;
3596
+ await _guardAndConnect('har');
3597
+ try { fs.mkdirSync(BUF_OUT, { recursive: true }); } catch {}
3598
+ try { fs.unlinkSync(BUF_HAR); } catch {}
3599
+ const bexplorePath = path.join(LIB_DIR, 'bexplore.js');
3600
+ const spawnArgs = [bexplorePath, url, '--depth', '0', '--output', BUF_OUT, '--har', BUF_HAR];
3601
+ if (sessionId) spawnArgs.push('--session-id', sessionId);
3602
+ const child = spawn('node', spawnArgs, { detached: true, stdio: ['ignore', 'ignore', 'ignore'] });
3603
+ child.unref();
3604
+ const state = { pid: child.pid, har: BUF_HAR, url, session_id: sessionId, started_at: new Date().toISOString() };
3605
+ writeState(state);
3606
+ if (jsonOutput) emitJson(true, state);
3607
+ else log.ok(`HAR capture started (pid=${child.pid}, url=${url}); dump with 'glider har dump [path]'`);
3464
3608
  } else if (sub === 'stop') {
3465
- await httpPost('/cdp', { method: 'Network.disable', params: {} });
3466
- if (jsonOutput) emitJson(true, { stopped: true });
3467
- else log.ok('HAR capture stopped');
3609
+ const st = readState();
3610
+ if (!st) { log.fail('No HAR capture in progress'); process.exit(1); }
3611
+ if (pidAlive(st.pid)) { try { process.kill(st.pid, 'SIGTERM'); } catch {} }
3612
+ try { fs.unlinkSync(STATE_PATH); } catch {}
3613
+ if (jsonOutput) emitJson(true, { stopped: true, pid: st.pid });
3614
+ else log.ok(`HAR capture stopped (pid=${st.pid})`);
3468
3615
  } else if (sub === 'dump') {
3469
3616
  const p = argv[1] || `/tmp/glider-${Date.now()}.har`;
3470
- let buf; try { buf = JSON.parse(fs.readFileSync(HAR_STATE, 'utf8')); } catch { buf = { entries: [] }; }
3471
- const har = { log: { version: '1.2', creator: { name: 'glider', version: require('../package.json').version }, entries: buf.entries } };
3472
- fs.writeFileSync(p, JSON.stringify(har, null, 2));
3473
- if (jsonOutput) emitJson(true, { path: p, entries: buf.entries.length });
3474
- else log.ok(`HAR dumped to ${p} (${buf.entries.length} entries - event stream not yet wired)`);
3617
+ const st = readState();
3618
+ if (!st) { log.fail('No HAR capture in progress. Run: glider har start <url>'); process.exit(1); }
3619
+ const timeoutMs = 60000;
3620
+ const started = Date.now();
3621
+ while (pidAlive(st.pid) && (Date.now() - started) < timeoutMs) {
3622
+ await new Promise(r => setTimeout(r, 500));
3623
+ }
3624
+ if (pidAlive(st.pid)) {
3625
+ log.fail(`HAR child still running after ${timeoutMs}ms; run 'glider har stop' or wait`);
3626
+ process.exit(1);
3627
+ }
3628
+ if (!fs.existsSync(st.har)) {
3629
+ log.fail(`HAR buffer not found at ${st.har} (capture may have failed)`);
3630
+ process.exit(1);
3631
+ }
3632
+ fs.copyFileSync(st.har, p);
3633
+ let entryCount = 0;
3634
+ try { entryCount = JSON.parse(fs.readFileSync(p, 'utf8')).log.entries.length; } catch {}
3635
+ try { fs.unlinkSync(STATE_PATH); } catch {}
3636
+ if (jsonOutput) emitJson(true, { path: p, entries: entryCount });
3637
+ else log.ok(`HAR dumped to ${p} (${entryCount} entries)`);
3638
+ } else if (sub === 'status') {
3639
+ const st = readState();
3640
+ if (!st) { if (jsonOutput) emitJson(true, { running: false }); else console.log('idle'); return; }
3641
+ const alive = pidAlive(st.pid);
3642
+ if (jsonOutput) emitJson(true, { running: alive, ...st });
3643
+ else console.log(`${alive ? 'RUNNING' : 'DONE'} pid=${st.pid} url=${st.url} started=${st.started_at}`);
3475
3644
  } else {
3476
- log.fail('Usage: glider har start | stop | dump [PATH] | replay <entry-id>'); process.exit(1);
3645
+ log.fail('Usage: glider har start <url> [--session-id id] | stop | dump [PATH] | status'); process.exit(1);
3477
3646
  }
3478
3647
  }
3479
3648
 
@@ -3872,6 +4041,11 @@ async function main() {
3872
4041
  case 'frozen':
3873
4042
  await cmdFrozen(args.slice(1));
3874
4043
  break;
4044
+ case 'thaw':
4045
+ case 'unfreeze':
4046
+ case 'wake':
4047
+ await cmdThaw(args.slice(1));
4048
+ break;
3875
4049
  case 'cookies':
3876
4050
  if (args.slice(1).some(a => a === '--set' || a === '--delete')) {
3877
4051
  await cmdCookieWrite(args.slice(1));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glidercli",
3
- "version": "0.4.0",
3
+ "version": "0.4.3",
4
4
  "description": "Browser automation CLI. Control Chrome from terminal via CDP, run YAML task files, autonomous loops until completion.",
5
5
  "main": "index.js",
6
6
  "bin": {