@opencode/browse 0.0.17-dev.170 → 0.0.17-dev.172

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 (27) hide show
  1. package/dist/{cli-k6tgme5c.mjs → cli-bgsndmk3.mjs} +12 -12
  2. package/dist/cli.mjs +12 -12
  3. package/dist/{helpers-g8dsh6s5.mjs → helpers-58105m1j.mjs} +1 -1
  4. package/dist/{legacy-runtime-jj1srsz7.mjs → legacy-runtime-897mfrrg.mjs} +4 -4
  5. package/dist/{main-e17wqzky.mjs → main-1k2c2ysm.mjs} +2 -2
  6. package/dist/{main-apebcva2.mjs → main-8nvvaw37.mjs} +3 -3
  7. package/dist/{main-16tqhq5g.mjs → main-a7ym6xse.mjs} +1 -1
  8. package/dist/main-ezvw6bdp.mjs +4 -0
  9. package/dist/{main-43k95nh0.mjs → main-fezz88pf.mjs} +1 -1
  10. package/dist/{main-99dxg777.mjs → main-pc6r231b.mjs} +2 -2
  11. package/dist/{main-32h1fmkw.mjs → main-pp3m0bqv.mjs} +3 -3
  12. package/dist/{main-8k9qykpa.mjs → main-swjwyj9k.mjs} +1 -1
  13. package/dist/{main-3g0xky5y.mjs → main-ytaan398.mjs} +2 -2
  14. package/dist/{main-0tr21dqs.mjs → main-z2s3g2jd.mjs} +3 -3
  15. package/dist/{main-63xjd6ts.mjs → main-zc7snhsf.mjs} +2 -2
  16. package/dist/{mcp-85av73hq.mjs → mcp-0et3j7sb.mjs} +7 -7
  17. package/dist/{migrate-1vqatsz2.mjs → migrate-fknwf3s1.mjs} +4 -4
  18. package/dist/{relay-xkw8xs4k.mjs → relay-ebsaj9bt.mjs} +414 -57
  19. package/dist/{runtime-update-ny5cgrba.mjs → runtime-update-z51y0yav.mjs} +4 -4
  20. package/dist/{setup-18revp9m.mjs → setup-z4ezv7ht.mjs} +7 -7
  21. package/dist/{skill-text-z1pce87x.mjs → skill-text-q7e8fafn.mjs} +18 -3
  22. package/dist/{supervisor-93fvdjav.mjs → supervisor-h2gzmqar.mjs} +3 -3
  23. package/dist/{update-y6xqxqww.mjs → update-sb64ka4c.mjs} +3 -3
  24. package/dist/{version-ngzs1vvq.mjs → version-c4p8fkj3.mjs} +1 -1
  25. package/package.json +1 -1
  26. package/skills/browse/SKILL.md +18 -3
  27. package/dist/main-dsx1pjp8.mjs +0 -4
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  opencodeBrowserVersion2,
6
6
  opencodeBrowserBuildId2
7
- } from "./main-dsx1pjp8.mjs";
7
+ } from "./main-ezvw6bdp.mjs";
8
8
  import {
9
9
  defaultRoots,
10
10
  configRoot2,
@@ -28,7 +28,7 @@ import {
28
28
  setStoredMode,
29
29
  autoUpdateStatus,
30
30
  createAutoUpdater
31
- } from "./main-apebcva2.mjs";
31
+ } from "./main-8nvvaw37.mjs";
32
32
  import {
33
33
  extensionProtocolVersion,
34
34
  minExtensionProtocolVersion,
@@ -108,7 +108,7 @@ import {
108
108
  dataUrlDocument2,
109
109
  appendManagedRelayProcessLog,
110
110
  relayLog
111
- } from "./main-0tr21dqs.mjs";
111
+ } from "./main-z2s3g2jd.mjs";
112
112
  import {
113
113
  context,
114
114
  pendingPairingCodeKeys,
@@ -126,7 +126,7 @@ import {
126
126
  pairingSessionKey,
127
127
  sessionProof,
128
128
  wrapToken
129
- } from "./main-43k95nh0.mjs";
129
+ } from "./main-fezz88pf.mjs";
130
130
  import {
131
131
  makeUnsafe,
132
132
  terminateChildProcess,
@@ -149,16 +149,16 @@ import {
149
149
  checkNavigationUrl,
150
150
  readSecret,
151
151
  secretText
152
- } from "./main-8k9qykpa.mjs";
152
+ } from "./main-swjwyj9k.mjs";
153
153
  import {
154
154
  defaultJournalBaseDir,
155
155
  makeJournalEntry,
156
156
  appendJournalEntry,
157
157
  startJournalRetention
158
- } from "./main-99dxg777.mjs";
158
+ } from "./main-pc6r231b.mjs";
159
159
  import {
160
160
  createUpdateWatcher2
161
- } from "./main-e17wqzky.mjs";
161
+ } from "./main-1k2c2ysm.mjs";
162
162
  import {
163
163
  SettingsInputError,
164
164
  parseSettingChanges,
@@ -166,13 +166,13 @@ import {
166
166
  settingsToExtension,
167
167
  describeSettings,
168
168
  describeChanges
169
- } from "./main-3g0xky5y.mjs";
169
+ } from "./main-ytaan398.mjs";
170
170
  import {
171
171
  relayHostname,
172
172
  isLocalPeer,
173
173
  installedDevExtension,
174
174
  syncDevExtension
175
- } from "./main-63xjd6ts.mjs";
175
+ } from "./main-zc7snhsf.mjs";
176
176
  import {
177
177
  currentTimeMillis,
178
178
  value,
@@ -185,7 +185,7 @@ import {
185
185
  relayToken,
186
186
  secretsEqual,
187
187
  ensurePrivateDirectory
188
- } from "./main-16tqhq5g.mjs";
188
+ } from "./main-a7ym6xse.mjs";
189
189
  import {
190
190
  join,
191
191
  interrupt,
@@ -846,6 +846,64 @@ class CdpClientPool {
846
846
  }
847
847
  }
848
848
 
849
+ // src/cdp/emulation.ts
850
+ var deviceMetricsClearRetryMs = 100;
851
+ function clearDeviceMetricsOverride(send, options = {}) {
852
+ const clear = send("Emulation.clearDeviceMetricsOverride", {});
853
+ return gen(function* () {
854
+ yield* clear;
855
+ yield* sleep(deviceMetricsClearRetryMs);
856
+ if (options.retry?.() === false)
857
+ return;
858
+ yield* clear;
859
+ });
860
+ }
861
+
862
+ class DeviceMetricsOverrides {
863
+ nextGeneration = 1;
864
+ entries = new Map;
865
+ mark(tabId, sessionId) {
866
+ const generation = this.nextGeneration++;
867
+ this.entries.set(tabId, { sessionId, generation });
868
+ return generation;
869
+ }
870
+ generation(tabId) {
871
+ return this.entries.get(tabId)?.generation ?? 0;
872
+ }
873
+ sessionId(tabId) {
874
+ return this.entries.get(tabId)?.sessionId;
875
+ }
876
+ isCurrent(tabId, generation) {
877
+ return this.generation(tabId) === generation;
878
+ }
879
+ take(sessionId) {
880
+ const taken = [];
881
+ for (const [tabId, entry] of this.entries) {
882
+ if (entry.sessionId !== sessionId)
883
+ continue;
884
+ entry.sessionId = undefined;
885
+ taken.push({ tabId, generation: entry.generation });
886
+ }
887
+ return taken;
888
+ }
889
+ clear(tabId, generation, sessionId) {
890
+ const entry = this.entries.get(tabId);
891
+ if (!entry || entry.generation !== generation)
892
+ return;
893
+ if (sessionId !== undefined && entry.sessionId !== undefined && entry.sessionId !== sessionId)
894
+ return;
895
+ entry.sessionId = undefined;
896
+ }
897
+ forget(tabId) {
898
+ this.entries.delete(tabId);
899
+ }
900
+ }
901
+ function tabsToClearOnExecuteEnd(options) {
902
+ if (options.readOnly)
903
+ return [];
904
+ return options.overrides.take(options.sessionId).filter(({ tabId }) => options.canSee(tabId));
905
+ }
906
+
849
907
  // src/cdp/visibility.ts
850
908
  function canClientSeeTarget(options) {
851
909
  if (options.targetOwnerSessionId === undefined) {
@@ -2148,18 +2206,9 @@ function installClosedPageReplacementGuard(page, clearRecreatedFromClosedUrl, ac
2148
2206
  }
2149
2207
  }
2150
2208
 
2151
- // src/snapshot/browser-capture.ts
2152
- var captureSnapshotInBrowser = (rootOrSettings, locatorSettings) => {
2153
- const settings = locatorSettings ?? rootOrSettings;
2209
+ // src/snapshot/naming.ts
2210
+ var snapshotNamingInBrowser = () => {
2154
2211
  const normalize = (value) => value.replace(/\s+/g, " ").trim();
2155
- const truncate = (value, maxLength) => {
2156
- if (value.length <= maxLength)
2157
- return value;
2158
- const prefix = value.slice(0, maxLength + 1);
2159
- const boundary = prefix.lastIndexOf(" ");
2160
- return `${prefix.slice(0, boundary >= Math.floor(maxLength * 0.6) ? boundary : maxLength).trimEnd()}...`;
2161
- };
2162
- const quote = (value) => value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
2163
2212
  const styleCache = new WeakMap;
2164
2213
  const styleOf = (element) => {
2165
2214
  let cached = styleCache.get(element);
@@ -2395,6 +2444,46 @@ var captureSnapshotInBrowser = (rootOrSettings, locatorSettings) => {
2395
2444
  return "navigation";
2396
2445
  return element.tagName.toLowerCase();
2397
2446
  };
2447
+ const nameFromAuthorOnlyRoles = new Set(["combobox", "listbox", "textbox", "searchbox", "spinbutton", "slider"]);
2448
+ const identityNameFor = (element, role) => nameFromAuthorOnlyRoles.has(role) ? authorAccessibleName(element) : accessibleName(element);
2449
+ return {
2450
+ normalize,
2451
+ styleOf,
2452
+ isVisible,
2453
+ visibleAssociatedLabel,
2454
+ explicitAriaName,
2455
+ labelledName,
2456
+ safeText,
2457
+ authorAccessibleName,
2458
+ accessibleName,
2459
+ roleFor,
2460
+ identityNameFor
2461
+ };
2462
+ };
2463
+
2464
+ // src/snapshot/browser-capture.ts
2465
+ var captureSnapshotInBrowser = (rootOrSettings, locatorSettings, naming) => {
2466
+ const settings = locatorSettings ?? rootOrSettings;
2467
+ const truncate = (value, maxLength) => {
2468
+ if (value.length <= maxLength)
2469
+ return value;
2470
+ const prefix = value.slice(0, maxLength + 1);
2471
+ const boundary = prefix.lastIndexOf(" ");
2472
+ return `${prefix.slice(0, boundary >= Math.floor(maxLength * 0.6) ? boundary : maxLength).trimEnd()}...`;
2473
+ };
2474
+ const quote = (value) => value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
2475
+ const {
2476
+ normalize,
2477
+ styleOf,
2478
+ isVisible,
2479
+ visibleAssociatedLabel,
2480
+ explicitAriaName,
2481
+ labelledName,
2482
+ safeText,
2483
+ accessibleName,
2484
+ roleFor,
2485
+ identityNameFor
2486
+ } = naming;
2398
2487
  const isRowCell = (child) => {
2399
2488
  const local = child.localName;
2400
2489
  if (local === "th" || local === "td")
@@ -3178,8 +3267,7 @@ var captureSnapshotInBrowser = (rootOrSettings, locatorSettings) => {
3178
3267
  const displayName = isFrame ? frameName(element) : isStructural ? structuralName(element, role) : accessibleName(element);
3179
3268
  if (isInteractive && isDuplicateCardLink(element, displayName))
3180
3269
  continue;
3181
- const nameFromAuthorOnly = role === "combobox" || role === "listbox" || role === "textbox" || role === "searchbox" || role === "spinbutton" || role === "slider";
3182
- const identityName = isInteractive ? nameFromAuthorOnly ? authorAccessibleName(element) : displayName : displayName;
3270
+ const identityName = isInteractive ? identityNameFor(element, role) : displayName;
3183
3271
  const isDisabled = element.disabled === true || element.getAttribute("aria-disabled") === "true";
3184
3272
  if (isInteractive && isDisabled && !displayName && !element.getAttribute("name") && !isNativeTextControl(element))
3185
3273
  continue;
@@ -3241,7 +3329,8 @@ var captureSnapshotInBrowser = (rootOrSettings, locatorSettings) => {
3241
3329
  };
3242
3330
  };
3243
3331
  var browserCapture = new Function("rootOrSettings", "locatorSettings", `const __name = (target) => target
3244
- return (${captureSnapshotInBrowser.toString()})(rootOrSettings, locatorSettings)`);
3332
+ const naming = (${snapshotNamingInBrowser.toString()})()
3333
+ return (${captureSnapshotInBrowser.toString()})(rootOrSettings, locatorSettings, naming)`);
3245
3334
 
3246
3335
  // src/snapshot/frames.ts
3247
3336
  var maxSnapshotFrames = 8;
@@ -3768,6 +3857,135 @@ function redactionContextIsGone(cause) {
3768
3857
  return kind === "context-destroyed" || kind === "context-missing" || kind === "target-closed";
3769
3858
  }
3770
3859
 
3860
+ // src/snapshot/ref-selector.ts
3861
+ var staleGraceMs = 3000;
3862
+ var refSelectorEngine = (graceMs, createNaming) => {
3863
+ const firstMiss = new Map;
3864
+ const quoted = (value) => {
3865
+ const short = value.length > 80 ? `${value.slice(0, 80)}...` : value;
3866
+ return `"${short.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
3867
+ };
3868
+ const hiddenFromAria = (element) => {
3869
+ if (element.closest("[aria-hidden='true']"))
3870
+ return true;
3871
+ const visible = element.checkVisibility?.({ visibilityProperty: true });
3872
+ if (visible !== undefined)
3873
+ return !visible;
3874
+ const style = getComputedStyle(element);
3875
+ return style.display === "none" || style.visibility === "hidden";
3876
+ };
3877
+ const stale = (message) => Object.assign(new Error(message), { stack: message });
3878
+ const resolve = (root, body) => {
3879
+ const parsed = /^(\S+)\.\d+ (act|read) (\S+) ("(?:[^"\\]|\\.)*") ([\s\S]+)$/.exec(body);
3880
+ if (!parsed)
3881
+ throw new Error(`Malformed snapshot ref selector: ${body}`);
3882
+ const [, id, mode, role, rawName, selector] = parsed;
3883
+ const name = JSON.parse(rawName);
3884
+ const naming = createNaming();
3885
+ const bySelector = Array.from(root.querySelectorAll(selector));
3886
+ const sameRole = bySelector.filter((element) => naming.roleFor(element) === role);
3887
+ const matches = sameRole.filter((element) => !hiddenFromAria(element) && naming.identityNameFor(element, role) === name);
3888
+ if (matches.length > 0) {
3889
+ firstMiss.delete(body);
3890
+ return matches;
3891
+ }
3892
+ if (mode !== "act" || root.nodeType !== Node.DOCUMENT_NODE)
3893
+ return [];
3894
+ if (sameRole.some(hiddenFromAria)) {
3895
+ firstMiss.delete(body);
3896
+ return [];
3897
+ }
3898
+ const now = Date.now();
3899
+ const first = firstMiss.get(body) ?? now;
3900
+ firstMiss.set(body, first);
3901
+ if (now - first < graceMs)
3902
+ return [];
3903
+ firstMiss.delete(body);
3904
+ const was = `${role} ${quoted(name)}`;
3905
+ const current = bySelector.length === 1 ? bySelector[0] : undefined;
3906
+ const change = current ? naming.roleFor(current) === role ? `now reads ${quoted(naming.identityNameFor(current, role))}` : `is now ${naming.roleFor(current)} ${quoted(naming.identityNameFor(current, naming.roleFor(current)))}` : bySelector.length === 0 ? "is gone; the page removed or re-rendered it" : `is gone; its selector now matches ${bySelector.length} other elements`;
3907
+ throw stale(`ref ${id} is stale: ${was} ${change}; call snapshot() again`);
3908
+ };
3909
+ return {
3910
+ query: (root, body) => resolve(root, body)[0] ?? null,
3911
+ queryAll: (root, body) => resolve(root, body)
3912
+ };
3913
+ };
3914
+ var refSelectorSource = `(() => {
3915
+ const __name = (target) => target
3916
+ return (${refSelectorEngine.toString()})(${staleGraceMs}, ${snapshotNamingInBrowser.toString()})
3917
+ })()`;
3918
+ var refSelectorName = `browse-ref-${globalThis.crypto.randomUUID().slice(0, 6)}`;
3919
+ var contextSelectors2 = new WeakMap;
3920
+ var registeredContexts = new WeakSet;
3921
+ var nextCall = 1;
3922
+ var actions = [
3923
+ "blur",
3924
+ "boundingBox",
3925
+ "check",
3926
+ "clear",
3927
+ "click",
3928
+ "dblclick",
3929
+ "dispatchEvent",
3930
+ "dragTo",
3931
+ "fill",
3932
+ "focus",
3933
+ "getAttribute",
3934
+ "hover",
3935
+ "innerHTML",
3936
+ "innerText",
3937
+ "inputValue",
3938
+ "isChecked",
3939
+ "isDisabled",
3940
+ "isEditable",
3941
+ "isEnabled",
3942
+ "press",
3943
+ "pressSequentially",
3944
+ "scrollIntoViewIfNeeded",
3945
+ "selectOption",
3946
+ "selectText",
3947
+ "setChecked",
3948
+ "tap",
3949
+ "textContent",
3950
+ "type",
3951
+ "uncheck",
3952
+ "waitFor"
3953
+ ];
3954
+ function refLocator(page, scope, id, ref) {
3955
+ if (!registeredContexts.has(page.context()))
3956
+ return;
3957
+ const selector = (mode) => `${refSelectorName}=${id}.${nextCall++} ${mode} ${ref.role} ${JSON.stringify(ref.name)} ${ref.selector}`;
3958
+ const locator = scope.locator(selector("read"));
3959
+ for (const action of actions) {
3960
+ const method = {
3961
+ async[action](...args) {
3962
+ const options = args.at(-1);
3963
+ const explicitTimeout = typeof options === "object" && options !== null && options.timeout !== undefined;
3964
+ const acting = scope.locator(selector(explicitTimeout ? "read" : "act"));
3965
+ return await acting[action](...args);
3966
+ }
3967
+ }[action];
3968
+ Object.defineProperty(locator, action, { value: method, configurable: true, writable: true });
3969
+ }
3970
+ return locator;
3971
+ }
3972
+ async function registerRefSelector(context) {
3973
+ const existing = contextSelectors2.get(context);
3974
+ if (existing)
3975
+ return existing;
3976
+ const { _channel } = context;
3977
+ const registration = _channel.registerSelectorEngine({
3978
+ selectorEngine: { name: refSelectorName, source: refSelectorSource, contentScript: true }
3979
+ }, { timeout: 0 }).then(() => {
3980
+ registeredContexts.add(context);
3981
+ }, (error) => {
3982
+ contextSelectors2.delete(context);
3983
+ throw error;
3984
+ });
3985
+ contextSelectors2.set(context, registration);
3986
+ return registration;
3987
+ }
3988
+
3771
3989
  // src/auth/authenticated-origin.ts
3772
3990
  var defaultTimeoutMs = 30000;
3773
3991
  var defaultMaxResponseBytes = 2000000;
@@ -6950,6 +7168,8 @@ var downloadCapabilityErrorMessage = "Downloads are unavailable in browse extens
6950
7168
  var downloadGuardedPages = new WeakSet;
6951
7169
  var downloadGuardedContexts = new WeakSet;
6952
7170
  var viewportZoomGuardedPages = new WeakSet;
7171
+ var viewportGuards = new WeakMap;
7172
+ var viewportRestoreTimeoutMs = 2000;
6953
7173
  var explicitMediaOptions = [
6954
7174
  ["colorScheme", "prefers-color-scheme"],
6955
7175
  ["reducedMotion", "prefers-reduced-motion"],
@@ -7027,9 +7247,17 @@ function installViewportZoomGuard(options) {
7027
7247
  }
7028
7248
  if (typeof page.setViewportSize === "function") {
7029
7249
  const originalSetViewportSize = page.setViewportSize.bind(page);
7250
+ const guard = { original: undefined, dirty: false };
7030
7251
  Object.defineProperty(page, "setViewportSize", {
7031
7252
  configurable: true,
7032
7253
  value: async (size) => {
7254
+ guard.dirty = true;
7255
+ if (!guard.original) {
7256
+ const before = await withTimeout(page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight, outerWidth: window.outerWidth })), 1000).catch(() => timedOut);
7257
+ if (typeof before !== "symbol" && before.width <= before.outerWidth && before.outerWidth - before.width <= 40) {
7258
+ guard.original = { width: before.width, height: before.height };
7259
+ }
7260
+ }
7033
7261
  await originalSetViewportSize(size);
7034
7262
  try {
7035
7263
  const measured = await withTimeout(page.evaluate(() => ({
@@ -7043,9 +7271,74 @@ function installViewportZoomGuard(options) {
7043
7271
  } catch {}
7044
7272
  }
7045
7273
  });
7274
+ viewportGuards.set(page, guard);
7046
7275
  }
7047
7276
  viewportZoomGuardedPages.add(page);
7048
7277
  }
7278
+ function forgetPlaywrightViewport(page) {
7279
+ try {
7280
+ const client = page;
7281
+ client._viewportSize = undefined;
7282
+ const server = client._connection?.toImpl?.(page);
7283
+ if (!server)
7284
+ return;
7285
+ server._emulatedSize = undefined;
7286
+ const mainFrameSession = server.delegate?._mainFrameSession;
7287
+ if (mainFrameSession)
7288
+ mainFrameSession._metricsOverride = undefined;
7289
+ } catch {}
7290
+ }
7291
+ async function restoreEmulatedViewport(page) {
7292
+ const guard = viewportGuards.get(page);
7293
+ if (!guard?.dirty)
7294
+ return;
7295
+ const original = guard.original;
7296
+ guard.dirty = false;
7297
+ guard.original = undefined;
7298
+ let cancelled = false;
7299
+ const restore = async () => {
7300
+ if (page.isClosed())
7301
+ return;
7302
+ const cdp = await page.context().newCDPSession(page);
7303
+ try {
7304
+ if (cancelled)
7305
+ return;
7306
+ const attempts = original ? 3 : 2;
7307
+ for (let attempt = 0;attempt < attempts; attempt++) {
7308
+ if (cancelled)
7309
+ return;
7310
+ await cdp.send("Emulation.clearDeviceMetricsOverride");
7311
+ await delay(120);
7312
+ if (cancelled)
7313
+ return;
7314
+ if (!original)
7315
+ continue;
7316
+ const measured = await withTimeout(page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight })), 500).catch(() => timedOut);
7317
+ if (typeof measured === "symbol")
7318
+ break;
7319
+ if (Math.abs(measured.width - original.width) <= 2 && Math.abs(measured.height - original.height) <= 2)
7320
+ break;
7321
+ }
7322
+ } finally {
7323
+ await cdp.detach().catch(() => {});
7324
+ }
7325
+ };
7326
+ const outcome = await withTimeout(restore(), viewportRestoreTimeoutMs).catch(() => timedOut);
7327
+ if (typeof outcome === "symbol")
7328
+ cancelled = true;
7329
+ forgetPlaywrightViewport(page);
7330
+ }
7331
+ async function withRestoredViewports(options) {
7332
+ try {
7333
+ return await options.run();
7334
+ } finally {
7335
+ let pages = [options.page];
7336
+ try {
7337
+ pages = Array.from(new Set([options.page, ...options.context.pages()]));
7338
+ } catch {}
7339
+ await Promise.all(pages.map((page) => restoreEmulatedViewport(page)));
7340
+ }
7341
+ }
7049
7342
 
7050
7343
  // src/execute/default-page.ts
7051
7344
  class DefaultPageHost {
@@ -10023,10 +10316,11 @@ function createSnapshotHelpers(page, registry) {
10023
10316
  entries.push({ prefix: frameSkipNote(frameBudget.skipped.deadline, "snapshot deadline reached") });
10024
10317
  if (omittedFrames > 0)
10025
10318
  entries.push({ prefix: frameSkipNote(omittedFrames, "maxItems reached") });
10026
- const compatiblePrevious = previousSnapshot?.page === page && previousSnapshot.signature === signature ? previousSnapshot : undefined;
10319
+ const samePagePrevious = previousSnapshot?.page === page ? previousSnapshot : undefined;
10320
+ const compatiblePrevious = samePagePrevious?.signature === signature ? samePagePrevious : undefined;
10027
10321
  let nextRef = registry.nextRef ?? 1;
10028
10322
  const reusableRefs = new Map;
10029
- for (const entry of compatiblePrevious?.entries ?? []) {
10323
+ for (const entry of samePagePrevious?.entries ?? []) {
10030
10324
  if (!entry.refId)
10031
10325
  continue;
10032
10326
  const key = snapshotRefIdentity(entry);
@@ -10107,9 +10401,9 @@ function createSnapshotHelpers(page, registry) {
10107
10401
  throw new Error(`Snapshot ref ${id} was captured in an iframe that has navigated or detached; call snapshot() again`);
10108
10402
  }
10109
10403
  }
10110
- const locator = frame ? frame.locator(snapshotRef.selector) : page.locator(snapshotRef.selector);
10404
+ const scope = frame ?? page;
10111
10405
  const role = snapshotRefAriaRole(snapshotRef.role);
10112
- const resolved = role ? frame ? locator.and(frame.getByRole(role, snapshotRef.name ? { name: snapshotRef.name, exact: true } : undefined)) : locator.and(page.getByRole(role, snapshotRef.name ? { name: snapshotRef.name, exact: true } : undefined)) : locator;
10406
+ const resolved = (role && snapshotRef.name && !snapshotRef.selector.includes(" >> ") ? refLocator(page, scope, normalized, { selector: snapshotRef.selector, role: snapshotRef.role, name: snapshotRef.name }) : undefined) ?? (role ? scope.locator(snapshotRef.selector).and(scope.getByRole(role, snapshotRef.name ? { name: snapshotRef.name, exact: true } : undefined)) : scope.locator(snapshotRef.selector));
10113
10407
  refRoots.set(resolved, snapshotRef);
10114
10408
  return resolved;
10115
10409
  };
@@ -11414,6 +11708,7 @@ class ExecuteSandbox extends DefaultPageHost {
11414
11708
  allowNode = executeAllowsNode();
11415
11709
  snapshotRefs = { selectors: new Map };
11416
11710
  networkCapture = new Recorder;
11711
+ viewportGuardContexts = new WeakSet;
11417
11712
  secrets;
11418
11713
  actionTimeoutContext;
11419
11714
  realm;
@@ -11458,32 +11753,38 @@ class ExecuteSandbox extends DefaultPageHost {
11458
11753
  for (const warning of pageVisibleApiSourceWarnings(code))
11459
11754
  this.addWarningOnce(warning);
11460
11755
  const globals = await this.getGlobals(options);
11461
- const { result, logs, logSummary, aftermath } = await runUserCode({
11462
- code,
11463
- globals,
11464
- ...this.realm ? { realm: this.realm } : {},
11465
- onUnhandledRejection: (warning) => this.addWarningOnce(warning)
11466
- }).then(async (completed) => ({ ...completed, aftermath: await this.withChallenge(globals.page, completed.aftermath, false) })).catch(async (error) => {
11467
- if (!(error instanceof ExecuteCodeError) || !error.aftermath)
11468
- throw error;
11469
- throw new ExecuteCodeError(error.originalError, error.logs, error.logSummary, await this.withChallenge(globals.page, error.aftermath, true));
11756
+ return await withRestoredViewports({
11757
+ context: globals.context,
11758
+ page: globals.page,
11759
+ run: async () => {
11760
+ const { result, logs, logSummary, aftermath } = await runUserCode({
11761
+ code,
11762
+ globals,
11763
+ ...this.realm ? { realm: this.realm } : {},
11764
+ onUnhandledRejection: (warning) => this.addWarningOnce(warning)
11765
+ }).then(async (completed) => ({ ...completed, aftermath: await this.withChallenge(globals.page, completed.aftermath, false) })).catch(async (error) => {
11766
+ if (!(error instanceof ExecuteCodeError) || !error.aftermath)
11767
+ throw error;
11768
+ throw new ExecuteCodeError(error.originalError, error.logs, error.logSummary, await this.withChallenge(globals.page, error.aftermath, true));
11769
+ });
11770
+ await this.networkCapture.settleForOutput();
11771
+ const extracted = extractExecuteMedia(result);
11772
+ const redactedValue = this.secrets.redactOutputValue(extracted.value);
11773
+ const jsonSafeResult = toJsonSafeValue(redactedValue);
11774
+ const bounded = boundExecuteResult(stringifyResult(redactedValue), jsonSafeResult.serializable ? jsonSafeResult.value : undefined, jsonSafeResult.serializable);
11775
+ const warnings = this.finalizeWarnings(logSummary, jsonValueWarning(redactedValue, jsonSafeResult), bounded.warning);
11776
+ return {
11777
+ text: bounded.text,
11778
+ ...bounded.hasValue ? { value: bounded.value } : {},
11779
+ ...extracted.media.length > 0 ? { media: extracted.media } : {},
11780
+ isError: false,
11781
+ logs: this.secrets.redactCaptureLogs(logs),
11782
+ logSummary,
11783
+ warnings,
11784
+ aftermath: this.secrets.redactCaptureAftermath(aftermath)
11785
+ };
11786
+ }
11470
11787
  });
11471
- await this.networkCapture.settleForOutput();
11472
- const extracted = extractExecuteMedia(result);
11473
- const redactedValue = this.secrets.redactOutputValue(extracted.value);
11474
- const jsonSafeResult = toJsonSafeValue(redactedValue);
11475
- const bounded = boundExecuteResult(stringifyResult(redactedValue), jsonSafeResult.serializable ? jsonSafeResult.value : undefined, jsonSafeResult.serializable);
11476
- const warnings = this.finalizeWarnings(logSummary, jsonValueWarning(redactedValue, jsonSafeResult), bounded.warning);
11477
- return {
11478
- text: bounded.text,
11479
- ...bounded.hasValue ? { value: bounded.value } : {},
11480
- ...extracted.media.length > 0 ? { media: extracted.media } : {},
11481
- isError: false,
11482
- logs: this.secrets.redactCaptureLogs(logs),
11483
- logSummary,
11484
- warnings,
11485
- aftermath: this.secrets.redactCaptureAftermath(aftermath)
11486
- };
11487
11788
  } finally {
11488
11789
  this.restoreActionTimeout();
11489
11790
  this.actionTimeoutContext?.setDefaultTimeout?.(defaultActionTimeoutMs);
@@ -11712,6 +12013,7 @@ class ExecuteSandbox extends DefaultPageHost {
11712
12013
  const browser = this.browser;
11713
12014
  const context = browser.contexts()[0] ?? await browser.newContext();
11714
12015
  await registerAriaSnapshotSelector(context);
12016
+ await registerRefSelector(context);
11715
12017
  installDownloadCapabilityGuards(context);
11716
12018
  return { browser, context };
11717
12019
  }
@@ -11748,7 +12050,12 @@ class ExecuteSandbox extends DefaultPageHost {
11748
12050
  this.actionTimeoutContext = context;
11749
12051
  context.setDefaultTimeout?.(this.actionTimeoutMs);
11750
12052
  this.applyActionTimeout(page);
11751
- installViewportZoomGuard({
12053
+ this.installViewportGuards(context);
12054
+ this.networkCapture.bindPage(this.page);
12055
+ return { browser, context, page };
12056
+ }
12057
+ installViewportGuards(context) {
12058
+ const install = (page) => installViewportZoomGuard({
11752
12059
  page,
11753
12060
  explicitMediaFeatures: this.explicitMediaFeatures,
11754
12061
  getExplicitMedia: () => this.explicitMedia,
@@ -11757,8 +12064,12 @@ class ExecuteSandbox extends DefaultPageHost {
11757
12064
  },
11758
12065
  addWarningOnce: (warning) => this.addWarningOnce(warning)
11759
12066
  });
11760
- this.networkCapture.bindPage(this.page);
11761
- return { browser, context, page };
12067
+ for (const page of context.pages())
12068
+ install(page);
12069
+ if (!this.viewportGuardContexts.has(context)) {
12070
+ context.on("page", install);
12071
+ this.viewportGuardContexts.add(context);
12072
+ }
11762
12073
  }
11763
12074
  ensureSessionPage(label) {
11764
12075
  return tryPromise({
@@ -13841,6 +14152,13 @@ class OpenCodeBrowserSessions {
13841
14152
  }));
13842
14153
  yield* manager.releaseSessionTargetOwnership(session);
13843
14154
  yield* manager.closeOpenCodeBrowserSession(session);
14155
+ yield* sync2(() => {
14156
+ try {
14157
+ manager.hooks.onSessionDeleted?.(id);
14158
+ } catch (error) {
14159
+ console.error("Session deleted hook failed", error);
14160
+ }
14161
+ });
13844
14162
  return true;
13845
14163
  })));
13846
14164
  return { deleted, ...stopped ? { stopped } : {} };
@@ -16468,6 +16786,7 @@ function createCdpDispatcher(options) {
16468
16786
  navigationGuard,
16469
16787
  ghostCursor,
16470
16788
  tabActivity,
16789
+ deviceMetricsOverrides,
16471
16790
  mainFrameIdsByTab,
16472
16791
  blankNavigationWaiters,
16473
16792
  sendDebuggerCommand,
@@ -16667,6 +16986,20 @@ function createCdpDispatcher(options) {
16667
16986
  }
16668
16987
  if (message.method === ghostCursorCommandMethod)
16669
16988
  return yield* ghostCursor.command(tabId, message.params);
16989
+ if (message.method === "Emulation.clearDeviceMetricsOverride") {
16990
+ const clientSessionId = cdpClients.sessionId(socket);
16991
+ const owner = deviceMetricsOverrides.sessionId(tabId);
16992
+ if (clientSessionId !== undefined && owner !== undefined && owner !== clientSessionId) {
16993
+ return {};
16994
+ }
16995
+ const generation = deviceMetricsOverrides.generation(tabId);
16996
+ yield* clearDeviceMetricsOverride((method, params) => sendDebuggerCommand({ tabId, method, params }), { retry: () => deviceMetricsOverrides.isCurrent(tabId, generation) });
16997
+ deviceMetricsOverrides.clear(tabId, generation, clientSessionId);
16998
+ return {};
16999
+ }
17000
+ if (message.method === "Emulation.setDeviceMetricsOverride" && route.chromeSessionId === undefined) {
17001
+ deviceMetricsOverrides.mark(tabId, cdpClients.sessionId(socket));
17002
+ }
16670
17003
  if (message.method === "Page.navigate" && route.chromeSessionId === undefined) {
16671
17004
  const dataNavigation = yield* navigateTopFrameToDataUrl({
16672
17005
  tabId,
@@ -19184,6 +19517,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
19184
19517
  const keepaliveIntervalMs = yield* Int("OPENCODE_BROWSER_KEEPALIVE_MS").pipe(withDefault(20000));
19185
19518
  const idleTabTtlMs = yield* Int("OPENCODE_BROWSER_IDLE_TAB_TTL_MS").pipe(withDefault(15 * 60000));
19186
19519
  const journalBaseDir = defaultJournalBaseDir();
19520
+ const deviceMetricsOverrides = new DeviceMetricsOverrides;
19187
19521
  const sessions = new OpenCodeBrowserSessions(endpointUrl, (id, onDefaultTargetChange) => new ExecuteSandbox({
19188
19522
  endpointUrl,
19189
19523
  authToken,
@@ -19216,7 +19550,28 @@ var makeRelay = fnUntraced(function* (options = {}) {
19216
19550
  targetBrowserKey: (tabId) => browsers.ownerKey(tabId),
19217
19551
  getUserAttachedPageUrls: (session) => registry.listRootTargets().filter((target) => target.owner === "user" && browsers.ownerKey(target.tabId) === session.browser?.key).map((target) => target.targetInfo.url || "about:blank"),
19218
19552
  ...executeTimeoutMs === undefined ? {} : { executeTimeoutMs },
19219
- onExecuteStateChange: (sessionId, executing) => presentation.onSessionExecuteStateChange(sessionId, executing),
19553
+ onExecuteStateChange: (sessionId, executing) => gen(function* () {
19554
+ yield* presentation.onSessionExecuteStateChange(sessionId, executing);
19555
+ if (executing)
19556
+ return;
19557
+ const tabs = tabsToClearOnExecuteEnd({
19558
+ overrides: deviceMetricsOverrides,
19559
+ readOnly: sessions.isReadOnly(sessionId),
19560
+ sessionId,
19561
+ canSee: (tabId) => {
19562
+ const target = registry.tabTargets.get(tabId);
19563
+ return target !== undefined && cdpRouter.canSessionSeeTarget(sessionId, target);
19564
+ }
19565
+ });
19566
+ for (const { tabId, generation } of tabs) {
19567
+ if (!deviceMetricsOverrides.isCurrent(tabId, generation))
19568
+ continue;
19569
+ yield* clearDeviceMetricsOverride((method, params) => sendDebuggerCommand({ tabId, method, params }), { retry: () => deviceMetricsOverrides.isCurrent(tabId, generation) }).pipe(timeoutOption("2 seconds"), ignore);
19570
+ }
19571
+ }),
19572
+ onSessionDeleted: (sessionId) => {
19573
+ deviceMetricsOverrides.take(sessionId);
19574
+ },
19220
19575
  onExecuteRecord: (record) => {
19221
19576
  const entry = makeJournalEntry({
19222
19577
  sessionId: record.sessionId,
@@ -19417,6 +19772,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
19417
19772
  protectedFrames.forgetTab(tabId);
19418
19773
  navigationGuard.forgetTab(tabId);
19419
19774
  ghostCursor.forget(tabId);
19775
+ deviceMetricsOverrides.forget(tabId);
19420
19776
  forgetTab(tabId);
19421
19777
  for (const [sessionId, childTabId] of suppressedChildSessions) {
19422
19778
  if (childTabId === tabId)
@@ -19547,6 +19903,7 @@ var makeRelay = fnUntraced(function* (options = {}) {
19547
19903
  navigationGuard,
19548
19904
  ghostCursor,
19549
19905
  tabActivity,
19906
+ deviceMetricsOverrides,
19550
19907
  mainFrameIdsByTab,
19551
19908
  blankNavigationWaiters,
19552
19909
  sendDebuggerCommand,