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: recover Bluesky composer verification and editing
Emre Sokullucdf09b83208e
diff --git a/docs/social-publication-contract.md b/docs/social-publication-contract.mdindex 3dea82234..86de214aa 100644--- a/docs/social-publication-contract.md+++ b/docs/social-publication-contract.md@@ -15,12 +15,16 @@ A ready contract is not sufficient permission to dispatch. Before a separate pub## Deterministic enforcement- Preserve exact body and alt text, accepting only NFC equivalence and CRLF normalization. Compose requests bind completion to the audited draft.+- Read ProseMirror paragraph boundaries and hard breaks as document text, excluding its trailing caret placeholder. Field verification, field digests, Chrome CDP verification, and publication snapshots preserve the same spaces and line breaks.- Require complete composer/account/media/context observations and a pre-dispatch permalink baseline. Unassigned or shared thread media makes the observation incomplete.+- Failed preflight reports `publicationValidation.issues`, distinguishing missing account/composer/baseline evidence from body, media, or context mismatches. Body mismatches include lengths and the first differing character position/code points without copying the observed draft into diagnostics.- Verify a new, account-bound permalink with complete authored body and media evidence. Reply, quote, and ordered thread relationships need their own observed proof.- Track each contract action as pending, failed, or verified. Uncertain delivery never unlocks an alternative or fallback, and cannot authorize another publish attempt.- Preserve the contract, authentic clarification pairs, and outcomes only across the existing trusted Continue boundary. A new user task gets a new contract. Clarification after an attempted publication retains its outcomes and blocks further dispatch under the stale instructions; it cannot reset delivery uncertainty or authorize a duplicate.- Preserve bound upload evidence when clarification recompiles an unchanged, unattempted action in the same workflow. Changed action constraints or workflow bindings reset it; every refreshed contract still requires a fresh authorization audit.- Recognize Bluesky desktop composer launchers as non-submitting controls outside forms/dialogs. Actual publish buttons retain the full contract checks.+- Recognize the modal Cancel and Keep editing controls as non-submitting recovery actions, rejecting conflicting publish labels, test IDs, or form ownership.+- A corrected replacement after an uncertain text write can proceed only after a read-only digest proves the original replacement landed in the same document and field. Changed, incomplete, or unavailable readbacks retain the block; generic page reads never clear it.- Convert screenshot clicks to CSS coordinates before target/iframe preflight, and use that same point for dispatch.Malformed output or failed model calls block publication. Schema validation establishes structure, not correct language understanding; the independent audit is also fallible. Missing site evidence blocks dispatch/completion rather than supplying inferred proof.diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 75d886913..5baa7bd88 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -18144,20 +18144,43 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn !!leftIdentity && leftIdentity === rightIdentity;}- _socialSnapshotMatchesAction(action, snapshot) {- if (!snapshot?.complete || snapshot.posts?.length !== action.posts.length || !snapshot.account) return false;+ _socialSnapshotActionIssues(action, snapshot) {+ const issues = [];+ if (!snapshot?.complete) issues.push({ reason: 'composer_incomplete' });+ if (snapshot?.posts?.length !== action.posts.length) issues.push({ reason: 'post_count_mismatch' });const workflow = { adapterName: action.platform };- const account = this._workflowSocialPublicationAccountIdentity(workflow, snapshot.account);- if (!account || (action.account && account !== this._workflowSocialPublicationAccountIdentity(workflow, action.account))) return false;- return action.posts.every((post, i) => {- const observed = snapshot.posts[i];- return typeof observed?.bodyText === 'string'- && observed.bodyText.length <= 25000- && (post.body.kind === 'compose' || exactPublicationText(post.body.value) === exactPublicationText(observed.bodyText))- && publicationMediaMatches(post.media, observed)- && observed.context?.kind === post.context.kind- && (post.context.target === null || this._sameSocialPublicationResource(action.platform, post.context.target, observed.context.target));+ const account = this._workflowSocialPublicationAccountIdentity(workflow, snapshot?.account);+ if (!account) issues.push({ reason: 'account_unobserved' });+ else if (action.account && account !== this._workflowSocialPublicationAccountIdentity(workflow, action.account)) {+ issues.push({ reason: 'account_mismatch' });+ }+ action.posts.forEach((post, postIndex) => {+ const observed = snapshot?.posts?.[postIndex];+ if (typeof observed?.bodyText !== 'string' || observed.bodyText.length > 25000) {+ issues.push({ reason: 'body_unobserved', postIndex });+ } else if (post.body.kind !== 'compose') {+ const expected = exactPublicationText(post.body.value);+ const actual = exactPublicationText(observed.bodyText);+ if (expected !== actual) {+ let offset = 0;+ while (offset < expected.length && offset < actual.length && expected[offset] === actual[offset]) offset++;+ issues.push({ reason: 'body_mismatch', postIndex,+ expectedLength: expected.length, observedLength: actual.length,+ firstDifference: { offset, expectedCodePoint: expected.codePointAt(offset) ?? null,+ observedCodePoint: actual.codePointAt(offset) ?? null } });+ }+ }+ if (!publicationMediaMatches(post.media, observed)) issues.push({ reason: 'media_mismatch', postIndex });+ if (observed?.context?.kind !== post.context.kind+ || (post.context.target !== null && !this._sameSocialPublicationResource(action.platform, post.context.target, observed?.context?.target))) {+ issues.push({ reason: 'context_mismatch', postIndex });+ }});+ return issues;+ }++ _socialSnapshotMatchesAction(action, snapshot) {+ return this._socialSnapshotActionIssues(action, snapshot).length === 0;}async _socialPublicationPreSubmitBlock(tabId, name, args, detected, provider) {@@ -18193,10 +18216,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn blocked(social?.error || 'This publication is not authorized, its prerequisite has not completed, or a previous dispatch still needs verification. Clarify unresolved intent; never repeat an uncertain publication.');}const snapshot = this._socialPublicationSnapshot(guard, detected.publicationSnapshot);- if (!this._socialSnapshotMatchesAction(action, snapshot)- || !Array.isArray(detected.publicationResourceUrls)- || detected.publicationResourceUrlsComplete !== true) {- return blocked('The complete composer, intended account, exact payload, media, context, and pre-publication baseline must be observed before publishing.');+ const issues = this._socialSnapshotActionIssues(action, snapshot);+ if (!Array.isArray(detected.publicationResourceUrls) || detected.publicationResourceUrlsComplete !== true) {+ issues.push({ reason: 'baseline_incomplete' });+ }+ if (issues.length) {+ return { ...blocked('Publication preflight failed: ' + [...new Set(issues.map(issue => issue.reason))].join(', ')+ + '. Resolve publicationValidation before retrying. For body_mismatch, use the exact contract body; preserve every space and line break. A pending text write must first be verified or restored.'),+ publicationValidation: { issues } };}const key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl }));if (social.deniedAuditKey === key) return blocked('This unchanged publication did not pass authorization. Use publicationAudit to resolve the stated issue through clarify; do not rewrite a matching draft or retry another click target.');@@ -22803,7 +22830,23 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}return { identity: '', complete: false };};+ function readProseMirrorText(el) {+ if (!el?.isContentEditable || !el.classList?.contains('ProseMirror')) return null;+ // Paragraphs are document line breaks, not innerText's visual spacing.+ // ProseMirror's final BR is a caret placeholder, not another hard break.+ const read = node => {+ if (node.nodeType === 3) return node.nodeValue || '';+ if (node.nodeType !== 1) return '';+ if (node.tagName === 'BR') return node.classList?.contains('ProseMirror-trailingBreak') ? '' : '\n';+ return Array.from(node.childNodes).map(read).join('');+ };+ const children = Array.from(el.childNodes);+ if (!children.every(node => node.nodeType === 1 && node.tagName === 'P')) return null;+ return children.map(read).join('\n');+ }const publicationEditorText = editor => {+ const semantic = readProseMirrorText(editor);+ if (semantic !== null) return semantic;if (typeof editor.value === 'string') return editor.value;const read = node => {if (node.nodeType === 3) return node.nodeValue || '';@@ -23347,6 +23390,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d))) {return { isSubmit: false, host, url, resolvedNonSubmitTarget: true };}+ // Bluesky's Cancel/Keep editing controls have no test IDs. Resolve+ // the actual modal button, reject conflicting publish labels/markers,+ // and exempt only these reversible composer recovery controls.+ const recoveryControl = target?.closest?.('button,[role="button"]');+ const recoveryModal = recoveryControl?.closest?.('dialog,[role="dialog"],[role="alertdialog"]');+ if (socialPublishAdapterName() === 'bluesky' && recoveryModal+ && ['click', 'click_ax', 'iframe_click'].includes(toolName)+ && !recoveryControl.form && !recoveryControl.closest?.('form')+ && !recoveryControl.hasAttribute?.('data-testid')+ && String(recoveryControl.getAttribute?.('type') || 'button').toLowerCase() === 'button') {+ const labels = [recoveryControl.textContent, recoveryControl.getAttribute?.('aria-label')]+ .map(value => compact(value || '')).filter(Boolean);+ const label = labels[0];+ const composer = recoveryModal.querySelector('textarea,[contenteditable="true"],[role="textbox"]');+ if (labels.length && labels.every(value => value.toLowerCase() === label.toLowerCase())+ && ((/^cancel$/i.test(label) && composer) || /^keep editing$/i.test(label))) {+ return { isSubmit: false, host, url, resolvedNonSubmitTarget: true };+ }+ }if (target && ['click', 'click_ax', 'iframe_click'].includes(toolName)&& target.closest?.('[data-testid="SideNav_NewTweet_Button"],[data-testid="FloatingActionButton"],[data-testid="composeFAB"],[data-testid="addButton"],[data-testid="attachments"],[data-testid="fileInput"],[data-testid="app-bar-back"],[data-testid="closeButton"],button[aria-label="Close"]')) {return { isSubmit: false, host, url, resolvedNonSubmitTarget: true };@@ -25184,6 +25246,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& debt.expectedLength === text.length&& !!expectedSha256&& debt.expectedSha256 === expectedSha256;+ // A correction may differ from the earlier replacement (for example a+ // missing space in an exact publication body). First prove that earlier+ // write landed in this same document/field, using its stored digest. This+ // is a read only check; an unverified or partial value never permits retry.+ if (!sameReplacement && replacement && debt.replacesValue === true+ && !target.ambiguous && debt.key === target.key && debt.documentToken) {+ const original = await this._textMutationValueDigest(tabId, target);+ if (original?.documentToken === debt.documentToken+ && original.valueLength === debt.expectedLength+ && original.valueSha256 === debt.expectedSha256+ && !this._textMutationFieldsProvenDistinct(debt.fieldMeta, original.fieldMeta)) {+ debts.delete(debt.key);+ if (debts.size === 0) this._uncertainTextMutations.delete(tabId);+ return debts.size ? this._uncertainTextMutationBlock(tabId, name, args) : null;+ }+ }// Readback-only recovery requires positive same-field identity. The// readback proves the current target holds the text, but when the debt// belongs to another field (ambiguous locator, or a re-issued AX ref that@@ -25299,7 +25377,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout drecoveryRequired: 'verify_or_restore_field',expectedLength: debt.expectedLength,expectedSha256: debt.expectedSha256,- error: 'Text entry is blocked because an earlier write to this editor may already have changed it. A generic page/tree read cannot prove the full value. Repeat the exact same replacement call once for readback-only recovery, or reload/restore the document before any further write to this editor.',+ recoveryOriginalReplacementMatches: sameReplacement,+ error: 'Text entry is blocked because an earlier write to this editor may already have changed it. A generic page/tree read cannot prove the full value. Repeat the original replacement text and target for readback-only recovery (not the most recent blocked correction), or reload/restore the document before any further write to this editor.',};}@@ -38680,7 +38759,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dverified: false,...(verification?.fieldMeta ? { fieldMeta: verification.fieldMeta } : {}),...(Object.prototype.hasOwnProperty.call(verification || {}, 'actual') ? { actual: verification.actual } : {}),- error: 'The field value still did not exactly match after one trusted Chrome retry. Re-read the accessibility tree before another action.',+ error: 'The field value still did not exactly match after trusted typing. Repeat this exact replacement once for readback-only recovery; a generic tree read cannot verify the full value. Restore the editor if the mismatch persists.',};}diff --git a/src/chrome/src/cdp/cdp-client.js b/src/chrome/src/cdp/cdp-client.jsindex eadfd34f6..29a99dc08 100644--- a/src/chrome/src/cdp/cdp-client.js+++ b/src/chrome/src/cdp/cdp-client.js@@ -6,6 +6,21 @@import { combineImages } from './image-utils.js';+function readProseMirrorText(el) {+ if (!el?.isContentEditable || !el.classList?.contains('ProseMirror')) return null;+ // Paragraphs are document line breaks, not innerText's visual spacing.+ // ProseMirror's final BR is a caret placeholder, not another hard break.+ const read = node => {+ if (node.nodeType === 3) return node.nodeValue || '';+ if (node.nodeType !== 1) return '';+ if (node.tagName === 'BR') return node.classList?.contains('ProseMirror-trailingBreak') ? '' : '\n';+ return Array.from(node.childNodes).map(read).join('');+ };+ const children = Array.from(el.childNodes);+ if (!children.every(node => node.nodeType === 1 && node.tagName === 'P')) return null;+ return children.map(read).join('\n');+}+const FULL_PAGE_SCROLL_SETTLE_MS = 100;const FULL_PAGE_STABLE_PASSES = 2;const FULL_PAGE_MAX_DISCOVERY_STEPS = 100;@@ -4258,7 +4273,8 @@ export class CDPClient {if (!el || el.nodeType !== 1 || !el.isConnected) return null;const tag = String(el.tagName || '').toUpperCase();if (!(el.isContentEditable || ['INPUT', 'TEXTAREA'].includes(tag))) return null;- const value = String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));+ const semantic = (${readProseMirrorText.toString()})(el);+ const value = semantic !== null ? semantic : String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));return (${TEXT_ENTRY_SIGNATURE_SOURCE})(value);}`;if (Number.isInteger(nodeId) && nodeId > 0) {@@ -4308,7 +4324,8 @@ export class CDPClient {if (!el || !el.isConnected) return null;const tag = String(el.tagName || '').toUpperCase();if (!(el.isContentEditable || ['INPUT', 'TEXTAREA'].includes(tag))) return null;- const value = String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));+ const semantic = (${readProseMirrorText.toString()})(el);+ const value = semantic !== null ? semantic : String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));return (${TEXT_ENTRY_SIGNATURE_SOURCE})(value);})()`).catch(() => null);@@ -4351,7 +4368,9 @@ export class CDPClient {const tag = String(el.tagName || '').toUpperCase();const typeable = el.isContentEditable || ['INPUT', 'TEXTAREA'].includes(tag);if (!typeable) return { found: true, verified: false };- const value = String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));+ const semantic = (${readProseMirrorText.toString()})(el);+ if (semantic !== null) expected = expected.replace(/\\r\\n?/g, '\\n');+ const value = semantic !== null ? semantic : String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));const signatureOf = ${TEXT_ENTRY_SIGNATURE_SOURCE};const exactInsertion = () => {if (value.length > ${TEXT_ENTRY_PROOF_MAX_CHARS}) return false;@@ -4405,7 +4424,7 @@ export class CDPClient {const result = await this.evaluate(tabId, `(() => {const selector = ${selectorJSON};- const expected = ${expectedJSON};+ let expected = ${expectedJSON};const shouldClear = ${clear === true};const beforeSignature = ${JSON.stringify(typeof beforeSignature === 'string' ? beforeSignature : '')};const queryDeep = (root) => {@@ -4431,7 +4450,9 @@ export class CDPClient {const tag = String(el.tagName || '').toUpperCase();const typeable = el.isContentEditable || ['INPUT', 'TEXTAREA'].includes(tag);if (!typeable) return { found: true, verified: false };- const value = String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));+ const semantic = (${readProseMirrorText.toString()})(el);+ if (semantic !== null) expected = expected.replace(/\\r\\n?/g, '\\n');+ const value = semantic !== null ? semantic : String(el.isContentEditable ? (el.textContent || '') : (el.value || ''));const signatureOf = ${TEXT_ENTRY_SIGNATURE_SOURCE};const exactInsertion = () => {if (value.length > ${TEXT_ENTRY_PROOF_MAX_CHARS}) return false;diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.jsindex 280486754..007f788e2 100644--- a/src/chrome/src/content/content.js+++ b/src/chrome/src/content/content.js@@ -3969,9 +3969,10 @@return true;}- function _setFieldValueMatches(actual, previous, text, clear, normalizeNewlines = false) {+ function _setFieldValueMatches(actual, previous, text, clear, normalizeNewlines = false, semanticNewlines = false) {const expected = clear ? text : previous + text;if (!normalizeNewlines) return actual === expected;+ if (semanticNewlines) return String(actual).replace(/\r\n?/g, '\n') === String(expected).replace(/\r\n?/g, '\n');if (clear) return _contentEditableValueMatches(actual, expected);const normalize = value => String(value).replace(/\r\n?/g, '\n');const actualText = normalize(actual);@@ -3985,8 +3986,24 @@return _contentEditableValueMatches(`\u0000${actualSuffix}`, `\u0000${text}`);}+ function readProseMirrorText(el) {+ if (!el?.isContentEditable || !el.classList?.contains('ProseMirror')) return null;+ // Paragraphs are document line breaks, not innerText's visual spacing.+ // ProseMirror's final BR is a caret placeholder, not another hard break.+ const read = node => {+ if (node.nodeType === 3) return node.nodeValue || '';+ if (node.nodeType !== 1) return '';+ if (node.tagName === 'BR') return node.classList?.contains('ProseMirror-trailingBreak') ? '' : '\n';+ return Array.from(node.childNodes).map(read).join('');+ };+ const children = Array.from(el.childNodes);+ if (!children.every(node => node.nodeType === 1 && node.tagName === 'P')) return null;+ return children.map(read).join('\n');+ }+function _editableTextValue(el) {- return typeof el.innerText === 'string' ? el.innerText : (el.textContent || '');+ const semantic = readProseMirrorText(el);+ return semantic !== null ? semantic : (typeof el.innerText === 'string' ? el.innerText : (el.textContent || ''));}// Pick the single commit path for set_field({submit:true}). Synthetic@@ -6344,11 +6361,11 @@const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');const verified = selectExpected !== null? actual === selectExpected- : _setFieldValueMatches(actual, previous, text, !!clear, el.isContentEditable);+ : _setFieldValueMatches(actual, previous, text, !!clear, el.isContentEditable, readProseMirrorText(el) !== null);const fallbackAttempted = false;if (!verified) {return failure(- 'The field value did not exactly match the requested text after the page settled. Re-read the field and retry with a fresh ref_id.',+ 'The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{method,ref_id,@@ -6500,7 +6517,7 @@);}const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');- const verified = _setFieldValueMatches(actual, prevValue, text, clear, el.isContentEditable);+ const verified = _setFieldValueMatches(actual, prevValue, text, clear, el.isContentEditable, readProseMirrorText(el) !== null);const fallbackAttempted = false;let nativeSubmitAttempted = false;let submissionOutcomeUnknown = false;@@ -6632,7 +6649,7 @@}if (!verified) {return failure(- 'The field value did not exactly match the requested text after the page settled. Re-read the field and retry with a fresh ref_id.',+ 'The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{method: 'set_field',ref_id,@@ -6735,7 +6752,7 @@expectedPrefix,verifiesAppend ? appendText : expected,!verifiesAppend,- el.isContentEditable,+ el.isContentEditable, readProseMirrorText(el) !== null,),actual: actual.slice(0, 200),fieldMeta: _fieldMeta(el),@@ -6798,7 +6815,7 @@return {success: true,...(typeof expected === 'string' ? {- verified: _setFieldValueMatches(value, '', expected, true, el.isContentEditable),+ verified: _setFieldValueMatches(value, '', expected, true, el.isContentEditable, readProseMirrorText(el) !== null),} : {}),valueLength: value.length,valueSha256,diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 9ed23ceb6..7dbbae3c1 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -15943,20 +15943,43 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn !!leftIdentity && leftIdentity === rightIdentity;}- _socialSnapshotMatchesAction(action, snapshot) {- if (!snapshot?.complete || snapshot.posts?.length !== action.posts.length || !snapshot.account) return false;+ _socialSnapshotActionIssues(action, snapshot) {+ const issues = [];+ if (!snapshot?.complete) issues.push({ reason: 'composer_incomplete' });+ if (snapshot?.posts?.length !== action.posts.length) issues.push({ reason: 'post_count_mismatch' });const workflow = { adapterName: action.platform };- const account = this._workflowSocialPublicationAccountIdentity(workflow, snapshot.account);- if (!account || (action.account && account !== this._workflowSocialPublicationAccountIdentity(workflow, action.account))) return false;- return action.posts.every((post, i) => {- const observed = snapshot.posts[i];- return typeof observed?.bodyText === 'string'- && observed.bodyText.length <= 25000- && (post.body.kind === 'compose' || exactPublicationText(post.body.value) === exactPublicationText(observed.bodyText))- && publicationMediaMatches(post.media, observed)- && observed.context?.kind === post.context.kind- && (post.context.target === null || this._sameSocialPublicationResource(action.platform, post.context.target, observed.context.target));+ const account = this._workflowSocialPublicationAccountIdentity(workflow, snapshot?.account);+ if (!account) issues.push({ reason: 'account_unobserved' });+ else if (action.account && account !== this._workflowSocialPublicationAccountIdentity(workflow, action.account)) {+ issues.push({ reason: 'account_mismatch' });+ }+ action.posts.forEach((post, postIndex) => {+ const observed = snapshot?.posts?.[postIndex];+ if (typeof observed?.bodyText !== 'string' || observed.bodyText.length > 25000) {+ issues.push({ reason: 'body_unobserved', postIndex });+ } else if (post.body.kind !== 'compose') {+ const expected = exactPublicationText(post.body.value);+ const actual = exactPublicationText(observed.bodyText);+ if (expected !== actual) {+ let offset = 0;+ while (offset < expected.length && offset < actual.length && expected[offset] === actual[offset]) offset++;+ issues.push({ reason: 'body_mismatch', postIndex,+ expectedLength: expected.length, observedLength: actual.length,+ firstDifference: { offset, expectedCodePoint: expected.codePointAt(offset) ?? null,+ observedCodePoint: actual.codePointAt(offset) ?? null } });+ }+ }+ if (!publicationMediaMatches(post.media, observed)) issues.push({ reason: 'media_mismatch', postIndex });+ if (observed?.context?.kind !== post.context.kind+ || (post.context.target !== null && !this._sameSocialPublicationResource(action.platform, post.context.target, observed?.context?.target))) {+ issues.push({ reason: 'context_mismatch', postIndex });+ }});+ return issues;+ }++ _socialSnapshotMatchesAction(action, snapshot) {+ return this._socialSnapshotActionIssues(action, snapshot).length === 0;}async _socialPublicationPreSubmitBlock(tabId, name, args, detected, provider) {@@ -15992,10 +16015,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn blocked(social?.error || 'This publication is not authorized, its prerequisite has not completed, or a previous dispatch still needs verification. Clarify unresolved intent; never repeat an uncertain publication.');}const snapshot = this._socialPublicationSnapshot(guard, detected.publicationSnapshot);- if (!this._socialSnapshotMatchesAction(action, snapshot)- || !Array.isArray(detected.publicationResourceUrls)- || detected.publicationResourceUrlsComplete !== true) {- return blocked('The complete composer, intended account, exact payload, media, context, and pre-publication baseline must be observed before publishing.');+ const issues = this._socialSnapshotActionIssues(action, snapshot);+ if (!Array.isArray(detected.publicationResourceUrls) || detected.publicationResourceUrlsComplete !== true) {+ issues.push({ reason: 'baseline_incomplete' });+ }+ if (issues.length) {+ return { ...blocked('Publication preflight failed: ' + [...new Set(issues.map(issue => issue.reason))].join(', ')+ + '. Resolve publicationValidation before retrying. For body_mismatch, use the exact contract body; preserve every space and line break. A pending text write must first be verified or restored.'),+ publicationValidation: { issues } };}const key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl }));if (social.deniedAuditKey === key) return blocked('This unchanged publication did not pass authorization. Use publicationAudit to resolve the stated issue through clarify; do not rewrite a matching draft or retry another click target.');@@ -20462,7 +20489,23 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}return { identity: '', complete: false };};+ function readProseMirrorText(el) {+ if (!el?.isContentEditable || !el.classList?.contains('ProseMirror')) return null;+ // Paragraphs are document line breaks, not innerText's visual spacing.+ // ProseMirror's final BR is a caret placeholder, not another hard break.+ const read = node => {+ if (node.nodeType === 3) return node.nodeValue || '';+ if (node.nodeType !== 1) return '';+ if (node.tagName === 'BR') return node.classList?.contains('ProseMirror-trailingBreak') ? '' : '\n';+ return Array.from(node.childNodes).map(read).join('');+ };+ const children = Array.from(el.childNodes);+ if (!children.every(node => node.nodeType === 1 && node.tagName === 'P')) return null;+ return children.map(read).join('\n');+ }const publicationEditorText = editor => {+ const semantic = readProseMirrorText(editor);+ if (semantic !== null) return semantic;if (typeof editor.value === 'string') return editor.value;const read = node => {if (node.nodeType === 3) return node.nodeValue || '';@@ -20971,6 +21014,25 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d))) {return { isSubmit: false, host, url, resolvedNonSubmitTarget: true };}+ // Bluesky's Cancel/Keep editing controls have no test IDs. Resolve+ // the actual modal button, reject conflicting publish labels/markers,+ // and exempt only these reversible composer recovery controls.+ const recoveryControl = target?.closest?.('button,[role="button"]');+ const recoveryModal = recoveryControl?.closest?.('dialog,[role="dialog"],[role="alertdialog"]');+ if (socialPublishAdapterName() === 'bluesky' && recoveryModal+ && ['click', 'click_ax', 'iframe_click'].includes(toolName)+ && !recoveryControl.form && !recoveryControl.closest?.('form')+ && !recoveryControl.hasAttribute?.('data-testid')+ && String(recoveryControl.getAttribute?.('type') || 'button').toLowerCase() === 'button') {+ const labels = [recoveryControl.textContent, recoveryControl.getAttribute?.('aria-label')]+ .map(value => compact(value || '')).filter(Boolean);+ const label = labels[0];+ const composer = recoveryModal.querySelector('textarea,[contenteditable="true"],[role="textbox"]');+ if (labels.length && labels.every(value => value.toLowerCase() === label.toLowerCase())+ && ((/^cancel$/i.test(label) && composer) || /^keep editing$/i.test(label))) {+ return { isSubmit: false, host, url, resolvedNonSubmitTarget: true };+ }+ }if (target && ['click', 'click_ax', 'iframe_click'].includes(toolName)&& target.closest?.('[data-testid="SideNav_NewTweet_Button"],[data-testid="FloatingActionButton"],[data-testid="composeFAB"],[data-testid="addButton"],[data-testid="attachments"],[data-testid="fileInput"],[data-testid="app-bar-back"],[data-testid="closeButton"],button[aria-label="Close"]')) {return { isSubmit: false, host, url, resolvedNonSubmitTarget: true };@@ -22740,6 +22802,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& debt.expectedLength === text.length&& !!expectedSha256&& debt.expectedSha256 === expectedSha256;+ // A correction may differ from the earlier replacement (for example a+ // missing space in an exact publication body). First prove that earlier+ // write landed in this same document/field, using its stored digest. This+ // is a read only check; an unverified or partial value never permits retry.+ if (!sameReplacement && replacement && debt.replacesValue === true+ && !target.ambiguous && debt.key === target.key && debt.documentToken) {+ const original = await this._textMutationValueDigest(tabId, target);+ if (original?.documentToken === debt.documentToken+ && original.valueLength === debt.expectedLength+ && original.valueSha256 === debt.expectedSha256+ && !this._textMutationFieldsProvenDistinct(debt.fieldMeta, original.fieldMeta)) {+ debts.delete(debt.key);+ if (debts.size === 0) this._uncertainTextMutations.delete(tabId);+ return debts.size ? this._uncertainTextMutationBlock(tabId, name, args) : null;+ }+ }// Readback-only recovery requires positive same-field identity. The// readback proves the current target holds the text, but when the debt// belongs to another field (ambiguous locator, or a re-issued AX ref that@@ -22860,7 +22938,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout drecoveryRequired: 'verify_or_restore_field',expectedLength: debt.expectedLength,expectedSha256: debt.expectedSha256,- error: 'Text entry is blocked because an earlier write to this editor may already have changed it. A generic page/tree read cannot prove the full value. Repeat the exact same replacement call once for readback-only recovery, or reload/restore the document before any further write to this editor.',+ recoveryOriginalReplacementMatches: sameReplacement,+ error: 'Text entry is blocked because an earlier write to this editor may already have changed it. A generic page/tree read cannot prove the full value. Repeat the original replacement text and target for readback-only recovery (not the most recent blocked correction), or reload/restore the document before any further write to this editor.',};}diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.jsindex 56db9c317..e0cfb27d0 100644--- a/src/firefox/src/content/content.js+++ b/src/firefox/src/content/content.js@@ -3250,15 +3250,31 @@const SET_FIELD_VERIFY_DELAY_MS = 80;- function _setFieldValueMatches(actual, previous, text, clear, normalizeNewlines = false) {+ function _setFieldValueMatches(actual, previous, text, clear, normalizeNewlines = false, semanticNewlines = false) {const expected = clear ? text : previous + text;if (!normalizeNewlines) return actual === expected;const normalize = value => String(value).replace(/\r\n?/g, '\n');return normalize(actual) === normalize(expected);}+ function readProseMirrorText(el) {+ if (!el?.isContentEditable || !el.classList?.contains('ProseMirror')) return null;+ // Paragraphs are document line breaks, not innerText's visual spacing.+ // ProseMirror's final BR is a caret placeholder, not another hard break.+ const read = node => {+ if (node.nodeType === 3) return node.nodeValue || '';+ if (node.nodeType !== 1) return '';+ if (node.tagName === 'BR') return node.classList?.contains('ProseMirror-trailingBreak') ? '' : '\n';+ return Array.from(node.childNodes).map(read).join('');+ };+ const children = Array.from(el.childNodes);+ if (!children.every(node => node.nodeType === 1 && node.tagName === 'P')) return null;+ return children.map(read).join('\n');+ }+function _editableTextValue(el) {- return typeof el.innerText === 'string' ? el.innerText : (el.textContent || '');+ const semantic = readProseMirrorText(el);+ return semantic !== null ? semantic : (typeof el.innerText === 'string' ? el.innerText : (el.textContent || ''));}// Synthetic (isTrusted:false) Enter events never trigger native submission —@@ -5451,11 +5467,11 @@const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');const verified = selectExpected !== null? actual === selectExpected- : _setFieldValueMatches(actual, previous, text, !!clear, el.isContentEditable);+ : _setFieldValueMatches(actual, previous, text, !!clear, el.isContentEditable, readProseMirrorText(el) !== null);const fallbackAttempted = false;if (!verified) {return failure(- 'The field value did not exactly match the requested text after the page settled. Re-read the field and retry with a fresh ref_id.',+ 'The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{method,ref_id,@@ -5609,7 +5625,7 @@}const fieldMeta = _fieldMeta(el);const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');- const verified = _setFieldValueMatches(actual, prevValue, text, clear, el.isContentEditable);+ const verified = _setFieldValueMatches(actual, prevValue, text, clear, el.isContentEditable, readProseMirrorText(el) !== null);const fallbackAttempted = false;let nativeSubmitAttempted = false;let submissionOutcomeUnknown = false;@@ -5735,7 +5751,7 @@}if (!verified) {return failure(- 'The field value did not exactly match the requested text after the page settled. Re-read the field and retry with a fresh ref_id.',+ 'The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{method: 'set_field',ref_id,@@ -5788,7 +5804,7 @@expectedPrefix,verifiesAppend ? appendText : expected,!verifiesAppend,- el.isContentEditable,+ el.isContentEditable, readProseMirrorText(el) !== null,),actual: actual.slice(0, 200),fieldMeta: _fieldMeta(el),@@ -5851,7 +5867,7 @@return {success: true,...(typeof expected === 'string' ? {- verified: _setFieldValueMatches(value, '', expected, true, el.isContentEditable),+ verified: _setFieldValueMatches(value, '', expected, true, el.isContentEditable, readProseMirrorText(el) !== null),} : {}),valueLength: value.length,valueSha256,diff --git a/test/run.js b/test/run.jsindex e13d27506..cca506ec6 100644--- a/test/run.js+++ b/test/run.js@@ -76412,7 +76412,7 @@ test('set_field waits for reconciliation and verifies the complete value', () =>const helperStart = source.indexOf(label === 'chrome'? 'function _contentEditableValueMatches(': 'function _setFieldValueMatches(');- const helperEnd = source.indexOf('\n\n function _editableTextValue', helperStart);+ const helperEnd = source.indexOf('\n\n function readProseMirrorText', helperStart);assert.ok(helperStart >= 0 && helperEnd > helperStart, `${label}: exact-value helper should remain independently testable`);const matches = label === 'chrome'? vm.runInNewContext(`(() => { ${source.slice(helperStart, helperEnd)}; return _setFieldValueMatches; })()`)@@ -76424,6 +76424,8 @@ test('set_field waits for reconciliation and verifies the complete value', () =>assert.equal(matches('old-new', 'old-', 'new', false), true, `${label}: exact append should verify`);assert.equal(matches('new', 'old-', 'new', false), false, `${label}: append verification must preserve prior content`);assert.equal(matches('first\nsecond', '', 'first\r\nsecond', true, true), true, `${label}: rich-editor CRLF should match rendered newlines`);+ assert.equal(matches('first\nsecond', '', 'first\r\nsecond', true, true, true), true, `${label}: semantic paragraph readback preserves CRLF equivalence`);+ assert.equal(matches('first\n\n\nsecond', '', 'first\n\nsecond', true, true, true), false, `${label}: semantic paragraph readback must not accept extra document newlines`);assert.equal(matches('first\n\n\nsecond', '', 'first\n\nsecond', true, true), label === 'chrome', `${label}: only Chromium should accept its empty-block readback expansion`);assert.equal(matches('first\n\n\n\n\nsecond', '', 'first\n\n\nsecond', true, true), label === 'chrome', `${label}: only Chromium should accept multiple empty-block expansions`);assert.equal(matches('\n\nfirst', '', '\nfirst', true, true), label === 'chrome', `${label}: only Chromium should accept a leading empty-block expansion`);@@ -76460,8 +76462,8 @@ test('set_field waits for reconciliation and verifies the complete value', () =>const settleIndex = branch.indexOf('await new Promise(resolve => setTimeout(resolve, SET_FIELD_VERIFY_DELAY_MS))');const readbackIndex = branch.search(/(?:const|let) actual = el\.isContentEditable/);assert.ok(settleIndex >= 0 && readbackIndex > settleIndex, `${label}: verification must happen after controlled-input reconciliation`);- assert.match(branch, /(?:const|let) actual = el\.isContentEditable \? _editableTextValue\(el\)/, `${label}: rich-editor verification must use rendered text`);- assert.match(branch, /_setFieldValueMatches\(actual, prevValue, text, clear, el\.isContentEditable\)/, `${label}: newline normalization must remain contenteditable-only`);+ assert.match(branch, /(?:const|let) actual = el\.isContentEditable \? _editableTextValue\(el\)/, `${label}: rich-editor verification must use the editor text reader`);+ assert.match(branch, /_setFieldValueMatches\(actual, prevValue, text, clear, el\.isContentEditable, readProseMirrorText\(el\) !== null\)/, `${label}: visual newline normalization must remain limited to contenteditables without semantic paragraph readback`);assert.match(branch, /await new Promise\(resolve => setTimeout\(resolve, SET_FIELD_VERIFY_DELAY_MS\)\);\s*if \(actionDeadlineExpired\(\)\) return deadlineFailure\(\);/, `${label}: set_field can continue after its verification wait expires`);assert.match(branch, /if \(usesNativeSubmit\)[\s\S]*if \(actionDeadlineExpired\(\)\) return deadlineFailure\(\);\s*submissionDispatched = true;\s*try \{\s*form\.requestSubmit\(\)/, `${label}: native set_field submission is not guarded at the mutation boundary`);assert.match(branch, /await new Promise\(r => setTimeout\(r, 80\)\);\s*if \(actionDeadlineExpired\(\)\) return deadlineFailure\(\);[\s\S]*await new Promise\(r => setTimeout\(r, 30\)\);\s*if \(actionDeadlineExpired\(\)\) return deadlineFailure\(\);[\s\S]*if \(actionDeadlineExpired\(\)\) return deadlineFailure\(\);\s*const enterResult = dispatchKeySequence\('Enter', 13, true\);\s*submissionDispatched = enterResult\.dispatched;\s*if \(!enterResult\.completedWithinDeadline\)/, `${label}: page-owned set_field submission can resume after its deadline`);diff --git a/test/social-publish-contract-dom.mjs b/test/social-publish-contract-dom.mjsindex f9d94f874..41d78295c 100644--- a/test/social-publish-contract-dom.mjs+++ b/test/social-publish-contract-dom.mjs@@ -66,6 +66,69 @@ try {}await clickPage.close();+ // Bluesky uses ProseMirror paragraphs. Verify the actual content-script+ // readback, digest, CDP paths and publication probe against the same DOM.+ const editorPage = await context.newPage();+ await editorPage.goto('https://bsky.app/');+ await editorPage.evaluate(() => {+ window.fieldListeners = [];+ window.chrome = {runtime:{sendMessage:()=>{},onMessage:{addListener:fn=>window.fieldListeners.push(fn)}}};+ window.browser = window.chrome;+ window.__wb_ax_lookup = () => document.querySelector('.ProseMirror');+ });+ await editorPage.addScriptTag({content:fs.readFileSync(`src/${build}/src/content/content.js`,'utf8')});+ const readField = (action, params) => editorPage.evaluate(({action,params}) => new Promise(resolve => {+ for (const listener of window.fieldListeners) listener({target:'content',action,params},{},resolve);+ }), {action,params});+ const announcement = 'WebBrain 35.0.0 is coming with a lot of fixes.\n\nCheck out the changelog: https://github.com/webbrain-one/webbrain/blob/main/CHANGELOG.md';+ const escape = text => text.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');+ const paragraphs = text => text.split('\n').map(line => `<p>${line ? escape(line) : '<br class="ProseMirror-trailingBreak">'}</p>`).join('');+ const editorCases = [+ [announcement, paragraphs(announcement)],+ [' Leading \n\nline \n', paragraphs(' Leading \n\nline \n')],+ ['a\nb', '<p>a<br>b</p>'],+ ['a\n', '<p>a<br><br class="ProseMirror-trailingBreak"></p>'],+ ['', '<p><br class="ProseMirror-trailingBreak"></p>'],+ ];+ const {cdpClient} = build === 'chrome' ? await import('../src/chrome/src/cdp/cdp-client.js') : {};+ const oldEvaluate = cdpClient?.evaluate;+ if (cdpClient) cdpClient.evaluate = async (_tab, code) => ({result:{value:await editorPage.evaluate(code => eval(code),code)}});+ try {+ for (const [expected,html] of editorCases) {+ await editorPage.setContent(`<nav><a href="/profile/alice.bsky.social">Profile</a></nav><div role="dialog"><div class="ProseMirror" contenteditable="true" style="white-space:pre-wrap">${html}</div><button id="publish" type="button" data-testid="composerPublishBtn">Post</button></div>`);+ const verification = await readField('ax_verify_field_value',{ref_id:'editor',expected});+ assert.equal(verification.verified,true,`${build}: semantic exact readback ${JSON.stringify(expected)}`);+ assert.equal(verification.actual,expected);+ assert.equal((await readField('ax_verify_field_value',{ref_id:'editor',expected:expected.replace(/\n/g,'\r\n')})).verified,true,'CRLF remains canonically equivalent');+ const wrong = await readField('ax_verify_field_value',{ref_id:'editor',expected:expected+' '});+ assert.equal(wrong.verified,false,'a missing space cannot be normalized away');+ const digest = await readField('field_value_digest',{ref_id:'editor',expected});+ assert.equal(digest.verified,true);+ assert.equal(digest.valueLength,expected.length);+ const {createHash} = await import('node:crypto');+ assert.equal(digest.valueSha256,createHash('sha256').update(expected).digest('hex'));+ const detected = await editorPage.evaluate(source => Function('return ('+source+')')()('click',{selector:'#publish'}),Agent._submitActionProbe.toString());+ assert.equal(detected.publicationSnapshot.posts[0].bodyText,expected,'preflight must read the same text as typing');+ if (cdpClient) {+ assert.equal(await cdpClient.verifyTextEntry(1,{selector:'.ProseMirror',text:expected,clear:true}),true);+ assert.equal(await cdpClient.verifyTextEntry(1,{selector:'.ProseMirror',text:expected.replace(/\n/g,'\r\n'),clear:true}),true);+ assert.equal(await cdpClient.verifyTextEntry(1,{selector:'.ProseMirror',text:expected+' ',clear:true}),null);+ const signature = await cdpClient.textEntrySignature(1,{selector:'.ProseMirror'});+ await editorPage.locator('.ProseMirror p').last().evaluate(el => el.append(' suffix'));+ assert.equal(await cdpClient.verifyTextEntry(1,{selector:'.ProseMirror',text:' suffix',beforeSignature:signature}),true);+ }+ checked++;+ }+ // Actual hard breaks must not receive innerText's expanded-newline+ // tolerance: these are two document line breaks, not three.+ await editorPage.setContent('<div class="ProseMirror" contenteditable="true"><p>a</p><p><br class="ProseMirror-trailingBreak"></p><p>b</p></div>');+ assert.equal((await readField('ax_verify_field_value',{ref_id:'editor',expected:'a\n\n\nb'})).verified,false);+ checked++;+ } finally {+ if (cdpClient) cdpClient.evaluate = oldEvaluate;+ await editorPage.close();+ }+const probe=async(selector='#publish')=>page.evaluate(({source,selector})=>{const fn=Function('return ('+source+')')();return fn('click',{selector});@@ -105,6 +168,28 @@ try {}}if (platform === 'bluesky') {+ for (const label of ['Cancel','Keep editing']) {+ const composer = '<div role="dialog"><div contenteditable="true">Draft</div><button data-testid="composerPublishBtn">Post</button>CONTROL</div>';+ const button = `<button id="recover" type="button" aria-label="${label}"><span>${label}</span></button>`;+ for (const nested of [false,true]) {+ await page.setContent(composer.replace('CONTROL',nested ? `<div role="alertdialog">${button}</div>` : button));+ if (label === 'Cancel' && nested) continue;+ await page.evaluate(() => { window.__wb_ax_lookup = () => document.querySelector('#recover span'); });+ for (const [name,args] of [['click_ax',{ref_id:'recover'}],['click',{text:label,textMatch:'exact'}],['click',{selector:'#recover span'}]]) {+ const detected = await scopeAgent._detectLikelySubmitAction(scopeTab,name,args);+ assert.equal(detected?.resolvedNonSubmitTarget,true,`${build}: ${label}/${name}`);+ assert.equal(await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,name,args,detected,providerScope),null);+ checked++;+ }+ }+ for (const attrs of ['data-testid="composerPublishBtn"','data-testid="unknown"','aria-label="Publish post"','type="submit"']) {+ await page.setContent(composer.replace('CONTROL',`<button id="recover" ${attrs}>${label}</button>`));+ const detected = await scopeAgent._detectLikelySubmitAction(scopeTab,'click',{selector:'#recover'});+ assert.notEqual(detected?.resolvedNonSubmitTarget,true,'conflicting publish/form identity must remain guarded');+ assert((await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,'click',{selector:'#recover'},detected,providerScope)).noDispatch);+ checked++;+ }+ }for (const html of ['<button id="launch" type="button" aria-label="Publish post">Post</button>','<div role="dialog"><button id="launch" type="button" aria-label="Compose new post">New Post</button></div>',diff --git a/test/social-publish-contract.mjs b/test/social-publish-contract.mjsindex 5bc7a5941..5579be0b5 100644--- a/test/social-publish-contract.mjs+++ b/test/social-publish-contract.mjs@@ -203,6 +203,60 @@ for (const browser of ['chrome', 'firefox']) {}});+ test(`${browser}: Bluesky exact-body mismatch identifies the missing space and gates the audit`, async () => {+ const typed = 'WebBrain 35.0.0 is coming with a lot of fixes.\n\nCheck out the changelog: https://github.com/webbrain-one/webbrain/blob/main/CHANGELOG.md';+ const body = typed.replace('.\n\n', '. \n\n');+ const f = setup('Post '+body+' on Bluesky',rawContract([rawAction('p1','bluesky',body)]));+ f.agent._currentUrl = async () => 'https://bsky.app/';+ f.detected.publicationSnapshot = snapshot(typed,'bluesky:alice.bsky.social');+ const blocked = await f.agent._workflowPreSubmitDispatchBlock(f.tabId,'click_ax',{ref_id:'publish'},f.detected,f.provider);+ assert.equal(blocked.noDispatch,true);+ assert.deepEqual(blocked.publicationValidation.issues,[{reason:'body_mismatch',postIndex:0,+ expectedLength:137,observedLength:136,firstDifference:{offset:46,expectedCodePoint:32,observedCodePoint:10}}]);+ assert.equal(f.calls.some(c=>c.meta.generationName==='social_publication_authorization'),false);+ f.detected.publicationSnapshot.posts[0].bodyText = body;+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId,'click_ax',{ref_id:'publish'},f.detected,f.provider),null);+ assert.equal(f.calls.filter(c=>c.meta.generationName==='social_publication_authorization').length,1);+ const missing = f.agent._socialSnapshotActionIssues(f.guard.socialPublication.contract.actions[0],null);+ assert(missing.some(issue=>issue.reason==='account_unobserved'));+ assert(missing.some(issue=>issue.reason==='composer_incomplete'));+ });++ test(`${browser}: changed replacement settles the original write by exact same-document digest`, async () => {+ for (const mode of ['exact','partial','wrong-document','wrong-target','append','second-debt','no-digest']) {+ const f = setup();+ const {agent,tabId} = f;+ const original = 'Original\n\nbody';+ const args = {ref_id:'editor',text:original,clear:true};+ agent._lastAxScopes.set(tabId,{documentToken:'doc',pageUrl:'https://bsky.app/'});+ agent._adoptLiveTextMutationScope = async () => null;+ const target = agent._textMutationTarget(tabId,'set_field',args);+ const debt = {...target,replacesValue:true,expectedLength:original.length,+ expectedSha256:await agent._sha256Text(original),fieldMeta:{contentEditable:true},recordedAt:Date.now()};+ agent._uncertainTextMutations.set(tabId,new Map([[target.key,debt]]));+ if (mode === 'second-debt') agent._uncertainTextMutations.get(tabId).set('other',{...debt,key:'other'});+ const probes = [];+ agent._textMutationValueDigest = async (_tab,probeTarget) => {+ probes.push(probeTarget.key);+ return mode === 'no-digest' ? null : {documentToken:mode==='wrong-document'?'stale':'doc',+ valueLength:original.length,valueSha256:mode==='partial'?'0'.repeat(64):debt.expectedSha256,+ fieldMeta:{contentEditable:true}};+ };+ const correction = {ref_id:mode==='wrong-target'?'other':'editor',text:'Original \n\nbody',clear:mode!=='append'};+ const result = await agent._uncertainTextMutationBlock(tabId,'type_ax',correction);+ if (mode === 'exact') {+ assert.equal(result,null,'verified original allows a subsequent replacement');+ assert.equal(agent._uncertainTextMutations.has(tabId),false);+ assert.deepEqual(probes,[target.key]);+ } else {+ assert.equal(result.noDispatch,true,mode);+ assert.equal(result.recoveryRequired,'verify_or_restore_field',mode);+ assert.equal(result.recoveryOriginalReplacementMatches,false,mode);+ assert(agent._uncertainTextMutations.get(tabId).size>0,mode);+ }+ }+ });+async function clarify(f, question, answer, source = 'option', beforeReply = () => {}) {f.agent._persistNow = async () => {};f.agent.clarifyTimeoutSec = -1;