Open-source AI browser agent for Chrome and Firefox (monorepo) π§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix(agent): bfcache debt retention, shared refresh identity
Emre Sokullub1aa60e8d82c
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 2faa1524a..b1d036183 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -812,6 +812,9 @@ export class Agent extends LoopDetector {this._lastAxScopes = new Map(); // tabId -> { documentToken, pageUrl }, captured by the latest AX readthis._uncertainTextMutations = new Map(); // tabId -> Map(target -> unresolved, potentially applied text write; no raw text)this._verifiedTextReplacements = new Map(); // tabId -> exact replacement digest bound to the live document+ // tabId -> recent document tokens (bounded) whose mutation records are+ // retained so a back-forward cache return restores their guards.+ this._recentTextMutationDocuments = new Map();this._richTextToolbarGuard = new RichTextToolbarGuard();this._richTextToolbarProbe = new RichTextToolbarProbe(this);this._uploadSelectorRecoveryRequired = new Map(); // tabId -> prior ambiguous match count; cleared only by inspection/navigation/cleanup@@ -4715,12 +4718,39 @@ export class Agent extends LoopDetector {// document, not the URL: a query/hash change or SPA navigation can change// the route while the same document and editor value persist. Clearing on// a bare route change would drop the readback-only guard and let an- // append-style retry duplicate landed text, so these records survive until- // the document itself changes. Per-field staleness across documents is- // still handled by the documentToken checks in the mutation guards.+ // append-style retry duplicate landed text. On a genuine document change+ // the records are NOT discarded wholesale either: a back-forward cache+ // return restores the exact document (same token, same heap, possibly+ // landed text), so token-scoped records are retained boundedly and guard+ // again on return, while per-write token checks keep other documents+ // unblocked. Records without a token cannot be scoped and are dropped+ // once a new documented scope arrives (except when they name it).if (documentChanged) {- this._uncertainTextMutations.delete(tabId);- this._verifiedTextReplacements.delete(tabId);+ let recent = this._recentTextMutationDocuments.get(tabId);+ if (!(recent instanceof Array)) {+ recent = [];+ this._recentTextMutationDocuments.set(tabId, recent);+ }+ for (const token of [previous?.documentToken, next.documentToken]) {+ if (token && !recent.includes(token)) recent.push(token);+ }+ while (recent.length > 5) recent.shift();+ const keep = new Set(recent);+ for (const [owner, map] of [+ [this._uncertainTextMutations, this._uncertainTextMutations.get(tabId)],+ [this._verifiedTextReplacements, this._verifiedTextReplacements.get(tabId)],+ ]) {+ if (!(map instanceof Map)) continue;+ for (const [key, entry] of map) {+ if (!entry?.documentToken) {+ if (!entry?.pageUrl || !next.pageUrl+ || this._normalizeUrl(entry.pageUrl) !== this._normalizeUrl(next.pageUrl)) map.delete(key);+ continue;+ }+ if (!keep.has(entry.documentToken)) map.delete(key);+ }+ if (map.size === 0) owner.delete(tabId);+ }}this._lastAxScopes.set(tabId, next);}@@ -20514,6 +20544,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._lastTypeFieldEpoch?.delete(tabId);this._uncertainTextMutations.delete(tabId);this._verifiedTextReplacements.delete(tabId);+ this._recentTextMutationDocuments.delete(tabId);this._lastCdpClickIdent?.delete(tabId);this._lastClickProgress?.delete(tabId);this._clickAxCdpFallbacks?.delete(tabId);@@ -20923,10 +20954,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});} catch { current = null; }const kindOk = record.focusedKind === 'editor'- ? (current?.fieldMeta?.contentEditable === true- || /\bediting\b[\s\S]*\bfile contents\b/i.test(String(- current?.fieldMeta?.ariaLabelledByText || current?.fieldMeta?.ariaLabel || '',- )))+ ? this._isGithubFileEditorRecord({ fieldMeta: current?.fieldMeta }): /^(?:commit-message-input|commit_message)$/i.test(String(current?.fieldMeta?.id || current?.fieldMeta?.name || '',));@@ -20970,14 +20998,62 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (records.size === 0) this._verifiedTextReplacements.delete(tabId);}+ // Probe the live document and adopt its scope when it differs from cache.+ // Shared by the allow path (a stale cache must not let retained debts be+ // skipped for the wrong document β e.g. a back-forward return) and the+ // blocking path's last resort. Adopting routes through _rememberAxScope,+ // so loop state resets and bounded retention pruning apply exactly as for+ // an observed navigation. Returns the live scope when adopted, else null.+ // Callers re-derive their target and re-scope debt selection afterwards.+ async _adoptLiveTextMutationScope(tabId, name, args = {}, debts = null) {+ let liveScope = null;+ try {+ liveScope = await this._liveTextMutationScope(tabId, name, args);+ } catch { liveScope = null; }+ if (!liveScope || (!liveScope.documentToken && !liveScope.pageUrl)) return null;+ const cachedScope = this._lastAxScopes.get(tabId) || {};+ if (String(liveScope.documentToken || '') === String(cachedScope.documentToken || '')+ && this._normalizeUrl(liveScope.pageUrl || '') === this._normalizeUrl(cachedScope.pageUrl || '')) {+ return null;+ }+ const bootstrappingFirstToken = !cachedScope.documentToken;+ this._rememberAxScope(tabId, liveScope.documentToken || cachedScope.documentToken || '',+ liveScope.pageUrl || cachedScope.pageUrl || '');+ // First-token bootstrap: debts recorded before any document was observed+ // carry no token. A tokenless debt whose recorded URL differs from the+ // live URL provably predates this document (full navigation), so drop it+ // instead of blocking the unrelated destination. Same-URL or URL-less+ // debts stay blocked fail-closed β a same-document route change keeps+ // its readback-only guard.+ if (bootstrappingFirstToken && debts instanceof Map) {+ for (const [key, candidate] of debts) {+ if (!candidate.documentToken+ && candidate.pageUrl+ && liveScope.pageUrl+ && this._normalizeUrl(candidate.pageUrl) !== this._normalizeUrl(liveScope.pageUrl)) {+ debts.delete(key);+ }+ }+ if (debts.size === 0) this._uncertainTextMutations.delete(tabId);+ }+ return liveScope;+ }+async _uncertainTextMutationBlock(tabId, name, args = {}) {if (!['set_field', 'type_ax', 'type_text'].includes(name)) return null;const debts = this._uncertainTextMutations?.get(tabId);if (!(debts instanceof Map) || debts.size === 0) return null;let target = this._textMutationTarget(tabId, name, args);+ // Token-scoped matching: debts retained for back-forward cache returns+ // must not guard other documents. Debts outside the recent-document+ // backlog are TTL-collected here; anything surviving but scoped+ // elsewhere is skipped below, never deleted.+ const recentDocuments = this._recentTextMutationDocuments.get(tabId);+ const recentSet = recentDocuments instanceof Array ? new Set(recentDocuments) : null;for (const [key, candidate] of debts) {if (candidate.documentToken && target.documentToken- && candidate.documentToken !== target.documentToken) debts.delete(key);+ && candidate.documentToken !== target.documentToken+ && (!recentSet || !recentSet.has(candidate.documentToken))) debts.delete(key);}if (debts.size === 0) {this._uncertainTextMutations.delete(tabId);@@ -21013,37 +21089,53 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn selectorReadback;};let debt = null;- for (const candidate of debts.values()) {- if (candidate.ambiguous || target.ambiguous || candidate.key === target.key) {- debt = candidate;- break;+ // Shared with the post-adoption re-scope below: out-of-scope debts are+ // skipped (retained for a back-forward return), never deleted here.+ const selectDebt = async () => {+ for (const candidate of debts.values()) {+ if (candidate.documentToken && target.documentToken+ && candidate.documentToken !== target.documentToken) continue;+ if (candidate.ambiguous || target.ambiguous || candidate.key === target.key) return candidate;+ const distinctAxRefs = candidate.key.startsWith('ax:')+ && target.key.startsWith('ax:')+ && candidate.key !== target.key;+ if (distinctAxRefs) {+ const readback = await readAxTarget();+ if (readback?.success === true+ && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;+ }+ // Mirror the AX escape hatch for selector pairs: the digest probe can+ // read the target's live metadata, so a demonstrably different field+ // (two or more differing identity fields, no shared one) must not be+ // blocked by another field's debt. The debt is kept β only this+ // dispatch is allowed β and an unprovable target stays blocked.+ const distinctSelectors = candidate.locatorType === 'selector'+ && target.locatorType === 'selector'+ && typeof candidate.selector === 'string'+ && typeof target.selector === 'string'+ && candidate.selector !== target.selector;+ if (distinctSelectors) {+ const readback = await readSelectorTarget();+ if (readback && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;+ }+ return candidate;+ }+ return null;+ };+ debt = await selectDebt();+ if (!debt) {+ // The cache may predate the live document (e.g. back-forward return+ // while the guard was retained): refresh once before allowing, so a+ // retained debt for the live document can still guard this write.+ if (await this._adoptLiveTextMutationScope(tabId, name, args, debts)) {+ if (!(this._uncertainTextMutations.get(tabId) instanceof Map)) return null;+ target = this._textMutationTarget(tabId, name, args);+ debt = await selectDebt();+ if (!debt) return null;+ } else {+ return null;}- const distinctAxRefs = candidate.key.startsWith('ax:')- && target.key.startsWith('ax:')- && candidate.key !== target.key;- if (distinctAxRefs) {- const readback = await readAxTarget();- if (readback?.success === true- && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;- }- // Mirror the AX escape hatch for selector pairs: the digest probe can- // read the target's live metadata, so a demonstrably different field- // (two or more differing identity fields, no shared one) must not be- // blocked by another field's debt. The debt is kept β only this- // dispatch is allowed β and an unprovable target stays blocked.- const distinctSelectors = candidate.locatorType === 'selector'- && target.locatorType === 'selector'- && typeof candidate.selector === 'string'- && typeof target.selector === 'string'- && candidate.selector !== target.selector;- if (distinctSelectors) {- const readback = await readSelectorTarget();- if (readback && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;- }- debt = candidate;- break;}- if (!debt) return null;const sameReplacement = debt.replacesValue === true&& replacement@@ -21140,41 +21232,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}- // Last resort before blocking: the cached scope may predate a full- // navigation that no AX read ever observed, pinning old debt to the new- // page. A genuinely new live token proves the debt's document is gone,- // so adopt it (clearing stale debt through the document-change path) and- // let the write proceed fresh. A matching token, or an unreachable page,- // keeps the block below exactly as before.- const liveScope = await this._liveTextMutationScope(tabId, name, args);- const cachedScope = this._lastAxScopes.get(tabId) || {};- if (liveScope- && liveScope.documentToken- && liveScope.documentToken !== String(cachedScope.documentToken || '')) {- const bootstrappingFirstToken = !cachedScope.documentToken;- this._rememberAxScope(tabId, liveScope.documentToken, liveScope.pageUrl || cachedScope.pageUrl || '');- // First-token bootstrap: debts recorded before any document was- // observed carry no token. A tokenless debt whose recorded URL differs- // from the live URL provably predates this document (full navigation),- // so drop it instead of blocking the unrelated destination. Same-URL- // or URL-less debts stay blocked fail-closed β a same-document route- // change keeps its readback-only guard.- if (bootstrappingFirstToken) {- for (const [key, candidate] of debts) {- if (!candidate.documentToken- && candidate.pageUrl- && liveScope.pageUrl- && this._normalizeUrl(candidate.pageUrl) !== this._normalizeUrl(liveScope.pageUrl)) {- debts.delete(key);- }- }- if (debts.size === 0) this._uncertainTextMutations.delete(tabId);- }- if (!(this._uncertainTextMutations.get(tabId) instanceof Map)- || this._uncertainTextMutations.get(tabId).size === 0) {- return null;- }+ // Last resort before blocking: same freshness guarantee for the+ // blocking path (covers an early probe that failed or scope that+ // changed mid-call).+ if (await this._adoptLiveTextMutationScope(tabId, name, args, debts)) {+ if (!(this._uncertainTextMutations.get(tabId) instanceof Map)) return null;target = this._textMutationTarget(tabId, name, args);+ // Re-scope after adoption: the pre-adopt selection may name a debt+ // from the previous document, which must not guard the new one.+ // Retained debts stay mapped for a back-forward return. (Both readback+ // caches stay valid: the probes read the live page, which is what the+ // new target names too.)+ debt = await selectDebt();+ if (!debt) return null;}return {diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex cc95aada0..1282c093c 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -625,6 +625,9 @@ export class Agent extends LoopDetector {this._lastAxScopes = new Map(); // tabId -> { documentToken, pageUrl }, captured by the latest AX readthis._uncertainTextMutations = new Map(); // tabId -> Map(target -> unresolved, potentially applied text write; no raw text)this._verifiedTextReplacements = new Map(); // tabId -> exact replacement digest bound to the live document+ // tabId -> recent document tokens (bounded) whose mutation records are+ // retained so a back-forward cache return restores their guards.+ this._recentTextMutationDocuments = new Map();this._richTextToolbarGuard = new RichTextToolbarGuard();this._richTextToolbarProbe = new RichTextToolbarProbe(this);this._uploadSelectorRecoveryRequired = new Map(); // tabId -> prior ambiguous match count; cleared only by inspection/navigation/cleanup@@ -4452,12 +4455,39 @@ export class Agent extends LoopDetector {// document, not the URL: a query/hash change or SPA navigation can change// the route while the same document and editor value persist. Clearing on// a bare route change would drop the readback-only guard and let an- // append-style retry duplicate landed text, so these records survive until- // the document itself changes. Per-field staleness across documents is- // still handled by the documentToken checks in the mutation guards.+ // append-style retry duplicate landed text. On a genuine document change+ // the records are NOT discarded wholesale either: a back-forward cache+ // return restores the exact document (same token, same heap, possibly+ // landed text), so token-scoped records are retained boundedly and guard+ // again on return, while per-write token checks keep other documents+ // unblocked. Records without a token cannot be scoped and are dropped+ // once a new documented scope arrives (except when they name it).if (documentChanged) {- this._uncertainTextMutations.delete(tabId);- this._verifiedTextReplacements.delete(tabId);+ let recent = this._recentTextMutationDocuments.get(tabId);+ if (!(recent instanceof Array)) {+ recent = [];+ this._recentTextMutationDocuments.set(tabId, recent);+ }+ for (const token of [previous?.documentToken, next.documentToken]) {+ if (token && !recent.includes(token)) recent.push(token);+ }+ while (recent.length > 5) recent.shift();+ const keep = new Set(recent);+ for (const [owner, map] of [+ [this._uncertainTextMutations, this._uncertainTextMutations.get(tabId)],+ [this._verifiedTextReplacements, this._verifiedTextReplacements.get(tabId)],+ ]) {+ if (!(map instanceof Map)) continue;+ for (const [key, entry] of map) {+ if (!entry?.documentToken) {+ if (!entry?.pageUrl || !next.pageUrl+ || this._normalizeUrl(entry.pageUrl) !== this._normalizeUrl(next.pageUrl)) map.delete(key);+ continue;+ }+ if (!keep.has(entry.documentToken)) map.delete(key);+ }+ if (map.size === 0) owner.delete(tabId);+ }}this._lastAxScopes.set(tabId, next);}@@ -18494,10 +18524,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});} catch { current = null; }const kindOk = record.focusedKind === 'editor'- ? (current?.fieldMeta?.contentEditable === true- || /\bediting\b[\s\S]*\bfile contents\b/i.test(String(- current?.fieldMeta?.ariaLabelledByText || current?.fieldMeta?.ariaLabel || '',- )))+ ? this._isGithubFileEditorRecord({ fieldMeta: current?.fieldMeta }): /^(?:commit-message-input|commit_message)$/i.test(String(current?.fieldMeta?.id || current?.fieldMeta?.name || '',));@@ -18541,14 +18568,62 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (records.size === 0) this._verifiedTextReplacements.delete(tabId);}+ // Probe the live document and adopt its scope when it differs from cache.+ // Shared by the allow path (a stale cache must not let retained debts be+ // skipped for the wrong document β e.g. a back-forward return) and the+ // blocking path's last resort. Adopting routes through _rememberAxScope,+ // so loop state resets and bounded retention pruning apply exactly as for+ // an observed navigation. Returns the live scope when adopted, else null.+ // Callers re-derive their target and re-scope debt selection afterwards.+ async _adoptLiveTextMutationScope(tabId, name, args = {}, debts = null) {+ let liveScope = null;+ try {+ liveScope = await this._liveTextMutationScope(tabId, name, args);+ } catch { liveScope = null; }+ if (!liveScope || (!liveScope.documentToken && !liveScope.pageUrl)) return null;+ const cachedScope = this._lastAxScopes.get(tabId) || {};+ if (String(liveScope.documentToken || '') === String(cachedScope.documentToken || '')+ && this._normalizeUrl(liveScope.pageUrl || '') === this._normalizeUrl(cachedScope.pageUrl || '')) {+ return null;+ }+ const bootstrappingFirstToken = !cachedScope.documentToken;+ this._rememberAxScope(tabId, liveScope.documentToken || cachedScope.documentToken || '',+ liveScope.pageUrl || cachedScope.pageUrl || '');+ // First-token bootstrap: debts recorded before any document was observed+ // carry no token. A tokenless debt whose recorded URL differs from the+ // live URL provably predates this document (full navigation), so drop it+ // instead of blocking the unrelated destination. Same-URL or URL-less+ // debts stay blocked fail-closed β a same-document route change keeps+ // its readback-only guard.+ if (bootstrappingFirstToken && debts instanceof Map) {+ for (const [key, candidate] of debts) {+ if (!candidate.documentToken+ && candidate.pageUrl+ && liveScope.pageUrl+ && this._normalizeUrl(candidate.pageUrl) !== this._normalizeUrl(liveScope.pageUrl)) {+ debts.delete(key);+ }+ }+ if (debts.size === 0) this._uncertainTextMutations.delete(tabId);+ }+ return liveScope;+ }+async _uncertainTextMutationBlock(tabId, name, args = {}) {if (!['set_field', 'type_ax', 'type_text'].includes(name)) return null;const debts = this._uncertainTextMutations?.get(tabId);if (!(debts instanceof Map) || debts.size === 0) return null;let target = this._textMutationTarget(tabId, name, args);+ // Token-scoped matching: debts retained for back-forward cache returns+ // must not guard other documents. Debts outside the recent-document+ // backlog are TTL-collected here; anything surviving but scoped+ // elsewhere is skipped below, never deleted.+ const recentDocuments = this._recentTextMutationDocuments.get(tabId);+ const recentSet = recentDocuments instanceof Array ? new Set(recentDocuments) : null;for (const [key, candidate] of debts) {if (candidate.documentToken && target.documentToken- && candidate.documentToken !== target.documentToken) debts.delete(key);+ && candidate.documentToken !== target.documentToken+ && (!recentSet || !recentSet.has(candidate.documentToken))) debts.delete(key);}if (debts.size === 0) {this._uncertainTextMutations.delete(tabId);@@ -18584,37 +18659,53 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn selectorReadback;};let debt = null;- for (const candidate of debts.values()) {- if (candidate.ambiguous || target.ambiguous || candidate.key === target.key) {- debt = candidate;- break;+ // Shared with the post-adoption re-scope below: out-of-scope debts are+ // skipped (retained for a back-forward return), never deleted here.+ const selectDebt = async () => {+ for (const candidate of debts.values()) {+ if (candidate.documentToken && target.documentToken+ && candidate.documentToken !== target.documentToken) continue;+ if (candidate.ambiguous || target.ambiguous || candidate.key === target.key) return candidate;+ const distinctAxRefs = candidate.key.startsWith('ax:')+ && target.key.startsWith('ax:')+ && candidate.key !== target.key;+ if (distinctAxRefs) {+ const readback = await readAxTarget();+ if (readback?.success === true+ && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;+ }+ // Mirror the AX escape hatch for selector pairs: the digest probe can+ // read the target's live metadata, so a demonstrably different field+ // (two or more differing identity fields, no shared one) must not be+ // blocked by another field's debt. The debt is kept β only this+ // dispatch is allowed β and an unprovable target stays blocked.+ const distinctSelectors = candidate.locatorType === 'selector'+ && target.locatorType === 'selector'+ && typeof candidate.selector === 'string'+ && typeof target.selector === 'string'+ && candidate.selector !== target.selector;+ if (distinctSelectors) {+ const readback = await readSelectorTarget();+ if (readback && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;+ }+ return candidate;+ }+ return null;+ };+ debt = await selectDebt();+ if (!debt) {+ // The cache may predate the live document (e.g. back-forward return+ // while the guard was retained): refresh once before allowing, so a+ // retained debt for the live document can still guard this write.+ if (await this._adoptLiveTextMutationScope(tabId, name, args, debts)) {+ if (!(this._uncertainTextMutations.get(tabId) instanceof Map)) return null;+ target = this._textMutationTarget(tabId, name, args);+ debt = await selectDebt();+ if (!debt) return null;+ } else {+ return null;}- const distinctAxRefs = candidate.key.startsWith('ax:')- && target.key.startsWith('ax:')- && candidate.key !== target.key;- if (distinctAxRefs) {- const readback = await readAxTarget();- if (readback?.success === true- && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;- }- // Mirror the AX escape hatch for selector pairs: the digest probe can- // read the target's live metadata, so a demonstrably different field- // (two or more differing identity fields, no shared one) must not be- // blocked by another field's debt. The debt is kept β only this- // dispatch is allowed β and an unprovable target stays blocked.- const distinctSelectors = candidate.locatorType === 'selector'- && target.locatorType === 'selector'- && typeof candidate.selector === 'string'- && typeof target.selector === 'string'- && candidate.selector !== target.selector;- if (distinctSelectors) {- const readback = await readSelectorTarget();- if (readback && this._textMutationFieldsProvenDistinct(candidate.fieldMeta, readback.fieldMeta)) continue;- }- debt = candidate;- break;}- if (!debt) return null;const sameReplacement = debt.replacesValue === true&& replacement@@ -18716,41 +18807,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}- // Last resort before blocking: the cached scope may predate a full- // navigation that no AX read ever observed, pinning old debt to the new- // page. A genuinely new live token proves the debt's document is gone,- // so adopt it (clearing stale debt through the document-change path) and- // let the write proceed fresh. A matching token, or an unreachable page,- // keeps the block below exactly as before.- const liveScope = await this._liveTextMutationScope(tabId, name, args);- const cachedScope = this._lastAxScopes.get(tabId) || {};- if (liveScope- && liveScope.documentToken- && liveScope.documentToken !== String(cachedScope.documentToken || '')) {- const bootstrappingFirstToken = !cachedScope.documentToken;- this._rememberAxScope(tabId, liveScope.documentToken, liveScope.pageUrl || cachedScope.pageUrl || '');- // First-token bootstrap: debts recorded before any document was- // observed carry no token. A tokenless debt whose recorded URL differs- // from the live URL provably predates this document (full navigation),- // so drop it instead of blocking the unrelated destination. Same-URL- // or URL-less debts stay blocked fail-closed β a same-document route- // change keeps its readback-only guard.- if (bootstrappingFirstToken) {- for (const [key, candidate] of debts) {- if (!candidate.documentToken- && candidate.pageUrl- && liveScope.pageUrl- && this._normalizeUrl(candidate.pageUrl) !== this._normalizeUrl(liveScope.pageUrl)) {- debts.delete(key);- }- }- if (debts.size === 0) this._uncertainTextMutations.delete(tabId);- }- if (!(this._uncertainTextMutations.get(tabId) instanceof Map)- || this._uncertainTextMutations.get(tabId).size === 0) {- return null;- }+ // Last resort before blocking: same freshness guarantee for the+ // blocking path (covers an early probe that failed or scope that+ // changed mid-call).+ if (await this._adoptLiveTextMutationScope(tabId, name, args, debts)) {+ if (!(this._uncertainTextMutations.get(tabId) instanceof Map)) return null;target = this._textMutationTarget(tabId, name, args);+ // Re-scope after adoption: the pre-adopt selection may name a debt+ // from the previous document, which must not guard the new one.+ // Retained debts stay mapped for a back-forward return. (Both readback+ // caches stay valid: the probes read the live page, which is what the+ // new target names too.)+ debt = await selectDebt();+ if (!debt) return null;}return {@@ -18953,6 +19022,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._lastTypeFieldEpoch?.delete(tabId);this._uncertainTextMutations.delete(tabId);this._verifiedTextReplacements.delete(tabId);+ this._recentTextMutationDocuments.delete(tabId);this.progressPageScopes.delete(tabId);this.progressSessions.delete(tabId);this.progressExpectedItems.delete(tabId);diff --git a/test/run.js b/test/run.jsindex 00b8ef2bc..5e8793e2f 100644--- a/test/run.js+++ b/test/run.js@@ -75322,8 +75322,23 @@ test('uncertain text mutation debt blocks blind retries until the document chang`${label}: recording a second uncertain target unblocked the first one`);agent._rememberAxScope(tabId, 'doc-two', 'https://github.com/example/repo/edit/main/README.md');- assert.equal(agent._uncertainTextMutations.has(tabId), false,- `${label}: a replacement document kept stale mutation debt`);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 2,+ `${label}: navigating away discarded scoped mutation debt`);+ // The new document is unblocked: retained debts are token-scoped.+ const movedOn = await agent._uncertainTextMutationBlock(+ tabId, 'set_field', { ref_id: 'ref_other_page', text: 'fresh field' },+ );+ assert.equal(movedOn, null, `${label}: retained debt blocked the new document`);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 2,+ `${label}: allowing the new document dropped the old debts`);+ // Back-forward return restores the guard: same token, same heap,+ // possibly landed text.+ agent._rememberAxScope(tabId, 'doc-one', 'https://github.com/example/repo/edit/main/README.md');+ const backBlocked = await agent._uncertainTextMutationBlock(+ tabId, 'set_field', { ref_id: 'ref_editor', text: 'appended after return' },+ );+ assert.equal(backBlocked?.repeatBlocked, true,+ `${label}: back-forward return lost the mutation guard`);}} finally {if (originalChrome === undefined) delete globalThis.chrome;@@ -75439,7 +75454,7 @@ test('an uncertain contenteditable write invalidates stale proof across locator}});-test('uncertain text mutation debt survives same-document route changes', async () => {+test('uncertain text mutation debt survives same-document route changes and back-forward returns', async () => {for (const [label, AgentClass, tabId] of [['chrome', AgentCh, 9453],['firefox', AgentFx, 9454],@@ -75463,10 +75478,18 @@ test('uncertain text mutation debt survives same-document route changes', async);assert.equal(stillBlocked?.repeatBlocked, true,`${label}: append retry escaped the guard after a same-document route change`);- // A genuine document change still discards the debt.+ // A genuine document change scopes (not discards) the debt: the new+ // document is unblocked while the record is retained boundedly.agent._rememberAxScope(tabId, 'doc-next', `${pageUrl}#L10`);- assert.equal(agent._uncertainTextMutations.has(tabId), false,- `${label}: document change retained stale mutation debt`);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1,+ `${label}: document change discarded scoped mutation debt`);+ // Back-forward return restores the guard.+ agent._rememberAxScope(tabId, 'doc-route', pageUrl);+ const backBlocked = await agent._uncertainTextMutationBlock(+ tabId, 'set_field', { ref_id: 'ref_editor', text: 'appended after return' },+ );+ assert.equal(backBlocked?.repeatBlocked, true,+ `${label}: back-forward return lost the mutation guard`);}});@@ -77252,7 +77275,8 @@ test('focused field_value_digest and live scope cover selectorless writes', asynassert.equal(live?.documentToken, 'doc-new', `${label}: focused live scope returned no token`);const allowed = await agent._uncertainTextMutationBlock(tabId, 'type_text', { text: 'fresh' });assert.equal(allowed, null, `${label}: stale debt blocked a focused write on a new document`);- assert.equal(agent._uncertainTextMutations.has(tabId), false, `${label}: stale debt survived navigation`);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1,+ `${label}: scoped debt was discarded instead of retained for return`);}} finally {if (originalChrome === undefined) delete globalThis.chrome;@@ -77742,7 +77766,7 @@ test('verified value with unobserved submission is not mutation debt', async ()}});-test('navigation clears stale text-mutation debt via live document check', async () => {+test('navigation scopes stale text-mutation debt to its document', async () => {const originalChrome = globalThis.chrome;const originalBrowser = globalThis.browser;try {@@ -77778,16 +77802,26 @@ test('navigation clears stale text-mutation debt via live document check', async);assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1, `${label}: debt was not recorded`);// No AX read happened after the navigation: the cached scope still- // points at the old document, but the live check proves the move.+ // points at the old document, but the live check proves the move. The+ // write is allowed, while the scoped debt is retained boundedly.liveDoc.documentToken = 'doc-new';liveDoc.refScopeUrl = 'https://other.test/page';const allowed = await agent._uncertainTextMutationBlock(tabId, 'type_text', { selector: '#other', text: 'fresh' },);assert.equal(allowed, null, `${label}: stale debt blocked a new document`);- assert.equal(agent._uncertainTextMutations.has(tabId), false, `${label}: stale debt survived navigation`);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1,+ `${label}: scoped debt was discarded instead of retained for return`);assert.equal(agent._lastAxScopes.get(tabId)?.documentToken, 'doc-new',`${label}: live scope was not adopted`);+ // Back-forward return restores the guard on the same field.+ liveDoc.documentToken = 'doc-old';+ liveDoc.refScopeUrl = 'https://example.test/form';+ const backBlocked = await agent._uncertainTextMutationBlock(+ tabId, 'type_text', { selector: '#field', text: 'draft appended' },+ );+ assert.equal(backBlocked?.repeatBlocked, true,+ `${label}: back-forward return lost the mutation guard`);}} finally {if (originalChrome === undefined) delete globalThis.chrome;