Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix(agent): focused commit proofs, continued task tokens, focused live scope

Emre Sokullu5bc09f787a29
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index c83503ace..a98940157 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -650,6 +650,7 @@ export class Agent extends LoopDetector {
this.abortFlags = new Map(); // tabId -> boolean
this.currentRunId = new Map(); // tabId -> active trace runId (for recorder hooks)
this._taskTokens = new Map(); // tabId -> per-task proof-scoping token, independent of optional tracing
+ this._continuationTaskTokens = new Map(); // tabId -> stashed task token carried only by trusted continuations
this._latestWorkflowDrafts = new Map(); // tabId -> sanitized, session-scoped workflow draft
this.currentCostState = new Map(); // tabId -> active cloud/router cost state
this.maxSteps = 130; // safety limit for autonomous loops (configurable via settings)
@@ -14752,7 +14753,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// recorder/storage failures that return before tracing starts (and the
// disabled-by-default untraced path). currentRunId must not double as the
// task boundary since it stays empty then.
- this._taskTokens.set(tabId, `task_${secureRandomBase36Token(12)}`);
+ // Trusted continuations (max_steps Continue) reuse the previous task's
+ // token so surviving replacement proofs stay usable for the same task;
+ // independent tasks always mint fresh and discard any stashed token.
+ if (runOptions?.trustedContinuation === true) {
+ const carried = this._takeContinuationTaskToken(tabId);
+ if (carried) this._taskTokens.set(tabId, carried);
+ else this._taskTokens.set(tabId, `task_${secureRandomBase36Token(12)}`);
+ } else {
+ this._continuationTaskTokens.delete(tabId);
+ this._taskTokens.set(tabId, `task_${secureRandomBase36Token(12)}`);
+ }
const { tabUrl, tabTitle } = this._isStandaloneChatRun(runOptions)
? { tabUrl: '', tabTitle: '' }
: (tabInfo || await this._getTabUrlTitle(tabId));
@@ -14851,6 +14862,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this.currentRunId.delete(tabId);
this.adapterMatchTraceKeys.delete(runId);
}
+ // Stash before deleting so an app-owned trusted continuation (Continue
+ // after max_steps) can reuse the same task's proofs. Independent tasks
+ // mint fresh at the next _startTraceRun and discard the stash there, so
+ // a prior task's proofs can never authorize a new task. Single-use and
+ // conversation-bound via _takeContinuationTaskToken.
+ this._storeContinuationTaskToken(tabId);
this._taskTokens.delete(tabId);
}
@@ -20113,6 +20130,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this._runningTabs.delete(tabId);
this.currentRunId.delete(tabId);
this._taskTokens.delete(tabId);
+ this._continuationTaskTokens.delete(tabId);
}
this._clearRunLoopState(tabId);
}
@@ -20193,12 +20211,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
async _textMutationValueDigest(tabId, target, expected = null) {
- if (!target || target.ambiguous === true) return null;
+ if (!target || (target.ambiguous === true && target.focusedProof !== true)) return null;
const params = target.locatorType === 'ax' && typeof target.refId === 'string'
? { ref_id: target.refId }
: target.locatorType === 'selector' && typeof target.selector === 'string'
? { selector: target.selector }
- : null;
+ : target.locatorType === 'focused'
+ ? { focused: true }
+ : null;
if (!params) return null;
try {
const response = await chrome.tabs.sendMessage(tabId, {
@@ -20229,14 +20249,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// pin old debt to the new page. The digest probe answers from the live
// document on success and failure alike (see the dispatcher scope wrap),
// so any token here is current by construction.
+ // Focused writes supply neither ref nor selector, so they previously
+ // returned null here and pinned stale debt to the new page after a full
+ // navigation. Probe with empty params instead: the handler still fails
+ // (ref_id or selector required) but the wrapper attaches the live
+ // documentToken/refScopeUrl, which is all this check needs.
async _liveTextMutationScope(tabId, name, args = {}) {
try {
const params = (name === 'set_field' || name === 'type_ax') && typeof args.ref_id === 'string'
? { ref_id: args.ref_id }
: name === 'type_text' && typeof args.selector === 'string' && args.selector.trim()
? { selector: args.selector.trim() }
- : null;
- if (!params) return null;
+ : {};
const response = await chrome.tabs.sendMessage(tabId, {
target: 'content',
action: 'field_value_digest',
@@ -20251,6 +20275,53 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
+ _focusedGithubFieldKind(meta = null) {
+ if (!meta || typeof meta !== 'object') return '';
+ if (/^(?:commit-message-input|commit_message)$/i.test(String(meta.id || meta.name || ''))) {
+ return 'commit-message';
+ }
+ if (meta.contentEditable === true) return 'editor';
+ if (/\bediting\b[\s\S]*\bfile contents\b/i.test(String(
+ meta.ariaLabelledByText || meta.ariaLabel || meta.labelText || '',
+ ))) return 'editor';
+ return '';
+ }
+
+ _normalizeFocusedFieldMeta(focusedField = null, fallbackMeta = null) {
+ if (focusedField && typeof focusedField === 'object'
+ && (focusedField.tag || focusedField.name || typeof focusedField.contentEditable === 'boolean')) {
+ return {
+ ...(fallbackMeta && typeof fallbackMeta === 'object' ? fallbackMeta : {}),
+ tag: String(focusedField.tag || fallbackMeta?.tag || '').toLowerCase() || null,
+ type: String(focusedField.type || fallbackMeta?.type || '').toLowerCase() || null,
+ name: focusedField.name != null ? String(focusedField.name) : (fallbackMeta?.name ?? null),
+ id: fallbackMeta?.id ?? (focusedField.name != null ? String(focusedField.name) : null),
+ contentEditable: focusedField.contentEditable === true || fallbackMeta?.contentEditable === true,
+ ariaLabel: fallbackMeta?.ariaLabel ?? null,
+ ariaLabelledByText: fallbackMeta?.ariaLabelledByText ?? null,
+ labelText: fallbackMeta?.labelText ?? null,
+ placeholder: fallbackMeta?.placeholder ?? null,
+ };
+ }
+ return fallbackMeta || null;
+ }
+
+ _focusedReplacementTarget(tabId, kind) {
+ const scope = this._lastAxScopes.get(tabId) || {};
+ const documentToken = String(scope.documentToken || '');
+ const pageUrl = String(scope.pageUrl || '');
+ const doc = documentToken || pageUrl || 'document';
+ return {
+ key: `focused:${doc}:${kind}`,
+ locatorType: 'focused',
+ documentToken,
+ pageUrl,
+ ambiguous: false,
+ focusedProof: true,
+ focusedKind: kind,
+ };
+ }
+
async _verifiedTextReplacementRecord(tabId, target, text, fieldMeta = null) {
const workflow = this._planExecutionGuards.get(tabId)?.siteWorkflow;
const needsCommitProof = workflow?.adapterName === 'github'
@@ -20284,6 +20355,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (!(records instanceof Map)) return;
for (const [key, record] of records) {
if (this._normalizeUrl(record?.pageUrl || '') !== this._normalizeUrl(pageUrl)) continue;
+ // Focused proofs are bound at write time to the then-focused field's
+ // live digest (focus stays on the edited field through verification).
+ // Re-digesting via {focused:true} after focus moved (e.g. editor proof
+ // while the commit-message input is focused) would compare the wrong
+ // field and delete a good proof, permanently blocking the documented
+ // click-then-type_text flow. External mutations after the proof are
+ // still caught fail-closed by the byte-exact raw-blob check post-commit,
+ // and any later write to the same focused kind overwrites this record.
+ if (record?.focusedProof === true) continue;
const githubEditor = record?.fieldMeta?.contentEditable === true
|| /contenteditable/i.test(String(record?.key || key))
|| /\bediting\b[\s\S]*\bfile contents\b/i.test(String(record?.fieldMeta?.ariaLabelledByText || ''));
@@ -20499,13 +20579,54 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
verifiedReplacements = new Map();
this._verifiedTextReplacements.set(tabId, verifiedReplacements);
}
- verifiedReplacements.set(target.key, await this._verifiedTextReplacementRecord(
- tabId, target, text, result.fieldMeta || null,
+ // Focused writes (documented click-then-type_text({text, clear:true}))
+ // have no selector/AX ref, so the base target is ambiguous and would
+ // otherwise never authorize a commit. When the write verified and its
+ // field identity proves the GitHub editor or commit-message input,
+ // bind it to a distinct non-ambiguous focused proof keyed by kind, so
+ // editor and commit-message proofs coexist instead of colliding on
+ // `focused:<doc>`. The live focused digest at write time (focus is
+ // still on the edited field) supplies the byte-observant readback;
+ // refresh skips focused proofs (focus moves before submit) and the
+ // byte-exact raw-blob check post-commit stays fail-closed.
+ let effectiveTarget = target;
+ let effectiveFieldMeta = result.fieldMeta || null;
+ if (target.ambiguous === true && name === 'type_text') {
+ const normalizedFocusedMeta = this._normalizeFocusedFieldMeta(
+ result.focusedField || null, result.fieldMeta || null,
+ );
+ const focusedKind = this._focusedGithubFieldKind(normalizedFocusedMeta);
+ if ((focusedKind === 'editor' || focusedKind === 'commit-message') && args.clear === true) {
+ effectiveTarget = this._focusedReplacementTarget(tabId, focusedKind);
+ effectiveFieldMeta = normalizedFocusedMeta;
+ }
+ }
+ verifiedReplacements.set(effectiveTarget.key, await this._verifiedTextReplacementRecord(
+ tabId, effectiveTarget, text, effectiveFieldMeta,
));
} else if (result.success === true) {
const verifiedReplacements = this._verifiedTextReplacements.get(tabId);
if (verifiedReplacements instanceof Map) {
- if (target.ambiguous) verifiedReplacements.clear();
+ if (target.ambiguous && name === 'type_text') {
+ const focusedKind = this._focusedGithubFieldKind(this._normalizeFocusedFieldMeta(
+ result.focusedField || null, result.fieldMeta || null,
+ ));
+ if (focusedKind === 'editor' || focusedKind === 'commit-message') {
+ for (const [key, record] of verifiedReplacements) {
+ const recordKind = record?.focusedKind
+ || this._focusedGithubFieldKind(record?.fieldMeta || null)
+ || (/contenteditable/i.test(String(record?.key || key)) ? 'editor' : '');
+ const sameKind = focusedKind === 'editor'
+ ? (recordKind === 'editor' || record?.fieldMeta?.contentEditable === true
+ || /contenteditable/i.test(String(record?.key || key)))
+ : (/^(?:commit-message-input|commit_message)$/i.test(String(
+ record?.fieldMeta?.id || record?.fieldMeta?.name || '',
+ )) || recordKind === 'commit-message');
+ if (sameKind) verifiedReplacements.delete(key);
+ }
+ } else verifiedReplacements.clear();
+ }
+ else if (target.ambiguous) verifiedReplacements.clear();
else verifiedReplacements.delete(target.key);
}
}
@@ -23127,6 +23248,27 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ _storeContinuationTaskToken(tabId) {
+ const token = this._taskTokens.get(tabId);
+ if (typeof token !== 'string' || !token) {
+ this._continuationTaskTokens.delete(tabId);
+ return false;
+ }
+ this._continuationTaskTokens.set(tabId, {
+ token,
+ conversationId: this.conversationIds.get(tabId) || null,
+ });
+ return true;
+ }
+
+ _takeContinuationTaskToken(tabId) {
+ const carried = this._continuationTaskTokens.get(tabId);
+ this._continuationTaskTokens.delete(tabId);
+ if (!carried || typeof carried.token !== 'string' || !carried.token) return null;
+ if (carried.conversationId !== (this.conversationIds.get(tabId) || null)) return null;
+ return carried.token;
+ }
+
_looksLikeMetaOnlyDoneSummary(content) {
const text = String(content || '').trim();
if (!text || text.length > 500) return false;
diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.js
index 9a0b91841..febd584d0 100644
--- a/src/chrome/src/content/content.js
+++ b/src/chrome/src/content/content.js
@@ -1897,7 +1897,7 @@
el.dispatchEvent(new Event('change', { bubbles: true }));
const verified = await verifyValue(el, typedText, params.clear === true, beforeValue);
if (actionDeadlineExpired()) return deadlineFailure();
- return { success: true, ...(verified === true ? { verified: true } : {}), method: 'contenteditable', value: el.textContent.slice(0, 100) };
+ return { success: true, ...(verified === true ? { verified: true } : {}), method: 'contenteditable', value: el.textContent.slice(0, 100), fieldMeta: _fieldMeta(el) };
}
// <select>: match by value, then by visible option text.
@@ -1962,7 +1962,7 @@
}
_lastTypeFieldIdent = routeStayedCurrent ? fieldIdent : null;
- return { success: true, ...(verified === true ? { verified: true } : {}), value: (el.value || '').slice(0, 100), ...(typeWarning ? { warning: typeWarning } : {}) };
+ return { success: true, ...(verified === true ? { verified: true } : {}), value: (el.value || '').slice(0, 100), fieldMeta: _fieldMeta(el), ...(typeWarning ? { warning: typeWarning } : {}) };
}
/**
@@ -6568,7 +6568,7 @@
},
'field_value_digest': async () => {
try {
- const { ref_id, selector, expected } = msg.params || {};
+ const { ref_id, selector, expected, focused } = msg.params || {};
let el = null;
if (typeof ref_id === 'string' && ref_id) {
if (typeof window.__wb_ax_lookup !== 'function') {
@@ -6591,6 +6591,18 @@
return null;
};
el = queryDeep(document);
+ } else if (focused === true) {
+ // Focused-field proof path for selectorless type_text({text}).
+ // Digests the deep active element so a verified focused write can
+ // bind to live field metadata. Failures still carry the live
+ // documentToken/refScopeUrl via the dispatcher scope wrap, so the
+ // agent's live-scope check can use this as a document oracle.
+ try {
+ let active = document.activeElement;
+ while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
+ el = active && active !== document.body && active !== document.documentElement ? active : null;
+ } catch { el = null; }
+ if (!el || !el.isConnected) return { success: false, error: 'no focused editable element' };
} else {
return { success: false, error: 'ref_id or selector is required' };
}
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 342358de3..96c11d976 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -513,6 +513,7 @@ export class Agent extends LoopDetector {
this.abortFlags = new Map(); // tabId -> boolean
this.currentRunId = new Map(); // tabId -> active trace runId
this._taskTokens = new Map(); // tabId -> per-task proof-scoping token, independent of optional tracing
+ this._continuationTaskTokens = new Map(); // tabId -> stashed task token carried only by trusted continuations
this._latestWorkflowDrafts = new Map(); // tabId -> sanitized, session-scoped workflow draft
this.currentCostState = new Map(); // tabId -> active cloud/router cost state
this.maxSteps = 130; // safety limit for autonomous loops (configurable via settings)
@@ -12552,7 +12553,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// recorder/storage failures that return before tracing starts (and the
// disabled-by-default untraced path). currentRunId must not double as the
// task boundary since it stays empty then.
- this._taskTokens.set(tabId, `task_${secureRandomBase36Token(12)}`);
+ // Trusted continuations (max_steps Continue) reuse the previous task's
+ // token so surviving replacement proofs stay usable for the same task;
+ // independent tasks always mint fresh and discard any stashed token.
+ if (runOptions?.trustedContinuation === true) {
+ const carried = this._takeContinuationTaskToken(tabId);
+ if (carried) this._taskTokens.set(tabId, carried);
+ else this._taskTokens.set(tabId, `task_${secureRandomBase36Token(12)}`);
+ } else {
+ this._continuationTaskTokens.delete(tabId);
+ this._taskTokens.set(tabId, `task_${secureRandomBase36Token(12)}`);
+ }
const { tabUrl, tabTitle } = this._isStandaloneChatRun(runOptions)
? { tabUrl: '', tabTitle: '' }
: (tabInfo || await this._getTabUrlTitle(tabId));
@@ -12646,6 +12657,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this.currentRunId.delete(tabId);
this.adapterMatchTraceKeys.delete(runId);
}
+ // Stash before deleting so an app-owned trusted continuation (Continue
+ // after max_steps) can reuse the same task's proofs. Independent tasks
+ // mint fresh at the next _startTraceRun and discard the stash there, so
+ // a prior task's proofs can never authorize a new task. Single-use and
+ // conversation-bound via _takeContinuationTaskToken.
+ this._storeContinuationTaskToken(tabId);
this._taskTokens.delete(tabId);
}
@@ -17765,12 +17782,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
async _textMutationValueDigest(tabId, target, expected = null) {
- if (!target || target.ambiguous === true) return null;
+ if (!target || (target.ambiguous === true && target.focusedProof !== true)) return null;
const params = target.locatorType === 'ax' && typeof target.refId === 'string'
? { ref_id: target.refId }
: target.locatorType === 'selector' && typeof target.selector === 'string'
? { selector: target.selector }
- : null;
+ : target.locatorType === 'focused'
+ ? { focused: true }
+ : null;
if (!params) return null;
try {
const response = await browser.tabs.sendMessage(tabId, {
@@ -17801,14 +17820,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// pin old debt to the new page. The digest probe answers from the live
// document on success and failure alike (see the dispatcher scope wrap),
// so any token here is current by construction.
+ // Focused writes supply neither ref nor selector, so they previously
+ // returned null here and pinned stale debt to the new page after a full
+ // navigation. Probe with empty params instead: the handler still fails
+ // (ref_id or selector required) but the wrapper attaches the live
+ // documentToken/refScopeUrl, which is all this check needs.
async _liveTextMutationScope(tabId, name, args = {}) {
try {
const params = (name === 'set_field' || name === 'type_ax') && typeof args.ref_id === 'string'
? { ref_id: args.ref_id }
: name === 'type_text' && typeof args.selector === 'string' && args.selector.trim()
? { selector: args.selector.trim() }
- : null;
- if (!params) return null;
+ : {};
const response = await browser.tabs.sendMessage(tabId, {
target: 'content',
action: 'field_value_digest',
@@ -17823,6 +17846,53 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
+ _focusedGithubFieldKind(meta = null) {
+ if (!meta || typeof meta !== 'object') return '';
+ if (/^(?:commit-message-input|commit_message)$/i.test(String(meta.id || meta.name || ''))) {
+ return 'commit-message';
+ }
+ if (meta.contentEditable === true) return 'editor';
+ if (/\bediting\b[\s\S]*\bfile contents\b/i.test(String(
+ meta.ariaLabelledByText || meta.ariaLabel || meta.labelText || '',
+ ))) return 'editor';
+ return '';
+ }
+
+ _normalizeFocusedFieldMeta(focusedField = null, fallbackMeta = null) {
+ if (focusedField && typeof focusedField === 'object'
+ && (focusedField.tag || focusedField.name || typeof focusedField.contentEditable === 'boolean')) {
+ return {
+ ...(fallbackMeta && typeof fallbackMeta === 'object' ? fallbackMeta : {}),
+ tag: String(focusedField.tag || fallbackMeta?.tag || '').toLowerCase() || null,
+ type: String(focusedField.type || fallbackMeta?.type || '').toLowerCase() || null,
+ name: focusedField.name != null ? String(focusedField.name) : (fallbackMeta?.name ?? null),
+ id: fallbackMeta?.id ?? (focusedField.name != null ? String(focusedField.name) : null),
+ contentEditable: focusedField.contentEditable === true || fallbackMeta?.contentEditable === true,
+ ariaLabel: fallbackMeta?.ariaLabel ?? null,
+ ariaLabelledByText: fallbackMeta?.ariaLabelledByText ?? null,
+ labelText: fallbackMeta?.labelText ?? null,
+ placeholder: fallbackMeta?.placeholder ?? null,
+ };
+ }
+ return fallbackMeta || null;
+ }
+
+ _focusedReplacementTarget(tabId, kind) {
+ const scope = this._lastAxScopes.get(tabId) || {};
+ const documentToken = String(scope.documentToken || '');
+ const pageUrl = String(scope.pageUrl || '');
+ const doc = documentToken || pageUrl || 'document';
+ return {
+ key: `focused:${doc}:${kind}`,
+ locatorType: 'focused',
+ documentToken,
+ pageUrl,
+ ambiguous: false,
+ focusedProof: true,
+ focusedKind: kind,
+ };
+ }
+
async _verifiedTextReplacementRecord(tabId, target, text, fieldMeta = null) {
const workflow = this._planExecutionGuards.get(tabId)?.siteWorkflow;
const needsCommitProof = workflow?.adapterName === 'github'
@@ -17856,6 +17926,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (!(records instanceof Map)) return;
for (const [key, record] of records) {
if (this._normalizeUrl(record?.pageUrl || '') !== this._normalizeUrl(pageUrl)) continue;
+ // Focused proofs are bound at write time to the then-focused field's
+ // live digest (focus stays on the edited field through verification).
+ // Re-digesting via {focused:true} after focus moved (e.g. editor proof
+ // while the commit-message input is focused) would compare the wrong
+ // field and delete a good proof, permanently blocking the documented
+ // click-then-type_text flow. External mutations after the proof are
+ // still caught fail-closed by the byte-exact raw-blob check post-commit,
+ // and any later write to the same focused kind overwrites this record.
+ if (record?.focusedProof === true) continue;
const githubEditor = record?.fieldMeta?.contentEditable === true
|| /contenteditable/i.test(String(record?.key || key))
|| /\bediting\b[\s\S]*\bfile contents\b/i.test(String(record?.fieldMeta?.ariaLabelledByText || ''));
@@ -18076,13 +18155,54 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
verifiedReplacements = new Map();
this._verifiedTextReplacements.set(tabId, verifiedReplacements);
}
- verifiedReplacements.set(target.key, await this._verifiedTextReplacementRecord(
- tabId, target, text, result.fieldMeta || null,
+ // Focused writes (documented click-then-type_text({text, clear:true}))
+ // have no selector/AX ref, so the base target is ambiguous and would
+ // otherwise never authorize a commit. When the write verified and its
+ // field identity proves the GitHub editor or commit-message input,
+ // bind it to a distinct non-ambiguous focused proof keyed by kind, so
+ // editor and commit-message proofs coexist instead of colliding on
+ // `focused:<doc>`. The live focused digest at write time (focus is
+ // still on the edited field) supplies the byte-observant readback;
+ // refresh skips focused proofs (focus moves before submit) and the
+ // byte-exact raw-blob check post-commit stays fail-closed.
+ let effectiveTarget = target;
+ let effectiveFieldMeta = result.fieldMeta || null;
+ if (target.ambiguous === true && name === 'type_text') {
+ const normalizedFocusedMeta = this._normalizeFocusedFieldMeta(
+ result.focusedField || null, result.fieldMeta || null,
+ );
+ const focusedKind = this._focusedGithubFieldKind(normalizedFocusedMeta);
+ if ((focusedKind === 'editor' || focusedKind === 'commit-message') && args.clear === true) {
+ effectiveTarget = this._focusedReplacementTarget(tabId, focusedKind);
+ effectiveFieldMeta = normalizedFocusedMeta;
+ }
+ }
+ verifiedReplacements.set(effectiveTarget.key, await this._verifiedTextReplacementRecord(
+ tabId, effectiveTarget, text, effectiveFieldMeta,
));
} else if (result.success === true) {
const verifiedReplacements = this._verifiedTextReplacements.get(tabId);
if (verifiedReplacements instanceof Map) {
- if (target.ambiguous) verifiedReplacements.clear();
+ if (target.ambiguous && name === 'type_text') {
+ const focusedKind = this._focusedGithubFieldKind(this._normalizeFocusedFieldMeta(
+ result.focusedField || null, result.fieldMeta || null,
+ ));
+ if (focusedKind === 'editor' || focusedKind === 'commit-message') {
+ for (const [key, record] of verifiedReplacements) {
+ const recordKind = record?.focusedKind
+ || this._focusedGithubFieldKind(record?.fieldMeta || null)
+ || (/contenteditable/i.test(String(record?.key || key)) ? 'editor' : '');
+ const sameKind = focusedKind === 'editor'
+ ? (recordKind === 'editor' || record?.fieldMeta?.contentEditable === true
+ || /contenteditable/i.test(String(record?.key || key)))
+ : (/^(?:commit-message-input|commit_message)$/i.test(String(
+ record?.fieldMeta?.id || record?.fieldMeta?.name || '',
+ )) || recordKind === 'commit-message');
+ if (sameKind) verifiedReplacements.delete(key);
+ }
+ } else verifiedReplacements.clear();
+ }
+ else if (target.ambiguous) verifiedReplacements.clear();
else verifiedReplacements.delete(target.key);
}
}
@@ -18157,6 +18277,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this._runningTabs.delete(tabId);
this.currentRunId.delete(tabId);
this._taskTokens.delete(tabId);
+ this._continuationTaskTokens.delete(tabId);
}
this._clearRunLoopState(tabId);
}
@@ -20735,6 +20856,27 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ _storeContinuationTaskToken(tabId) {
+ const token = this._taskTokens.get(tabId);
+ if (typeof token !== 'string' || !token) {
+ this._continuationTaskTokens.delete(tabId);
+ return false;
+ }
+ this._continuationTaskTokens.set(tabId, {
+ token,
+ conversationId: this.conversationIds.get(tabId) || null,
+ });
+ return true;
+ }
+
+ _takeContinuationTaskToken(tabId) {
+ const carried = this._continuationTaskTokens.get(tabId);
+ this._continuationTaskTokens.delete(tabId);
+ if (!carried || typeof carried.token !== 'string' || !carried.token) return null;
+ if (carried.conversationId !== (this.conversationIds.get(tabId) || null)) return null;
+ return carried.token;
+ }
+
_looksLikeMetaOnlyDoneSummary(content) {
const text = String(content || '').trim();
if (!text || text.length > 500) return false;
diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.js
index 737c78e30..29f945448 100644
--- a/src/firefox/src/content/content.js
+++ b/src/firefox/src/content/content.js
@@ -2215,7 +2215,7 @@
el.dispatchEvent(new Event('change', { bubbles: true }));
const verified = await verifyValue(el, typedText, params.clear === true, beforeValue);
if (actionDeadlineExpired()) return deadlineFailure();
- return { success: true, ...(verified === true ? { verified: true } : {}), method: 'contenteditable', value: el.textContent.slice(0, 100) };
+ return { success: true, ...(verified === true ? { verified: true } : {}), method: 'contenteditable', value: el.textContent.slice(0, 100), fieldMeta: _fieldMeta(el) };
}
// <select>: match by value or option text.
@@ -2281,7 +2281,7 @@
}
_lastTypeFieldIdent = routeStayedCurrent ? fieldIdent : null;
- return { success: true, ...(verified === true ? { verified: true } : {}), value: (el.value || '').slice(0, 100), ...(typeWarning ? { warning: typeWarning } : {}) };
+ return { success: true, ...(verified === true ? { verified: true } : {}), value: (el.value || '').slice(0, 100), fieldMeta: _fieldMeta(el), ...(typeWarning ? { warning: typeWarning } : {}) };
}
/**
@@ -5617,7 +5617,7 @@
},
'field_value_digest': async () => {
try {
- const { ref_id, selector, expected } = msg.params || {};
+ const { ref_id, selector, expected, focused } = msg.params || {};
let el = null;
if (typeof ref_id === 'string' && ref_id) {
if (typeof window.__wb_ax_lookup !== 'function') {
@@ -5640,6 +5640,18 @@
return null;
};
el = queryDeep(document);
+ } else if (focused === true) {
+ // Focused-field proof path for selectorless type_text({text}).
+ // Digests the deep active element so a verified focused write can
+ // bind to live field metadata. Failures still carry the live
+ // documentToken/refScopeUrl via the dispatcher scope wrap, so the
+ // agent's live-scope check can use this as a document oracle.
+ try {
+ let active = document.activeElement;
+ while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
+ el = active && active !== document.body && active !== document.documentElement ? active : null;
+ } catch { el = null; }
+ if (!el || !el.isConnected) return { success: false, error: 'no focused editable element' };
} else {
return { success: false, error: 'ref_id or selector is required' };
}
diff --git a/test/run.js b/test/run.js
index 334283b34..553dbb3a1 100644
--- a/test/run.js
+++ b/test/run.js
@@ -75210,6 +75210,194 @@ test('GitHub replacement proofs require a nonempty task token', async () => {
}
});
+test('trusted continuations reuse the task token for the same task', async () => {
+ for (const [label, AgentClass, tabId] of [
+ ['chrome', AgentCh, 9480],
+ ['firefox', AgentFx, 9481],
+ ]) {
+ const agent = new AgentClass({});
+ agent.conversationIds.set(tabId, 'conv-continue');
+ agent._taskTokens.set(tabId, 'task-original');
+ assert.equal(agent._storeContinuationTaskToken(tabId), true,
+ `${label}: continuation token was not stashed`);
+ agent._taskTokens.delete(tabId);
+ // Trusted continuation of the same conversation reuses the stashed token.
+ assert.equal(agent._takeContinuationTaskToken(tabId), 'task-original',
+ `${label}: trusted continuation lost its task token`);
+ // Single-use: a second take finds nothing.
+ assert.equal(agent._takeContinuationTaskToken(tabId), null,
+ `${label}: continuation token was reusable`);
+ // Conversation mismatch rejects the stash.
+ agent._taskTokens.set(tabId, 'task-other');
+ agent._storeContinuationTaskToken(tabId);
+ agent.conversationIds.set(tabId, 'conv-new');
+ assert.equal(agent._takeContinuationTaskToken(tabId), null,
+ `${label}: continuation token crossed conversations`);
+ agent.conversationIds.set(tabId, 'conv-continue');
+ agent._continuationTaskTokens.delete(tabId);
+ }
+ for (const rel of [
+ 'src/chrome/src/agent/agent.js',
+ 'src/firefox/src/agent/agent.js',
+ ]) {
+ const source = fs.readFileSync(path.join(ROOT, rel), 'utf8');
+ assert.match(source, /trustedContinuation === true/,
+ `${rel}: task token mint lost its trusted-continuation branch`);
+ assert.match(source, /_takeContinuationTaskToken\(tabId\)/,
+ `${rel}: trusted continuation does not restore the stashed task token`);
+ assert.match(source, /_storeContinuationTaskToken\(tabId\)/,
+ `${rel}: run teardown does not stash the task token for continuations`);
+ }
+});
+
+test('focused editor and commit-message writes authorize a commit', async () => {
+ const originalChrome = globalThis.chrome;
+ const originalBrowser = globalThis.browser;
+ try {
+ const body = '# Focused document\n\nOne complete copy.\n';
+ const commitMsg = 'Update docs/plan.md';
+ // Digest probe answers for the then-focused field at write time. Focus
+ // stays on the edited field through verification, so {focused:true}
+ // observes the right element here; refresh skips focused proofs because
+ // focus moves before submit.
+ const makeTabs = (agent) => ({
+ async sendMessage(_tabId, message) {
+ assert.equal(message.action, 'field_value_digest');
+ const expected = message.params?.expected;
+ if (expected === body) {
+ return {
+ success: true, verified: true,
+ valueLength: body.length,
+ valueSha256: await agent._sha256Text(body),
+ fieldMeta: { contentEditable: true, ariaLabelledByText: 'Editing file contents' },
+ documentToken: 'doc-focused', refScopeUrl: 'https://github.com/example/repo/edit/main/docs/plan.md',
+ };
+ }
+ if (expected === commitMsg) {
+ return {
+ success: true, verified: true,
+ valueLength: commitMsg.length,
+ valueSha256: await agent._sha256Text(commitMsg),
+ fieldMeta: { id: 'commit-message-input', name: 'commit-message-input' },
+ documentToken: 'doc-focused', refScopeUrl: 'https://github.com/example/repo/edit/main/docs/plan.md',
+ };
+ }
+ return { success: false, documentToken: 'doc-focused', refScopeUrl: 'https://github.com/example/repo/edit/main/docs/plan.md' };
+ },
+ });
+ for (const [label, AgentClass, resolveJob, tabId] of [
+ ['chrome', AgentCh, resolveAdapterWorkflowJob, 9482],
+ ['firefox', AgentFx, resolveAdapterWorkflowJobFx, 9483],
+ ]) {
+ const agent = new AgentClass({});
+ const pageUrl = 'https://github.com/Example/Repo/edit/main/docs/plan.md';
+ agent._planExecutionGuards.set(tabId, {
+ enabled: true,
+ siteWorkflow: resolveJob(pageUrl, 'edit-file-and-commit'),
+ workflowMetadataRequirements: [{ field: 'commit_message', value: commitMsg }],
+ workflowMetadataRequirementsResolved: true,
+ });
+ agent._taskTokens.set(tabId, 'task-focused');
+ agent._lastAxScopes.set(tabId, { documentToken: 'doc-focused', pageUrl });
+ const tabs = makeTabs(agent);
+ globalThis.chrome = { tabs };
+ globalThis.browser = { tabs };
+ // Documented flow: click the editor, then type_text({text, clear:true})
+ // with no selector. Chrome reports focusedField via CDP; Firefox (and
+ // the content fallback) reports fieldMeta. Both must bind.
+ const editorResult = label === 'chrome'
+ ? { success: true, verified: true, method: 'cdp-insert-focused', focusedField: { tag: 'DIV', type: '', name: '', contentEditable: true } }
+ : { success: true, verified: true, method: 'contenteditable', fieldMeta: { contentEditable: true, ariaLabelledByText: 'Editing file contents' } };
+ await agent._finalizeTextMutationResult(tabId, 'type_text', { text: body, clear: true }, editorResult);
+ const editorKeys = [...(agent._verifiedTextReplacements.get(tabId)?.keys() || [])];
+ assert.ok(editorKeys.some(key => String(key).endsWith(':editor')),
+ `${label}: focused editor write did not mint a distinct editor proof (keys: ${editorKeys})`);
+ const editorRecord = [...agent._verifiedTextReplacements.get(tabId).values()]
+ .find(record => record?.focusedKind === 'editor');
+ assert.equal(editorRecord?.ambiguous, false, `${label}: focused editor proof stayed ambiguous`);
+ assert.ok(editorRecord?.readbackSha256, `${label}: focused editor proof lacks a live readback`);
+ // Commit message via the same focused form coexists on a distinct key.
+ const messageResult = label === 'chrome'
+ ? { success: true, verified: true, method: 'cdp-insert-focused', focusedField: { tag: 'INPUT', type: 'text', name: 'commit-message-input', contentEditable: false } }
+ : { success: true, verified: true, fieldMeta: { id: 'commit-message-input', name: 'commit-message-input' } };
+ await agent._finalizeTextMutationResult(tabId, 'type_text', { text: commitMsg, clear: true }, messageResult);
+ const keys = [...(agent._verifiedTextReplacements.get(tabId)?.keys() || [])];
+ assert.ok(keys.some(key => String(key).endsWith(':editor')) && keys.some(key => String(key).endsWith(':commit-message')),
+ `${label}: focused editor and commit-message proofs collided (keys: ${keys})`);
+ const binding = agent._workflowSubmitBindingForAttempt(tabId, pageUrl, {});
+ assert.ok(binding?.githubFileCommit, `${label}: focused proofs did not authorize a commit`);
+ // Pre-submit refresh (focus now elsewhere) must keep focused proofs.
+ await agent._refreshGithubTextReplacementProofs(tabId, pageUrl);
+ assert.ok(agent._workflowSubmitBindingForAttempt(tabId, pageUrl, {})?.githubFileCommit,
+ `${label}: refresh dropped a focused proof after focus moved`);
+ // Same-kind focused append invalidates only its own kind.
+ await agent._finalizeTextMutationResult(tabId, 'type_text', { text: ' typo' }, {
+ success: true, verified: true,
+ ...(label === 'chrome'
+ ? { focusedField: { tag: 'DIV', type: '', name: '', contentEditable: true } }
+ : { fieldMeta: { contentEditable: true, ariaLabelledByText: 'Editing file contents' } }),
+ });
+ const afterKeys = [...(agent._verifiedTextReplacements.get(tabId)?.keys() || [])];
+ assert.ok(!afterKeys.some(key => String(key).endsWith(':editor')),
+ `${label}: focused editor append kept a stale editor proof`);
+ assert.ok(afterKeys.some(key => String(key).endsWith(':commit-message')),
+ `${label}: focused editor append cleared the commit-message proof`);
+ }
+ } finally {
+ if (originalChrome === undefined) delete globalThis.chrome;
+ else globalThis.chrome = originalChrome;
+ if (originalBrowser === undefined) delete globalThis.browser;
+ else globalThis.browser = originalBrowser;
+ }
+});
+
+test('focused field_value_digest and live scope cover selectorless writes', async () => {
+ for (const rel of [
+ 'src/chrome/src/content/content.js',
+ 'src/firefox/src/content/content.js',
+ ]) {
+ const source = fs.readFileSync(path.join(ROOT, rel), 'utf8');
+ assert.match(source, /focused === true/,
+ `${rel}: field_value_digest lost its focused-field proof path`);
+ }
+ const originalChrome = globalThis.chrome;
+ const originalBrowser = globalThis.browser;
+ try {
+ for (const [label, AgentClass, tabId] of [
+ ['chrome', AgentCh, 9484],
+ ['firefox', AgentFx, 9485],
+ ]) {
+ const agent = new AgentClass({});
+ agent._lastAxScopes.set(tabId, { documentToken: 'doc-old', pageUrl: 'https://example.test/form' });
+ await agent._finalizeTextMutationResult(
+ tabId, 'type_text', { selector: '#field', text: 'draft', clear: true },
+ { success: false, dispatched: true, verified: false },
+ );
+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1, `${label}: debt was not recorded`);
+ // Full navigation with no AX read: the cached scope still points at the
+ // old document, but the live probe (empty params for focused) proves it.
+ const tabs = {
+ async sendMessage(_tabId, message) {
+ assert.equal(message.action, 'field_value_digest');
+ return { success: false, documentToken: 'doc-new', refScopeUrl: 'https://other.test/page' };
+ },
+ };
+ globalThis.chrome = { tabs };
+ globalThis.browser = { tabs };
+ const live = await agent._liveTextMutationScope(tabId, 'type_text', { text: 'fresh' });
+ assert.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`);
+ }
+ } finally {
+ if (originalChrome === undefined) delete globalThis.chrome;
+ else globalThis.chrome = originalChrome;
+ if (originalBrowser === undefined) delete globalThis.browser;
+ else globalThis.browser = originalBrowser;
+ }
+});
+
test('Firefox selector debt recovers on exact digest readback', async () => {
const originalChrome = globalThis.chrome;
const originalBrowser = globalThis.browser;