Skip to content

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

Fix shared composer ownership and trusted text recovery

Barack Sokulluce13cfb91df8
diff --git a/docs/accessibility-tree-and-refs.md b/docs/accessibility-tree-and-refs.md
index 13d7d2b9a..51cd60812 100644
--- a/docs/accessibility-tree-and-refs.md
+++ b/docs/accessibility-tree-and-refs.md
@@ -155,10 +155,13 @@ No finite observation window can prove application-internal state that produces
### `type_ax({ref_id, text, clear})`
-1. Resolves `ref_id`
-2. Uses `Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, value)` to bypass React/Vue controlled-component wrappers
-3. Dispatches `input` + `change` events
-4. For contenteditable: sets `textContent` + dispatches `beforeinput` + `input`
+The handler resolves the original `ref_id`, prepares that exact editor and verifies
+the resulting text. Native input fields use the prototype value setter plus input
+events where supported. Model-managed rich-text editors use their supported input
+transport instead of replacing their rendered DOM; Chrome uses trusted browser
+input and Firefox uses trusted automation when enabled. DraftJS multiline input
+uses a single public plain-text paste. See [rich-text input](rich-text-input.md)
+for editor detection, frame ownership and exact full-document readback.
Rejects non-typeable input types (checkbox, radio, submit, file) with a clear error.
diff --git a/docs/rich-text-input.md b/docs/rich-text-input.md
index c7cdb664c..1c902ca61 100644
--- a/docs/rich-text-input.md
+++ b/docs/rich-text-input.md
@@ -25,8 +25,22 @@ the internal AX paste route shares `type_ax` input ownership.
Firefox trusted automation uses the same strict DraftJS and ProseMirror document
readers before and after input, including empty caret placeholders and paragraph
-boundaries. Without a supported transport, WebBrain leaves the draft intact and
-explains how to enable trusted automation.
+boundaries. ProseMirror text uses one public plain-text paste into the pinned
+selection, so a replacement does not briefly clear the draft and disable sibling
+controls before inserting its new value. Empty clears use one native deletion.
+The original editor, document, root, selection and task fences remain required.
+Without a supported transport, WebBrain leaves the draft intact and explains how
+to enable trusted automation. Chrome canonicalizes CRLF and CR to LF before its
+single native insertion, preventing carriage returns from becoming extra spaces.
+
+When the browser blocks Enter after verifying a draft, that draft proof is
+retained separately from submission. A pending chat send still requires fresh
+observation and its existing reconciliation flow before another mutation; the
+typed value alone cannot certify delivery or authorize an automatic resend.
+Explicit Chrome native-chat clears retain an empty-caret receipt only after
+both the trusted browser delete and a private content receipt certify the same
+editor, document and conversation. Synthetic input, changed ownership and
+authored or generic line-break nodes cannot grant that empty state.
Regression tests use the actual React/DraftJS libraries and compare application
EditorState, rendered document blocks and saved POST data. They cover replacement,
@@ -34,8 +48,40 @@ append, clear, multiline text, Unicode, literal markup, iframe ownership and los
responses. Additional fixtures check that managed editors cannot reach legacy DOM
setters and that ordinary editors preserve their exact text and formatting.
+Input transport and action ownership are separate checks. A visible editor can
+still be rejected before typing if its surrounding composer has no verified
+owner. X's inline home composer exposed this second gap: it has no form or dialog,
+and binding the whole home timeline would make unrelated feed updates invalidate
+every action. WebBrain instead binds the local native editor, publishing control,
+audience and matching local/navigation account links. It observes those identities
+before a decision and rechecks them before dispatch; feed counters stay outside
+the composer. Focus that reveals new audience controls requires a fresh observation.
+
+The shared ownership check also supports explicitly named forms, sections and
+regions without a heading, using complete local label and control coverage.
+Bounded owners bind visible image resources as well as text and controls,
+so an unnamed account avatar can change neither silently nor outside observation.
+Those images are exposed as value-free visual inventory; their sources stay in
+the private comparison. An arbitrary toolbar or unnamed container does not gain
+an owner merely because it contains an editor.
+
+Bluesky regression fixtures use real ProseMirror EditorView/EditorState and the
+composer schema, clipboard parser, placeholder and native controls from
+social-app commit `46d98dd457a197cee8502863b420222508f29fa6`. They compare the
+application document and saved request with exact replacement, append, multiline,
+Windows line endings, Unicode, whitespace and empty-clear requests in both
+browsers. They cover a dialog and generic named form, region, section and headed
+main boundaries. Installed Chrome extension tests also run the complete X and
+Bluesky typing, local publication and fresh completion-proof flow. These are
+owned local fixtures; no live account is used or posted to.
+
+When context verification or repeated page changes prevent the next action,
+the task shows a specific explanation and Give up / Retry choices. Retry keeps
+completed progress and verifies the current page again using the normal checks.
+
Run the focused suite with:
```sh
node --test test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/draftjs-text.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/contenteditable-beforeinput.mjs
+npm run test:composer-context
```
diff --git a/firefox-companion/session.mjs b/firefox-companion/session.mjs
index 3393d65e0..cdf493149 100644
--- a/firefox-companion/session.mjs
+++ b/firefox-companion/session.mjs
@@ -2,20 +2,42 @@ import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, basename } from 'node:path';
-// Keep these document readers equivalent to the content/CDP readers. A rendered
-// prefix cannot certify an unsupported DraftJS document, and paragraph spacing
+// A rendered prefix cannot certify an unsupported rich-text document, and paragraph spacing
// in innerText is not the document's authored line breaks.
function readProseMirrorText(el) {
if (!el?.isContentEditable || !el.classList?.contains('ProseMirror')) return null;
- const read = node => {
+ let visited = 0;
+ const supported = node => {
+ if (++visited > 4096 || node.shadowRoot || node.hidden
+ || String(node.getAttribute('aria-hidden') || '').trim().toLowerCase() === 'true'
+ || String(node.getAttribute('contenteditable') || '').trim().toLowerCase() === 'false') return false;
+ const style = node.ownerDocument?.defaultView?.getComputedStyle?.(node);
+ return !!style && style.display !== 'none' && !['hidden', 'collapse'].includes(style.visibility)
+ && style.opacity !== '0' && style.contentVisibility !== 'hidden';
+ };
+ if (!supported(el)) return null;
+ const read = (node, depth = 0) => {
+ if (depth > 32) return null;
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('');
+ if (node.nodeType !== 1 || !supported(node)) return null;
+ if (node.tagName === 'BR') {
+ if (node.childNodes.length) return null;
+ if (!node.classList.contains('ProseMirror-trailingBreak')) return '\n';
+ return node.parentNode?.tagName === 'P' && !node.nextSibling ? '' : null;
+ }
+ // Text marks may wrap authored text. Embedded/node-view content has no
+ // complete plain-text receipt, so it must never collapse to a visible prefix.
+ if (!['SPAN', 'STRONG', 'EM', 'B', 'I', 'U', 'S', 'DEL', 'CODE', 'A'].includes(node.tagName)) return null;
+ const values = Array.from(node.childNodes).map(child => read(child, depth + 1));
+ return values.some(value => value === null) ? null : values.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');
+ if (!children.length || !children.every(node => node.nodeType === 1 && node.tagName === 'P' && supported(node))) return null;
+ const paragraphs = children.map(node => {
+ const values = Array.from(node.childNodes).map(child => read(child));
+ return values.some(value => value === null) ? null : values.join('');
+ });
+ return paragraphs.some(value => value === null) ? null : paragraphs.join('\n');
}
function isDraftJsEditor(el) {
@@ -74,11 +96,26 @@ function readDraftJsText(el) {
function readRichTextFieldValue(el, semanticKind = '') {
if (!el?.isConnected) return null;
const draftJs = semanticKind === 'draftjs' || isDraftJsEditor(el);
+ const proseMirror = semanticKind === 'prosemirror' || el.classList?.contains('ProseMirror');
const semantic = draftJs ? readDraftJsText(el) : readProseMirrorText(el);
- if ((draftJs || semanticKind === 'prosemirror') && semantic === null) return null;
+ if ((draftJs || proseMirror) && semantic === null) return null;
return semantic !== null ? semantic : (el.isContentEditable ? el.innerText : el.value);
}
+function proseMirrorSelectionMatches(el, bound) {
+ if (!bound || el !== bound.editor || !el.isConnected || el.disabled
+ || el.ownerDocument !== bound.document || el.getRootNode() !== bound.root
+ || bound.root.activeElement !== el || readProseMirrorText(el) !== bound.before
+ || el.childNodes.length !== bound.paragraphs.length
+ || bound.paragraphs.some((node, index) => el.childNodes[index] !== node)
+ || !el.contains(bound.startNode) || !el.contains(bound.endNode)) return false;
+ const selection = bound.document.defaultView.getSelection();
+ if (!selection || selection.rangeCount !== 1) return false;
+ const range = selection.getRangeAt(0);
+ return range.startContainer === bound.startNode && range.startOffset === bound.startOffset
+ && range.endContainer === bound.endNode && range.endOffset === bound.endOffset;
+}
+
const FIELD_TEXT_READBACK_SOURCE = [readProseMirrorText, isDraftJsEditor, readDraftJsText, readRichTextFieldValue]
.map(fn => fn.toString()).join('\n');
@@ -268,9 +305,10 @@ export class BidiSession {
await this.call(match, '(el, token) => { if (el.getAttribute("data-webbrain-bidi") === token) el.removeAttribute("data-webbrain-bidi"); }', [{ type: 'string', value: token }]).catch(() => {});
}
}
- call(match, functionDeclaration, args = []) {
+ call(match, functionDeclaration, args = [], resultOwnership = null) {
return this.send('script.callFunction', { target: { context: match.context }, functionDeclaration,
- arguments: [{ sharedId: match.node.sharedId }, ...args], awaitPromise: true });
+ arguments: [{ sharedId: match.node.sharedId }, ...args], awaitPromise: true,
+ ...(resultOwnership ? { resultOwnership } : {}) });
}
async _waitForCheckableState(match, desiredChecked, timeoutMs = 80) {
const result = await this.call(match, `async (el, desired, timeout) => {
@@ -326,7 +364,7 @@ export class BidiSession {
return {};
}
async perform(id, action, payload, validatePageDispatch = null) {
- const dispatch = { started: false };
+ const dispatch = { started: false, ownedHandles: [] };
try { return await this.performAction(id, action, payload, dispatch, validatePageDispatch); }
catch (error) {
error.dispatchState = { dispatched: dispatch.started, noDispatch: !dispatch.started,
@@ -334,6 +372,10 @@ export class BidiSession {
...(error.code === 'page_feedback_pending' ? { pageFeedbackPending: true } : {}) };
throw error;
}
+ finally {
+ for (const { context, handle } of dispatch.ownedHandles)
+ await this.send('script.disown', { target: { context }, handles: [handle] }).catch(() => {});
+ }
}
async performAction(id, action, payload, dispatch, validatePageDispatch = null) {
if (!['navigate', 'click', 'hover', 'type', 'field', 'key', 'upload'].includes(action)) throw new Error('Unsupported BiDi action');
@@ -501,6 +543,7 @@ export class BidiSession {
const beforeReadback = typing ? unpackRemoteObjectValue(before.result?.type ? before.result : before.result?.value) : null;
const beforeSnapshot = beforeReadback && typeof beforeReadback === 'object' && Object.hasOwn(beforeReadback, 'value')
? beforeReadback : { value: before?.result?.value, semanticKind: '' };
+ let proseMirrorBinding = null;
const assertFocus = async () => {
assertLive();
const focused = await this.call(match, '(el) => el.isConnected && !el.disabled && el.getRootNode().activeElement === el');
@@ -585,103 +628,179 @@ export class BidiSession {
const multiline = await this.call(match, '(el) => el.tagName === "TEXTAREA" || el.isContentEditable');
if (multiline.result?.value !== true) throw new Error('Newlines require a multiline editor; no text sent');
}
- if (clear) {
- const platform = await this.call(match, '() => navigator.platform');
- await press('a', /Mac/.test(platform.result?.value || '') ? '\uE03D' : '\uE009');
- await press('\uE003');
- if (beforeSnapshot.semanticKind === 'draftjs') {
- const cleared = await this.call(match, `(el) => {
- ${FIELD_TEXT_READBACK_SOURCE}
- return readRichTextFieldValue(el, 'draftjs') === '';
- }`);
- if (cleared.result?.value !== true) throw new Error('DraftJS clearing did not establish an empty document; no further text sent');
- }
- } else {
- const positioned = await this.call(match, `(el) => {
- if (!el.isConnected || el.getRootNode().activeElement !== el) return false;
- if (el.isContentEditable) {
- const selection = getSelection(); const range = document.createRange();
- let container = el;
- while (container.lastChild?.nodeType === 1 && container.lastChild.isContentEditable
- && container.lastChild.nodeName !== 'BR') container = container.lastChild;
- range.selectNodeContents(container); range.collapse(false);
- selection.removeAllRanges(); selection.addRange(range);
- } else if (typeof el.setSelectionRange === 'function') {
- const end = el.value.length; el.setSelectionRange(end, end);
- } else return false;
- return true;
- }`);
- if (positioned.result?.value !== true) throw new Error('Could not position caret for append; no text sent');
- }
- if (beforeSnapshot.semanticKind === 'draftjs' && /[\r\n]/.test(payload.text)) {
- // DraftJS treats literal LF editing commands inconsistently. Its public paste
- // handler accepts a whole plain-text document without using a submit shortcut.
- const positioned = await this.call(match, `(el, clear) => {
- if (!el.isConnected || el.getRootNode().activeElement !== el) return false;
- const leaves = el.querySelectorAll('[data-text="true"]');
- const leaf = leaves[clear ? 0 : leaves.length - 1];
- if (!leaf) return false;
- const range = el.ownerDocument.createRange();
- if (leaf.nodeName === 'BR') range.setStartBefore(leaf);
- else {
- const text = clear ? leaf.firstChild : leaf.lastChild;
- if (text?.nodeType !== 3) return false;
- range.setStart(text, clear ? 0 : text.nodeValue.length);
- }
- range.collapse(true);
- const selection = el.ownerDocument.defaultView.getSelection();
+ if (beforeSnapshot.semanticKind === 'prosemirror') {
+ // A whole public paste avoids intermediate deletion/character updates to
+ // composer peers, and preserves literal LFs through the editor's parser.
+ // Remote ownership keeps these DOM identities private to this operation.
+ const positioned = await this.call(match, `(el, clear, before) => {
+ ${FIELD_TEXT_READBACK_SOURCE}
+ if (!el.isConnected || el.getRootNode().activeElement !== el
+ || readProseMirrorText(el) !== before) return null;
+ const document = el.ownerDocument;
+ const paragraphs = Array.from(el.childNodes);
+ const edge = (paragraph, end) => {
+ let node = end ? paragraph.lastChild : paragraph.firstChild;
+ if (end && node?.nodeName === 'BR' && node.classList.contains('ProseMirror-trailingBreak')) node = node.previousSibling;
+ if (!node) return [paragraph, 0];
+ while (node.nodeType === 1 && node.nodeName !== 'BR' && node.childNodes.length)
+ node = end ? node.lastChild : node.firstChild;
+ if (node.nodeType === 3) return [node, end ? node.nodeValue.length : 0];
+ if (node.nodeName === 'BR') return [node.parentNode, Array.from(node.parentNode.childNodes).indexOf(node) + (end ? 1 : 0)];
+ return [node, 0];
+ };
+ const [endNode, endOffset] = edge(paragraphs[paragraphs.length - 1], true);
+ const [startNode, startOffset] = clear ? edge(paragraphs[0], false) : [endNode, endOffset];
+ const range = document.createRange();
+ range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset);
+ const selection = document.defaultView.getSelection();
selection.removeAllRanges(); selection.addRange(range);
- return true;
- }`, [{ type: 'boolean', value: clear }]);
- if (positioned.result?.value !== true) throw new Error('Could not position the DraftJS caret; no further text sent');
- // Let the browser's selectionchange reach the framework before the paste.
+ return { editor: el, document, root: el.getRootNode(), paragraphs, before,
+ startNode, startOffset, endNode, endOffset };
+ }`, [{ type: 'boolean', value: clear }, { type: 'string', value: String(beforeSnapshot.value || '') }], 'root');
+ const binding = positioned.result?.handle;
+ if (!binding) throw new Error('Could not position the ProseMirror selection; no text sent');
+ proseMirrorBinding = binding;
+ (dispatch.ownedHandles ||= []).push({ context: match.context, handle: binding });
+ // Public selectionchange must reach the framework before it reads paste.
await new Promise(resolve => setTimeout(resolve, 30));
await assertFocus();
- const marker = await markNativeDispatch('input', { domDispatch: true });
- try {
- dispatch.started = true;
- const pasted = await this.call(match, `(el, text, guardJson) => {
- ${FIELD_TEXT_READBACK_SOURCE}
- if (!el.isConnected || el.getRootNode().activeElement !== el || readDraftJsText(el) === null) return false;
- const view = el.ownerDocument.defaultView;
- const data = new view.DataTransfer(); data.setData('text/plain', text);
- const event = new view.ClipboardEvent('paste', { bubbles: true, cancelable: true, composed: true, clipboardData: data });
- // Firefox drops the constructor's clipboardData. Preserve the public
- // plain-text payload without reading or writing the OS clipboard.
- if (event.clipboardData?.getData('text/plain') !== text)
- Object.defineProperty(event, 'clipboardData', { value: data });
- const guard = JSON.parse(guardJson);
- if (guard && !el.dispatchEvent(new view.CustomEvent('webbrain-agent-dom-dispatch', {
- detail: JSON.stringify({ ...guard, dispatchPhase: 'input' }), bubbles: true, composed: true, cancelable: true,
- }))) return false;
- el.dispatchEvent(event);
- // Cancellation can mean the framework consumed the paste. Only the
- // settled exact document readback below establishes its outcome.
- return true;
- }`, [{ type: 'string', value: payload.text.replace(/\r\n?/g, '\n') },
- { type: 'string', value: JSON.stringify(payload.pageFeedbackGuard || null) }]);
- if (pasted.result?.value !== true) throw new Error('DraftJS paste dispatch could not be established; inspect before another write');
- } finally { await clearNativeDispatch(marker); }
- assertLive();
+ const selected = await this.call(match, `(el, bound) => {
+ ${FIELD_TEXT_READBACK_SOURCE}
+ ${proseMirrorSelectionMatches.toString()}
+ return proseMirrorSelectionMatches(el, bound);
+ }`, [{ handle: binding }]);
+ if (selected.result?.value !== true) throw new Error('The ProseMirror document or selection changed; no text sent');
+ if (payload.text === '') {
+ // ProseMirror does not consume an empty clipboard. A single native
+ // deletion of the pinned whole-document selection needs no follow-up edit.
+ if (clear && beforeSnapshot.value !== '') await press('\uE003');
+ } else {
+ const marker = await markNativeDispatch('input', { domDispatch: true });
+ try {
+ dispatch.started = true;
+ const pasted = await this.call(match, `(el, bound, text, guardJson) => {
+ ${FIELD_TEXT_READBACK_SOURCE}
+ ${proseMirrorSelectionMatches.toString()}
+ if (!proseMirrorSelectionMatches(el, bound)) return false;
+ const view = bound.document.defaultView;
+ const data = new view.DataTransfer(); data.setData('text/plain', text);
+ const event = new view.ClipboardEvent('paste', { bubbles: true, cancelable: true, composed: true, clipboardData: data });
+ if (event.clipboardData?.getData('text/plain') !== text)
+ Object.defineProperty(event, 'clipboardData', { value: data });
+ const guard = JSON.parse(guardJson);
+ if (guard && !el.dispatchEvent(new view.CustomEvent('webbrain-agent-dom-dispatch', {
+ detail: JSON.stringify({ ...guard, dispatchPhase: 'input' }), bubbles: true, composed: true, cancelable: true,
+ }))) return false;
+ // The phase event can run page listeners; recheck the exact
+ // editor and range before sending any clipboard content.
+ if (!proseMirrorSelectionMatches(el, bound)) return false;
+ el.dispatchEvent(event);
+ return true;
+ }`, [{ handle: binding }, { type: 'string', value: payload.text.replace(/\r\n?/g, '\n') },
+ { type: 'string', value: JSON.stringify(payload.pageFeedbackGuard || null) }]);
+ if (pasted.result?.value !== true) throw new Error('ProseMirror paste dispatch could not be established; inspect before another write');
+ } finally { await clearNativeDispatch(marker); }
+ assertLive();
+ }
} else {
- // One character per dispatch bounds work after Stop and catches focus changes between keys.
- for (const char of payload.text.replace(/\r\n?/g, '\n')) {
- if (char === '\n' || char === '\r') {
- await assertFocus();
- // Enter is a submit shortcut on many editors, even with Shift. Insert a literal
- // newline through the editing command instead; never synthesize a submit key.
- const marker = await markNativeDispatch('input');
- let inserted;
- try {
- dispatch.started = true;
- inserted = await this.call(match, `(el, text) => {
- if (!el.isConnected || el.getRootNode().activeElement !== el) return false;
- return document.execCommand('insertText', false, text);
- }`, [{ type: 'string', value: char }]);
- } finally { await clearNativeDispatch(marker); }
- if (inserted.result?.value !== true) throw new Error('Editor rejected literal newline insertion');
- assertLive();
- } else await press(char);
+ if (clear) {
+ const platform = await this.call(match, '() => navigator.platform');
+ await press('a', /Mac/.test(platform.result?.value || '') ? '\uE03D' : '\uE009');
+ await press('\uE003');
+ if (beforeSnapshot.semanticKind === 'draftjs') {
+ const cleared = await this.call(match, `(el) => {
+ ${FIELD_TEXT_READBACK_SOURCE}
+ return readRichTextFieldValue(el, 'draftjs') === '';
+ }`);
+ if (cleared.result?.value !== true) throw new Error('DraftJS clearing did not establish an empty document; no further text sent');
+ }
+ } else {
+ const positioned = await this.call(match, `(el) => {
+ if (!el.isConnected || el.getRootNode().activeElement !== el) return false;
+ if (el.isContentEditable) {
+ const selection = getSelection(); const range = document.createRange();
+ let container = el;
+ while (container.lastChild?.nodeType === 1 && container.lastChild.isContentEditable
+ && container.lastChild.nodeName !== 'BR') container = container.lastChild;
+ range.selectNodeContents(container); range.collapse(false);
+ selection.removeAllRanges(); selection.addRange(range);
+ } else if (typeof el.setSelectionRange === 'function') {
+ const end = el.value.length; el.setSelectionRange(end, end);
+ } else return false;
+ return true;
+ }`);
+ if (positioned.result?.value !== true) throw new Error('Could not position caret for append; no text sent');
+ }
+ if (beforeSnapshot.semanticKind === 'draftjs' && /[\r\n]/.test(payload.text)) {
+ // DraftJS treats literal LF editing commands inconsistently. Its public paste
+ // handler accepts a whole plain-text document without using a submit shortcut.
+ const positioned = await this.call(match, `(el, clear) => {
+ if (!el.isConnected || el.getRootNode().activeElement !== el) return false;
+ const leaves = el.querySelectorAll('[data-text="true"]');
+ const leaf = leaves[clear ? 0 : leaves.length - 1];
+ if (!leaf) return false;
+ const range = el.ownerDocument.createRange();
+ if (leaf.nodeName === 'BR') range.setStartBefore(leaf);
+ else {
+ const text = clear ? leaf.firstChild : leaf.lastChild;
+ if (text?.nodeType !== 3) return false;
+ range.setStart(text, clear ? 0 : text.nodeValue.length);
+ }
+ range.collapse(true);
+ const selection = el.ownerDocument.defaultView.getSelection();
+ selection.removeAllRanges(); selection.addRange(range);
+ return true;
+ }`, [{ type: 'boolean', value: clear }]);
+ if (positioned.result?.value !== true) throw new Error('Could not position the DraftJS caret; no further text sent');
+ // Let the browser's selectionchange reach the framework before the paste.
+ await new Promise(resolve => setTimeout(resolve, 30));
+ await assertFocus();
+ const marker = await markNativeDispatch('input', { domDispatch: true });
+ try {
+ dispatch.started = true;
+ const pasted = await this.call(match, `(el, text, guardJson) => {
+ ${FIELD_TEXT_READBACK_SOURCE}
+ if (!el.isConnected || el.getRootNode().activeElement !== el || readDraftJsText(el) === null) return false;
+ const view = el.ownerDocument.defaultView;
+ const data = new view.DataTransfer(); data.setData('text/plain', text);
+ const event = new view.ClipboardEvent('paste', { bubbles: true, cancelable: true, composed: true, clipboardData: data });
+ // Firefox drops the constructor's clipboardData. Preserve the public
+ // plain-text payload without reading or writing the OS clipboard.
+ if (event.clipboardData?.getData('text/plain') !== text)
+ Object.defineProperty(event, 'clipboardData', { value: data });
+ const guard = JSON.parse(guardJson);
+ if (guard && !el.dispatchEvent(new view.CustomEvent('webbrain-agent-dom-dispatch', {
+ detail: JSON.stringify({ ...guard, dispatchPhase: 'input' }), bubbles: true, composed: true, cancelable: true,
+ }))) return false;
+ el.dispatchEvent(event);
+ // Cancellation can mean the framework consumed the paste. Only the
+ // settled exact document readback below establishes its outcome.
+ return true;
+ }`, [{ type: 'string', value: payload.text.replace(/\r\n?/g, '\n') },
+ { type: 'string', value: JSON.stringify(payload.pageFeedbackGuard || null) }]);
+ if (pasted.result?.value !== true) throw new Error('DraftJS paste dispatch could not be established; inspect before another write');
+ } finally { await clearNativeDispatch(marker); }
+ assertLive();
+ } else {
+ // One character per dispatch bounds work after Stop and catches focus changes between keys.
+ for (const char of payload.text.replace(/\r\n?/g, '\n')) {
+ if (char === '\n' || char === '\r') {
+ await assertFocus();
+ // Enter is a submit shortcut on many editors, even with Shift. Insert a literal
+ // newline through the editing command instead; never synthesize a submit key.
+ const marker = await markNativeDispatch('input');
+ let inserted;
+ try {
+ dispatch.started = true;
+ inserted = await this.call(match, `(el, text) => {
+ if (!el.isConnected || el.getRootNode().activeElement !== el) return false;
+ return document.execCommand('insertText', false, text);
+ }`, [{ type: 'string', value: char }]);
+ } finally { await clearNativeDispatch(marker); }
+ if (inserted.result?.value !== true) throw new Error('Editor rejected literal newline insertion');
+ assertLive();
+ } else await press(char);
+ }
}
}
} else if (action === 'key') {
@@ -696,14 +815,16 @@ export class BidiSession {
await new Promise(resolve => setTimeout(resolve, 100));
assertLive();
const expected = clear ? payload.text : String(beforeSnapshot.value || '') + payload.text;
- const verified = await this.call(match, `(el, expected, semanticKind) => {
+ const verified = await this.call(match, `(el, expected, semanticKind, bound) => {
${FIELD_TEXT_READBACK_SOURCE}
+ if (bound && (el !== bound.editor || el.ownerDocument !== bound.document || el.getRootNode() !== bound.root)) return false;
const actual = readRichTextFieldValue(el, semanticKind);
if (actual === null) return false;
if (!el.isContentEditable) return actual === expected;
const normalize = value => String(value).replace(/\\r\\n?/g, '\\n');
return normalize(actual) === normalize(expected);
- }`, [{ type: 'string', value: expected }, { type: 'string', value: beforeSnapshot.semanticKind || '' }]);
+ }`, [{ type: 'string', value: expected }, { type: 'string', value: beforeSnapshot.semanticKind || '' },
+ proseMirrorBinding ? { handle: proseMirrorBinding } : { type: 'null' }]);
if (verified.result?.value !== true) return { success: false, dispatched: true, verified: false, submitted: false, outcomeUnknown: true, retryable: false, error: 'Trusted typing did not match the requested value; inspect before another write.' };
if (action === 'field' && payload.submit === true) {
assertLive();
diff --git a/package-lock.json b/package-lock.json
index 32a15ae83..c0b8c461a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,8 +11,14 @@
"devDependencies": {
"c8": "^12.0.0",
"draft-js": "0.11.7",
+ "esbuild": "0.28.2",
"immutable": "3.8.4",
"playwright": "^1.48.0",
+ "prosemirror-commands": "1.7.1",
+ "prosemirror-keymap": "1.2.3",
+ "prosemirror-model": "1.25.12",
+ "prosemirror-state": "1.4.4",
+ "prosemirror-view": "1.42.6",
"react": "18.2.0",
"react-dom": "18.2.0",
"tldts": "7.4.10"
@@ -28,6 +34,448 @@
"node": ">=18"
}
},
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz",
@@ -266,6 +714,48 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/esbuild": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.2",
+ "@esbuild/android-arm": "0.28.2",
+ "@esbuild/android-arm64": "0.28.2",
+ "@esbuild/android-x64": "0.28.2",
+ "@esbuild/darwin-arm64": "0.28.2",
+ "@esbuild/darwin-x64": "0.28.2",
+ "@esbuild/freebsd-arm64": "0.28.2",
+ "@esbuild/freebsd-x64": "0.28.2",
+ "@esbuild/linux-arm": "0.28.2",
+ "@esbuild/linux-arm64": "0.28.2",
+ "@esbuild/linux-ia32": "0.28.2",
+ "@esbuild/linux-loong64": "0.28.2",
+ "@esbuild/linux-mips64el": "0.28.2",
+ "@esbuild/linux-ppc64": "0.28.2",
+ "@esbuild/linux-riscv64": "0.28.2",
+ "@esbuild/linux-s390x": "0.28.2",
+ "@esbuild/linux-x64": "0.28.2",
+ "@esbuild/netbsd-arm64": "0.28.2",
+ "@esbuild/netbsd-x64": "0.28.2",
+ "@esbuild/openbsd-arm64": "0.28.2",
+ "@esbuild/openbsd-x64": "0.28.2",
+ "@esbuild/openharmony-arm64": "0.28.2",
+ "@esbuild/sunos-x64": "0.28.2",
+ "@esbuild/win32-arm64": "0.28.2",
+ "@esbuild/win32-ia32": "0.28.2",
+ "@esbuild/win32-x64": "0.28.2"
+ }
+ },
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -582,6 +1072,13 @@
"node": ">=0.10.0"
}
},
+ "node_modules/orderedmap": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz",
+ "integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/p-limit": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
@@ -693,6 +1190,73 @@
"asap": "~2.0.3"
}
},
+ "node_modules/prosemirror-commands": {
+ "version": "1.7.1",
+ "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz",
+ "integrity": "sha512-rT7qZnQtx5c0/y/KlYaGvtG411S97UaL6gdp6RIZ23DLHanMYLyfGBV5DtSnZdthQql7W+lEVbpSfwtO8T+L2w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.0.0",
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.10.2"
+ }
+ },
+ "node_modules/prosemirror-keymap": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz",
+ "integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-state": "^1.0.0",
+ "w3c-keyname": "^2.2.0"
+ }
+ },
+ "node_modules/prosemirror-model": {
+ "version": "1.25.12",
+ "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.12.tgz",
+ "integrity": "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "orderedmap": "^2.0.0"
+ }
+ },
+ "node_modules/prosemirror-state": {
+ "version": "1.4.4",
+ "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz",
+ "integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.0.0",
+ "prosemirror-transform": "^1.0.0",
+ "prosemirror-view": "^1.27.0"
+ }
+ },
+ "node_modules/prosemirror-transform": {
+ "version": "1.12.2",
+ "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.2.tgz",
+ "integrity": "sha512-PE/aY0HEY4zczvmqrilgkUK/WautF0chvMqkmM/iN5/aPHvwrCWaQZjS6CIZp+K84YrvPFqrL+YArrfJX8xX7g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.21.0"
+ }
+ },
+ "node_modules/prosemirror-view": {
+ "version": "1.42.6",
+ "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.6.tgz",
+ "integrity": "sha512-3g25f6hKV2bBxo3puH3EcYWmmVNSH0iWmNsMVT7sugDSpA025jgpOLarcDWr39SdzPjYMaiYtRdNtXialPSjEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "prosemirror-model": "^1.25.12",
+ "prosemirror-state": "^1.0.0",
+ "prosemirror-transform": "^1.1.0"
+ }
+ },
"node_modules/react": {
"version": "18.2.0",
"resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
@@ -916,6 +1480,13 @@
"node": ">=10.12.0"
}
},
+ "node_modules/w3c-keyname": {
+ "version": "2.2.8",
+ "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
+ "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
diff --git a/package.json b/package.json
index cf0ef9154..fc213b7a0 100644
--- a/package.json
+++ b/package.json
@@ -55,8 +55,8 @@
"benchmark:relevance": "node scripts/benchmark-offline-relevance.mjs --verbose",
"test:social-contract": "node --test test/social-publish-contract.mjs",
"test:social-contract:dom": "node test/social-publish-contract-dom.mjs",
- "test:runtime-lifecycle": "node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/cdp-clear-receipt.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/chat-steering.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/completion-current-execution-evidence.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs",
- "test:page-feedback": "node --test test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs",
+ "test:runtime-lifecycle": "node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/chat-steering.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/completion-current-execution-evidence.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs",
+ "test:page-feedback": "node --test test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs",
"test:chat-steering": "node --test test/chat-steering.mjs test/chat-steering-ui.mjs",
"test:rich-text-dom": "node test/ui-content-lifecycle.mjs --dom",
"test:firefox-bidi": "node --test test/firefox-bidi.mjs test/firefox-full-page-screenshot.mjs",
@@ -87,24 +87,33 @@
"test:chat-draft-recovery": "node --test test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs && node test/quality/native-chat-presubmit-mv3.mjs",
"test:upload-owner": "node --test test/page-monitor-upload-owner.mjs",
"test:shard:quick": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-bridge-registration.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:provider-instances:ui && npm run test:openrouter-capabilities && npm run test:anthropic && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs",
- "test:shard:runtime-unit": "node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/cdp-clear-receipt.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/chat-steering.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/completion-current-execution-evidence.mjs",
- "test:shard:browser-a": "node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs",
+ "test:shard:runtime-unit": "node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/chat-steering.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/completion-current-execution-evidence.mjs",
+ "test:shard:browser-a": "node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs",
"test:shard:browser-b1": "node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs",
"test:shard:browser-b2": "node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs",
- "test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs",
- "test:shard:tail": "node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security"
+ "test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs",
+ "test:shard:tail": "node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",
+ "test:composer-context": "node --test test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs"
},
"devDependencies": {
"c8": "^12.0.0",
"draft-js": "0.11.7",
+ "esbuild": "0.28.2",
"immutable": "3.8.4",
"playwright": "^1.48.0",
+ "prosemirror-commands": "1.7.1",
+ "prosemirror-keymap": "1.2.3",
+ "prosemirror-model": "1.25.12",
+ "prosemirror-state": "1.4.4",
+ "prosemirror-view": "1.42.6",
"react": "18.2.0",
"react-dom": "18.2.0",
"tldts": "7.4.10"
},
"overrides": {
- "draft-js": { "immutable": "$immutable" }
+ "draft-js": {
+ "immutable": "$immutable"
+ }
},
"repository": {
"type": "git",
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 82533501f..d90c28979 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -43647,10 +43647,11 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
dispatched = true;
markEarlyCdpDispatched();
- await cdpClient.sendCommand(tabId, 'Input.insertText', { text: args.text || '' });
+ const nativeText = String(args.text ?? '').replace(/\r\n?/g, '\n');
+ await cdpClient.sendCommand(tabId, 'Input.insertText', { text: nativeText });
throwIfEarlyCdpAborted();
const verification = await sendFocusedTarget('verify_focused_type_dispatch', {
- text: args.text || '',
+ text: nativeText,
clear: !!args.clear,
beforeSignature: prepared.beforeSignature || '',
});
@@ -43950,11 +43951,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
dispatched = true;
markEarlyCdpDispatched();
- await cdpClient.sendCommand(tabId, 'Input.insertText', { text: args.text || '' });
+ const nativeText = String(args.text ?? '').replace(/\r\n?/g, '\n');
+ await cdpClient.sendCommand(tabId, 'Input.insertText', { text: nativeText });
throwIfEarlyCdpAborted();
const verified = await cdpClient.verifyTextEntry(tabId, {
focused: true,
- text: args.text || '',
+ text: nativeText,
clear: !!args.clear,
beforeSignature,
});
@@ -45241,6 +45243,8 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
};
let trustedDispatched = false;
let trustedTextAttempted = false;
+ let nativeClearReceipt = null;
+ let nativeChatClearToken = null;
let beforePreparation = null;
const digestTarget = { locatorType: 'ax', refId: args.ref_id, frameId };
const actionDeadlineAt = Number(CONTENT_ACTION_SIGNAL_DEADLINES.get(abortSignal)?.deadlineAt) || 0;
@@ -45328,9 +45332,11 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
trustedDispatched = true;
const appendingContentEditable = prepared.contentEditable && !clearsExisting;
- const trustedText = appendingContentEditable
+ // Canonicalize before native insertion as well as readback: raw CRLF
+ // becomes CR spaces plus LF paragraphs in browser-managed editors.
+ const trustedText = (appendingContentEditable
? (typeof args?.text === 'string' ? args.text : '')
- : expected;
+ : expected).replace(/\r\n?/g, '\n');
this._throwIfAborted(abortSignal);
// A lost response can precede a delayed applied write. After this
// boundary an unchanged sample cannot make the text command retry-safe.
@@ -45351,6 +45357,29 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
if (trustedText || appendingContentEditable) {
await cdpClient.sendCommand(tabId, 'Input.insertText', { text: trustedText });
} else {
+ // Native chat knows that an explicitly deleted caret is an empty
+ // message. Keep that proof private and scoped; generic BRs stay LF.
+ if (prepared.contentEditable && frameId === 0) {
+ const clearPreparation = await sendContent({ target: 'content', action: 'ax_prepare_native_chat_clear',
+ params: { ref_id: args.ref_id } });
+ this._throwIfAborted(abortSignal);
+ if (clearPreparation?.success === true && typeof clearPreparation.token === 'string') {
+ nativeChatClearToken = clearPreparation.token;
+ nativeClearReceipt = await cdpClient.captureTextClearReceipt(tabId, { focused: true });
+ this._throwIfAborted(abortSignal);
+ if (nativeClearReceipt) {
+ const modifiers = await cdpClient.selectAllModifier(tabId);
+ this._throwIfAborted(abortSignal);
+ await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
+ type: 'keyDown', key: 'a', code: 'KeyA', modifiers, windowsVirtualKeyCode: 65, commands: ['selectAll'],
+ });
+ await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
+ type: 'keyUp', key: 'a', code: 'KeyA', modifiers, windowsVirtualKeyCode: 65,
+ });
+ }
+ }
+ }
+ this._throwIfAborted(abortSignal);
await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
type: 'keyDown', key: 'Delete', code: 'Delete', windowsVirtualKeyCode: 46,
});
@@ -45361,12 +45390,18 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
this._throwIfAborted(abortSignal);
await new Promise(resolve => setTimeout(resolve, 120));
this._throwIfAborted(abortSignal);
+ if (nativeChatClearToken && await nativeClearReceipt?.verify() === true) {
+ this._throwIfAborted(abortSignal);
+ await sendContent({ target: 'content', action: 'ax_verify_native_chat_clear',
+ params: { ref_id: args.ref_id, token: nativeChatClearToken } });
+ this._throwIfAborted(abortSignal);
+ }
verification = await sendContent({
target: 'content',
action: 'ax_verify_field_value',
params: {
ref_id: args.ref_id,
- expected,
+ expected: expected.replace(/\r\n?/g, '\n'),
...(appendingContentEditable ? { appendText: trustedText } : {}),
},
});
@@ -45444,12 +45479,39 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
}
this._throwIfAborted(abortSignal);
- await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
- type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
- });
- await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
- type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
- });
+ let enterDispatched = false;
+ try {
+ await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
+ type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
+ });
+ enterDispatched = true;
+ await cdpClient.sendCommand(tabId, 'Input.dispatchKeyEvent', {
+ type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13,
+ });
+ } catch (error) {
+ if (error?.code !== 'page_feedback_pending' || enterDispatched) throw error;
+ // The native-input transport rejected Enter before dispatch. Keep
+ // the exact settled draft proof, but retain uncertainty from typing:
+ // a page-owned beforeinput handler may already have acted on it.
+ return {
+ ...recovered,
+ success: false,
+ submitted: false,
+ messageDispatched: false,
+ draftMutationDispatched: true,
+ submissionDispatched: false,
+ submissionBlockedBeforeDispatch: true,
+ submissionBlockReason: 'page_feedback_pending',
+ submissionOutcomeUnknown: false,
+ outcomeUnknown: true,
+ mutationMayHaveOccurred: true,
+ repeatBlocked: true,
+ retryable: false,
+ pageFeedbackPending: true,
+ recoveryRequired: 'verify_or_restore_field',
+ error: 'The exact draft was verified, but the browser changed before Enter could be dispatched. Observe the conversation and reconcile any pending send before another mutation; no automatic retry occurred.',
+ };
+ }
recovered.submitted = true;
}
return recovered;
@@ -45461,6 +45523,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
...(error?.code === 'page_feedback_pending' ? { pageFeedbackPending: true } : {}),
error: `${response.error || 'Field verification failed'} Trusted Chrome retry failed: ${error?.message || String(error)}`,
});
+ } finally {
+ await nativeClearReceipt?.dispose();
+ if (nativeChatClearToken) {
+ try { await sendContent({ target: 'content', action: 'ax_release_native_chat_clear',
+ params: { token: nativeChatClearToken } }); } catch { /* short private expiry is the backup cleanup */ }
+ }
}
}
diff --git a/src/chrome/src/agent/page-feedback-recovery.js b/src/chrome/src/agent/page-feedback-recovery.js
index 07070e4f8..943032e90 100644
--- a/src/chrome/src/agent/page-feedback-recovery.js
+++ b/src/chrome/src/agent/page-feedback-recovery.js
@@ -6,15 +6,15 @@ export const PAGE_FEEDBACK_STOP_AT = 5;
export const PAGE_FEEDBACK_STOP_CODE = 'page_unstable';
const STOP_MESSAGE = 'Stopped because the page kept changing before the next action could be safely dispatched. '
- + 'The task is incomplete; no stale action was dispatched.';
+ + 'The task is incomplete; no stale action was dispatched. Wait for the page to settle, then choose Retry.';
const NUDGE_MESSAGE = '[PAGE KEEPS CHANGING: Browser updates repeatedly prevented the next action from being dispatched. '
+ 'Use the fresh observation to choose an action whose intended target can be verified. '
+ 'Do not repeat stale targets or coordinates.]';
const UNVERIFIED_NUDGE = '[ACTION CONTEXT UNVERIFIED: The requested control had no verified original action context. '
+ 'No action was dispatched. Inspect the fresh bounded target observation and its intended owner before choosing another action; '
+ 'do not repeatedly attempt a control whose context remains unverified.]';
-const UNVERIFIED_STOP = 'Stopped because the requested control could not be bound to a verified action context. '
- + 'The task is incomplete; no unverified action was dispatched.';
+const UNVERIFIED_STOP = 'Stopped before the next action because WebBrain could not confirm which part of the page the control belongs to. '
+ + 'The task is incomplete. Open or focus the intended area, then choose Retry.';
function boundedStreak(value) {
return Number.isSafeInteger(value) && value > 0 ? Math.min(value, PAGE_FEEDBACK_STOP_AT) : 0;
diff --git a/src/chrome/src/agent/page-feedback.js b/src/chrome/src/agent/page-feedback.js
index 3d7b1696a..6cd7a7c00 100644
--- a/src/chrome/src/agent/page-feedback.js
+++ b/src/chrome/src/agent/page-feedback.js
@@ -796,6 +796,10 @@ export const pageFeedbackMethods = {
this._flushPageFeedbackMessages(tabId, messages);
const recovery = run?.recoveryResult;
if (!recovery) return null;
+ // Retry observes the current page through the normal gates. A context
+ // failure never grants the publication-audit bypass reserved for that audit.
+ this._offerFailureRecovery?.(tabId, { stage: 'action_preparation', code: recovery.code,
+ message: recovery.message }, onUpdate);
onUpdate('warning', { message: recovery.message });
return { action: 'return', value: recovery.message, status: recovery.code };
},
diff --git a/src/chrome/src/cdp/cdp-client.js b/src/chrome/src/cdp/cdp-client.js
index e062c5c2d..afc41180b 100644
--- a/src/chrome/src/cdp/cdp-client.js
+++ b/src/chrome/src/cdp/cdp-client.js
@@ -193,6 +193,26 @@ function nativeTextClearReceipt(el) {
const sameRange = (a, b) => !!a && !!b && a.startContainer === b.startContainer && a.startOffset === b.startOffset
&& a.endContainer === b.endContainer && a.endOffset === b.endOffset;
const within = value => !!value && el.contains(value.startContainer) && el.contains(value.endContainer);
+ const originalBreaks = new Set(el.querySelectorAll('br'));
+ const originalNodes = new Set([el]), originalText = new Map(), deletedTextNodes = new Set();
+ const originalWalker = doc.createTreeWalker(el, view.NodeFilter.SHOW_ALL);
+ for (let node = originalWalker.nextNode(); node; node = originalWalker.nextNode()) {
+ originalNodes.add(node); if (node.nodeType === 3) originalText.set(node, node.nodeValue);
+ }
+ const fullySelected = () => {
+ const value = range();
+ if (!within(value) || value.collapsed) return false;
+ const walker = doc.createTreeWalker(el, view.NodeFilter.SHOW_ELEMENT | view.NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (node.nodeType === 3) {
+ if (value.comparePoint(node, 0) !== 0 || value.comparePoint(node, node.length) !== 0) return false;
+ } else if (!node.childNodes.length) {
+ const offset = Array.prototype.indexOf.call(node.parentNode.childNodes, node);
+ if (value.comparePoint(node.parentNode, offset) !== 0 || value.comparePoint(node.parentNode, offset + 1) !== 0) return false;
+ }
+ }
+ return true;
+ };
const originalRange = range()?.cloneRange();
let invalid = false, closed = false, selected = 0, deleted = 0, released = 0, before = 0, inputs = 0, caret = null, settledRange = null;
const current = () => {
@@ -207,20 +227,45 @@ function nativeTextClearReceipt(el) {
// All other editor/identity mutations remain part of the receipt's fence.
const relevant = record => !(record.type === 'attributes'
&& ['data-webbrain-native-target', 'data-webbrain-page-revision'].includes(record.attributeName))
- && (record.target === el || el.contains(record.target)
+ && (originalNodes.has(record.target) || record.target === el || el.contains(record.target)
|| (record.type === 'childList' && [...record.addedNodes, ...record.removedNodes]
.some(node => node === el || node.contains?.(el) || ancestors.some(ancestor => node === ancestor || node.contains?.(ancestor))))
|| (record.type === 'attributes' && ancestors.includes(record.target)
&& /^(?:id|role|aria-label|contenteditable|disabled|readonly|inert|hidden|data-)/.test(record.attributeName || '')));
- const observer = new view.MutationObserver(records => { if (records.some(relevant)) invalid = true; });
- observer.observe(doc.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });
+ let pendingDeleteRecords = [];
+ const nativeDeleteMutation = record => ['childList', 'characterData'].includes(record.type)
+ && (originalNodes.has(record.target) || record.target === el || el.contains(record.target));
+ const observer = new view.MutationObserver(records => {
+ const changes = records.filter(relevant);
+ if (!changes.length) return;
+ // Another capture listener can yield a mutation checkpoint before this
+ // receipt sees input. Hold only the expected native deletion's records;
+ // the one matching trusted input must consume them before any proof.
+ if (deleted === 1 && before === 1 && inputs === 0 && current()
+ && changes.every(nativeDeleteMutation) && pendingDeleteRecords.length + changes.length <= 128) {
+ pendingDeleteRecords.push(...changes);
+ } else invalid = true;
+ });
+ observer.observe(doc.documentElement, { subtree: true, childList: true, characterData: true, characterDataOldValue: true, attributes: true });
for (const [scope] of activeBindings) if (scope !== doc) {
- observer.observe(scope, { subtree: true, childList: true, characterData: true, attributes: true });
+ observer.observe(scope, { subtree: true, childList: true, characterData: true, characterDataOldValue: true, attributes: true });
}
- const drain = () => { if (observer.takeRecords().some(relevant)) invalid = true; };
+ const drain = () => {
+ if (pendingDeleteRecords.length || observer.takeRecords().some(relevant)) invalid = true;
+ };
const drainNativeDelete = () => {
- if (observer.takeRecords().some(record => relevant(record)
- && !(['childList', 'characterData'].includes(record.type) && (record.target === el || el.contains(record.target))))) invalid = true;
+ const changes = [...pendingDeleteRecords, ...observer.takeRecords()]; pendingDeleteRecords = [];
+ for (const record of changes.filter(relevant)) {
+ if (!nativeDeleteMutation(record)) { invalid = true; continue; }
+ if (record.type === 'characterData') {
+ if (!originalText.has(record.target) || record.oldValue !== originalText.get(record.target)
+ || record.target.nodeValue !== '' || deletedTextNodes.has(record.target)) invalid = true;
+ deletedTextNodes.add(record.target);
+ } else if (!originalNodes.has(record.target)
+ || [...record.removedNodes].some(node => !originalNodes.has(node))
+ || [...record.addedNodes].some(node => node !== el.firstChild || node.nodeName !== 'BR'
+ || node.attributes.length !== 0 || originalBreaks.has(node))) invalid = true;
+ }
};
let retargetedInput = null;
const handlers = {
@@ -229,7 +274,7 @@ function nativeTextClearReceipt(el) {
if (event.code === 'KeyA' && (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey
&& selected === 0 && deleted === 0) { selected++; return; }
if (event.code === 'Delete' && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
- && selected === 1 && deleted === 0) { deleted++; return; }
+ && selected === 1 && deleted === 0 && fullySelected()) { deleted++; return; }
invalid = true;
},
keyup(event) {
@@ -242,6 +287,7 @@ function nativeTextClearReceipt(el) {
drain();
if (!event.isTrusted || event.target !== el || event.inputType !== 'deleteContentForward'
|| selected !== 1 || deleted !== 1 || before !== 0 || !current()) { invalid = true; return; }
+ if (!fullySelected()) { invalid = true; return; }
before++;
},
input(event) {
@@ -251,7 +297,7 @@ function nativeTextClearReceipt(el) {
// changes, including a change followed by restoration, invalidate proof.
drainNativeDelete(); inputs++;
caret = el.isContentEditable && el.childNodes.length === 1 && el.firstChild?.nodeName === 'BR'
- && el.firstChild.attributes.length === 0 && el.textContent === '' ? el.firstChild : null;
+ && !originalBreaks.has(el.firstChild) && el.firstChild.attributes.length === 0 && el.textContent === '' ? el.firstChild : null;
settledRange = range()?.cloneRange();
},
selectionchange() {
@@ -270,7 +316,9 @@ function nativeTextClearReceipt(el) {
for (const [name, handler] of Object.entries(handlers)) {
// Native events are retargeted to the host at document listeners. Count the
// exact keyboard/input sequence once, in the original editable's own root.
- listen(root, name, handler);
+ // For a document editor, observe input before document-capture handlers
+ // in the installed content scripts create a mutation microtask checkpoint.
+ listen(root === doc ? view : root, name, handler);
if (root !== doc) listen(doc, name, event => {
if (name === 'selectionchange' || ['focusout', 'blur', 'pointerdown', 'wheel', 'paste', 'drop'].includes(name)) handler(event);
else if (!event.isTrusted || !event.composed || event.target !== activeBindings.at(-1)[1]) invalid = true;
@@ -5927,6 +5975,11 @@ export class CDPClient {
};
}
+ // HTML text entry uses LF document separators. Sending raw CRLF through
+ // Input.insertText can insert an extra space for each CR in ProseMirror.
+ // Normalize the payload before the single native write and verify that
+ // exact payload; the native select matching path above stays separate.
+ const insertionText = String(text ?? '').replace(/\r\n?/g, '\n');
const beforeSignature = await this.textEntrySignature(tabId, {
selector,
nodeId: info.nodeId,
@@ -6156,7 +6209,7 @@ export class CDPClient {
try {
dispatched = true;
markDispatch();
- await this.sendCommand(tabId, 'Input.insertText', { text });
+ await this.sendCommand(tabId, 'Input.insertText', { text: insertionText });
throwIfAborted();
} catch (e) {
if (e?.code === 'page_feedback_pending') throw e;
@@ -6173,7 +6226,7 @@ export class CDPClient {
const verified = await this.verifyTextEntry(tabId, {
selector,
nodeId: info.nodeId,
- text,
+ text: insertionText,
clear,
beforeSignature,
});
diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.js
index ba43cc6bc..21b473f49 100644
--- a/src/chrome/src/content/content.js
+++ b/src/chrome/src/content/content.js
@@ -4976,6 +4976,166 @@
return texts.join('\n');
}
+ const _nativeChatClearPreparations = new Map();
+
+ function _releaseNativeChatClear(token) {
+ const record = _nativeChatClearPreparations.get(token);
+ if (!record) return;
+ _nativeChatClearPreparations.delete(token);
+ clearTimeout(record.timer);
+ record.observer.disconnect();
+ for (const [name, listener] of record.listeners) record.view.removeEventListener(name, listener, true);
+ }
+
+ function _prepareNativeChatClear(ref) {
+ const el = window.__wb_ax_lookup?.(ref), context = _nativeChatCaretContext(el);
+ if (!el?.isContentEditable || !el.isConnected || !context || !el.textContent) return { success: false };
+ const doc = el.ownerDocument, root = el.getRootNode(), view = doc.defaultView;
+ const url = doc.URL, documentToken = _axDocumentToken();
+ const ancestors = []; for (let node = el.parentElement; node; node = node.parentElement) ancestors.push(node);
+ const identityNodes = [context.header, context.carrier, context.title, context.selfMarker, context.owner]
+ .filter(node => node?.nodeType === 1);
+ const selection = () => root.getSelection?.() || view.getSelection();
+ const rangeNow = () => { const value = selection(); return value?.rangeCount === 1 ? value.getRangeAt(0) : null; };
+ const sameRange = (a, b) => !!a && !!b && a.startContainer === b.startContainer && a.startOffset === b.startOffset
+ && a.endContainer === b.endContainer && a.endOffset === b.endOffset;
+ const originalBreaks = new Set(el.querySelectorAll('br'));
+ const originalNodes = new Set([el]), originalText = new Map(), deletedTextNodes = new Set();
+ const originalWalker = doc.createTreeWalker(el, view.NodeFilter.SHOW_ALL);
+ for (let node = originalWalker.nextNode(); node; node = originalWalker.nextNode()) {
+ originalNodes.add(node); if (node.nodeType === 3) originalText.set(node, node.nodeValue);
+ }
+ const fullySelected = () => {
+ const value = rangeNow();
+ if (!value || value.collapsed || !el.contains(value.startContainer) || !el.contains(value.endContainer)) return false;
+ const walker = doc.createTreeWalker(el, view.NodeFilter.SHOW_ELEMENT | view.NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (node.nodeType === 3) {
+ if (value.comparePoint(node, 0) !== 0 || value.comparePoint(node, node.length) !== 0) return false;
+ } else if (!node.childNodes.length) {
+ const offset = Array.prototype.indexOf.call(node.parentNode.childNodes, node);
+ if (value.comparePoint(node.parentNode, offset) !== 0 || value.comparePoint(node.parentNode, offset + 1) !== 0) return false;
+ }
+ }
+ return true;
+ };
+ const focused = () => (root.activeElement || doc.activeElement) === el;
+ const current = () => el.isConnected && el.ownerDocument === doc && doc.defaultView === view
+ && view.document === doc && el.getRootNode() === root && doc.URL === url
+ && _axDocumentToken() === documentToken && window.__wb_ax_lookup?.(ref) === el && focused()
+ && _sameNativeChatCaretContext(context, _nativeChatCaretContext(el));
+ const selected = selection();
+ if (!current() || selected?.rangeCount !== 1) return { success: false };
+ const range = selected.getRangeAt(0);
+ if (!fullySelected() || !el.contains(range.startContainer) || !el.contains(range.endContainer)
+ || range.cloneContents().textContent !== el.textContent) return { success: false };
+ const token = crypto.randomUUID();
+ const record = { el, doc, view, context, current, listeners: [], selected: 0, deleted: 0, before: 0,
+ inputs: 0, released: 0, invalid: false, caret: null, settledRange: null, pendingDeleteRecords: [] };
+ const originalRange = range.cloneRange();
+ record.selectionCurrent = () => sameRange(rangeNow(), record.settledRange);
+ const relevant = mutation => !(mutation.type === 'attributes'
+ && ['data-webbrain-native-target', 'data-webbrain-page-revision'].includes(mutation.attributeName))
+ && (originalNodes.has(mutation.target) || mutation.target === el || el.contains(mutation.target)
+ || (mutation.type === 'attributes' && ancestors.includes(mutation.target))
+ || identityNodes.some(node => mutation.target === node
+ || (node !== context.owner && node.contains(mutation.target)))
+ || (mutation.type === 'childList' && [...mutation.addedNodes, ...mutation.removedNodes]
+ .some(node => node === el || node.contains?.(el) || identityNodes.includes(node))));
+ const nativeDeleteMutation = mutation => ['childList', 'characterData'].includes(mutation.type)
+ && (originalNodes.has(mutation.target) || mutation.target === el || el.contains(mutation.target));
+ record.observer = new view.MutationObserver(records => {
+ const changes = records.filter(relevant);
+ if (!changes.length) return;
+ // Capture listeners in another world can yield before our trusted input
+ // callback. Only that exact pending native Delete may consume this buffer.
+ if (record.deleted === 1 && record.before === 1 && record.inputs === 0 && current()
+ && changes.every(nativeDeleteMutation) && record.pendingDeleteRecords.length + changes.length <= 128) {
+ record.pendingDeleteRecords.push(...changes);
+ } else record.invalid = true;
+ });
+ record.observer.observe(doc.documentElement, { subtree: true, attributes: true, childList: true, characterData: true, characterDataOldValue: true });
+ const drain = nativeDelete => {
+ const changes = [...record.pendingDeleteRecords, ...record.observer.takeRecords()]; record.pendingDeleteRecords = [];
+ for (const mutation of changes.filter(relevant)) {
+ if (!nativeDelete || !nativeDeleteMutation(mutation)) { record.invalid = true; continue; }
+ if (mutation.type === 'characterData') {
+ if (!originalText.has(mutation.target) || mutation.oldValue !== originalText.get(mutation.target)
+ || mutation.target.nodeValue !== '' || deletedTextNodes.has(mutation.target)) record.invalid = true;
+ deletedTextNodes.add(mutation.target);
+ } else if (!originalNodes.has(mutation.target)
+ || [...mutation.removedNodes].some(node => !originalNodes.has(node))
+ || [...mutation.addedNodes].some(node => node !== el.firstChild || node.nodeName !== 'BR'
+ || node.attributes.length !== 0 || originalBreaks.has(node))) record.invalid = true;
+ }
+ };
+ record.drain = drain;
+ const handlers = {
+ keydown(event) {
+ if (!event.isTrusted || event.target !== el || !current()) { record.invalid = true; return; }
+ if (/^(?:Control|Meta)(?:Left|Right)$/.test(event.code) && !record.selected && !record.deleted
+ && !record.modifierCode && !event.altKey && !event.shiftKey) { record.modifierCode = event.code; return; }
+ if (event.code === 'KeyA' && (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey
+ && !record.selected && !record.deleted) { record.selected++; return; }
+ if (event.code === 'Delete' && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
+ && record.selected === 1 && !record.deleted && fullySelected()) { record.deleted++; return; }
+ record.invalid = true;
+ },
+ keyup(event) {
+ if (!event.isTrusted || event.target !== el) { record.invalid = true; return; }
+ if (event.code === record.modifierCode && record.selected === 1 && !record.deleted
+ && !record.modifierReleased) { record.modifierReleased = true; return; }
+ if (event.code === 'KeyA' && record.selected === 1 && !record.deleted) return;
+ if (event.code === 'Delete' && record.deleted === 1 && !record.released) { record.released++; return; }
+ record.invalid = true;
+ },
+ beforeinput(event) {
+ drain(false);
+ if (!event.isTrusted || event.target !== el || event.inputType !== 'deleteContentForward'
+ || record.selected !== 1 || record.deleted !== 1 || record.before || !current() || !fullySelected()) record.invalid = true;
+ else record.before++;
+ },
+ input(event) {
+ if (!event.isTrusted || event.target !== el || event.inputType !== 'deleteContentForward'
+ || record.before !== 1 || record.inputs || !current()) { record.invalid = true; return; }
+ drain(true); record.inputs++;
+ const caret = _singleEditableCaretBreak(el); record.caret = originalBreaks.has(caret) ? null : caret;
+ record.settledRange = rangeNow()?.cloneRange();
+ },
+ selectionchange() {
+ const value = rangeNow();
+ if (record.inputs ? !sameRange(value, record.settledRange)
+ : (!record.selected && !sameRange(value, originalRange))
+ || !value || !el.contains(value.startContainer) || !el.contains(value.endContainer)) record.invalid = true;
+ },
+ focusin(event) { if (event.target !== el) record.invalid = true; },
+ focusout() { record.invalid = true; }, pointerdown() { record.invalid = true; },
+ wheel() { record.invalid = true; }, paste() { record.invalid = true; }, drop() { record.invalid = true; },
+ };
+ for (const [name, listener] of Object.entries(handlers)) {
+ // Capture above existing document listeners: their callback checkpoint
+ // must not deliver this exact native deletion as an unrelated mutation.
+ view.addEventListener(name, listener, true); record.listeners.push([name, listener]);
+ }
+ while (_nativeChatClearPreparations.size >= 8) _releaseNativeChatClear(_nativeChatClearPreparations.keys().next().value);
+ record.timer = setTimeout(() => _releaseNativeChatClear(token), 5000);
+ _nativeChatClearPreparations.set(token, record);
+ return { success: true, token };
+ }
+
+ function _verifyNativeChatClear(ref, token) {
+ const record = _nativeChatClearPreparations.get(token);
+ if (!record) return { success: false };
+ record.drain(false);
+ const valid = !record.invalid && record.current() && window.__wb_ax_lookup?.(ref) === record.el
+ && record.selected === 1 && record.deleted === 1 && record.before === 1 && record.inputs === 1
+ && record.released === 1 && record.selectionCurrent() && record.caret && record.caret === _singleEditableCaretBreak(record.el);
+ _releaseNativeChatClear(token);
+ if (!valid) return { success: false };
+ _rememberNativeChatEmptyCaret(record.el, record.context);
+ return { success: _nativeChatCaretValueIsEmpty(record.el) };
+ }
+
function _rememberNativeChatEmptyCaret(el, context) {
const br = _singleEditableCaretBreak(el);
if (br && _sameNativeChatCaretContext(context, _nativeChatCaretContext(el))) {
@@ -9487,6 +9647,10 @@
return { success: false, error: error && error.message || String(error) };
}
},
+ // Private native-clear receipts do not authorize another input command.
+ 'ax_prepare_native_chat_clear': () => _prepareNativeChatClear(msg.params?.ref_id),
+ 'ax_verify_native_chat_clear': () => _verifyNativeChatClear(msg.params?.ref_id, msg.params?.token),
+ 'ax_release_native_chat_clear': () => { _releaseNativeChatClear(msg.params?.token); return { success: true }; },
'ax_verify_field_value': () => {
try {
const { ref_id, expected, appendText } = msg.params || {};
diff --git a/src/chrome/src/content/page-monitor.js b/src/chrome/src/content/page-monitor.js
index c5f94f130..2a13578a4 100644
--- a/src/chrome/src/content/page-monitor.js
+++ b/src/chrome/src/content/page-monitor.js
@@ -651,7 +651,7 @@
'aria-valuenow', 'aria-valuetext', 'aria-hidden', 'contenteditable', 'tabindex', 'name', 'placeholder', 'title', 'alt',
'for', 'form', 'type', 'href', 'target', 'download', 'action', 'method', 'enctype', 'accept', 'multiple',
'formaction', 'formmethod', 'formenctype', 'formtarget', 'novalidate', 'formnovalidate', 'required', 'readonly',
- 'disabled', 'open', 'inert', 'popover', 'onclick', 'data-selected'];
+ 'disabled', 'open', 'inert', 'popover', 'onclick', 'data-selected', 'src', 'srcset', 'sizes', 'media'];
const modelIdentityDataAttributePattern = /^data-(?:(?:recipient|conversation|thread|chat|channel|resource|entity|record|post|item|message|user|account)(?:-(?:id|key|name|type))?|id|key|uuid|target|action|command|operation|selected|active|current|state|status|testid)$/;
function plainDescriptionTypeIsInert(node) {
const type = node.getAttribute('type');
@@ -795,7 +795,8 @@
text && !nameOnly ? buttonTextWithoutDescription(el, redundantDescription?.node) : directText ? [...el.childNodes].filter(node => node.nodeType === 3).map(node => node.data) : null,
accessibleName, control ? controlState(el) : null,
control && /^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(el.tagName) ? el.value : null,
- control && el.isContentEditable ? el.innerHTML : null]);
+ control && el.isContentEditable ? el.innerHTML : null,
+ el instanceof HTMLImageElement ? el.currentSrc : null]);
}
function modelLabels(el) {
const labels = new Set(el.labels || []);
@@ -876,7 +877,17 @@
&& ![...current.attributes].some(attribute => /^on/i.test(attribute.name))
&& !hasDecorativeEventHandler(current));
}
- function dialogTextIsCovered(owner, boundTextNodes, addNode, identities, form, namedNavigationControls = null) {
+ function bindCollateralImage(node, addNode, visualImages) {
+ const named = ['aria-label', 'aria-labelledby', 'aria-describedby', 'title', 'alt']
+ .some(attribute => (attribute !== 'aria-describedby' || !redundantDescriptionBinding(node))
+ && node.getAttribute(attribute)?.trim());
+ if (!addNode(node, { text: named, fullTextRequired: named })) return false;
+ const sources = node.parentElement?.tagName === 'PICTURE' ? [...node.parentElement.querySelectorAll('source')] : [];
+ if (sources.length > 8 || sources.some(source => !addNode(source))) return false;
+ if (!named && visible(node) && !node.closest('[aria-hidden="true"]')) visualImages?.add(node);
+ return true;
+ }
+ function dialogTextIsCovered(owner, boundTextNodes, addNode, identities, form, namedNavigationControls = null, visualImages = null) {
const authoredLabel = node => ['aria-label', 'aria-labelledby', 'aria-describedby', 'title', 'alt']
.some(attribute => (attribute !== 'aria-describedby' || !redundantDescriptionBinding(node))
&& node.getAttribute(attribute)?.trim());
@@ -938,6 +949,10 @@
// Bind the same plain wrapper before any tooltip appears. Normalizing
// duplicate text never exempts its original type, identity or focus/state.
if (ownedNativeButtonWrapper(node) && !addNode(node)) return false;
+ // Some composers expose the current account only through its avatar.
+ // Bind its original node and selected resource without inventing a name
+ // or allowing an image to establish the action's semantic owner.
+ if (node instanceof HTMLImageElement && !bindCollateralImage(node, addNode, visualImages)) return false;
if (authoredLabel(node)) {
// Account avatars and other authored labels are meaningful context.
// Bind their complete subtree and expose the current rendered identity
@@ -1013,6 +1028,59 @@
try { return window.__wb_readonly_identity_preparation_matches?.(snapshot) === true; }
catch { return false; }
}
+ function nativeInlinePostOwner(action) {
+ // X's home composer has no form, dialog or page-purpose heading. Its
+ // native editor/publish pair and matching local/navigation account links
+ // establish a bounded owner; the live timeline never becomes its context.
+ if (!['x.com', 'www.x.com', 'twitter.com', 'www.twitter.com'].includes(location.hostname)
+ || !/^\/home\/?$/.test(location.pathname)
+ || action.closest('form,[role="form"],'+entityOwnerSelector)) return null;
+ const main = action.closest('main,[role="main"]');
+ if (!main || [...document.querySelectorAll('main,[role="main"]')].filter(visible).length !== 1) return null;
+ const rendered = node => {
+ if (!visible(node)) return false;
+ for (let current = node; current; current = bindingParent(current)) {
+ const style = getComputedStyle(current);
+ if (current.inert || current.hasAttribute('hidden') || current.getAttribute('aria-hidden') === 'true'
+ || style.display === 'none' || ['hidden', 'collapse'].includes(style.visibility)
+ || Number(style.opacity) === 0 || style.contentVisibility === 'hidden') return false;
+ }
+ return true;
+ };
+ const accountKey = link => {
+ if (!(link instanceof HTMLAnchorElement) || !rendered(link)) return '';
+ try {
+ const url = new URL(link.getAttribute('href') || '', location.href);
+ const handle = url.pathname.match(/^\/([A-Za-z0-9_]{1,15})\/?$/)?.[1] || '';
+ return url.origin === location.origin && !url.search && !url.hash && !url.username && !url.password
+ && handle && !/^(home|explore|notifications|messages|search|settings|compose|i)$/i.test(handle)
+ ? handle.toLowerCase() : '';
+ } catch { return ''; }
+ };
+ const navigationLinks = [...document.querySelectorAll('a[data-testid="AppTabBar_Profile_Link"][href]')]
+ .filter(link => rendered(link) && link.closest('nav,[role="navigation"]'));
+ if (navigationLinks.length !== 1 || !accountKey(navigationLinks[0])) return null;
+ for (let owner = bindingParent(action), depth = 0; owner && owner !== main && depth < 32;
+ owner = bindingParent(owner), depth++) {
+ if (owner === document.body || owner === document.documentElement || owner.shadowRoot
+ || owner.matches('form,[role="form"],'+entityOwnerSelector)) return null;
+ const descendants = owner.querySelectorAll('*');
+ if (descendants.length > 256 || owner.querySelectorAll(modelControlSelector).length > 64) return null;
+ const editors = [...owner.querySelectorAll('[contenteditable]:not([contenteditable="false"]),input:not([type="hidden"]):not([type="file"]),textarea')];
+ const publishers = [...owner.querySelectorAll('[data-testid="tweetButtonInline"]')];
+ if (!editors.length || !publishers.length) continue;
+ const editor = editors[0], publisher = publishers[0];
+ if (editors.length !== 1 || publishers.length !== 1 || !editor.isContentEditable
+ || editor.getAttribute('role') !== 'textbox' || editor.getAttribute('data-testid') !== 'tweetTextarea_0'
+ || publisher.tagName !== 'BUTTON' || publisher.type !== 'button' || publisher.form
+ || !rendered(editor) || !rendered(publisher)) return null;
+ const accountLinks = [...owner.querySelectorAll('a[href]')].filter(link => accountKey(link));
+ if (!accountLinks.length) continue;
+ if (accountLinks.length !== 1 || accountKey(accountLinks[0]) !== accountKey(navigationLinks[0])) return null;
+ return { owner, editor, publisher, accountLinks: [accountLinks[0], navigationLinks[0]] };
+ }
+ return null;
+ }
function mainActionOwner(action) {
const main = action.closest('main,[role="main"]');
if (!main || main === action || main === document.body || main === document.documentElement || !visible(main)) return null;
@@ -1043,13 +1111,18 @@
&& activeNode(node, node.matches('input[type="file"]')));
const identities = nodes.filter(node => local(node) && visible(node) && activeNode(node) && node.matches(modelEntityIdentitySelector));
const owners = nodes.filter(node => local(node) && activeNode(node) && node.matches(entityOwnerSelector + ',form,[role="form"]'));
+ // A main heading already supplies ownership. Its own account imagery is
+ // still material collateral; another entity, feed item, form or navigation
+ // must not turn all page imagery into the action's current account proof.
+ const images = nodes.filter(node => node instanceof HTMLImageElement && local(node) && activeNode(node)
+ && !node.closest(entityOwnerSelector + ',form,[role="form"],input,textarea,[contenteditable]:not([contenteditable="false"])'));
const ownedHeadings = headings.filter(node => !action.contains(node)
&& !node.closest(entityOwnerSelector + ',form,[role="form"]'));
const primary = ownedHeadings.filter(node => node.matches('h1,[role="heading"][aria-level="1"]'));
const purpose = primary.length ? primary : ownedHeadings;
if (purpose.length !== 1 || !purpose[0].textContent.trim() || headings.length > 32
- || controls.length > 64 || identities.length > 64 || owners.length > 64) return null;
- return { main, headings, controls, identities, owners };
+ || controls.length > 64 || identities.length > 64 || owners.length > 64 || images.length > 64) return null;
+ return { main, headings, controls, identities, owners, images };
}
function actionFootprint(target, readonlyPreparation = null) {
if (readonlyPreparation && !readonlyPreparationMatches(readonlyPreparation, target)) return null;
@@ -1067,9 +1140,30 @@
const conversation = currentConversationContext(target);
if (conversation && form && !conversation.footer.contains(form)) return null;
let owner = readonlyPreparation?.scope || conversation?.pane || (ownerBase.matches(entityOwnerSelector) ? ownerBase : ownerBase.closest(entityOwnerSelector));
+ const namedSemanticScope = node => {
+ if (!(node instanceof Element) || node === action || node.matches(modelControlSelector)
+ || !node.matches('form,[role="form"],section,[role="region"]')) return false;
+ if (String(node.getAttribute('aria-label') || '').trim()) return true;
+ const ids = (node.getAttribute('aria-labelledby') || '').trim().split(/\s+/).filter(Boolean);
+ const labels = ids.length ? modelLabels(node) : null;
+ // A dangling reference must not borrow a name from contained draft or
+ // button text. Exact, complete current associated labels are observed
+ // separately before this semantic scope can certify an action.
+ return !!labels && ids.every(id => labels.some(label => label.node.id === id))
+ && labels.some(label => ids.includes(label.node.id) && String(window.__wb_ax_name?.(label.node) || label.node.textContent || '').trim());
+ };
+ if (!owner && !conversation && !readonlyPreparation) {
+ const semanticScope = form || action.closest('section,[role="form"]');
+ if (namedSemanticScope(semanticScope)) owner = semanticScope;
+ }
let navigationOwner = false;
let nativeFileSection = null;
let mainOwner = null;
+ let inlinePostOwner = null;
+ if (!owner && !form && !conversation && !structuralFile) {
+ inlinePostOwner = nativeInlinePostOwner(action);
+ if (inlinePostOwner) owner = inlinePostOwner.owner;
+ }
if (!owner && !form && !conversation) {
const section = action.closest('section'), purpose = window.__wb_ax_section_purpose?.(section);
if (section && purpose && section.querySelectorAll('*').length <= 256
@@ -1124,7 +1218,7 @@
// below, instead of including unrelated body counters in its owner.
owner = form; unstructuredOwner = true; meaningfulOwner = true;
}
- const nodes = [], ancestors = [], boundTextNodes = new Set(), dialogIdentities = new Set(), namedNavigationControls = new Set();
+ const nodes = [], ancestors = [], boundTextNodes = new Set(), dialogIdentities = new Set(), namedNavigationControls = new Set(), visualImages = new Set();
let uncoveredLabel = false;
const addNode = (node, options = {}) => {
const previous = nodes.find(item => item.node === node);
@@ -1136,6 +1230,8 @@
return !options.fullTextRequired || boundTextNodes.has(node);
}
if (nodes.length >= 256 || (node.tagName === 'INPUT' && node.type === 'file' && node.files?.length > 32)) return false;
+ if (node instanceof HTMLImageElement && [node.currentSrc, node.getAttribute('src'), node.getAttribute('srcset'), node.getAttribute('sizes')]
+ .some(value => String(value || '').length > 8192)) return false;
const labels = modelLabels(node);
if (!labels) return false;
nodes.push({ node, value: modelSemantic(node, options),
@@ -1193,6 +1289,13 @@
for (const node of mainOwner.headings) if (!addNode(node, { text: true })) return null;
for (const node of mainOwner.identities) if (!addNode(node, { text: true, control: true })) return null;
for (const node of mainOwner.controls) if (!addNode(node, { text: true, control: true })) return null;
+ for (const image of mainOwner.images) {
+ if (!bindCollateralImage(image, addNode, visualImages)) return null;
+ if (boundTextNodes.has(image)) {
+ dialogIdentities.add(image);
+ for (const label of modelLabels(image) || []) dialogIdentities.add(label.node);
+ }
+ }
meaningfulOwner = !uncoveredLabel;
} else if (owner) {
if (!addNode(owner, { directText: true })) return null;
@@ -1205,7 +1308,7 @@
const relatedForm = node.closest('form,[role="form"]');
return (!closest || closest === owner || closest.contains(owner))
&& (!relatedForm || relatedForm === form)
- && !node.closest(allowNavigation === true ? 'aside,[role="complementary"]'
+ && !node.closest(allowNavigation === true || inlinePostOwner ? 'aside,[role="complementary"]'
: 'aside,nav,[role="navigation"],[role="complementary"]');
};
const headings = [...owner.querySelectorAll('h1,h2,h3,h4,h5,h6,[role="heading"],[aria-current]')]
@@ -1216,11 +1319,25 @@
if (identities.length > 64) return null;
for (const identity of identities) if (!addNode(identity, { text: true, control: true })) return null;
meaningfulOwner ||= headings.length > 0 || identities.length > 0 || owner.matches(modelEntityIdentitySelector);
+ if (meaningfulOwner) {
+ const images = [...owner.querySelectorAll('img')].filter(node => belongs(node, navigationOwner)
+ && !node.closest('input,textarea,[contenteditable]:not([contenteditable="false"])')
+ && visible(node));
+ if (images.length > 64) return null;
+ for (const image of images) {
+ if (!bindCollateralImage(image, addNode, visualImages)) return null;
+ if (boundTextNodes.has(image)) {
+ dialogIdentities.add(image);
+ for (const label of modelLabels(image) || []) dialogIdentities.add(label.node);
+ }
+ }
+ }
// Recipients and attachment/caption editors may live next to the form.
// Bind every local control, excluding a separate entity, form or sidebar.
const headingFreeDialog = !meaningfulOwner && owner.matches('dialog,[role="dialog"],[role="alertdialog"]');
+ const headingFreeNamedScope = !meaningfulOwner && namedSemanticScope(owner);
for (const control of owner.querySelectorAll(modelControlSelector)) {
- if (!belongs(control, headingFreeDialog || navigationOwner)) continue;
+ if (!belongs(control, headingFreeDialog || headingFreeNamedScope || navigationOwner)) continue;
// Other authored navigation names stay bound exactly as observed.
// Their non-name badge/icon text does not become account identity.
// The target, selected items, fields and declared entities retain
@@ -1234,9 +1351,19 @@
}
// A heading-free dialog can supply a boundary when all local labels,
// text and controls are bound and identities are completely observed.
- if (navigationOwner) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, namedNavigationControls) && !uncoveredLabel;
- else if (nativeFileSection) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form) && !uncoveredLabel;
- else meaningfulOwner ||= headingFreeDialog && dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form) && !uncoveredLabel;
+ if (headingFreeNamedScope) {
+ dialogIdentities.add(owner);
+ for (const label of modelLabels(owner) || []) dialogIdentities.add(label.node);
+ }
+ if (inlinePostOwner) {
+ meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, null, visualImages) && !uncoveredLabel;
+ // Bind the external signed-in identity only after the complete local
+ // coverage check; unrelated navigation controls are not composer data.
+ for (const link of inlinePostOwner.accountLinks) if (!addNode(link, { text: true, control: true })) return null;
+ } else if (navigationOwner) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, namedNavigationControls, visualImages) && !uncoveredLabel;
+ else if (nativeFileSection) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, null, visualImages) && !uncoveredLabel;
+ else meaningfulOwner ||= (headingFreeDialog || headingFreeNamedScope)
+ && dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, null, visualImages) && !uncoveredLabel;
}
// An arbitrary container/toolbar with no entity anchor cannot establish
// the recipient or item. Such targets retain strict legacy dispatch only.
@@ -1255,6 +1382,8 @@
const hit = structuralFile ? null : modelHit(target, action, rawHit);
return { model: true, structuralFile, target, scope: owner || form || action, ancestors, nodes, hit,
dialogIdentities,
+ visualImages,
+ ...(inlinePostOwner ? { observedAccountLinks: inlinePostOwner.accountLinks } : {}),
...(mainOwner ? { observedMainControls: mainOwner.controls.filter(node => visible(node)) } : {}),
...(conversation ? { conversationCarrier: conversation.carrier, conversationComposer: conversation.composer } : {}),
context: JSON.stringify([location.href, document.baseURI, currentViewport(), window.scrollX, window.scrollY,
@@ -1445,8 +1574,8 @@
const exposedCompleteLabels = new WeakSet();
const collateralMainControls = new WeakSet();
let collateralHeaderExposed = false;
- const exposeIdentity = (node, { authoredEditableName = false, completeLabel = false } = {}) => {
- if (publicNodes.has(node) && !authoredEditableName && !completeLabel) return true;
+ const exposeIdentity = (node, { authoredEditableName = false, completeLabel = false, accountLink = false } = {}) => {
+ if (publicNodes.has(node) && !authoredEditableName && !completeLabel && !accountLink) return true;
if (completeLabel && exposedCompleteLabels.has(node)) return true;
// Emit only current rendered page labels. Editable contents, input
// values, data identities and private control/file state stay private.
@@ -1473,7 +1602,7 @@
// labels are exposed separately before the footprint is certified.
const referencedName = completeLabel && node.getAttribute('aria-labelledby')
? String(window.__wb_ax_name?.(node) || '').replace(/\s+/g, ' ').trim() : '';
- const name = authored || rendered || referencedName;
+ const name = accountLink ? new URL(node.getAttribute('href'), location.href).href : authored || rendered || referencedName;
if (!name || authored.length > 512) return false;
if (authoredEditableName && exposedEditableNames.get(node) === authored) return true;
const ref = window.__wb_ax_ref?.(node);
@@ -1517,6 +1646,19 @@
// direct action or acquire an uncertified fallback during the scan.
return true;
};
+ const exposeVisualImage = node => {
+ if (!visible(node) || node.closest('[aria-hidden="true"]')) return false;
+ const ref = window.__wb_ax_ref?.(node);
+ if (!ref || window.__wb_ax_lookup?.(ref) !== node) return false;
+ const header = evidenceLength ? '' : '\n\n[CURRENT VISIBLE ACTION IDENTITY]\n';
+ const line = header + `visible image name-unavailable=true direct-action=false [${ref}] resource-values-omitted\n`;
+ if (exposedCompleteLabels.has(node)) return true;
+ if (evidenceLength + line.length > MODEL_EVIDENCE_MAX || page.pageContent.length + line.length > MODEL_PUBLIC_MAX
+ || JSON.stringify({ ...page, pageContent: page.pageContent + line }).length > 16000) return false;
+ page.pageContent += line; evidenceLength += line.length; exposedCompleteLabels.add(node);
+ refs.set(ref, node);
+ return true;
+ };
const observedFootprint = footprint => {
if (!page) return true;
if (!footprint.structuralFile && !publicNodes.has(footprint.target)) return false;
@@ -1532,6 +1674,8 @@
} else if (!publicNodes.has(composer)) return false;
}
if (footprint.observedMainControls?.some(node => !exposeMainControl(node))) return false;
+ if (footprint.observedAccountLinks?.some(node => !exposeIdentity(node, { completeLabel: true, accountLink: true }))) return false;
+ if ([...footprint.visualImages || []].some(node => !exposeVisualImage(node))) return false;
const evidence = footprint.nodes.filter(item => item.node !== footprint.target
&& (item.node === footprint.conversationCarrier
|| footprint.dialogIdentities?.has(item.node)
diff --git a/src/chrome/src/trace/privacy.js b/src/chrome/src/trace/privacy.js
index a5c3fdcb8..9eb0b0574 100644
--- a/src/chrome/src/trace/privacy.js
+++ b/src/chrome/src/trace/privacy.js
@@ -70,7 +70,7 @@ const PUBLICATION_CONTRACT_CODES = new Set([...PUBLICATION_CONTRACT_FAILURES]
const EMPTY_OUTPUT_REASONS = new Set(['output_limit', 'reasoning_only', 'content_filter', 'provider_empty']);
const RECOVERY_STAGES = new Set([
'model', 'inference', 'planning', 'plan_alignment', 'publication_audit',
- 'completion_verification', 'verification',
+ 'completion_verification', 'verification', 'action_preparation',
'response_generation', 'browser_interaction',
]);
const RECOVERY_RETRY_MODES = new Set(['resume', 'publication_without_audit', 'publication_audit_bypass']);
diff --git a/src/firefox/src/agent/page-feedback-recovery.js b/src/firefox/src/agent/page-feedback-recovery.js
index 07070e4f8..943032e90 100644
--- a/src/firefox/src/agent/page-feedback-recovery.js
+++ b/src/firefox/src/agent/page-feedback-recovery.js
@@ -6,15 +6,15 @@ export const PAGE_FEEDBACK_STOP_AT = 5;
export const PAGE_FEEDBACK_STOP_CODE = 'page_unstable';
const STOP_MESSAGE = 'Stopped because the page kept changing before the next action could be safely dispatched. '
- + 'The task is incomplete; no stale action was dispatched.';
+ + 'The task is incomplete; no stale action was dispatched. Wait for the page to settle, then choose Retry.';
const NUDGE_MESSAGE = '[PAGE KEEPS CHANGING: Browser updates repeatedly prevented the next action from being dispatched. '
+ 'Use the fresh observation to choose an action whose intended target can be verified. '
+ 'Do not repeat stale targets or coordinates.]';
const UNVERIFIED_NUDGE = '[ACTION CONTEXT UNVERIFIED: The requested control had no verified original action context. '
+ 'No action was dispatched. Inspect the fresh bounded target observation and its intended owner before choosing another action; '
+ 'do not repeatedly attempt a control whose context remains unverified.]';
-const UNVERIFIED_STOP = 'Stopped because the requested control could not be bound to a verified action context. '
- + 'The task is incomplete; no unverified action was dispatched.';
+const UNVERIFIED_STOP = 'Stopped before the next action because WebBrain could not confirm which part of the page the control belongs to. '
+ + 'The task is incomplete. Open or focus the intended area, then choose Retry.';
function boundedStreak(value) {
return Number.isSafeInteger(value) && value > 0 ? Math.min(value, PAGE_FEEDBACK_STOP_AT) : 0;
diff --git a/src/firefox/src/agent/page-feedback.js b/src/firefox/src/agent/page-feedback.js
index 3d7b1696a..6cd7a7c00 100644
--- a/src/firefox/src/agent/page-feedback.js
+++ b/src/firefox/src/agent/page-feedback.js
@@ -796,6 +796,10 @@ export const pageFeedbackMethods = {
this._flushPageFeedbackMessages(tabId, messages);
const recovery = run?.recoveryResult;
if (!recovery) return null;
+ // Retry observes the current page through the normal gates. A context
+ // failure never grants the publication-audit bypass reserved for that audit.
+ this._offerFailureRecovery?.(tabId, { stage: 'action_preparation', code: recovery.code,
+ message: recovery.message }, onUpdate);
onUpdate('warning', { message: recovery.message });
return { action: 'return', value: recovery.message, status: recovery.code };
},
diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.js
index 6c682c091..1d84ed23f 100644
--- a/src/firefox/src/content/content.js
+++ b/src/firefox/src/content/content.js
@@ -4237,6 +4237,166 @@
return texts.join('\n');
}
+ const _nativeChatClearPreparations = new Map();
+
+ function _releaseNativeChatClear(token) {
+ const record = _nativeChatClearPreparations.get(token);
+ if (!record) return;
+ _nativeChatClearPreparations.delete(token);
+ clearTimeout(record.timer);
+ record.observer.disconnect();
+ for (const [name, listener] of record.listeners) record.view.removeEventListener(name, listener, true);
+ }
+
+ function _prepareNativeChatClear(ref) {
+ const el = window.__wb_ax_lookup?.(ref), context = _nativeChatCaretContext(el);
+ if (!el?.isContentEditable || !el.isConnected || !context || !el.textContent) return { success: false };
+ const doc = el.ownerDocument, root = el.getRootNode(), view = doc.defaultView;
+ const url = doc.URL, documentToken = _axDocumentToken();
+ const ancestors = []; for (let node = el.parentElement; node; node = node.parentElement) ancestors.push(node);
+ const identityNodes = [context.header, context.carrier, context.title, context.selfMarker, context.owner]
+ .filter(node => node?.nodeType === 1);
+ const selection = () => root.getSelection?.() || view.getSelection();
+ const rangeNow = () => { const value = selection(); return value?.rangeCount === 1 ? value.getRangeAt(0) : null; };
+ const sameRange = (a, b) => !!a && !!b && a.startContainer === b.startContainer && a.startOffset === b.startOffset
+ && a.endContainer === b.endContainer && a.endOffset === b.endOffset;
+ const originalBreaks = new Set(el.querySelectorAll('br'));
+ const originalNodes = new Set([el]), originalText = new Map(), deletedTextNodes = new Set();
+ const originalWalker = doc.createTreeWalker(el, view.NodeFilter.SHOW_ALL);
+ for (let node = originalWalker.nextNode(); node; node = originalWalker.nextNode()) {
+ originalNodes.add(node); if (node.nodeType === 3) originalText.set(node, node.nodeValue);
+ }
+ const fullySelected = () => {
+ const value = rangeNow();
+ if (!value || value.collapsed || !el.contains(value.startContainer) || !el.contains(value.endContainer)) return false;
+ const walker = doc.createTreeWalker(el, view.NodeFilter.SHOW_ELEMENT | view.NodeFilter.SHOW_TEXT);
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+ if (node.nodeType === 3) {
+ if (value.comparePoint(node, 0) !== 0 || value.comparePoint(node, node.length) !== 0) return false;
+ } else if (!node.childNodes.length) {
+ const offset = Array.prototype.indexOf.call(node.parentNode.childNodes, node);
+ if (value.comparePoint(node.parentNode, offset) !== 0 || value.comparePoint(node.parentNode, offset + 1) !== 0) return false;
+ }
+ }
+ return true;
+ };
+ const focused = () => (root.activeElement || doc.activeElement) === el;
+ const current = () => el.isConnected && el.ownerDocument === doc && doc.defaultView === view
+ && view.document === doc && el.getRootNode() === root && doc.URL === url
+ && _axDocumentToken() === documentToken && window.__wb_ax_lookup?.(ref) === el && focused()
+ && _sameNativeChatCaretContext(context, _nativeChatCaretContext(el));
+ const selected = selection();
+ if (!current() || selected?.rangeCount !== 1) return { success: false };
+ const range = selected.getRangeAt(0);
+ if (!fullySelected() || !el.contains(range.startContainer) || !el.contains(range.endContainer)
+ || range.cloneContents().textContent !== el.textContent) return { success: false };
+ const token = crypto.randomUUID();
+ const record = { el, doc, view, context, current, listeners: [], selected: 0, deleted: 0, before: 0,
+ inputs: 0, released: 0, invalid: false, caret: null, settledRange: null, pendingDeleteRecords: [] };
+ const originalRange = range.cloneRange();
+ record.selectionCurrent = () => sameRange(rangeNow(), record.settledRange);
+ const relevant = mutation => !(mutation.type === 'attributes'
+ && ['data-webbrain-native-target', 'data-webbrain-page-revision'].includes(mutation.attributeName))
+ && (originalNodes.has(mutation.target) || mutation.target === el || el.contains(mutation.target)
+ || (mutation.type === 'attributes' && ancestors.includes(mutation.target))
+ || identityNodes.some(node => mutation.target === node
+ || (node !== context.owner && node.contains(mutation.target)))
+ || (mutation.type === 'childList' && [...mutation.addedNodes, ...mutation.removedNodes]
+ .some(node => node === el || node.contains?.(el) || identityNodes.includes(node))));
+ const nativeDeleteMutation = mutation => ['childList', 'characterData'].includes(mutation.type)
+ && (originalNodes.has(mutation.target) || mutation.target === el || el.contains(mutation.target));
+ record.observer = new view.MutationObserver(records => {
+ const changes = records.filter(relevant);
+ if (!changes.length) return;
+ // Capture listeners in another world can yield before our trusted input
+ // callback. Only that exact pending native Delete may consume this buffer.
+ if (record.deleted === 1 && record.before === 1 && record.inputs === 0 && current()
+ && changes.every(nativeDeleteMutation) && record.pendingDeleteRecords.length + changes.length <= 128) {
+ record.pendingDeleteRecords.push(...changes);
+ } else record.invalid = true;
+ });
+ record.observer.observe(doc.documentElement, { subtree: true, attributes: true, childList: true, characterData: true, characterDataOldValue: true });
+ const drain = nativeDelete => {
+ const changes = [...record.pendingDeleteRecords, ...record.observer.takeRecords()]; record.pendingDeleteRecords = [];
+ for (const mutation of changes.filter(relevant)) {
+ if (!nativeDelete || !nativeDeleteMutation(mutation)) { record.invalid = true; continue; }
+ if (mutation.type === 'characterData') {
+ if (!originalText.has(mutation.target) || mutation.oldValue !== originalText.get(mutation.target)
+ || mutation.target.nodeValue !== '' || deletedTextNodes.has(mutation.target)) record.invalid = true;
+ deletedTextNodes.add(mutation.target);
+ } else if (!originalNodes.has(mutation.target)
+ || [...mutation.removedNodes].some(node => !originalNodes.has(node))
+ || [...mutation.addedNodes].some(node => node !== el.firstChild || node.nodeName !== 'BR'
+ || node.attributes.length !== 0 || originalBreaks.has(node))) record.invalid = true;
+ }
+ };
+ record.drain = drain;
+ const handlers = {
+ keydown(event) {
+ if (!event.isTrusted || event.target !== el || !current()) { record.invalid = true; return; }
+ if (/^(?:Control|Meta)(?:Left|Right)$/.test(event.code) && !record.selected && !record.deleted
+ && !record.modifierCode && !event.altKey && !event.shiftKey) { record.modifierCode = event.code; return; }
+ if (event.code === 'KeyA' && (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey
+ && !record.selected && !record.deleted) { record.selected++; return; }
+ if (event.code === 'Delete' && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey
+ && record.selected === 1 && !record.deleted && fullySelected()) { record.deleted++; return; }
+ record.invalid = true;
+ },
+ keyup(event) {
+ if (!event.isTrusted || event.target !== el) { record.invalid = true; return; }
+ if (event.code === record.modifierCode && record.selected === 1 && !record.deleted
+ && !record.modifierReleased) { record.modifierReleased = true; return; }
+ if (event.code === 'KeyA' && record.selected === 1 && !record.deleted) return;
+ if (event.code === 'Delete' && record.deleted === 1 && !record.released) { record.released++; return; }
+ record.invalid = true;
+ },
+ beforeinput(event) {
+ drain(false);
+ if (!event.isTrusted || event.target !== el || event.inputType !== 'deleteContentForward'
+ || record.selected !== 1 || record.deleted !== 1 || record.before || !current() || !fullySelected()) record.invalid = true;
+ else record.before++;
+ },
+ input(event) {
+ if (!event.isTrusted || event.target !== el || event.inputType !== 'deleteContentForward'
+ || record.before !== 1 || record.inputs || !current()) { record.invalid = true; return; }
+ drain(true); record.inputs++;
+ const caret = _singleEditableCaretBreak(el); record.caret = originalBreaks.has(caret) ? null : caret;
+ record.settledRange = rangeNow()?.cloneRange();
+ },
+ selectionchange() {
+ const value = rangeNow();
+ if (record.inputs ? !sameRange(value, record.settledRange)
+ : (!record.selected && !sameRange(value, originalRange))
+ || !value || !el.contains(value.startContainer) || !el.contains(value.endContainer)) record.invalid = true;
+ },
+ focusin(event) { if (event.target !== el) record.invalid = true; },
+ focusout() { record.invalid = true; }, pointerdown() { record.invalid = true; },
+ wheel() { record.invalid = true; }, paste() { record.invalid = true; }, drop() { record.invalid = true; },
+ };
+ for (const [name, listener] of Object.entries(handlers)) {
+ // Capture above existing document listeners: their callback checkpoint
+ // must not deliver this exact native deletion as an unrelated mutation.
+ view.addEventListener(name, listener, true); record.listeners.push([name, listener]);
+ }
+ while (_nativeChatClearPreparations.size >= 8) _releaseNativeChatClear(_nativeChatClearPreparations.keys().next().value);
+ record.timer = setTimeout(() => _releaseNativeChatClear(token), 5000);
+ _nativeChatClearPreparations.set(token, record);
+ return { success: true, token };
+ }
+
+ function _verifyNativeChatClear(ref, token) {
+ const record = _nativeChatClearPreparations.get(token);
+ if (!record) return { success: false };
+ record.drain(false);
+ const valid = !record.invalid && record.current() && window.__wb_ax_lookup?.(ref) === record.el
+ && record.selected === 1 && record.deleted === 1 && record.before === 1 && record.inputs === 1
+ && record.released === 1 && record.selectionCurrent() && record.caret && record.caret === _singleEditableCaretBreak(record.el);
+ _releaseNativeChatClear(token);
+ if (!valid) return { success: false };
+ _rememberNativeChatEmptyCaret(record.el, record.context);
+ return { success: _nativeChatCaretValueIsEmpty(record.el) };
+ }
+
function _rememberNativeChatEmptyCaret(el, context) {
const br = _singleEditableCaretBreak(el);
if (br && _sameNativeChatCaretContext(context, _nativeChatCaretContext(el))) {
@@ -8416,6 +8576,10 @@
return failure(e && e.message || String(e));
}
},
+ // Private native-clear receipts do not authorize another input command.
+ 'ax_prepare_native_chat_clear': () => _prepareNativeChatClear(msg.params?.ref_id),
+ 'ax_verify_native_chat_clear': () => _verifyNativeChatClear(msg.params?.ref_id, msg.params?.token),
+ 'ax_release_native_chat_clear': () => { _releaseNativeChatClear(msg.params?.token); return { success: true }; },
'ax_verify_field_value': () => {
try {
const { ref_id, expected, appendText } = msg.params || {};
diff --git a/src/firefox/src/content/page-monitor.js b/src/firefox/src/content/page-monitor.js
index c5f94f130..2a13578a4 100644
--- a/src/firefox/src/content/page-monitor.js
+++ b/src/firefox/src/content/page-monitor.js
@@ -651,7 +651,7 @@
'aria-valuenow', 'aria-valuetext', 'aria-hidden', 'contenteditable', 'tabindex', 'name', 'placeholder', 'title', 'alt',
'for', 'form', 'type', 'href', 'target', 'download', 'action', 'method', 'enctype', 'accept', 'multiple',
'formaction', 'formmethod', 'formenctype', 'formtarget', 'novalidate', 'formnovalidate', 'required', 'readonly',
- 'disabled', 'open', 'inert', 'popover', 'onclick', 'data-selected'];
+ 'disabled', 'open', 'inert', 'popover', 'onclick', 'data-selected', 'src', 'srcset', 'sizes', 'media'];
const modelIdentityDataAttributePattern = /^data-(?:(?:recipient|conversation|thread|chat|channel|resource|entity|record|post|item|message|user|account)(?:-(?:id|key|name|type))?|id|key|uuid|target|action|command|operation|selected|active|current|state|status|testid)$/;
function plainDescriptionTypeIsInert(node) {
const type = node.getAttribute('type');
@@ -795,7 +795,8 @@
text && !nameOnly ? buttonTextWithoutDescription(el, redundantDescription?.node) : directText ? [...el.childNodes].filter(node => node.nodeType === 3).map(node => node.data) : null,
accessibleName, control ? controlState(el) : null,
control && /^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(el.tagName) ? el.value : null,
- control && el.isContentEditable ? el.innerHTML : null]);
+ control && el.isContentEditable ? el.innerHTML : null,
+ el instanceof HTMLImageElement ? el.currentSrc : null]);
}
function modelLabels(el) {
const labels = new Set(el.labels || []);
@@ -876,7 +877,17 @@
&& ![...current.attributes].some(attribute => /^on/i.test(attribute.name))
&& !hasDecorativeEventHandler(current));
}
- function dialogTextIsCovered(owner, boundTextNodes, addNode, identities, form, namedNavigationControls = null) {
+ function bindCollateralImage(node, addNode, visualImages) {
+ const named = ['aria-label', 'aria-labelledby', 'aria-describedby', 'title', 'alt']
+ .some(attribute => (attribute !== 'aria-describedby' || !redundantDescriptionBinding(node))
+ && node.getAttribute(attribute)?.trim());
+ if (!addNode(node, { text: named, fullTextRequired: named })) return false;
+ const sources = node.parentElement?.tagName === 'PICTURE' ? [...node.parentElement.querySelectorAll('source')] : [];
+ if (sources.length > 8 || sources.some(source => !addNode(source))) return false;
+ if (!named && visible(node) && !node.closest('[aria-hidden="true"]')) visualImages?.add(node);
+ return true;
+ }
+ function dialogTextIsCovered(owner, boundTextNodes, addNode, identities, form, namedNavigationControls = null, visualImages = null) {
const authoredLabel = node => ['aria-label', 'aria-labelledby', 'aria-describedby', 'title', 'alt']
.some(attribute => (attribute !== 'aria-describedby' || !redundantDescriptionBinding(node))
&& node.getAttribute(attribute)?.trim());
@@ -938,6 +949,10 @@
// Bind the same plain wrapper before any tooltip appears. Normalizing
// duplicate text never exempts its original type, identity or focus/state.
if (ownedNativeButtonWrapper(node) && !addNode(node)) return false;
+ // Some composers expose the current account only through its avatar.
+ // Bind its original node and selected resource without inventing a name
+ // or allowing an image to establish the action's semantic owner.
+ if (node instanceof HTMLImageElement && !bindCollateralImage(node, addNode, visualImages)) return false;
if (authoredLabel(node)) {
// Account avatars and other authored labels are meaningful context.
// Bind their complete subtree and expose the current rendered identity
@@ -1013,6 +1028,59 @@
try { return window.__wb_readonly_identity_preparation_matches?.(snapshot) === true; }
catch { return false; }
}
+ function nativeInlinePostOwner(action) {
+ // X's home composer has no form, dialog or page-purpose heading. Its
+ // native editor/publish pair and matching local/navigation account links
+ // establish a bounded owner; the live timeline never becomes its context.
+ if (!['x.com', 'www.x.com', 'twitter.com', 'www.twitter.com'].includes(location.hostname)
+ || !/^\/home\/?$/.test(location.pathname)
+ || action.closest('form,[role="form"],'+entityOwnerSelector)) return null;
+ const main = action.closest('main,[role="main"]');
+ if (!main || [...document.querySelectorAll('main,[role="main"]')].filter(visible).length !== 1) return null;
+ const rendered = node => {
+ if (!visible(node)) return false;
+ for (let current = node; current; current = bindingParent(current)) {
+ const style = getComputedStyle(current);
+ if (current.inert || current.hasAttribute('hidden') || current.getAttribute('aria-hidden') === 'true'
+ || style.display === 'none' || ['hidden', 'collapse'].includes(style.visibility)
+ || Number(style.opacity) === 0 || style.contentVisibility === 'hidden') return false;
+ }
+ return true;
+ };
+ const accountKey = link => {
+ if (!(link instanceof HTMLAnchorElement) || !rendered(link)) return '';
+ try {
+ const url = new URL(link.getAttribute('href') || '', location.href);
+ const handle = url.pathname.match(/^\/([A-Za-z0-9_]{1,15})\/?$/)?.[1] || '';
+ return url.origin === location.origin && !url.search && !url.hash && !url.username && !url.password
+ && handle && !/^(home|explore|notifications|messages|search|settings|compose|i)$/i.test(handle)
+ ? handle.toLowerCase() : '';
+ } catch { return ''; }
+ };
+ const navigationLinks = [...document.querySelectorAll('a[data-testid="AppTabBar_Profile_Link"][href]')]
+ .filter(link => rendered(link) && link.closest('nav,[role="navigation"]'));
+ if (navigationLinks.length !== 1 || !accountKey(navigationLinks[0])) return null;
+ for (let owner = bindingParent(action), depth = 0; owner && owner !== main && depth < 32;
+ owner = bindingParent(owner), depth++) {
+ if (owner === document.body || owner === document.documentElement || owner.shadowRoot
+ || owner.matches('form,[role="form"],'+entityOwnerSelector)) return null;
+ const descendants = owner.querySelectorAll('*');
+ if (descendants.length > 256 || owner.querySelectorAll(modelControlSelector).length > 64) return null;
+ const editors = [...owner.querySelectorAll('[contenteditable]:not([contenteditable="false"]),input:not([type="hidden"]):not([type="file"]),textarea')];
+ const publishers = [...owner.querySelectorAll('[data-testid="tweetButtonInline"]')];
+ if (!editors.length || !publishers.length) continue;
+ const editor = editors[0], publisher = publishers[0];
+ if (editors.length !== 1 || publishers.length !== 1 || !editor.isContentEditable
+ || editor.getAttribute('role') !== 'textbox' || editor.getAttribute('data-testid') !== 'tweetTextarea_0'
+ || publisher.tagName !== 'BUTTON' || publisher.type !== 'button' || publisher.form
+ || !rendered(editor) || !rendered(publisher)) return null;
+ const accountLinks = [...owner.querySelectorAll('a[href]')].filter(link => accountKey(link));
+ if (!accountLinks.length) continue;
+ if (accountLinks.length !== 1 || accountKey(accountLinks[0]) !== accountKey(navigationLinks[0])) return null;
+ return { owner, editor, publisher, accountLinks: [accountLinks[0], navigationLinks[0]] };
+ }
+ return null;
+ }
function mainActionOwner(action) {
const main = action.closest('main,[role="main"]');
if (!main || main === action || main === document.body || main === document.documentElement || !visible(main)) return null;
@@ -1043,13 +1111,18 @@
&& activeNode(node, node.matches('input[type="file"]')));
const identities = nodes.filter(node => local(node) && visible(node) && activeNode(node) && node.matches(modelEntityIdentitySelector));
const owners = nodes.filter(node => local(node) && activeNode(node) && node.matches(entityOwnerSelector + ',form,[role="form"]'));
+ // A main heading already supplies ownership. Its own account imagery is
+ // still material collateral; another entity, feed item, form or navigation
+ // must not turn all page imagery into the action's current account proof.
+ const images = nodes.filter(node => node instanceof HTMLImageElement && local(node) && activeNode(node)
+ && !node.closest(entityOwnerSelector + ',form,[role="form"],input,textarea,[contenteditable]:not([contenteditable="false"])'));
const ownedHeadings = headings.filter(node => !action.contains(node)
&& !node.closest(entityOwnerSelector + ',form,[role="form"]'));
const primary = ownedHeadings.filter(node => node.matches('h1,[role="heading"][aria-level="1"]'));
const purpose = primary.length ? primary : ownedHeadings;
if (purpose.length !== 1 || !purpose[0].textContent.trim() || headings.length > 32
- || controls.length > 64 || identities.length > 64 || owners.length > 64) return null;
- return { main, headings, controls, identities, owners };
+ || controls.length > 64 || identities.length > 64 || owners.length > 64 || images.length > 64) return null;
+ return { main, headings, controls, identities, owners, images };
}
function actionFootprint(target, readonlyPreparation = null) {
if (readonlyPreparation && !readonlyPreparationMatches(readonlyPreparation, target)) return null;
@@ -1067,9 +1140,30 @@
const conversation = currentConversationContext(target);
if (conversation && form && !conversation.footer.contains(form)) return null;
let owner = readonlyPreparation?.scope || conversation?.pane || (ownerBase.matches(entityOwnerSelector) ? ownerBase : ownerBase.closest(entityOwnerSelector));
+ const namedSemanticScope = node => {
+ if (!(node instanceof Element) || node === action || node.matches(modelControlSelector)
+ || !node.matches('form,[role="form"],section,[role="region"]')) return false;
+ if (String(node.getAttribute('aria-label') || '').trim()) return true;
+ const ids = (node.getAttribute('aria-labelledby') || '').trim().split(/\s+/).filter(Boolean);
+ const labels = ids.length ? modelLabels(node) : null;
+ // A dangling reference must not borrow a name from contained draft or
+ // button text. Exact, complete current associated labels are observed
+ // separately before this semantic scope can certify an action.
+ return !!labels && ids.every(id => labels.some(label => label.node.id === id))
+ && labels.some(label => ids.includes(label.node.id) && String(window.__wb_ax_name?.(label.node) || label.node.textContent || '').trim());
+ };
+ if (!owner && !conversation && !readonlyPreparation) {
+ const semanticScope = form || action.closest('section,[role="form"]');
+ if (namedSemanticScope(semanticScope)) owner = semanticScope;
+ }
let navigationOwner = false;
let nativeFileSection = null;
let mainOwner = null;
+ let inlinePostOwner = null;
+ if (!owner && !form && !conversation && !structuralFile) {
+ inlinePostOwner = nativeInlinePostOwner(action);
+ if (inlinePostOwner) owner = inlinePostOwner.owner;
+ }
if (!owner && !form && !conversation) {
const section = action.closest('section'), purpose = window.__wb_ax_section_purpose?.(section);
if (section && purpose && section.querySelectorAll('*').length <= 256
@@ -1124,7 +1218,7 @@
// below, instead of including unrelated body counters in its owner.
owner = form; unstructuredOwner = true; meaningfulOwner = true;
}
- const nodes = [], ancestors = [], boundTextNodes = new Set(), dialogIdentities = new Set(), namedNavigationControls = new Set();
+ const nodes = [], ancestors = [], boundTextNodes = new Set(), dialogIdentities = new Set(), namedNavigationControls = new Set(), visualImages = new Set();
let uncoveredLabel = false;
const addNode = (node, options = {}) => {
const previous = nodes.find(item => item.node === node);
@@ -1136,6 +1230,8 @@
return !options.fullTextRequired || boundTextNodes.has(node);
}
if (nodes.length >= 256 || (node.tagName === 'INPUT' && node.type === 'file' && node.files?.length > 32)) return false;
+ if (node instanceof HTMLImageElement && [node.currentSrc, node.getAttribute('src'), node.getAttribute('srcset'), node.getAttribute('sizes')]
+ .some(value => String(value || '').length > 8192)) return false;
const labels = modelLabels(node);
if (!labels) return false;
nodes.push({ node, value: modelSemantic(node, options),
@@ -1193,6 +1289,13 @@
for (const node of mainOwner.headings) if (!addNode(node, { text: true })) return null;
for (const node of mainOwner.identities) if (!addNode(node, { text: true, control: true })) return null;
for (const node of mainOwner.controls) if (!addNode(node, { text: true, control: true })) return null;
+ for (const image of mainOwner.images) {
+ if (!bindCollateralImage(image, addNode, visualImages)) return null;
+ if (boundTextNodes.has(image)) {
+ dialogIdentities.add(image);
+ for (const label of modelLabels(image) || []) dialogIdentities.add(label.node);
+ }
+ }
meaningfulOwner = !uncoveredLabel;
} else if (owner) {
if (!addNode(owner, { directText: true })) return null;
@@ -1205,7 +1308,7 @@
const relatedForm = node.closest('form,[role="form"]');
return (!closest || closest === owner || closest.contains(owner))
&& (!relatedForm || relatedForm === form)
- && !node.closest(allowNavigation === true ? 'aside,[role="complementary"]'
+ && !node.closest(allowNavigation === true || inlinePostOwner ? 'aside,[role="complementary"]'
: 'aside,nav,[role="navigation"],[role="complementary"]');
};
const headings = [...owner.querySelectorAll('h1,h2,h3,h4,h5,h6,[role="heading"],[aria-current]')]
@@ -1216,11 +1319,25 @@
if (identities.length > 64) return null;
for (const identity of identities) if (!addNode(identity, { text: true, control: true })) return null;
meaningfulOwner ||= headings.length > 0 || identities.length > 0 || owner.matches(modelEntityIdentitySelector);
+ if (meaningfulOwner) {
+ const images = [...owner.querySelectorAll('img')].filter(node => belongs(node, navigationOwner)
+ && !node.closest('input,textarea,[contenteditable]:not([contenteditable="false"])')
+ && visible(node));
+ if (images.length > 64) return null;
+ for (const image of images) {
+ if (!bindCollateralImage(image, addNode, visualImages)) return null;
+ if (boundTextNodes.has(image)) {
+ dialogIdentities.add(image);
+ for (const label of modelLabels(image) || []) dialogIdentities.add(label.node);
+ }
+ }
+ }
// Recipients and attachment/caption editors may live next to the form.
// Bind every local control, excluding a separate entity, form or sidebar.
const headingFreeDialog = !meaningfulOwner && owner.matches('dialog,[role="dialog"],[role="alertdialog"]');
+ const headingFreeNamedScope = !meaningfulOwner && namedSemanticScope(owner);
for (const control of owner.querySelectorAll(modelControlSelector)) {
- if (!belongs(control, headingFreeDialog || navigationOwner)) continue;
+ if (!belongs(control, headingFreeDialog || headingFreeNamedScope || navigationOwner)) continue;
// Other authored navigation names stay bound exactly as observed.
// Their non-name badge/icon text does not become account identity.
// The target, selected items, fields and declared entities retain
@@ -1234,9 +1351,19 @@
}
// A heading-free dialog can supply a boundary when all local labels,
// text and controls are bound and identities are completely observed.
- if (navigationOwner) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, namedNavigationControls) && !uncoveredLabel;
- else if (nativeFileSection) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form) && !uncoveredLabel;
- else meaningfulOwner ||= headingFreeDialog && dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form) && !uncoveredLabel;
+ if (headingFreeNamedScope) {
+ dialogIdentities.add(owner);
+ for (const label of modelLabels(owner) || []) dialogIdentities.add(label.node);
+ }
+ if (inlinePostOwner) {
+ meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, null, visualImages) && !uncoveredLabel;
+ // Bind the external signed-in identity only after the complete local
+ // coverage check; unrelated navigation controls are not composer data.
+ for (const link of inlinePostOwner.accountLinks) if (!addNode(link, { text: true, control: true })) return null;
+ } else if (navigationOwner) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, namedNavigationControls, visualImages) && !uncoveredLabel;
+ else if (nativeFileSection) meaningfulOwner = dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, null, visualImages) && !uncoveredLabel;
+ else meaningfulOwner ||= (headingFreeDialog || headingFreeNamedScope)
+ && dialogTextIsCovered(owner, boundTextNodes, addNode, dialogIdentities, form, null, visualImages) && !uncoveredLabel;
}
// An arbitrary container/toolbar with no entity anchor cannot establish
// the recipient or item. Such targets retain strict legacy dispatch only.
@@ -1255,6 +1382,8 @@
const hit = structuralFile ? null : modelHit(target, action, rawHit);
return { model: true, structuralFile, target, scope: owner || form || action, ancestors, nodes, hit,
dialogIdentities,
+ visualImages,
+ ...(inlinePostOwner ? { observedAccountLinks: inlinePostOwner.accountLinks } : {}),
...(mainOwner ? { observedMainControls: mainOwner.controls.filter(node => visible(node)) } : {}),
...(conversation ? { conversationCarrier: conversation.carrier, conversationComposer: conversation.composer } : {}),
context: JSON.stringify([location.href, document.baseURI, currentViewport(), window.scrollX, window.scrollY,
@@ -1445,8 +1574,8 @@
const exposedCompleteLabels = new WeakSet();
const collateralMainControls = new WeakSet();
let collateralHeaderExposed = false;
- const exposeIdentity = (node, { authoredEditableName = false, completeLabel = false } = {}) => {
- if (publicNodes.has(node) && !authoredEditableName && !completeLabel) return true;
+ const exposeIdentity = (node, { authoredEditableName = false, completeLabel = false, accountLink = false } = {}) => {
+ if (publicNodes.has(node) && !authoredEditableName && !completeLabel && !accountLink) return true;
if (completeLabel && exposedCompleteLabels.has(node)) return true;
// Emit only current rendered page labels. Editable contents, input
// values, data identities and private control/file state stay private.
@@ -1473,7 +1602,7 @@
// labels are exposed separately before the footprint is certified.
const referencedName = completeLabel && node.getAttribute('aria-labelledby')
? String(window.__wb_ax_name?.(node) || '').replace(/\s+/g, ' ').trim() : '';
- const name = authored || rendered || referencedName;
+ const name = accountLink ? new URL(node.getAttribute('href'), location.href).href : authored || rendered || referencedName;
if (!name || authored.length > 512) return false;
if (authoredEditableName && exposedEditableNames.get(node) === authored) return true;
const ref = window.__wb_ax_ref?.(node);
@@ -1517,6 +1646,19 @@
// direct action or acquire an uncertified fallback during the scan.
return true;
};
+ const exposeVisualImage = node => {
+ if (!visible(node) || node.closest('[aria-hidden="true"]')) return false;
+ const ref = window.__wb_ax_ref?.(node);
+ if (!ref || window.__wb_ax_lookup?.(ref) !== node) return false;
+ const header = evidenceLength ? '' : '\n\n[CURRENT VISIBLE ACTION IDENTITY]\n';
+ const line = header + `visible image name-unavailable=true direct-action=false [${ref}] resource-values-omitted\n`;
+ if (exposedCompleteLabels.has(node)) return true;
+ if (evidenceLength + line.length > MODEL_EVIDENCE_MAX || page.pageContent.length + line.length > MODEL_PUBLIC_MAX
+ || JSON.stringify({ ...page, pageContent: page.pageContent + line }).length > 16000) return false;
+ page.pageContent += line; evidenceLength += line.length; exposedCompleteLabels.add(node);
+ refs.set(ref, node);
+ return true;
+ };
const observedFootprint = footprint => {
if (!page) return true;
if (!footprint.structuralFile && !publicNodes.has(footprint.target)) return false;
@@ -1532,6 +1674,8 @@
} else if (!publicNodes.has(composer)) return false;
}
if (footprint.observedMainControls?.some(node => !exposeMainControl(node))) return false;
+ if (footprint.observedAccountLinks?.some(node => !exposeIdentity(node, { completeLabel: true, accountLink: true }))) return false;
+ if ([...footprint.visualImages || []].some(node => !exposeVisualImage(node))) return false;
const evidence = footprint.nodes.filter(item => item.node !== footprint.target
&& (item.node === footprint.conversationCarrier
|| footprint.dialogIdentities?.has(item.node)
diff --git a/src/firefox/src/trace/privacy.js b/src/firefox/src/trace/privacy.js
index a5c3fdcb8..9eb0b0574 100644
--- a/src/firefox/src/trace/privacy.js
+++ b/src/firefox/src/trace/privacy.js
@@ -70,7 +70,7 @@ const PUBLICATION_CONTRACT_CODES = new Set([...PUBLICATION_CONTRACT_FAILURES]
const EMPTY_OUTPUT_REASONS = new Set(['output_limit', 'reasoning_only', 'content_filter', 'provider_empty']);
const RECOVERY_STAGES = new Set([
'model', 'inference', 'planning', 'plan_alignment', 'publication_audit',
- 'completion_verification', 'verification',
+ 'completion_verification', 'verification', 'action_preparation',
'response_generation', 'browser_interaction',
]);
const RECOVERY_RETRY_MODES = new Set(['resume', 'publication_without_audit', 'publication_audit_bypass']);
diff --git a/test/bluesky-composer-context.mjs b/test/bluesky-composer-context.mjs
new file mode 100644
index 000000000..6197054a6
--- /dev/null
+++ b/test/bluesky-composer-context.mjs
@@ -0,0 +1,475 @@
+import assert from 'node:assert/strict';
+import { readFile, mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test } from 'node:test';
+import { chromium, firefox } from 'playwright';
+import { build as bundle } from 'esbuild';
+import { BidiSession } from '../firefox-companion/session.mjs';
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const output = path.join(root, 'build/test-logs/bluesky-composer-context');
+await mkdir(output, { recursive: true });
+const editorBundle = (await bundle({ entryPoints: [path.join(root, 'test/fixtures/bluesky-composer-editor.mjs')],
+ bundle: true, write: false, format: 'iife', globalName: 'qaEditorLibrary', platform: 'browser' })).outputFiles[0].text;
+const sourceFiles = ['rich-text-toolbar-heuristic.js', 'accessibility-tree.js', 'chat-observation.js', 'page-monitor.js', 'content.js'];
+const sources = new Map(await Promise.all(['chrome', 'firefox'].map(async build => [build,
+ await Promise.all(sourceFiles.map(name => readFile(path.join(root, 'src', build, 'src/content', name), 'utf8')))])));
+const transparentAvatar = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="42" height="42"%3E%3Crect width="42" height="42" fill="%238ac"/%3E%3C/svg%3E';
+
+// Source-backed native topology from official Bluesky social-app commit
+// 46d98dd457a197cee8502863b420222508f29fa6. Composer.web.tsx supplies the
+// heading-free modal boundary. Composer.tsx supplies a current account avatar,
+// composerPublishBtn; ThreadgateBtn.tsx supplies openReplyGateButton. The web
+// TextInput ignores the accessibilityLabel passed by Composer; Tiptap adds
+// role=textbox itself, with placeholder on a paragraph rather than an aria name.
+// All saves are local fixture requests; this never loads or posts to Bluesky.
+function html(shape = 'bluesky-dialog') {
+ const boundary = shape === 'bluesky-dialog' ? 'div role="dialog" aria-modal="true"'
+ : shape === 'named-form' ? 'form aria-label="Create owned post"'
+ : shape === 'named-region' ? 'div role="region" aria-label="Create owned post"'
+ : shape === 'named-section' ? 'section aria-label="Create owned post"'
+ : shape === 'headed-main' ? 'main' : 'div';
+ const tag = boundary.split(' ')[0];
+ return `<!doctype html><style>
+ body{margin:0;font:16px sans-serif;width:1200px;height:800px;background:#eee}
+ #composer{position:absolute;left:230px;top:30px;width:620px;height:550px;background:white;padding:12px}
+ #topbar{display:flex;justify-content:space-between;height:45px}#editor-row{display:flex;gap:12px}
+ #editor-host{width:540px}.ProseMirror{height:220px;min-height:220px;white-space:pre-wrap;outline:1px solid #aaa}
+ .ProseMirror p{margin:0}.ProseMirror p.is-empty:before{content:attr(data-placeholder);color:#888;pointer-events:none;float:left;height:0}
+ [role="button"],button{padding:8px;min-height:28px;cursor:pointer}#feed{position:absolute;left:920px;top:0;width:260px}
+ #account-navigation{position:absolute;left:10px;top:10px;width:190px}#avatar-wrapper{width:42px;height:42px;position:relative;overflow:hidden}#avatar{width:42px;height:42px;object-fit:cover}
+ </style><nav id="account-navigation"><a id="profile" href="/profile/owned.bsky.social">Profile</a></nav>
+ <aside id="feed"><h2>Following</h2><span id="feed-counter">12 likes</span><div id="feed-items">An unrelated feed post.</div></aside>
+ <${boundary} id="composer"><div data-testid="composePostView">
+ ${shape === 'headed-main' ? '<h1>Create owned post</h1>' : ''}
+ <div id="topbar"><div role="button" tabindex="0" aria-label="Cancel">Cancel</div>
+ <div id="publish" role="button" tabindex="0" aria-label="Publish post" aria-disabled="true" data-testid="composerPublishBtn">Post</div></div>
+ <div id="editor-row"><div id="avatar-wrapper" data-testid="userAvatarImage" data-expoimage="true"><img id="avatar" src='${transparentAvatar}'></div><div id="editor-host"></div></div>
+ <div id="footer"><div id="audience" role="button" tabindex="0" aria-label="Anyone can interact" data-testid="openReplyGateButton">Anyone can interact</div>
+ <div role="button" tabindex="0" aria-label="Add image">Add image</div></div>
+ </div></${tag}>`;
+}
+
+async function fixture(browser, build, { shape = 'bluesky-dialog', value = '', background } = {}) {
+ const context = await browser.newContext({ viewport: { width: 1200, height: 800 } });
+ const saves = [], errors = [];
+ await context.route('https://bsky.app/**', async route => {
+ if (route.request().method() === 'POST') {
+ assert.equal(new URL(route.request().url()).pathname, '/owned-fixture-save');
+ saves.push(route.request().postDataJSON());
+ await route.fulfill({ contentType: 'application/json', body: '{"saved":true}' });
+ } else await route.fulfill({ contentType: 'text/html', body: html(shape) });
+ });
+ await context.exposeFunction('qaBackground', background || (async message => (
+ message.action === 'get_page_monitor_state'
+ ? { active: true, runToken: 'bluesky-owned-run', documentToken: message.documentToken }
+ : message.action === 'page_feedback' ? { accepted: true } : {}
+ )));
+ await context.addInitScript(() => {
+ window.qaListeners = []; window.qaFeedback = []; window.qaInputEvents = []; window.qaExecCommands = [];
+ window.chrome = window.browser = { runtime: {
+ getURL: value => value, onMessage: { addListener: listener => qaListeners.push(listener), removeListener() {} },
+ sendMessage: message => { if (message.action === 'page_feedback') qaFeedback.push(message.feedback); return window.qaBackground(message); },
+ } };
+ window.qaMessage = (action, params = {}, original = {}) => new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error(`Missing production response: ${action}`)), 5000);
+ let answered = false;
+ const respond = result => { answered = true; clearTimeout(timeout); resolve(result); };
+ for (const listener of qaListeners) {
+ const result = listener({ ...original, target: 'content', action, params: { runToken: 'bluesky-owned-run', ...params } }, {}, respond);
+ if (answered || result === true) return;
+ }
+ clearTimeout(timeout); resolve(undefined);
+ });
+ });
+ for (const content of sources.get(build)) await context.addInitScript({ content });
+ const page = await context.newPage();
+ page.setDefaultTimeout(5000);
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto('https://bsky.app/');
+ await page.addScriptTag({ content: editorBundle });
+ await page.evaluate(value => {
+ qaEditorLibrary.mountEditor(value);
+ for (const type of ['beforeinput', 'input', 'paste']) document.getElementById('editor-host').addEventListener(type,
+ event => qaInputEvents.push({ type, trusted: event.isTrusted, inputType: event.inputType, data: event.data }), true);
+ const original = document.execCommand.bind(document);
+ document.execCommand = (command, ui, value) => { qaExecCommands.push({ command, value }); return original(command, ui, value); };
+ document.getElementById('publish').addEventListener('click', async event => {
+ event.preventDefault();
+ if (document.getElementById('publish').getAttribute('aria-disabled') === 'true') return;
+ await fetch('/owned-fixture-save', { method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ value: qaSnapshotEditor().model }) });
+ window.qaSaved = qaSnapshotEditor().model;
+ });
+ }, value);
+ if (!background) await page.waitForFunction(() => __wbPageMonitor.active);
+ await page.waitForTimeout(180);
+ return { context, page, saves, errors };
+}
+
+async function capture(page) {
+ return page.evaluate(async () => {
+ const snapshot = await qaMessage('page_monitor_capture_model', { includeTree: true });
+ const ref = __wb_ax_ref(document.querySelector('.ProseMirror'));
+ return { snapshot, ref, originalTree: snapshot.page?.pageContent, editor: qaSnapshotEditor() };
+ });
+}
+async function validate(page, observed) {
+ return page.evaluate(({ snapshot, ref }) => qaMessage('page_monitor_validate_model', {
+ tool: 'type_ax', ref_id: ref, snapshotToken: snapshot.snapshotToken, runToken: snapshot.runToken,
+ }), observed);
+}
+async function churn(page) {
+ await page.evaluate(() => {
+ document.getElementById('feed-counter').textContent = '13 likes';
+ document.getElementById('feed-items').append(Object.assign(document.createElement('article'), { textContent: 'A newly arrived unrelated feed post.' }));
+ });
+ await page.waitForTimeout(180);
+}
+
+// Exercise the production companion declarations against actual Firefox and
+// EditorView. As in firefox-rich-text-readback.mjs, only the native transport is
+// adapted to Playwright's trusted keyboard; preparation, per-key monitor fences,
+// focus, exact semantic readback and outcome classification are production code.
+async function firefoxNative(page, guard) {
+ const session = new BidiSession();
+ const runId = crypto.randomUUID(), commands = [];
+ session.runs.set(runId, { context: 'owned-bluesky-firefox' });
+ session.locate = async () => ({ context: 'owned-bluesky-firefox', node: { sharedId: 'original-prosemirror' } });
+ const editor = await page.evaluateHandle(() => qaEditorView.dom);
+ session.call = async (_match, declaration, args = [], resultOwnership = null) => {
+ const handle = resultOwnership === 'root' ? crypto.randomUUID() : null;
+ const value = await page.evaluate(({ declaration, args, handle, editor }) => {
+ window.qaRemoteObjects ||= new Map();
+ const value = (0, eval)(`(${declaration})`)(editor,
+ ...args.map(arg => arg.handle ? qaRemoteObjects.get(arg.handle) : arg.value ?? null));
+ if (handle && value !== null) { qaRemoteObjects.set(handle, value); return { qaHandle: handle }; }
+ return value;
+ }, { declaration, args, handle, editor });
+ if (value?.qaHandle) return { result: { type: 'object', handle: value.qaHandle } };
+ return { result: value && typeof value === 'object'
+ ? { type: 'object', value: Object.entries(value).map(([name, item]) => [name, { type: typeof item, value: item }]) }
+ : value === null ? { type: 'null' } : { value } };
+ };
+ const keys = new Map([['\uE009', 'Control'], ['\uE03D', 'Meta'], ['\uE003', 'Backspace'], ['\uE007', 'Enter']]);
+ const held = new Set();
+ session.send = async (method, params) => {
+ commands.push({ method, params });
+ if (method === 'script.disown') {
+ await page.evaluate(handles => { for (const handle of handles) qaRemoteObjects?.delete(handle); }, params.handles);
+ } else if (method === 'input.releaseActions') {
+ for (const key of held) await page.keyboard.up(key);
+ held.clear();
+ } else if (method === 'input.performActions') {
+ for (const action of params.actions[0].actions) {
+ const key = keys.get(action.value);
+ if (key) {
+ if (action.type === 'keyDown') { await page.keyboard.down(key); held.add(key); }
+ else { await page.keyboard.up(key); held.delete(key); }
+ } else if (action.type === 'keyDown') {
+ if (held.has('Control') || held.has('Meta')) await page.keyboard.press(action.value);
+ else await page.keyboard.type(action.value);
+ }
+ }
+ }
+ return {};
+ };
+ return { commands, async perform(text, clear) {
+ const token = crypto.randomUUID();
+ await page.evaluate(token => qaEditorView.dom.setAttribute('data-webbrain-bidi', token), token);
+ return session.perform(runId, 'field', { token, text, clear, pageFeedbackGuard: guard },
+ async (_id, currentGuard, kind, rebindFocus) => (await page.evaluate(({ guard, kind, rebindFocus }) =>
+ qaMessage('page_monitor_validate', { ...guard, kind, rebindFocus }),
+ { guard: currentGuard, kind, rebindFocus })).ready === true);
+ } };
+}
+
+for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
+ test(`${build}: source-backed Bluesky and generic composer owners survive passive outside churn`, { timeout: 120000 }, async t => {
+ const browser = await engine.launch({ headless: true });
+ try {
+ for (const shape of ['bluesky-dialog', 'named-form', 'named-region', 'named-section', 'headed-main']) {
+ await t.test(shape, async () => {
+ const f = await fixture(browser, build, { shape });
+ try {
+ const observed = await capture(f.page);
+ assert.equal(observed.snapshot.ready, true);
+ assert.ok(observed.originalTree?.includes(`[${observed.ref}]`), observed.originalTree);
+ assert.equal(observed.editor.editorName, null, 'Do not invent the web editor aria-label that the native app drops');
+ assert.equal(observed.editor.placeholder, "What's up?");
+ assert.equal((await validate(f.page, observed)).ready, true, JSON.stringify({ shape, observed }));
+ await churn(f.page);
+ assert.equal((await validate(f.page, observed)).ready, true, 'The original observation remains valid after unrelated feed changes');
+ const preparation = await f.page.evaluate(({ snapshot, ref }) => qaMessage('page_monitor_prepare', {
+ tool: 'type_ax', ref_id: ref, operationId: 'bluesky-prepared', expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true,
+ }), observed);
+ assert.equal(preparation.ready, true, JSON.stringify(preparation));
+ assert.equal(preparation.modelBindingValid, true);
+ const expected = 'One source-bound draft.\n\nTürkçe 中文 🧠';
+ const result = await f.page.evaluate(({ ref, expected }) => qaMessage('type_ax', {
+ ref_id: ref, text: expected, clear: true,
+ }), { ref: observed.ref, expected });
+ const state = await f.page.evaluate(() => qaSnapshotEditor());
+ assert.equal(result.success, false, JSON.stringify({ result, state }));
+ assert.equal(result.trustedTypeRequired, true, 'The managed ProseMirror document requires the trusted browser transport');
+ assert.equal(result.dispatched, false);
+ assert.equal(state.model, '', 'Content preflight does not mutate the managed editor ahead of trusted input');
+ assert.deepEqual(await f.page.evaluate(() => qaExecCommands), []);
+ const events = await f.page.evaluate(() => qaInputEvents);
+ assert.deepEqual(events, []);
+ assert.deepEqual(f.errors, []);
+ assert.equal(f.saves.length, 0);
+ await writeFile(path.join(output, `${build}-${shape}.json`), JSON.stringify({
+ original: observed.snapshot, preparation, result, state,
+ }, null, 2));
+ } finally { await f.context.close(); }
+ });
+ }
+ const changes = [
+ ['audience', () => { const node = document.getElementById('audience'); node.setAttribute('aria-label', 'Interaction limited'); node.textContent = 'Interaction limited'; }],
+ ['account avatar source', () => document.getElementById('avatar').setAttribute('src', 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg"/%3E')],
+ ['account avatar node', () => { const avatar = document.getElementById('avatar'); avatar.replaceWith(avatar.cloneNode(true)); }],
+ ['owner node', () => { const owner = document.getElementById('composer'); owner.replaceWith(owner.cloneNode(true)); }],
+ ['hidden associated account', () => { const node = document.createElement('span'); node.id = 'current-account-name'; node.style.display = 'none'; node.textContent = 'Posting as other account'; document.getElementById('composer').append(node); document.getElementById('composer').setAttribute('aria-labelledby', node.id); }],
+ ['nested audience identity', () => { document.getElementById('audience').innerHTML = '<span aria-label="Only mentioned accounts">Anyone can interact</span>'; }],
+ ['editor document', () => { const view = qaEditorView; view.dispatch(view.state.tr.insertText('Human changed draft')); }],
+ ];
+ for (const [name, change] of changes) await t.test(`original Bluesky observation vetoes ${name} drift before input`, async () => {
+ const f = await fixture(browser, build);
+ try {
+ const observed = await capture(f.page);
+ assert.equal((await validate(f.page, observed)).ready, true);
+ await f.page.evaluate(change);
+ await f.page.waitForTimeout(180);
+ const checked = await validate(f.page, observed);
+ assert.equal(checked.ready, false, JSON.stringify({ name, checked }));
+ const prepared = await f.page.evaluate(({ snapshot, ref }) => qaMessage('page_monitor_prepare', {
+ tool: 'type_ax', ref_id: ref, operationId: 'bluesky-veto', expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true,
+ }), observed);
+ assert.equal(prepared.ready && prepared.modelBindingValid, false, JSON.stringify(prepared));
+ const result = await f.page.evaluate(({ snapshot, ref }) => qaMessage('type_ax', {
+ ref_id: ref, text: 'Do not insert stale draft\nDo not publish', clear: true,
+ expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true,
+ }), observed);
+ assert.equal(result.success, false, JSON.stringify(result));
+ assert.ok(result.dispatched === false || result.noDispatch === true, JSON.stringify(result));
+ assert.equal(await f.page.evaluate(() => qaInputEvents.length), 0);
+ assert.equal(f.saves.length, 0);
+ await writeFile(path.join(output, `${build}-${name.replaceAll(' ', '-')}.json`), JSON.stringify({ checked, prepared, result }, null, 2));
+ } finally { await f.context.close(); }
+ });
+ for (const shape of ['named-form', 'named-region', 'named-section', 'headed-main']) {
+ for (const [name, change] of changes.slice(0, 2)) await t.test(`${shape} vetoes ${name} drift before input`, async () => {
+ const f = await fixture(browser, build, { shape });
+ try {
+ const observed = await capture(f.page);
+ assert.equal((await validate(f.page, observed)).ready, true);
+ await f.page.evaluate(change);
+ await f.page.waitForTimeout(180);
+ const checked = await validate(f.page, observed);
+ await writeFile(path.join(output, `${build}-${shape}-${name.replaceAll(' ', '-')}.json`), JSON.stringify({ checked }, null, 2));
+ assert.equal(checked.ready, false, JSON.stringify({ shape, name, checked }));
+ assert.equal(await f.page.evaluate(() => qaInputEvents.length), 0);
+ assert.equal(f.saves.length, 0);
+ } finally { await f.context.close(); }
+ });
+ }
+ await t.test('an arbitrary unlabelled DIV remains uncertified despite real ProseMirror markup', async () => {
+ const f = await fixture(browser, build, { shape: 'unlabelled-div' });
+ try { assert.equal((await validate(f.page, await capture(f.page))).ready, false); }
+ finally { await f.context.close(); }
+ });
+ } finally { await browser.close(); }
+ });
+}
+
+test('Chrome: actual Bluesky ProseMirror model receives one certified native edit and saves exact text', { timeout: 120000 }, async t => {
+ const previousChrome = globalThis.chrome, previousBrowser = globalThis.browser;
+ const { installPageFeedback } = await import('../src/chrome/src/agent/page-feedback.js');
+ const { cdpClient } = await import('../src/chrome/src/cdp/cdp-client.js');
+ const { Agent } = await import('../src/chrome/src/agent/agent.js');
+ const originalAttach = cdpClient.attach, originalCommand = cdpClient.sendCommand;
+ const browser = await chromium.launch({ headless: true });
+ const tabId = 83, documentId = 'bluesky-owned-document';
+ const previousSession = cdpClient.sessions.get(tabId);
+ let f, session, host;
+ const messages = [], commands = [], captures = [];
+ const compatibility = new Agent({});
+ class Host {
+ static STATE_CHANGE_TOOLS = new Set(['type_ax', 'set_field']);
+ isRunning() { return true; }
+ _checkAbort() { return false; }
+ _throwIfAborted() {}
+ _persist() {}
+ _effectiveRunMode() { return 'act'; }
+ _appOwnedUserMessage(content, webbrainAppOwnedKind) { return { role: 'user', content, webbrainAppOwnedKind }; }
+ _wrapUntrusted(_kind, value) { return value; }
+ _finalizeToolResultOnce(_tab, _name, _args, result) { return result; }
+ async executeTool(_tab, name, args, _onUpdate, context) {
+ const result = await f.page.evaluate(({ name, args }) => qaMessage(name, args), { name, args });
+ return compatibility._maybeFallbackFieldWithCdpImpl(tabId, name, args, result, context);
+ }
+ }
+ installPageFeedback(Host);
+ const api = { runtime: {}, tabs: {
+ get: async () => ({ id: tabId, url: f.page.url() }),
+ sendMessage: async (_tab, message) => {
+ messages.push(message);
+ const result = await f.page.evaluate(message => qaMessage(message.action, message.params || {}, message), message);
+ if (message.action === 'page_monitor_capture_model') captures.push(result);
+ return result;
+ },
+ }, webNavigation: { getAllFrames: async () => [{ frameId: 0, documentId, url: f.page.url() }] },
+ debugger: { sendCommand: (_target, method, params, callback) => {
+ commands.push({ method, params });
+ session.send(method, params).then(callback, error => {
+ api.runtime.lastError = { message: error.message }; callback(); delete api.runtime.lastError;
+ });
+ } } };
+ globalThis.chrome = globalThis.browser = api;
+ const cases = [
+ { name: 'empty replacement', previous: '', text: 'One owned Bluesky draft.', clear: true },
+ { name: 'nonempty replacement', previous: 'Old draft', text: 'New draft', clear: true },
+ { name: 'append', previous: 'Owned draft', text: ' appended once', clear: false },
+ { name: 'multiline', previous: '', text: 'First\n\nSecond\nThird', clear: true },
+ { name: 'multiline append', previous: 'Existing\nlast', text: '\n\nAnother\n', clear: false },
+ { name: 'leading and trailing line breaks', previous: '', text: '\nFirst\n\n', clear: true },
+ { name: 'CRLF document separators', previous: 'Old', text: 'First\r\n\r\nLast\r\n', clear: true },
+ { name: 'empty clear', previous: 'Old\n\ndraft', text: '', clear: true },
+ { name: 'already empty clear', previous: '', text: '', clear: true },
+ { name: 'literal markup and Unicode', previous: '', text: '<b>literal</b> & Türkçe 中文 العربية 🧠 e\u0301', clear: true },
+ { name: 'exact whitespace', previous: 'Old', text: ' spaces and\ttab\u00a0nonbreaking ', clear: true },
+ ...['named-form', 'named-region', 'named-section', 'headed-main'].map(shape => ({
+ name: `${shape} exact native edit`, shape, previous: 'Original\nlast', text: '\n\nGeneric owner 🧠', clear: false,
+ })),
+ ];
+ try {
+ for (const item of cases) await t.test(item.name, async () => {
+ host = new Host(); captures.length = 0; commands.length = 0; messages.length = 0;
+ f = await fixture(browser, 'chrome', { value: item.previous, shape: item.shape, background: async message => {
+ const sender = { tab: { id: tabId }, frameId: 0, documentId, url: f?.page.url() || 'https://bsky.app/' };
+ if (message.action === 'get_page_monitor_state') return host.pageMonitorState(sender, message.documentToken);
+ if (message.action === 'page_feedback') return host.observePageFeedback(sender, message.feedback);
+ return {};
+ } });
+ try {
+ session = await f.page.context().newCDPSession(f.page);
+ cdpClient.attach = async () => cdpClient.sessions.set(tabId, {});
+ cdpClient.sendCommand = originalCommand;
+ await host._beginPageFeedbackRun(tabId, 'bluesky-context');
+ await f.page.waitForFunction(() => __wbPageMonitor.active);
+ await f.page.waitForTimeout(180);
+ await host._capturePageFeedbackModelState(tabId, []);
+ assert.equal(captures.length, 1);
+ const snapshot = captures[0];
+ const ref = await f.page.evaluate(() => __wb_ax_ref(document.querySelector('.ProseMirror')));
+ assert.ok(snapshot.page.pageContent.includes(`[${ref}]`), snapshot.page.pageContent);
+ await churn(f.page);
+ assert.equal((await validate(f.page, { snapshot, ref })).ready, true);
+ const result = await host.executeTool(tabId, 'type_ax', { ref_id: ref, text: item.text, clear: item.clear });
+ const expected = (item.clear ? '' : item.previous) + item.text.replace(/\r\n?/g, '\n');
+ const state = await f.page.evaluate(() => qaSnapshotEditor());
+ assert.equal(result.success, true, JSON.stringify({ result, state }));
+ assert.equal(result.verified, true);
+ assert.equal(state.model, expected, 'Read the real application EditorState independently of extension readback');
+ assert.equal(captures.length, 1, 'Native dispatch uses the original pre-churn observation, not a fresh baseline');
+ assert.deepEqual(await f.page.evaluate(() => qaExecCommands), [], 'Managed editor never reaches generic execCommand or HTML insertion');
+ assert.deepEqual(f.errors, []);
+ assert.ok(commands.filter(command => command.method === 'Input.insertText').length <= 1, 'Never duplicate the requested native insertion');
+ if (expected.trim()) {
+ await f.page.locator('#publish').click();
+ await f.page.waitForFunction(expected => window.qaSaved === expected, expected);
+ assert.equal(f.saves.length, 1);
+ assert.equal(f.saves[0].value, expected, 'Saved application request agrees with the original requested exact text');
+ } else {
+ assert.equal(await f.page.locator('#publish').getAttribute('aria-disabled'), 'true');
+ assert.equal(f.saves.length, 0, 'The app prevents publishing an empty draft');
+ }
+ await writeFile(path.join(output, `chrome-native-${item.name.replaceAll(' ', '-')}.json`), JSON.stringify({ result, state, save: f.saves[0] }, null, 2));
+ } finally { await f.context.close(); }
+ });
+ } finally {
+ await browser.close();
+ cdpClient.attach = originalAttach; cdpClient.sendCommand = originalCommand;
+ if (previousSession) cdpClient.sessions.set(tabId, previousSession); else cdpClient.sessions.delete(tabId);
+ if (previousChrome === undefined) delete globalThis.chrome; else globalThis.chrome = previousChrome;
+ if (previousBrowser === undefined) delete globalThis.browser; else globalThis.browser = previousBrowser;
+ }
+});
+
+test('Firefox: production BiDi input preserves the real Bluesky ProseMirror document and original owner', { timeout: 120000 }, async t => {
+ const browser = await firefox.launch({ headless: true });
+ const cases = [
+ { name: 'empty replacement', previous: '', text: 'One owned draft 🧠', clear: true },
+ { name: 'nonempty replacement', previous: 'Old draft', text: 'New draft', clear: true },
+ { name: 'append', previous: 'Original\nlast', text: ' appended once', clear: false },
+ { name: 'multiline replacement', previous: 'Old\n\ndraft', text: '\nFirst\n\nLast\n', clear: true },
+ { name: 'multiline append', previous: 'Original\nlast', text: '\n\nAnother\n', clear: false },
+ { name: 'CRLF document separators', previous: 'Old', text: 'First\r\n\r\nLast\r\n', clear: true },
+ { name: 'empty clear', previous: 'Old\n\ndraft', text: '', clear: true },
+ { name: 'already empty clear', previous: '', text: '', clear: true },
+ { name: 'literal markup and Unicode', previous: '', text: '<b>literal</b> & Türkçe 中文 🧠 e\u0301', clear: true },
+ { name: 'exact whitespace', previous: 'Old', text: ' spaces and\ttab\u00a0nonbreaking ', clear: true },
+ ...['named-form', 'named-region', 'named-section', 'headed-main'].map(shape => ({
+ name: `${shape} exact native edit`, shape, previous: 'Original\nlast', text: '\nGeneric owner', clear: false,
+ })),
+ ];
+ try {
+ for (const item of cases) await t.test(item.name, async () => {
+ const f = await fixture(browser, 'firefox', { value: item.previous, shape: item.shape });
+ try {
+ const observed = await capture(f.page);
+ assert.equal((await validate(f.page, observed)).ready, true);
+ await churn(f.page);
+ assert.equal((await validate(f.page, observed)).ready, true);
+ const fence = await f.page.evaluate(async ({ snapshot, ref, text, clear }) => {
+ const preparation = await qaMessage('page_monitor_prepare', { tool: 'type_ax', ref_id: ref, operationId: 'bluesky-bidi-input',
+ expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true });
+ const target = await qaMessage('type_ax', { ref_id: ref, text, clear, _bidiPrepare: crypto.randomUUID(),
+ expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true });
+ const dispatch = await qaMessage('page_monitor_dispatch', { operationId: 'bluesky-bidi-input', kind: 'input', fenceOnly: true });
+ return { preparation, target, dispatch };
+ }, { ...observed, text: item.text, clear: item.clear });
+ assert.equal(fence.preparation.modelBindingValid, true, JSON.stringify(fence));
+ assert.equal(fence.target.bidiPrepared, true, JSON.stringify(fence));
+ assert.equal(fence.dispatch.ready, true, JSON.stringify(fence));
+ const native = await firefoxNative(f.page, fence.dispatch.guard);
+ let result;
+ try { result = await native.perform(item.text, item.clear); }
+ catch (error) {
+ const evidence = await f.page.evaluate(guard => ({ model: qaSnapshotEditor(), feedback: qaFeedback,
+ publishDisabled: document.getElementById('publish').getAttribute('aria-disabled'),
+ }), fence.dispatch.guard);
+ evidence.validation = await f.page.evaluate(guard => qaMessage('page_monitor_validate', { ...guard, kind: 'input' }), fence.dispatch.guard);
+ evidence.veto = await f.page.evaluate(guard => qaMessage('page_monitor_dispatch', { ...guard, kind: 'input', fenceOnly: true }), fence.dispatch.guard);
+ await writeFile(path.join(output, `firefox-native-${item.name.replaceAll(' ', '-')}-failure.json`),
+ JSON.stringify({ error: error.message, dispatchState: error.dispatchState, evidence }, null, 2));
+ throw error;
+ }
+ const state = await f.page.evaluate(() => qaSnapshotEditor());
+ const expected = (item.clear ? '' : item.previous) + item.text.replace(/\r\n?/g, '\n');
+ assert.equal(result.success, true, JSON.stringify({ result, state }));
+ assert.equal(result.verified, true);
+ assert.equal(state.model, expected, 'Read the real PM document independently of companion readback');
+ assert.deepEqual(f.errors, []);
+ const commands = await f.page.evaluate(() => qaExecCommands);
+ assert.ok(commands.every(command => command.command === 'insertText' && command.value === '\n'),
+ 'The companion uses editing commands only for literal line breaks, never generic HTML or document replacement');
+ assert.equal(native.commands.some(command => command.params?.actions?.[0]?.actions.some(action => action.value === '\uE007')), false,
+ 'An authored line break never sends the publish Enter shortcut');
+ if (expected.trim()) {
+ await f.page.locator('#publish').click();
+ await f.page.waitForFunction(expected => window.qaSaved === expected, expected);
+ assert.equal(f.saves.length, 1);
+ assert.equal(f.saves[0].value, expected);
+ } else {
+ assert.equal(await f.page.locator('#publish').getAttribute('aria-disabled'), 'true');
+ assert.equal(f.saves.length, 0, 'The app prevents publishing an empty draft');
+ }
+ await writeFile(path.join(output, `firefox-native-${item.name.replaceAll(' ', '-')}.json`),
+ JSON.stringify({ original: observed.snapshot, result, state, save: f.saves[0] }, null, 2));
+ } finally { await f.context.close(); }
+ });
+ } finally { await browser.close(); }
+});
diff --git a/test/cdp-clear-receipt.mjs b/test/cdp-clear-receipt.mjs
index 2fc10924e..7c52cfc94 100644
--- a/test/cdp-clear-receipt.mjs
+++ b/test/cdp-clear-receipt.mjs
@@ -7,6 +7,41 @@ import { createHash } from 'node:crypto';
// Native Chromium keyboard events and the actual public CDP/Agent entry paths.
// Everything is served by the owned fixture; no external account or network.
+test('native textarea replacement and append canonicalize Windows document separators once', async () => {
+ const browser = await chromium.launch({ headless: true });
+ const originals = { attach: cdpClient.attach, sendCommand: cdpClient.sendCommand };
+ try {
+ const page = await browser.newPage();
+ const session = await page.context().newCDPSession(page);
+ const insertions = [];
+ cdpClient.attach = async () => ({ attached: true });
+ cdpClient.sendCommand = async (_tab, method, params) => {
+ if (method === 'Input.insertText') insertions.push(params.text);
+ return session.send(method, params);
+ };
+ for (const route of ['selector', 'focused']) for (const clear of [true, false]) {
+ await page.setContent('<textarea id="editor" style="width:800px">Existing draft</textarea>');
+ await page.locator('#editor').focus();
+ await page.evaluate(() => {
+ const el = document.getElementById('editor'); el.setSelectionRange(el.value.length, el.value.length);
+ });
+ insertions.length = 0;
+ const agent = new Agent({}); agent._showAgentTarget = () => {};
+ const result = route === 'selector'
+ ? await cdpClient.typeText(10, '#editor', 'First\r\n\r\nLast\r', clear)
+ : await agent.executeTool(10, 'type_text', { text: 'First\r\n\r\nLast\r', clear });
+ assert.equal(result.success, true, JSON.stringify(result));
+ assert.equal(result.verified, true);
+ assert.deepEqual(insertions, ['First\n\nLast\n']);
+ assert.equal(await page.locator('#editor').inputValue(), (clear ? '' : 'Existing draft') + 'First\n\nLast\n');
+ }
+ await session.detach();
+ } finally {
+ Object.assign(cdpClient, originals);
+ await browser.close();
+ }
+});
+
test('native generic editor clear receipts preserve literal breaks and reject intervention', async () => {
const browser = await chromium.launch({ headless: true });
const originals = { attach: cdpClient.attach, sendCommand: cdpClient.sendCommand, captureTextClearReceipt: cdpClient.captureTextClearReceipt };
diff --git a/test/cdp-field-submit-recovery.mjs b/test/cdp-field-submit-recovery.mjs
new file mode 100644
index 000000000..882677ae0
--- /dev/null
+++ b/test/cdp-field-submit-recovery.mjs
@@ -0,0 +1,93 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { chromium } from 'playwright';
+import { Agent } from '../src/chrome/src/agent/agent.js';
+import { cdpClient } from '../src/chrome/src/cdp/cdp-client.js';
+
+// Isolate the fallback's submission boundary with real Chromium input. The
+// installed WhatsApp case separately verifies the actual monitor veto, durable
+// pending-send block and shipped reconciliation card before any later send.
+test('trusted field fallback preserves draft proof only for a pre-Enter veto', async t => {
+ const browser = await chromium.launch({ headless: true });
+ const originalChrome = globalThis.chrome, originalBrowser = globalThis.browser;
+ const originals = { attach: cdpClient.attach, sendCommand: cdpClient.sendCommand };
+ const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };
+ const body = 'One exact native draft with spaces and Unicode ı 🧠.';
+ try {
+ for (const boundary of ['before-enter', 'lost-enter-response', 'after-enter']) await t.test(boundary, async () => {
+ const context = await browser.newContext();
+ const posts = [], commands = [];
+ await context.route('**/*', route => {
+ if (route.request().method() === 'POST') {
+ posts.push(route.request().postDataJSON());
+ return route.fulfill({ status: 201, contentType: 'application/json', body: '{"saved":true}' });
+ }
+ return route.fulfill({ contentType: 'text/html', body: '<textarea id="editor" style="width:800px;height:90px"></textarea>' });
+ });
+ const page = await context.newPage(); await page.goto('https://owned-submit.invalid/');
+ await page.evaluate(() => {
+ window.qaInputs = []; window.qaEnter = 0;
+ const editor = document.querySelector('#editor');
+ editor.addEventListener('input', event => qaInputs.push({ trusted: event.isTrusted, value: editor.value }));
+ editor.addEventListener('keydown', event => {
+ if (event.key !== 'Enter') return;
+ event.preventDefault(); qaEnter++;
+ void fetch('/owned-save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ body: editor.value }) });
+ });
+ });
+ globalThis.chrome = globalThis.browser = { storage: { local: area, session: area }, runtime: { getURL: value => value },
+ tabs: { get: async id => ({ id, url: page.url() }), sendMessage: async (_tab, message) => {
+ const params = message.params || {};
+ if (message.action === 'field_value_digest') return { success: false };
+ if (message.action === 'consume_message_recipient_dispatch_binding') return { success: true };
+ if (message.action === 'ax_prepare_field_for_trusted_type') return page.evaluate(() => {
+ const editor = document.querySelector('#editor'); editor.focus(); editor.select();
+ return { success: true, contentEditable: false, isCombobox: false };
+ });
+ if (message.action === 'ax_verify_field_value') return page.evaluate(expected => {
+ const editor = document.querySelector('#editor');
+ return { success: true, verified: editor.value === expected, actual: editor.value };
+ }, params.expected);
+ throw new Error(`Unexpected fallback message ${message.action}`);
+ } } };
+ const session = await context.newCDPSession(page);
+ cdpClient.attach = async () => {};
+ cdpClient.sendCommand = async (_tab, method, params) => {
+ const enterDown = method === 'Input.dispatchKeyEvent' && params.type === 'keyDown' && params.key === 'Enter';
+ const enterUp = method === 'Input.dispatchKeyEvent' && params.type === 'keyUp' && params.key === 'Enter';
+ if (enterDown && boundary === 'before-enter') throw Object.assign(new Error('Owned monitor veto before dispatch'), { code: 'page_feedback_pending' });
+ commands.push({ method, params });
+ const result = await session.send(method, params);
+ if (enterDown && boundary === 'lost-enter-response') throw new Error('Owned lost Enter acknowledgement');
+ if (enterUp && boundary === 'after-enter') throw Object.assign(new Error('Owned feedback after actual Enter'), { code: 'page_feedback_pending' });
+ return result;
+ };
+ const agent = new Agent({});
+ const result = await agent._maybeFallbackFieldWithCdpImpl(10, 'set_field',
+ { ref_id: 'ref_owned', text: body, clear: true, submit: true },
+ { success: false, verified: false, noDispatch: true, dispatched: false, _expectedValue: body, error: 'Owned native input required' },
+ { messageRecipientGuardRequired: true });
+ const native = await page.evaluate(() => ({ body: document.querySelector('#editor').value, inputs: qaInputs, enter: qaEnter }));
+ for (let attempt = 0; boundary !== 'before-enter' && !posts.length && attempt < 20; attempt++) await page.waitForTimeout(10);
+ assert.equal(native.body, body); assert.deepEqual(native.inputs, [{ trusted: true, value: body }]);
+ assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 1);
+ assert.equal(result.success, false); assert.equal(result.dispatched, true); assert.notEqual(result.noDispatch, true);
+ assert.notEqual(result.submitted, true); assert.equal(result.pageHandledBeforeInput, undefined);
+ if (boundary === 'before-enter') {
+ assert.equal(native.enter, 0); assert.deepEqual(posts, []);
+ assert.equal(result.verified, true); assert.equal(result.trusted, true);
+ assert.equal(result.submissionDispatched, false); assert.equal(result.submissionBlockedBeforeDispatch, true);
+ assert.equal(result.submissionOutcomeUnknown, false); assert.equal(result.outcomeUnknown, true);
+ assert.equal(result.repeatBlocked, true); assert.equal(result.retryable, false);
+ } else {
+ assert.equal(native.enter, 1); assert.deepEqual(posts, [{ body }]);
+ assert.notEqual(result.submissionDispatched, false, 'A lost acknowledgement or post-Enter failure cannot prove no submission.');
+ assert.notEqual(result.submissionBlockedBeforeDispatch, true);
+ }
+ await session.detach(); await context.close();
+ });
+ } finally {
+ Object.assign(cdpClient, originals); globalThis.chrome = originalChrome; globalThis.browser = originalBrowser;
+ await browser.close();
+ }
+});
diff --git a/test/firefox-rich-text-readback.mjs b/test/firefox-rich-text-readback.mjs
index 489021ad3..901eb5e64 100644
--- a/test/firefox-rich-text-readback.mjs
+++ b/test/firefox-rich-text-readback.mjs
@@ -1,7 +1,13 @@
import assert from 'node:assert/strict';
-import { readFile } from 'node:fs/promises';
+import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
+import { spawn } from 'node:child_process';
+import { createServer } from 'node:http';
+import { tmpdir } from 'node:os';
+import { basename, dirname, join } from 'node:path';
import { test } from 'node:test';
+import { fileURLToPath } from 'node:url';
import { firefox } from 'playwright';
+import { build } from 'esbuild';
import { BidiSession } from '../firefox-companion/session.mjs';
// Exercise production BiDi declarations against real Firefox DOM and trusted
@@ -14,12 +20,21 @@ async function nativeSession(page, { guard = null, validate = null } = {}) {
session.locate = async () => ({ context: 'owned-firefox-editor', node: { sharedId: 'original-editor' } });
const commands = [];
const declarations = [];
- session.call = async (_match, declaration, args = []) => {
+ const editor = await page.evaluateHandle(() => qaEditor);
+ session.call = async (_match, declaration, args = [], resultOwnership = null) => {
declarations.push(declaration);
- const value = await page.evaluate(({ declaration, args }) => {
+ const handle = resultOwnership === 'root' ? crypto.randomUUID() : null;
+ const value = await page.evaluate(({ declaration, args, handle, editor }) => {
const fn = (0, eval)(`(${declaration})`);
- return fn(window.qaEditor, ...args.map(arg => arg.value ?? null));
- }, { declaration, args });
+ const value = fn(editor, ...args.map(arg => arg.handle
+ ? window.qaNativeHandles?.get(arg.handle) : arg.value ?? null));
+ if (handle && value !== null) {
+ (window.qaNativeHandles ||= new Map()).set(handle, value);
+ return { ownedHandle: handle };
+ }
+ return value;
+ }, { declaration, args, handle, editor });
+ if (value?.ownedHandle) return { result: { type: 'object', handle: value.ownedHandle } };
if (value && typeof value === 'object') {
return { result: { type: 'object', value: Object.entries(value).map(([name, item]) => [name, { type: typeof item, value: item }]) } };
}
@@ -29,7 +44,9 @@ async function nativeSession(page, { guard = null, validate = null } = {}) {
const held = new Set();
session.send = async (method, params) => {
commands.push({ method, params });
- if (method === 'input.releaseActions') {
+ if (method === 'script.disown') {
+ await page.evaluate(handles => { for (const handle of handles) qaNativeHandles.delete(handle); }, params.handles);
+ } else if (method === 'input.releaseActions') {
for (const key of held) await page.keyboard.up(key);
held.clear();
} else if (method === 'input.performActions') {
@@ -47,7 +64,7 @@ async function nativeSession(page, { guard = null, validate = null } = {}) {
return {};
};
return {
- commands, declarations,
+ commands, declarations, session, runId,
async perform(action, payload) {
const token = crypto.randomUUID();
await page.evaluate(token => qaEditor.setAttribute('data-webbrain-bidi', token), token);
@@ -79,6 +96,23 @@ async function loadDraftJs(page, previous = '') {
}, previous);
}
+const proseMirrorBundle = (await build({ entryPoints: [fileURLToPath(new URL('./fixtures/bluesky-composer-editor.mjs', import.meta.url))],
+ bundle: true, write: false, format: 'iife', globalName: 'qaEditorLibrary', platform: 'browser' })).outputFiles[0].text;
+
+async function loadProseMirror(page, previous = '') {
+ await page.evaluate(() => window.__wbPageMonitor?.dispose?.());
+ await page.setContent('<style>.ProseMirror{height:180px;white-space:pre-wrap}.ProseMirror p{margin:0}body{font:16px sans-serif}</style>'
+ + '<main id="app"><div id="editor-host"></div><button id="publish" aria-label="Publish post">Post</button></main>');
+ await page.addScriptTag({ content: proseMirrorBundle });
+ await page.evaluate(previous => {
+ qaEditorLibrary.mountEditor(previous);
+ window.qaEditor = qaEditorView.dom;
+ window.qaPastes = []; window.qaEvents = [];
+ qaEditor.addEventListener('paste', event => qaPastes.push(event.clipboardData?.getData('text/plain')));
+ qaEditor.addEventListener('input', event => qaEvents.push({ trusted: event.isTrusted, inputType: event.inputType }));
+ }, previous);
+}
+
test('Firefox: production BiDi typing uses exact DraftJS model text for empty appends, replacements and existing multiline documents', async t => {
const browser = await firefox.launch({ headless: true });
try {
@@ -111,7 +145,7 @@ test('Firefox: production BiDi typing uses exact DraftJS model text for empty ap
} finally { await browser.close(); }
});
-async function installOwnedMonitor(page) {
+async function installOwnedMonitor(page, selector = '.public-DraftEditor-content') {
await page.evaluate(() => {
const heading = document.createElement('h1'); heading.textContent = 'Owned draft';
document.querySelector('main').prepend(heading);
@@ -122,7 +156,7 @@ async function installOwnedMonitor(page) {
window.qaMonitorListeners = []; window.qaFeedback = []; window.qaEnterDocuments = [];
qaEditor.addEventListener('keydown', event => {
if (event.key !== 'Enter') return;
- qaEnterDocuments.push(qaModel); event.preventDefault(); event.stopImmediatePropagation();
+ qaEnterDocuments.push(typeof qaModel === 'undefined' ? qaModelText : qaModel); event.preventDefault(); event.stopImmediatePropagation();
});
window.chrome = window.browser = { runtime: {
onMessage: { addListener: listener => qaMonitorListeners.push(listener), removeListener() {} },
@@ -144,16 +178,16 @@ async function installOwnedMonitor(page) {
}
await page.waitForFunction(() => window.__wbPageMonitor?.active);
await page.waitForTimeout(100);
- const fence = await page.evaluate(async () => {
+ const fence = await page.evaluate(async selector => {
const snapshot = await qaDeliver('page_monitor_capture_model', { includeTree: true });
const prepared = await qaDeliver('page_monitor_prepare', {
- operationId: 'owned-multiline-edit', tool: 'type_text', selector: '.public-DraftEditor-content',
+ operationId: 'owned-multiline-edit', tool: 'type_text', selector,
expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true,
});
const fence = await qaDeliver('page_monitor_dispatch', { operationId: 'owned-multiline-edit', kind: 'input', fenceOnly: true });
qaFeedback = [];
return { prepared, fence };
- });
+ }, selector);
assert.equal(fence.prepared.modelBindingValid, true, JSON.stringify(fence));
assert.equal(fence.fence.ready, true, JSON.stringify(fence));
return {
@@ -207,20 +241,25 @@ test('Firefox: semantic readback preserves ProseMirror paragraphs and generic re
try {
const page = await browser.newPage();
for (const scenario of [
- { name: 'ProseMirror empty caret', html: '<div id="editor" contenteditable class="ProseMirror"><p><br class="ProseMirror-trailingBreak"></p></div>', text: 'body', expected: 'body' },
- { name: 'ProseMirror document separators', html: '<div id="editor" contenteditable class="ProseMirror"><p>First</p><p>Last</p></div>', text: ' suffix', expected: 'First\nLast suffix' },
+ { name: 'ProseMirror empty caret', previous: '', text: 'body', expected: 'body' },
+ { name: 'ProseMirror document separators', previous: 'First\nLast', text: ' suffix', expected: 'First\nLast suffix' },
{ name: 'ordinary visual paragraph spacing', html: '<div id="editor" contenteditable><p>First</p><p>Last</p></div>', text: ' suffix', expected: 'First\n\nLast suffix' },
{ name: 'ordinary authored spaces', html: '<div id="editor" contenteditable style="white-space:pre-wrap"> Existing </div>', text: ' suffix ', expected: ' Existing suffix ' },
{ name: 'plain input value', html: '<input id="editor" value="Existing">', text: ' suffix', expected: 'Existing suffix' },
]) await t.test(scenario.name, async () => {
- await page.setContent(scenario.html);
- await page.evaluate(() => { window.qaEditor = document.querySelector('#editor'); });
+ if (Object.hasOwn(scenario, 'previous')) await loadProseMirror(page, scenario.previous);
+ else {
+ await page.setContent(scenario.html);
+ await page.evaluate(() => { window.qaEditor = document.querySelector('#editor'); });
+ }
const native = await nativeSession(page);
const result = await native.perform('type', { text: scenario.text });
assert.equal(result.verified, true, JSON.stringify(result));
const state = await page.evaluate(() => ({ text: qaEditor.isContentEditable ? qaEditor.innerText : qaEditor.value, children: qaEditor.childNodes.length }));
- if (scenario.name === 'ProseMirror document separators') assert.equal(state.text, 'First\n\nLast suffix');
- else assert.equal(state.text, scenario.expected);
+ if (scenario.name === 'ProseMirror document separators') {
+ assert.equal(state.text, 'First\n\nLast suffix');
+ assert.equal(await page.evaluate(() => qaModelText), scenario.expected, 'Semantic readback must use authored paragraph separators, not rendered spacing.');
+ } else assert.equal(state.text, scenario.expected);
if (scenario.name === 'ProseMirror empty caret') assert.equal(state.children, 1, 'The caret stays within the ProseMirror paragraph.');
});
} finally { await browser.close(); }
@@ -340,3 +379,215 @@ test('Firefox: DraftJS plain-text paste writes a complete multiline document exa
});
} finally { await browser.close(); }
});
+
+test('Firefox: actual ProseMirror writes one complete plain-text edit without intermediate composer changes', async t => {
+ const browser = await firefox.launch({ headless: true });
+ try {
+ const page = await browser.newPage();
+ for (const scenario of [
+ { name: 'empty replacement', previous: '', action: 'field', text: 'Original draft' },
+ { name: 'nonempty replacement', previous: 'Old draft', action: 'field', text: 'Replacement' },
+ { name: 'empty append', previous: '', action: 'type', text: 'Original draft' },
+ { name: 'single-line append', previous: 'Original', action: 'type', text: ' suffix' },
+ { name: 'multiline replacement', previous: 'Old\n\ndraft', action: 'field', text: 'First\n\nLast\n' },
+ { name: 'multiline append', previous: 'Original\nlast', action: 'type', text: '\n\nAnother\n' },
+ { name: 'empty final paragraph', previous: 'Original\n', action: 'type', text: '\nAnother\n' },
+ { name: 'CRLF paragraphs', previous: '', action: 'field', text: '\r\nFirst\r\n\r\nLast\r\n' },
+ { name: 'literal Unicode and markup', previous: 'Old', action: 'field', text: ' Türkçe ıİ 🧠 <b>literal</b> &\n Next \n' },
+ { name: 'field append without clear', previous: 'Original\nlast', action: 'field', clear: false, text: '\nNext' },
+ { name: 'empty replacement value', previous: 'Original\nlast', action: 'field', text: '' },
+ ]) await t.test(scenario.name, async () => {
+ await loadProseMirror(page, scenario.previous);
+ const native = await nativeSession(page, await installOwnedMonitor(page, '.ProseMirror'));
+ const result = await native.perform(scenario.action, { text: scenario.text, ...(scenario.clear === false ? { clear: false } : {}) });
+ const expected = (scenario.action === 'type' || scenario.clear === false ? scenario.previous : '') + scenario.text.replace(/\r\n?/g, '\n');
+ const facts = await page.evaluate(() => ({ model: qaModelText, pastes: qaPastes, html: qaEditor.innerHTML,
+ disabled: document.querySelector('#publish').getAttribute('aria-disabled'), feedback: qaFeedback,
+ handles: qaNativeHandles.size }));
+ assert.equal(result.success, true, JSON.stringify({ result, facts, expected }));
+ assert.equal(result.verified, true);
+ assert.equal(result.submitted, false);
+ assert.equal(facts.model, expected);
+ assert.equal(facts.disabled, String(!expected.trim()), 'The actual peer submit state changes inside the one verified edit.');
+ assert.deepEqual(facts.pastes, scenario.text ? [scenario.text.replace(/\r\n?/g, '\n')] : []);
+ assert.equal(facts.handles, 0, 'The private owned selection must be released after dispatch.');
+ assert.equal(facts.feedback.some(item => item.source !== 'agent'), false, JSON.stringify(facts.feedback));
+ assert.equal(await page.locator('b').count(), 0, 'Only plain text enters the real editor model.');
+ const keys = native.commands.filter(command => command.method === 'input.performActions')
+ .flatMap(command => command.params.actions[0].actions.filter(action => action.type === 'keyDown').map(action => action.value));
+ assert.deepEqual(keys, scenario.text ? [] : ['\uE003'], 'Replacement must not dispatch an intermediate clear or individual characters.');
+ assert.equal(native.declarations.some(source => source.includes("execCommand('insertText'")), false);
+ });
+ await t.test('peer submit activation retains the following submit fence', async () => {
+ await loadProseMirror(page);
+ const native = await nativeSession(page, await installOwnedMonitor(page, '.ProseMirror'));
+ await assert.rejects(native.perform('field', { text: 'Verified document', submit: true }), error => {
+ assert.equal(error.code, 'page_feedback_pending');
+ assert.equal(error.dispatchState.dispatched, true);
+ assert.equal(error.dispatchState.retryable, false);
+ return true;
+ });
+ assert.equal(await page.evaluate(() => qaModelText), 'Verified document');
+ assert.deepEqual(await page.evaluate(() => qaPastes), ['Verified document']);
+ assert.deepEqual(await page.evaluate(() => qaEnterDocuments), []);
+ });
+ await t.test('a cancelled unchanged paste cannot submit or replay', async () => {
+ await loadProseMirror(page, 'Original');
+ await page.evaluate(() => qaEditor.addEventListener('paste', event => {
+ event.preventDefault(); event.stopImmediatePropagation();
+ }, { capture: true }));
+ const native = await nativeSession(page);
+ const result = await native.perform('field', { text: 'First\n\nLast', submit: true });
+ assert.equal(result.success, false);
+ assert.equal(result.verified, false);
+ assert.equal(result.outcomeUnknown, true);
+ assert.equal(result.retryable, false);
+ assert.equal(result.submitted, false);
+ assert.equal(await page.evaluate(() => qaModelText), 'Original');
+ assert.equal(native.commands.some(command => command.method === 'input.performActions'), false);
+ assert.equal(native.declarations.filter(source => source.includes("new view.ClipboardEvent('paste'")).length, 1);
+ });
+ } finally { await browser.close(); }
+});
+
+test('Firefox: ProseMirror paste retains complete document and original selection ownership', async t => {
+ const browser = await firefox.launch({ headless: true });
+ try {
+ const page = await browser.newPage();
+ for (const shape of ['hidden text', 'opaque inline node', 'noneditable node', 'unsupported block']) await t.test(`unsupported preflight: ${shape}`, async () => {
+ await loadProseMirror(page, 'Original');
+ await page.evaluate(shape => {
+ // Preserve the unsupported rendered document until the production
+ // preflight reads it; PM would otherwise normalize this external edit.
+ qaEditorView.domObserver.stop();
+ const node = document.createElement(shape === 'opaque inline node' ? 'img' : shape === 'unsupported block' ? 'h2' : 'span');
+ if (shape === 'hidden text') node.hidden = true;
+ if (shape === 'noneditable node') node.contentEditable = 'false';
+ if (node.tagName !== 'IMG') node.textContent = 'Unverified';
+ (shape === 'unsupported block' ? qaEditor : qaEditor.firstChild).append(node);
+ }, shape);
+ const native = await nativeSession(page);
+ await assert.rejects(native.perform('field', { text: 'Replacement', submit: true }), error => {
+ assert.equal(error.dispatchState.noDispatch, true);
+ assert.match(error.message, /exact document text/);
+ return true;
+ });
+ assert.equal(native.commands.length, 0);
+ assert.deepEqual(await page.evaluate(() => qaPastes), []);
+ });
+ for (const drift of ['selection', 'paragraph identity', 'editor identity', 'document root', 'focus', 'Stop']) await t.test(`changed before paste: ${drift}`, async () => {
+ await loadProseMirror(page, 'Original');
+ const native = await nativeSession(page);
+ const originalCall = native.session.call;
+ native.session.call = async (...args) => {
+ const result = await originalCall(...args);
+ if (args[3] === 'root') {
+ if (drift === 'Stop') native.session.runs.delete(native.runId);
+ else await page.evaluate(drift => {
+ if (drift === 'selection') getSelection().collapse(qaEditor.firstChild.firstChild, 1);
+ else if (drift === 'paragraph identity') qaEditor.firstChild.replaceWith(qaEditor.firstChild.cloneNode(true));
+ else if (drift === 'editor identity') qaEditor.replaceWith(qaEditor.cloneNode(true));
+ else if (drift === 'document root') {
+ const host = document.createElement('div'); document.body.append(host);
+ host.attachShadow({ mode: 'open' }).append(qaEditor); qaEditor.focus();
+ } else { const input = document.createElement('input'); document.body.append(input); input.focus(); }
+ }, drift);
+ }
+ return result;
+ };
+ await assert.rejects(native.perform('field', { text: 'Replacement', submit: true }), error => {
+ assert.equal(error.dispatchState.noDispatch, true);
+ return true;
+ });
+ assert.deepEqual(await page.evaluate(() => qaPastes), []);
+ assert.equal(native.commands.some(command => command.method === 'input.performActions'), false);
+ assert.equal(await page.evaluate(() => qaNativeHandles.size), 0);
+ });
+ await t.test('loss of the exact document after one paste remains uncertain', async () => {
+ await loadProseMirror(page);
+ await page.evaluate(() => qaEditor.addEventListener('paste', () => setTimeout(() => qaEditor.classList.remove('ProseMirror'), 15)));
+ const native = await nativeSession(page);
+ const result = await native.perform('field', { text: 'First\nLast', submit: true });
+ assert.equal(result.verified, false);
+ assert.equal(result.submitted, false);
+ assert.equal(result.outcomeUnknown, true);
+ assert.equal(result.retryable, false);
+ assert.equal(await page.evaluate(() => qaModelText), 'First\nLast');
+ assert.deepEqual(await page.evaluate(() => qaPastes), ['First\nLast']);
+ assert.equal(native.commands.some(command => command.method === 'input.performActions'), false);
+ });
+ } finally { await browser.close(); }
+});
+
+test('Firefox: actual WebDriver BiDi retains private ProseMirror selection handles through complete edits', { timeout: 30000 }, async () => {
+ const temporaryRoot = await realpath(tmpdir());
+ const profile = await mkdtemp(join(temporaryRoot, 'webbrain-pm-bidi-test-'));
+ const server = createServer((request, response) => {
+ response.setHeader('Content-Type', request.url === '/editor.js' ? 'application/javascript' : 'text/html');
+ response.end(request.url === '/editor.js' ? proseMirrorBundle
+ : '<style>.ProseMirror{height:180px;white-space:pre-wrap}.ProseMirror p{margin:0}</style>'
+ + '<main><div id="editor-host"></div><button id="publish">Post</button></main>'
+ + '<script src="/editor.js"></script><script>qaEditorLibrary.mountEditor();window.qaPastes=[];'
+ + 'qaEditorView.dom.addEventListener("paste",event=>qaPastes.push(event.clipboardData.getData("text/plain")))</script>');
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const url = `http://127.0.0.1:${server.address().port}/`;
+ const child = spawn(firefox.executablePath(), ['--headless', '--no-remote', '--profile', profile, '--remote-debugging-port', '0', url],
+ { stdio: ['ignore', 'ignore', 'pipe'] });
+ const exited = new Promise(resolve => child.once('close', resolve));
+ const session = new BidiSession();
+ try {
+ const port = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Firefox did not start its native BiDi endpoint')), 10000);
+ let output = '';
+ child.stderr.on('data', data => {
+ output += data;
+ const match = output.match(/WebDriver BiDi listening on ws:\/\/127\.0\.0\.1:(\d+)/);
+ if (match) { clearTimeout(timer); resolve(Number(match[1])); }
+ });
+ child.once('error', error => { clearTimeout(timer); reject(error); });
+ });
+ await session.connect(port);
+ let context;
+ const startupDeadline = Date.now() + 10000;
+ while (!context && Date.now() < startupDeadline) {
+ const tree = await session.send('browsingContext.getTree', {});
+ context = tree.contexts.find(item => item.url === url)?.context;
+ if (!context) await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ assert.ok(context, 'The isolated native Firefox profile must open its local test page.');
+ await session.send('browsingContext.navigate', { context, url, wait: 'complete' });
+ const evaluate = async expression => {
+ const response = await session.send('script.evaluate', { target: { context }, expression, awaitPromise: true });
+ assert.notEqual(response.type, 'exception', response.exceptionDetails?.text);
+ return response.result;
+ };
+ const mark = async selector => {
+ const token = crypto.randomUUID();
+ await evaluate(`document.querySelector(${JSON.stringify(selector)}).setAttribute('data-webbrain-bidi', ${JSON.stringify(token)})`);
+ return { token, url };
+ };
+ const runId = crypto.randomUUID(), binding = await mark('#editor-host');
+ await session.openRun(runId, binding.token, binding.url);
+ for (const [action, text, expected] of [
+ ['field', 'Original\nlast', 'Original\nlast'],
+ ['type', '\n\nAnother\n', 'Original\nlast\n\nAnother\n'],
+ ['field', ' Türkçe 🧠 <b>literal</b>\r\nNext\r\n', ' Türkçe 🧠 <b>literal</b>\nNext\n'],
+ ['field', '', ''],
+ ]) {
+ const result = await session.perform(runId, action, { ...await mark('.ProseMirror'), text });
+ assert.equal(result.verified, true, JSON.stringify(result));
+ assert.equal((await evaluate('qaModelText')).value, expected);
+ }
+ assert.deepEqual(JSON.parse((await evaluate('JSON.stringify(qaPastes)')).value),
+ ['Original\nlast', '\n\nAnother\n', ' Türkçe 🧠 <b>literal</b>\nNext\n']);
+ } finally {
+ await session.close().catch(() => {});
+ child.kill(); await exited;
+ await new Promise(resolve => server.close(resolve));
+ const resolved = await realpath(profile);
+ assert.equal(dirname(resolved).toLowerCase(), temporaryRoot.toLowerCase());
+ assert.ok(basename(resolved).startsWith('webbrain-pm-bidi-test-'));
+ await rm(resolved, { recursive: true, force: true });
+ }
+});
diff --git a/test/fixtures/bluesky-composer-editor.mjs b/test/fixtures/bluesky-composer-editor.mjs
new file mode 100644
index 000000000..4244a689e
--- /dev/null
+++ b/test/fixtures/bluesky-composer-editor.mjs
@@ -0,0 +1,62 @@
+import { Fragment, Node, Schema, Slice } from 'prosemirror-model';
+import { EditorState, Plugin, TextSelection } from 'prosemirror-state';
+import { EditorView, Decoration, DecorationSet } from 'prosemirror-view';
+import { baseKeymap } from 'prosemirror-commands';
+import { keymap } from 'prosemirror-keymap';
+
+// Source-backed subset of social-app commit
+// 46d98dd457a197cee8502863b420222508f29fa6:
+// TextInput.web.tsx uses Tiptap's Document/Paragraph/Text/HardBreak extensions,
+// an unlabelled role=textbox host, and this exact plain-text clipboard parser.
+// The actual PM document/view owns every editor mutation; no input listener
+// rebuilds HTML or changes textContent to imitate a rich editor.
+const schema = new Schema({
+ nodes: {
+ doc: { content: 'block+' },
+ paragraph: { content: 'inline*', group: 'block', parseDOM: [{ tag: 'p' }], toDOM: () => ['p', 0] },
+ text: { group: 'inline' },
+ hard_break: { inline: true, group: 'inline', selectable: false, parseDOM: [{ tag: 'br' }], toDOM: () => ['br'] },
+ },
+});
+const documentFromText = value => schema.node('doc', null, String(value).replace(/\r\n?/g, '\n').split('\n')
+ .map(line => schema.node('paragraph', null, line ? schema.text(line) : undefined)));
+
+export function mountEditor(value = '') {
+ window.qaEditorView?.destroy();
+ const host = document.getElementById('editor-host');
+ const placeholder = new Plugin({ props: { decorations(state) {
+ return state.doc.childCount === 1 && state.doc.firstChild.content.size === 0
+ ? DecorationSet.create(state.doc, [Decoration.node(0, state.doc.firstChild.nodeSize, {
+ class: 'is-empty is-editor-empty', 'data-placeholder': "What's up?",
+ })]) : null;
+ } } });
+ const doc = documentFromText(value);
+ const view = new EditorView(host, {
+ state: EditorState.create({ schema, doc, selection: TextSelection.atEnd(doc), plugins: [keymap(baseKeymap), placeholder] }),
+ attributes: { role: 'textbox', class: 'tiptap ProseMirror-light' },
+ clipboardTextParser(text, context) {
+ const nodes = text.split(/(?:\r\n?|\n)/).map(line => Node.fromJSON(context.doc.type.schema,
+ line.length ? { type: 'paragraph', content: [{ type: 'text', text: line }] } : { type: 'paragraph', content: [] }));
+ return Slice.maxOpen(Fragment.fromArray(nodes));
+ },
+ dispatchTransaction(transaction) {
+ const next = view.state.apply(transaction);
+ view.updateState(next);
+ window.qaModelText = next.doc.textBetween(0, next.doc.content.size, '\n', '\n');
+ document.getElementById('publish').setAttribute('aria-disabled', String(!window.qaModelText.trim()));
+ },
+ });
+ window.qaEditorView = view;
+ // Active Composer passes autoFocus, which TextInput.web.tsx maps to 'end'.
+ // Establish this native app state before any model observation or test action.
+ view.focus();
+ window.qaModelText = view.state.doc.textBetween(0, view.state.doc.content.size, '\n', '\n');
+ document.getElementById('publish').setAttribute('aria-disabled', String(!window.qaModelText.trim()));
+ window.qaSnapshotEditor = () => ({
+ model: view.state.doc.textBetween(0, view.state.doc.content.size, '\n', '\n'),
+ doc: view.state.doc.toJSON(), html: view.dom.innerHTML,
+ blocks: [...view.dom.children].map(node => node.textContent),
+ editorName: view.dom.getAttribute('aria-label'),
+ placeholder: view.dom.querySelector('p')?.getAttribute('data-placeholder'),
+ });
+}
diff --git a/test/native-chat-trusted-clear.mjs b/test/native-chat-trusted-clear.mjs
new file mode 100644
index 000000000..0d72cc73f
--- /dev/null
+++ b/test/native-chat-trusted-clear.mjs
@@ -0,0 +1,149 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { test } from 'node:test';
+import { chromium, firefox } from 'playwright';
+import { telegramLab } from './quality/native-chat-fixture.mjs';
+import { cdpClient } from '../src/chrome/src/cdp/cdp-client.js';
+
+for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
+ test(`${build}: private native-chat clear receipt accepts one scoped native delete and rejects intervention`, async t => {
+ const browser = await engine.launch({ headless: true });
+ const sources = await Promise.all(['accessibility-tree.js', 'rich-text-toolbar-heuristic.js', 'chat-observation.js', 'content.js']
+ .map(file => readFile(new URL(`../src/${build}/src/content/${file}`, import.meta.url), 'utf8')));
+ try {
+ for (const fault of ['none', 'cdp-first', 'checkpoint-first', 'cancelled', 'cancelled-mutating', 'beforeinput-restored', 'synthetic', 'partial-selection-authored-break', 'extra-delete', 'caret-replaced', 'identity-restored', 'focus-restored', 'selection-restored', 'authored-break', 'generic']) await t.test(fault, async () => {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ await page.route('**/*', route => route.fulfill({ contentType: 'text/html', body: telegramLab }));
+ await page.goto('https://web.telegram.org/k/#123456');
+ await page.evaluate(build => {
+ window[build === 'firefox' ? 'browser' : 'chrome'] = { runtime: { getURL: value => value,
+ onMessage: { addListener: handler => { window.qaHandler = handler; } } } };
+ window.qaCall = (action, params) => new Promise(resolve => qaHandler({ target: 'content', action, params }, {}, resolve));
+ window.qaInputs = [];
+ document.querySelector('.input-message-input').addEventListener('input', event => qaInputs.push({ trusted: event.isTrusted, inputType: event.inputType }));
+ }, build);
+ for (const source of sources) await page.addScriptTag({ content: source });
+ const composer = page.locator('.input-message-input');
+ await composer.focus(); await page.keyboard.insertText('Owned draft before native clear');
+ if (fault === 'partial-selection-authored-break') await composer.evaluate(el => {
+ window.qaAuthoredBreak = document.createElement('br'); el.append(qaAuthoredBreak);
+ });
+ await composer.selectText();
+ if (fault === 'generic') await composer.evaluate(el => el.removeAttribute('data-peer-id'));
+ if (fault === 'authored-break') await composer.evaluate(el => el.replaceChildren(document.createElement('br')));
+ const ref = await composer.evaluate(el => __wb_ax_ref(el));
+ const call = (action, params = {}) => page.evaluate(({ action, params }) => qaCall(action, params), { action, params });
+ const positive = ['none', 'cdp-first', 'checkpoint-first'].includes(fault);
+ if (fault === 'checkpoint-first') await page.evaluate(() => {
+ window.qaOrder = [];
+ window.addEventListener('input', event => {
+ if (event.isTrusted && event.inputType === 'deleteContentForward') {
+ qaOrder.push('first-listener'); queueMicrotask(() => qaOrder.push('microtask'));
+ }
+ }, true);
+ });
+ let session, cdpReceipt;
+ const originalCommand = cdpClient.sendCommand;
+ const capture = async () => {
+ session = await context.newCDPSession(page);
+ cdpClient.sendCommand = (_tab, method, params) => session.send(method, params);
+ cdpReceipt = await cdpClient.captureTextClearReceipt(10, { focused: true });
+ assert.ok(cdpReceipt);
+ };
+ if (build === 'chrome' && fault === 'cdp-first') await capture();
+ const prepared = await call('ax_prepare_native_chat_clear', { ref_id: ref });
+ if (fault === 'generic' || fault === 'authored-break') {
+ assert.equal(prepared.success, false, 'An unbound editor or pre-existing authored BR cannot acquire native empty authority.');
+ assert.equal(prepared.token, undefined); await context.close(); return;
+ }
+ assert.equal(prepared.success, true, JSON.stringify(prepared)); assert.ok(prepared.token);
+ if (build === 'chrome' && !cdpReceipt) await capture();
+ if (fault === 'checkpoint-first') await page.evaluate(() => window.addEventListener('input', event => {
+ if (event.isTrusted && event.inputType === 'deleteContentForward') qaOrder.push('last-listener');
+ }, true));
+ if (fault === 'cancelled') await composer.evaluate(el => el.addEventListener('beforeinput', event => event.preventDefault(), { once: true }));
+ if (fault === 'cancelled-mutating') await composer.evaluate(el => el.addEventListener('beforeinput', event => {
+ event.preventDefault(); el.replaceChildren(document.createElement('br'));
+ }, { once: true }));
+ if (fault === 'beforeinput-restored') await composer.evaluate(el => el.addEventListener('beforeinput', () => {
+ const original = el.firstChild; el.replaceChildren(document.createTextNode('Changed draft')); el.replaceChildren(original);
+ const range = document.createRange(); range.selectNodeContents(el);
+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
+ }, { once: true }));
+ if (fault === 'partial-selection-authored-break') await composer.evaluate(el => el.addEventListener('keydown', event => {
+ if (event.code !== 'KeyA') return;
+ event.preventDefault(); const range = document.createRange();
+ range.setStart(el.firstChild, 0); range.setEnd(el.firstChild, el.firstChild.length);
+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
+ }));
+ if (fault === 'synthetic') await composer.evaluate(el => {
+ for (const type of ['keydown', 'keyup']) el.dispatchEvent(new KeyboardEvent(type, { key: 'a', code: 'KeyA', ctrlKey: true, bubbles: true }));
+ el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', code: 'Delete', bubbles: true }));
+ el.dispatchEvent(new InputEvent('beforeinput', { inputType: 'deleteContentForward', bubbles: true }));
+ el.replaceChildren(document.createElement('br'));
+ el.dispatchEvent(new InputEvent('input', { inputType: 'deleteContentForward', bubbles: true }));
+ el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Delete', code: 'Delete', bubbles: true }));
+ });
+ else {
+ if (build === 'chrome') {
+ await session.send('Input.dispatchKeyEvent', { type:'keyDown', key:'a', code:'KeyA', modifiers:2, windowsVirtualKeyCode:65, commands:['selectAll'] });
+ await session.send('Input.dispatchKeyEvent', { type:'keyUp', key:'a', code:'KeyA', modifiers:2, windowsVirtualKeyCode:65 });
+ await session.send('Input.dispatchKeyEvent', { type:'keyDown', key:'Delete', code:'Delete', windowsVirtualKeyCode:46 });
+ await session.send('Input.dispatchKeyEvent', { type:'keyUp', key:'Delete', code:'Delete', windowsVirtualKeyCode:46 });
+ } else {
+ await page.keyboard.press('ControlOrMeta+A'); await page.keyboard.press('Delete');
+ }
+ }
+ if (fault === 'extra-delete') await page.keyboard.press('Delete');
+ if (fault === 'caret-replaced') await composer.evaluate(el => el.replaceChildren(document.createElement('br')));
+ if (fault === 'identity-restored') await page.evaluate(() => {
+ const carrier = document.querySelector('.input-message-input');
+ carrier.dataset.peerId = '654321'; carrier.dataset.peerId = '123456';
+ });
+ if (fault === 'focus-restored') await page.evaluate(() => {
+ const button = document.querySelector('button'); button.focus(); document.querySelector('.input-message-input').focus();
+ });
+ if (fault === 'selection-restored') {
+ await page.evaluate(() => {
+ const range = document.createRange(); range.selectNodeContents(document.querySelector('button'));
+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
+ });
+ await page.waitForTimeout(10);
+ await page.evaluate(() => {
+ const range = document.createRange(); range.selectNodeContents(document.querySelector('.input-message-input')); range.collapse(false);
+ const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range);
+ });
+ }
+ await page.waitForTimeout(40);
+ if (cdpReceipt) {
+ const nativeVerified = await cdpReceipt.verify();
+ await cdpReceipt.dispose(); cdpClient.sendCommand = originalCommand;
+ assert.equal(nativeVerified, positive, 'Main-world CDP proof must survive the installed content listeners and reject native interventions.');
+ }
+ const verified = await call('ax_verify_native_chat_clear', { ref_id: ref, token: prepared.token });
+ const value = await call('ax_verify_field_value', { ref_id: ref, expected: '' });
+ assert.equal(verified.success, positive, JSON.stringify({ fault, verified, value }));
+ assert.equal(value.verified, positive);
+ assert.equal((await call('ax_verify_native_chat_clear', { ref_id: ref, token: prepared.token })).success, false, 'The private token is single-use.');
+ const inputs = await page.evaluate(() => qaInputs);
+ if (positive) {
+ assert.equal(value.actual, ''); assert.equal(await composer.textContent(), '');
+ assert.deepEqual(inputs, [{ trusted: true, inputType: build === 'firefox' ? 'insertCompositionText' : 'insertText' },
+ { trusted: true, inputType: 'deleteContentForward' }]);
+ if (fault === 'checkpoint-first') assert.deepEqual(await page.evaluate(() => qaOrder),
+ build === 'chrome' ? ['first-listener', 'microtask', 'last-listener'] : ['first-listener', 'last-listener', 'microtask'],
+ 'Chromium yields a real listener checkpoint before receipt input; Firefox finishes the event first.');
+ } else {
+ assert.notEqual(value.actual, '', 'Rejected proof must preserve the actual nonempty or literal-BR readback.');
+ if (fault === 'partial-selection-authored-break') {
+ assert.equal(value.actual, '\n');
+ assert.equal(await composer.evaluate(el => el.firstChild === qaAuthoredBreak), true,
+ 'The original authored BR remains literal even after one genuine native text deletion.');
+ }
+ }
+ await context.close();
+ });
+ } finally { await browser.close(); }
+ });
+}
diff --git a/test/page-feedback-progress.mjs b/test/page-feedback-progress.mjs
index 06eadf224..0fe93f89d 100644
--- a/test/page-feedback-progress.mjs
+++ b/test/page-feedback-progress.mjs
@@ -211,6 +211,7 @@ for (const build of ['chrome', 'firefox']) {
return call('context-' + requests, 'click_ax', { ref_id: 'ref_standalone' });
};
agent = makeAgent(Agent, next); agent.maxSteps = Infinity;
+ agent._grantSocialPublicationAuditRetry = () => assert.fail('Context recovery must not bypass publication checks.');
agent._endTraceRun = async (_tab, _run, status) => { terminalStatus = status; };
agent._enrichUserMessageWithCurrentPage = async (_tab, _messages, content) => { send = bind(agent, tab); return { role: 'user', content }; };
agent.executeTool = async (_id, name, args) => {
@@ -228,16 +229,26 @@ for (const build of ['chrome', 'firefox']) {
} else {
assert.equal(requests, 5); assert.equal(validations, 5); assert.equal(dispatched, 0);
if (condition === 'unsupported') {
- assert.match(result, /could not be bound to a verified action context/);
+ assert.match(result, /could not confirm which part of the page the control belongs to/);
assert.doesNotMatch(result, /page kept changing/);
assert.equal(terminalStatus, 'action_context_unverified');
- assert.ok(updates.some(u => u.type === 'warning' && /verified action context/.test(u.data.message)));
+ assert.ok(updates.some(u => u.type === 'warning' && /could not confirm/.test(u.data.message)));
assert.ok(modelMessages[1].some(m => /ACTION CONTEXT UNVERIFIED/.test(JSON.stringify(m))));
} else {
assert.match(result, /page kept changing/);
assert.equal(modelMessages.some(messages => messages.some(m => /ACTION CONTEXT UNVERIFIED/.test(JSON.stringify(m)))), false);
assert.equal(captures.some(c => c.actionTarget), false);
}
+ const offer = updates.find(u => u.type === 'failure_recovery')?.data;
+ assert.equal(offer?.stage, 'action_preparation');
+ assert.equal(offer.code, condition === 'unsupported' ? 'action_context_unverified' : 'page_unstable');
+ assert.equal(offer.retryMode, 'resume');
+ assert.equal(offer.message, result);
+ assert.match(result, /choose Retry/);
+ assert.equal(agent._pendingFailureRecoveryForUi(tab).recoveryId, offer.recoveryId);
+ assert.deepEqual(agent.requestFailureRecovery(tab, offer.recoveryId, streaming ? 'retry' : 'give_up'),
+ { ok: true, continue: streaming, retryMode: 'resume' });
+ assert.equal(agent._pendingFailureRecoveryForUi(tab), null);
}
assert.equal(agent._pageFeedbackRuns.size, 0);
} finally { api.tabs.sendMessage = oldSend; documents.delete(tab); }
diff --git a/test/page-feedback-recovery.mjs b/test/page-feedback-recovery.mjs
index 0f2881033..7fe83b773 100644
--- a/test/page-feedback-recovery.mjs
+++ b/test/page-feedback-recovery.mjs
@@ -14,7 +14,8 @@ for (const browser of ['chrome', 'firefox']) {
}));
assert.match(attempts[PAGE_FEEDBACK_NUDGE_AT - 1].message, /ACTION CONTEXT UNVERIFIED/);
assert.equal(attempts.at(-1).code, 'action_context_unverified');
- assert.match(attempts.at(-1).message, /could not be bound to a verified action context/);
+ assert.match(attempts.at(-1).message, /could not confirm which part of the page the control belongs to/);
+ assert.match(attempts.at(-1).message, /Open or focus the intended area, then choose Retry/);
assert.doesNotMatch(attempts.at(-1).message, /page kept changing/);
assert.deepEqual(attempts.at(-1).metadata, { stage: 'response', streak: PAGE_FEEDBACK_STOP_AT,
toolNames: ['click_ax'], reason: 'target_context_unverified' });
diff --git a/test/page-monitor-inline-post.mjs b/test/page-monitor-inline-post.mjs
new file mode 100644
index 000000000..48b1e7c7e
--- /dev/null
+++ b/test/page-monitor-inline-post.mjs
@@ -0,0 +1,248 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { test, describe, before, after } from 'node:test';
+import { chromium, firefox } from 'playwright';
+
+// The observed X /home composer is a heading-free, form-less sibling of a
+// virtualized timeline. Native post controls live below a deep editable host;
+// the avatar/account link is outside the editor's immediate shared wrapper.
+const html = `<!doctype html><meta charset="utf-8"><style>
+body{margin:0;width:1100px;height:760px;font:16px sans-serif}
+#primary{position:absolute;left:15px;top:20px;width:180px}
+main{position:absolute;left:220px;top:20px;width:650px}
+#composer{display:flex;width:620px;gap:12px;padding:10px}
+#avatar{width:40px;height:40px;display:block}#avatar img{width:40px;height:40px}
+#composer-body{width:560px}#editor{height:80px;width:540px;border:1px solid #888}
+button{height:32px}#feed{height:350px}#human{position:absolute;left:900px;top:30px}
+</style><nav id="primary" aria-label="Primary"><a href="/home">Home</a>
+<a id="profile" data-testid="AppTabBar_Profile_Link" href="/ownedqa">Profile</a>
+<a href="/compose/post">Post</a></nav><main><div aria-label="Home timeline">
+<nav><div role="tablist"><button role="tab" aria-selected="true">For you</button><button role="tab">Following</button></div></nav>
+<div id="composer"><a id="avatar" href="/ownedqa"><img alt="Owned QA account"></a>
+<div id="composer-body"><div id="audience">Everyone</div>
+<div id="editor" contenteditable="true" role="textbox" aria-label="Post text" data-testid="tweetTextarea_0"></div>
+<button id="reply-audience" type="button">Everyone can reply</button>
+<nav><div role="tablist"><button type="button" aria-label="Add photos or video">Photo</button><button type="button" aria-label="Add a GIF">GIF</button>
+<button type="button" aria-label="Schedule post">Schedule</button></div></nav>
+<button id="post" type="button" data-testid="tweetButtonInline" disabled>Post</button></div></div>
+<section id="feed" role="region" aria-label="Timeline"><article data-post-id="unrelated"><h2>Unrelated author</h2>
+<button id="feed-reply">393 Replies. Reply</button><span id="counter">1m</span></article>
+${'<span aria-hidden="true"></span>'.repeat(300)}</section></div></main><button id="human">Human control</button>
+<script>window.qaPosts=[];window.qaInputs=[];
+document.querySelector('#editor').addEventListener('input',event=>{qaInputs.push({trusted:event.isTrusted,type:event.inputType});document.querySelector('#post').disabled=!event.target.textContent.trim();});
+document.querySelector('#post').addEventListener('click',()=>qaPosts.push(document.querySelector('#editor').innerText));
+</script>`;
+
+async function fixture(browser, build, body = html, url = 'https://x.com/home') {
+ const context = await browser.newContext({ viewport: { width: 1100, height: 760 } });
+ await context.route('**/*', route => route.fulfill({ contentType: 'text/html', body }));
+ await context.addInitScript(() => {
+ window.qaListeners = []; window.qaFeedback = []; window.qaRun = 'inline-post-run'; window.qaActive = true;
+ window.chrome = window.browser = { runtime: {
+ onMessage: { addListener: listener => qaListeners.push(listener), removeListener() {} },
+ async sendMessage(message) {
+ if (message.action === 'get_page_monitor_state') return { active: qaActive, runToken: qaRun, documentToken: message.documentToken };
+ if (message.action === 'page_feedback') { qaFeedback.push(message.feedback); return { accepted: true }; }
+ return {};
+ },
+ } };
+ window.qaMessage = (action, params = {}) => new Promise(resolve => {
+ let answered = false;
+ for (const listener of qaListeners) {
+ const result = listener({ target: 'content', action, params: { runToken: qaRun, ...params } }, {}, value => { answered = true; resolve(value); });
+ if (answered || result === true) break;
+ }
+ });
+ });
+ for (const name of ['rich-text-toolbar-heuristic.js', 'file-upload-policy.js', 'accessibility-tree.js', 'page-monitor.js', 'content.js']) {
+ await context.addInitScript({ content: await readFile(new URL(`../src/${build}/src/content/${name}`, import.meta.url), 'utf8') });
+ }
+ const page = await context.newPage(); await page.goto(url);
+ await page.waitForFunction(() => window.__wbPageMonitor?.active && window.__wb_ax_installed);
+ await page.waitForTimeout(180);
+ await page.evaluate(() => {
+ let child = document.querySelector('#editor');
+ for (let depth = 0; depth < 18; depth++) { const wrapper = document.createElement('div'); child.before(wrapper); wrapper.append(child); child = wrapper; }
+ qaFeedback = [];
+ });
+ return { context, page };
+}
+
+async function capture(page) {
+ return page.evaluate(async () => {
+ const snapshot = await qaMessage('page_monitor_capture_model', { includeTree: true });
+ return { ...snapshot, editorRef: __wb_ax_ref(document.querySelector('#editor')), postRef: __wb_ax_ref(document.querySelector('#post')) };
+ });
+}
+async function validate(page, snapshot, target = { tool: 'set_field', ref_id: snapshot.editorRef }) {
+ return page.evaluate(({ snapshot, target }) => qaMessage('page_monitor_validate_model', { snapshotToken: snapshot.snapshotToken, ...target }), { snapshot, target });
+}
+async function dispatch(page, snapshot, action, args) {
+ return page.evaluate(async ({ snapshot, action, args }) => {
+ const prepare = await qaMessage('page_monitor_prepare', { tool: action, operationId: 'owned-inline-dispatch',
+ expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true, ...args });
+ const result = prepare.modelBindingValid === true ? await qaMessage(action, {
+ expectedModelSnapshot: snapshot.snapshotToken, allowPassiveRebase: true, ...args,
+ }) : null;
+ return { prepare, result, posts: qaPosts, text: document.querySelector('#editor').innerText, enabled: !document.querySelector('#post').disabled };
+ }, { snapshot, action, args });
+}
+
+for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) describe(`${build}: native inline post ownership`, () => {
+ let browser;
+ before(async () => { browser = await engine.launch({ headless: true }); });
+ after(async () => { await browser.close(); });
+ const withFixture = async (work, body = html, url) => {
+ const { context, page } = await fixture(browser, build, body, url);
+ try { await work(page); } finally { await context.close(); }
+ };
+ test('observes account identity and certifies an empty heading-free home editor under live feed churn', () => withFixture(async page => {
+ await page.locator('#editor').focus();
+ const snapshot = await capture(page);
+ assert.equal(snapshot.ready, true); assert.equal(snapshot.focusedTargetAvailable, true, JSON.stringify(snapshot));
+ assert.match(snapshot.page.pageContent, /visible identity "https:\/\/x\.com\/ownedqa"/);
+ await page.evaluate(() => { document.querySelector('#counter').textContent = '2m'; document.querySelector('#feed-reply').textContent = '394 Replies. Reply'; });
+ await page.waitForTimeout(180);
+ for (const tool of ['set_field', 'type_ax']) assert.equal((await validate(page, snapshot, { tool, ref_id: snapshot.editorRef })).ready, true, tool);
+ assert.equal((await validate(page, snapshot, { tool: 'type_text', selector: '[data-testid="tweetTextarea_0"]' })).ready, true);
+ assert.equal((await validate(page, snapshot, { tool: 'type_text' })).ready, true);
+ const text = 'Owned QA announcement: WebBrain is live.';
+ const typed = await dispatch(page, snapshot, 'set_field', { ref_id: snapshot.editorRef, text, clear: true });
+ assert.equal(typed.prepare.modelBindingValid, true); assert.equal(typed.result.success, true, JSON.stringify(typed));
+ assert.equal(typed.text, text); assert.equal(typed.enabled, true); assert.deepEqual(typed.posts, [], 'Typing must never submit the post.');
+ const fresh = await capture(page);
+ assert.equal((await validate(page, fresh, { tool: 'click_ax', ref_id: fresh.postRef })).ready, true);
+ const posted = await dispatch(page, fresh, 'click_ax', { ref_id: fresh.postRef });
+ assert.equal(posted.result.success, true, JSON.stringify(posted)); assert.deepEqual(posted.posts, [text]);
+ }));
+ for (const [name, mutate] of [
+ ['local account', () => document.querySelector('#avatar').href = '/otherqa'],
+ ['navigation account', () => document.querySelector('#profile').href = '/otherqa'],
+ ['avatar label', () => document.querySelector('#avatar img').alt = 'Another account'],
+ ['audience', () => document.querySelector('#audience').textContent = 'Private circle'],
+ ['reply audience', () => document.querySelector('#reply-audience').textContent = 'Only mentioned accounts can reply'],
+ ['publisher state', () => document.querySelector('#post').disabled = false],
+ ['editor replacement', () => { const node = document.querySelector('#editor'); node.replaceWith(node.cloneNode(true)); }],
+ ['composer replacement', () => { const node = document.querySelector('#composer'); node.replaceWith(node.cloneNode(true)); }],
+ ['new destination', () => { const p = document.createElement('p'); p.textContent = 'Replying to another user'; document.querySelector('#composer').append(p); }],
+ ['new local control', () => { const p = document.createElement('button'); p.textContent = 'Send elsewhere'; document.querySelector('#composer').append(p); }],
+ ['hidden account navigation', () => document.querySelector('#primary').setAttribute('aria-hidden', 'true')],
+ ['inactive account navigation', () => document.querySelector('#primary').inert = true],
+ ['account node replacement', () => { const node = document.querySelector('#profile'); node.replaceWith(node.cloneNode(true)); }],
+ ['target overlay', () => { const r = document.querySelector('#editor').getBoundingClientRect(); const node = document.createElement('div'); node.style.cssText = `position:fixed;z-index:999;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px`; document.body.append(node); }],
+ ['new run', () => { qaRun = 'other-run'; }],
+ ['Stop', () => { qaActive = false; }],
+ ]) test(`${name} rejects the prior native certificate before input`, () => withFixture(async page => {
+ const snapshot = await capture(page); assert.equal((await validate(page, snapshot)).ready, true);
+ await page.evaluate(mutate); await page.waitForTimeout(180);
+ if (name === 'Stop') await page.evaluate(() => { for (const listener of qaListeners) listener({ target: 'content', action: 'page_monitor_state', active: false }, {}, () => {}); });
+ if (name === 'new run') await page.evaluate(async () => { for (const listener of qaListeners) listener({ target: 'content', action: 'page_monitor_state', active: true }, {}, () => {}); });
+ assert.equal((await validate(page, snapshot)).ready, false);
+ assert.equal((await validate(page, snapshot, { tool: 'type_text', selector: '[data-testid="tweetTextarea_0"]' })).ready, false);
+ const rejected = await dispatch(page, snapshot, 'set_field', { ref_id: snapshot.editorRef, text: 'Must not be inserted' });
+ assert.equal(rejected.prepare.modelBindingValid, false); assert.equal(rejected.result, null); assert.deepEqual(rejected.posts, []);
+ }));
+ test('trusted user input returned to the same empty draft invalidates the original decision', () => withFixture(async page => {
+ const snapshot = await capture(page); assert.equal((await validate(page, snapshot)).ready, true);
+ await page.locator('#editor').fill('Human draft'); await page.locator('#editor').fill('');
+ assert.equal((await validate(page, snapshot)).ready, false);
+ assert.deepEqual(await page.evaluate(() => qaPosts), []);
+ }));
+ test('focus-revealed audience requires a fresh decision before any text is inserted', () => withFixture(async page => {
+ await page.evaluate(() => {
+ document.querySelector('#audience').remove(); document.querySelector('#reply-audience').remove();
+ document.querySelector('#editor').addEventListener('focus', () => {
+ const audience = document.createElement('button'); audience.id = 'new-audience'; audience.textContent = 'Everyone can reply';
+ document.querySelector('#composer-body').prepend(audience);
+ }, { once: true });
+ });
+ const original = await capture(page); assert.equal((await validate(page, original)).ready, true);
+ const first = await dispatch(page, original, 'set_field', { ref_id: original.editorRef, text: 'Owned focus-reveal draft' });
+ assert.equal(first.result.success, false); assert.equal(first.text, '', JSON.stringify(first)); assert.deepEqual(first.posts, []);
+ const fresh = await capture(page); assert.match(fresh.page.pageContent, /Everyone can reply/);
+ assert.equal((await validate(page, fresh)).ready, true);
+ const second = await dispatch(page, fresh, 'set_field', { ref_id: fresh.editorRef, text: 'Owned focus-reveal draft' });
+ assert.equal(second.result.success, true, JSON.stringify(second)); assert.equal(second.text, 'Owned focus-reveal draft'); assert.deepEqual(second.posts, []);
+ }));
+ for (const owner of ['form', 'div role="form"', 'section', 'div role="region"']) {
+ const close = owner.split(' ')[0];
+ const named = html.replace('<div id="composer">', `<${owner} id="composer" aria-label="Public announcement for Owned QA account">`)
+ .replace('</button></div></div>\n<section id="feed"', `</button></div></${close}>\n<section id="feed"`);
+ test(`named semantic ${owner} observes its full scope and types without a page heading on any host`, () => withFixture(async page => {
+ const snapshot = await capture(page);
+ assert.match(snapshot.page.pageContent, /Public announcement for Owned QA account/);
+ assert.equal((await validate(page, snapshot)).ready, true, JSON.stringify(snapshot));
+ const typed = await dispatch(page, snapshot, 'set_field', { ref_id: snapshot.editorRef, text: 'Owned generic app draft' });
+ assert.equal(typed.result.success, true, JSON.stringify(typed)); assert.equal(typed.text, 'Owned generic app draft');
+ assert.deepEqual(typed.posts, []);
+ }, named, 'https://generic-editor.test/write'));
+ for (const [name, mutation] of [
+ ['scope name', () => document.querySelector('#composer').setAttribute('aria-label', 'Other account announcement')],
+ ['scope replacement', () => { const node = document.querySelector('#composer'); node.replaceWith(node.cloneNode(true)); }],
+ ['new destination', () => { const node = document.createElement('p'); node.textContent = 'Destination: Another channel'; document.querySelector('#composer-body').append(node); }],
+ ['toolbar control', () => document.querySelector('[aria-label="Schedule post"]').setAttribute('aria-label', 'Schedule for other account')],
+ ]) test(`${owner}: ${name} invalidates the original semantic scope`, () => withFixture(async page => {
+ const snapshot = await capture(page); assert.equal((await validate(page, snapshot)).ready, true);
+ await page.evaluate(mutation); assert.equal((await validate(page, snapshot)).ready, false);
+ }, named, 'https://generic-editor.test/write'));
+ test(`${owner}: dangling associated name cannot borrow contained editor/control text`, () => withFixture(async page => {
+ await page.evaluate(() => { document.querySelector('#composer').removeAttribute('aria-label'); document.querySelector('#composer').setAttribute('aria-labelledby', 'missing-scope-name'); });
+ const snapshot = await capture(page); assert.equal((await validate(page, snapshot)).ready, false);
+ }, named, 'https://generic-editor.test/write'));
+ test(`${owner}: complete associated scope label stays bound outside a short AX name`, () => withFixture(async page => {
+ await page.evaluate(() => {
+ const label = document.createElement('div'); label.id = 'scope-name'; label.textContent = 'Owned QA account announcement ' + 'A'.repeat(150);
+ document.body.append(label); document.querySelector('#composer').removeAttribute('aria-label'); document.querySelector('#composer').setAttribute('aria-labelledby', label.id);
+ });
+ const snapshot = await capture(page); assert.equal((await validate(page, snapshot)).ready, true);
+ assert.match(snapshot.page.pageContent, /A{150}/, 'The complete referenced scope identity must be observed.');
+ await page.evaluate(() => document.querySelector('#scope-name').textContent += ' another account');
+ assert.equal((await validate(page, snapshot)).ready, false);
+ }, named, 'https://generic-editor.test/write'));
+ }
+ for (const owner of ['div', 'div role="toolbar"']) test(`named ${owner} cannot establish its own action scope`, () => withFixture(async page => {
+ await page.evaluate(() => document.querySelector('#composer').setAttribute('aria-label', 'Owned account announcement'));
+ const snapshot = await capture(page); assert.equal((await validate(page, snapshot)).ready, false);
+ }, html.replace('<div id="composer">', `<${owner} id="composer">`), 'https://generic-editor.test/write'));
+ const headedMain = html.replace('<main><div', '<main><h1>Publish owned draft</h1><div');
+ for (const [name, mutation] of [
+ ['source', () => document.querySelector('#avatar img').src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>'],
+ ['node identity', () => { const image = document.querySelector('#avatar img'); image.replaceWith(image.cloneNode()); }],
+ ]) test(`heading-backed main keeps its current account image ${name} bound`, () => withFixture(async page => {
+ await page.evaluate(() => document.querySelector('#avatar img').removeAttribute('alt'));
+ const original = await capture(page); assert.equal((await validate(page, original)).ready, true);
+ assert.match(original.page.pageContent, /visible image name-unavailable=true direct-action=false/);
+ await page.evaluate(mutation); assert.equal((await validate(page, original)).ready, false);
+ }, headedMain, 'https://generic-editor.test/write'));
+ test('heading-backed main leaves another feed entity image outside its account proof', () => withFixture(async page => {
+ await page.evaluate(() => {
+ const image = document.createElement('img'); image.id = 'feed-avatar'; image.style.cssText = 'width:30px;height:30px';
+ document.querySelector('#feed article').append(image);
+ });
+ const original = await capture(page); assert.equal((await validate(page, original)).ready, true);
+ await page.evaluate(() => document.querySelector('#feed-avatar').src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>');
+ assert.equal((await validate(page, original)).ready, true, 'Unrelated feed entity visuals cannot identify the owned composer account.');
+ }, headedMain, 'https://generic-editor.test/write'));
+ for (const [name, body, url] of [
+ ['missing native editor marker', html.replace('data-testid="tweetTextarea_0"', '')],
+ ['missing native publisher marker', html.replace('data-testid="tweetButtonInline"', '')],
+ ['missing account navigation evidence', html.replace('data-testid="AppTabBar_Profile_Link"', '')],
+ ['mismatched local account', html.replace('id="avatar" href="/ownedqa"', 'id="avatar" href="/otherqa"')],
+ ['foreign host with copied markers', html, 'https://unrelated.test/home'],
+ ['wrong route with copied markers', html, 'https://x.com/settings'],
+ ['extra editable', html.replace('<div id="audience">', '<input aria-label="Other recipient"><div id="audience">')],
+ ['ambiguous account', html.replace('<div id="composer-body">', '<a href="/otherqa">Other account</a><div id="composer-body">')],
+ ['ambiguous account navigation', html.replace('</nav><main>', '<a data-testid="AppTabBar_Profile_Link" href="/otherqa">Other Profile</a></nav><main>')],
+ ['unbounded inline context', html.replace('<div id="composer-body">', '<div>' + '<span aria-hidden="true"></span>'.repeat(260) + '</div><div id="composer-body">')],
+ ['account hidden in navigation', html.replace('id="primary"', 'id="primary" aria-hidden="true"')],
+ ]) test(`${name} keeps the heading-free composer uncertified`, () => withFixture(async page => {
+ const snapshot = await capture(page); assert.equal(snapshot.ready, true);
+ const result = await validate(page, snapshot); assert.equal(result.ready, false, JSON.stringify(result));
+ assert.deepEqual(await page.evaluate(() => qaPosts), []);
+ }, body, url));
+});
+
+test('Chrome and Firefox inline post ownership stays byte-identical', async () => {
+ assert.equal(await readFile(new URL('../src/chrome/src/content/page-monitor.js', import.meta.url), 'utf8'),
+ await readFile(new URL('../src/firefox/src/content/page-monitor.js', import.meta.url), 'utf8'));
+});
diff --git a/test/quality/bluesky-composer-mv3.mjs b/test/quality/bluesky-composer-mv3.mjs
new file mode 100644
index 000000000..c5ae1a5b7
--- /dev/null
+++ b/test/quality/bluesky-composer-mv3.mjs
@@ -0,0 +1,290 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import { chromium } from 'playwright';
+import { build as bundle } from 'esbuild';
+
+// Real installed MV3 background, Agent, monitor and CDP input. The editor is
+// the actual ProseMirror model/view from the source-backed Bluesky fixture;
+// deterministic inference and intercepted owned HTTP responses are the only
+// substitutes. No Bluesky account, API or external posting service is opened.
+const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS
+ || 'ci/artifacts/quality-audit-2026-10-11/bluesky-composer-mv3');
+await fs.mkdir(out, { recursive: true });
+const editorBundle = (await bundle({ entryPoints: [path.resolve('test/fixtures/bluesky-composer-editor.mjs')],
+ bundle: true, write: false, format: 'iife', globalName: 'qaEditorLibrary', platform: 'browser' })).outputFiles[0].text;
+const fixtureUrl = 'https://bsky.app/';
+const account = 'owned.bsky.social';
+const singleLineBody = 'One owned Bluesky draft: exact spaces and Turkish ıİşŞğĞüÜöÖçÇ 🧠.';
+const multilineBody = 'First owned Bluesky paragraph: exact spaces and Turkish ıİşŞğĞüÜöÖçÇ 🧠.\nSecond owned paragraph preserves its newline and spaces exactly.';
+const postUrl = `https://bsky.app/profile/${account}/post/3ownedqa`;
+const textOf = value => typeof value === 'string' ? value : Array.isArray(value)
+ ? value.filter(part => part?.type === 'text').map(part => part.text || '').join('\n') : '';
+function toolObject(content) {
+ const text = textOf(content);
+ for (let start = text.indexOf('{'); start >= 0; start = text.indexOf('{', start + 1)) {
+ let depth = 0, quoted = false, escaped = false;
+ for (let cursor = start; cursor < text.length; cursor++) {
+ const char = text[cursor];
+ if (quoted) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === '"') quoted = false; }
+ else if (char === '"') quoted = true;
+ else if (char === '{') depth++;
+ else if (char === '}' && --depth === 0) {
+ try { return JSON.parse(text.slice(start, cursor + 1)); } catch { break; }
+ }
+ }
+ }
+ return null;
+}
+function latestTools(messages) {
+ const names = new Map();
+ for (const message of messages || []) for (const call of message.tool_calls || []) names.set(call.id, call.function?.name);
+ return (messages || []).filter(message => message.role === 'tool')
+ .map(message => ({ name: names.get(message.tool_call_id) || message.name, result: toolObject(message.content) }));
+}
+function references(tree) {
+ const lines = String(tree?.pageContent || '').split('\n');
+ const ref = expression => lines.find(line => expression.test(line))?.match(/\[(ref_\d+)\]/)?.[1];
+ return { editor: ref(/textbox(?: "[^"]*")? \[ref_/), publish: ref(/button "Publish post"/), tree: tree?.pageContent };
+}
+const intent = { request_kind: 'execute', scope_relation: 'new', requires_state_change: true,
+ requires_submission: true, messaging: null, deliverables: ['One exact owned Bluesky QA post, freshly verified.'],
+ allows_planner_shaped_result: false, allows_app_state_tool_evidence: false,
+ completion_requirements: { download: false }, read_scope: 'visible_page',
+ summary: 'Publish one exact local QA post from the current owned Bluesky account and verify its native saved record.',
+ steps: [{ id: '1', action: 'Read the composer, write once, re-observe Publish, submit once and verify the native owned post.' }],
+ memory: { use_progress_ledger: false, progress_action: null }, scheduling: null, risks: [] };
+let current, context;
+const submissions = [], blockedRemote = [], summaries = [];
+const server = http.createServer(async (request, response) => {
+ try {
+ if (request.url !== '/v1/chat/completions') { response.writeHead(404).end(); return; }
+ let raw = ''; for await (const part of request) raw += part;
+ const input = JSON.parse(raw), system = textOf(input.messages?.[0]?.content);
+ let completion;
+ if (system.startsWith('Extract stable user preferences for WebBrain memory.'))
+ completion = { role: 'assistant', content: '{"memories":[]}' };
+ else {
+ assert.ok(current && JSON.stringify(input.messages).includes(current.marker), 'Inference must retain the exact owned Bluesky task.');
+ const body = current.body;
+ current.requests.push(input);
+ if (system.startsWith("Compile the user's social-publication intent across languages.")) {
+ current.compilers++;
+ completion = { role: 'assistant', content: JSON.stringify({ version: 1, status: 'ready',
+ actions: [{ id: 'p1', platform: 'bluesky', account: { source: 'task', start: account, end: account },
+ posts: [{ body: { kind: 'exact', source: { source: 'task', start: body, end: body } },
+ media: { kind: 'count', type: 'any', format: null, min: 0, max: 0 }, context: { kind: 'post', target: null } }] }],
+ requirements: 'p1', prohibited: [], reason: 'The authentic task authorizes one exact owned local Bluesky post.' }) };
+ } else if (system.startsWith('Independently check whether the authentic user request authorizes this concrete public dispatch.')) {
+ current.audits++;
+ const audit = JSON.parse(textOf(input.messages.find(message => message.role === 'user')?.content));
+ completion = { role: 'assistant', content: JSON.stringify({ key: audit.key, actionId: audit.action.id,
+ authorized: true, reason: 'The account, complete exact body and plain-post scope match the authentic task.' }) };
+ } else if (system.startsWith('Evaluate only the observable requirements of the genuine user task')) {
+ current.judges++;
+ completion = { role: 'assistant', content: JSON.stringify({ outcome: 'succeeded', reason: 'The fresh native owned post has the authorized account, full body and stable permalink.' }) };
+ } else if (!input.tools?.length) completion = { role: 'assistant', content: JSON.stringify(intent) };
+ else {
+ const step = current.steps++, tools = latestTools(input.messages);
+ const last = tools.at(-1), observed = tools.findLast(tool => tool.name === 'get_accessibility_tree' && tool.result?.pageContent);
+ let call;
+ if (step === 0) call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ else if (step === 1) {
+ current.beforeWrite = references(observed?.result);
+ assert.ok(current.beforeWrite.editor && current.beforeWrite.publish, JSON.stringify(observed));
+ await current.page.evaluate(() => qaChurnFeed());
+ current.inferenceChanges++;
+ await new Promise(resolve => setTimeout(resolve, 240));
+ call = { name: current.tool, args: { ref_id: current.beforeWrite.editor, text: body, clear: true } };
+ } else if (step === 2) {
+ current.writeResult = tools.findLast(tool => tool.name === current.tool)?.result;
+ current.afterWrite = await current.page.evaluate(() => qaSnapshot());
+ call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ } else if (step === 3 && current.writeResult?.success === true) {
+ const fresh = references(observed?.result);
+ assert.ok(fresh.publish && last?.name === 'get_accessibility_tree', 'Use a separately re-observed native Publish control.');
+ current.publishReobserved = true;
+ await current.page.evaluate(() => qaChurnFeed());
+ current.inferenceChanges++;
+ await new Promise(resolve => setTimeout(resolve, 240));
+ call = { name: 'click_ax', args: { ref_id: fresh.publish } };
+ } else if (step === 4 && current.writeResult?.success === true)
+ call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ else call = { name: 'done', args: { outcome: current.writeResult?.success === true ? 'success' : 'partial',
+ summary: 'The exact owned local Bluesky post was published once and freshly verified.' } };
+ current.calls.push(call);
+ completion = { role: 'assistant', content: '', tool_calls: [{ id: `owned-bsky-${current.tool}-${step}`,
+ type: 'function', function: { name: call.name, arguments: JSON.stringify(call.args) } }] };
+ }
+ }
+ response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ id: 'owned-bsky-response',
+ choices: [{ message: completion, finish_reason: completion.tool_calls ? 'tool_calls' : 'stop' }],
+ usage: { prompt_tokens: 100, completion_tokens: 30 } }));
+ } catch (error) {
+ if (current) current.providerError = error.stack;
+ response.writeHead(500, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: error.message }));
+ }
+});
+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+
+// Native web topology from official social-app commit
+// 46d98dd457a197cee8502863b420222508f29fa6, also documented and exercised in
+// test/bluesky-composer-context.mjs. Do not supply the aria name dropped by the
+// native web TextInput, or relabel its heading-free modal to certify it.
+const html = `<!doctype html><meta charset="utf-8"><title>Owned Bluesky home</title><style>
+body{margin:0;font:16px sans-serif;background:#eee}#composer{position:absolute;left:230px;top:30px;width:620px;height:550px;background:white;padding:12px}
+#topbar{display:flex;justify-content:space-between;height:45px}#editor-row{display:flex;gap:12px}#editor-host{width:540px}
+.ProseMirror{height:220px;min-height:220px;white-space:pre-wrap;outline:1px solid #aaa}.ProseMirror p{margin:0}
+.ProseMirror p.is-empty:before{content:attr(data-placeholder);color:#888;pointer-events:none;float:left;height:0}
+[role=button],button{padding:8px;min-height:28px;cursor:pointer}#feed{position:absolute;left:920px;top:0;width:260px}
+#account-navigation{position:absolute;left:10px;top:10px;width:190px}#avatar{width:42px;height:42px}
+#timeline{margin:80px 230px;width:620px}[data-word-wrap="1"]{white-space:pre-wrap}</style>
+<script src="/owned-fixture/editor.js"></script>
+<nav id="account-navigation"><a href="/profile/${account}">Profile</a></nav>
+<aside id="feed"><span id="feed-counter">12 likes</span><div id="feed-items">An unrelated feed post.</div></aside>
+<main id="timeline"></main><div role="dialog" aria-modal="true" id="composer"><div data-testid="composePostView">
+<div id="topbar"><div role="button" tabindex="0" aria-label="Cancel">Cancel</div>
+<div id="publish" role="button" tabindex="0" aria-label="Publish post" aria-disabled="true" data-testid="composerPublishBtn">Post</div></div>
+<div id="editor-row"><div data-testid="userAvatarImage" data-expoimage="true"><img id="avatar" alt="" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='42' height='42'%3E%3Crect width='42' height='42' fill='%238ac'/%3E%3C/svg%3E"></div><div id="editor-host"></div></div>
+<div id="footer"><div role="button" tabindex="0" aria-label="Anyone can interact" data-testid="openReplyGateButton">Anyone can interact</div>
+<div role="button" tabindex="0" aria-label="Add image">Add image</div></div></div></div><script>
+qaEditorLibrary.mountEditor('');window.qaEvents=[];window.qaCommands=[];window.qaFeedChanges=0;window.qaSaved=[];
+for(const type of ['beforeinput','input','paste'])document.querySelector('#editor-host').addEventListener(type,event=>
+ qaEvents.push({type,trusted:event.isTrusted,inputType:event.inputType,data:event.data}),true);
+const execCommand=document.execCommand.bind(document);
+document.execCommand=(command,ui,value)=>{qaCommands.push({command,value});return execCommand(command,ui,value);};
+window.qaChurnFeed=()=>{qaFeedChanges++;document.querySelector('#feed-counter').textContent=(12+qaFeedChanges)+' likes';
+ const record=document.createElement('article');record.textContent='Unrelated incoming feed record '+qaFeedChanges;document.querySelector('#feed-items').append(record);};
+document.querySelector('#publish').addEventListener('click',async()=>{
+ if(document.querySelector('#publish').getAttribute('aria-disabled')==='true')return;
+ const payload={account:'${account}',body:qaSnapshotEditor().model};
+ const response=await fetch('/owned-fixture/post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
+ if(!response.ok)return;qaSaved.push(payload);qaEditorView.destroy();document.querySelector('#composer').remove();
+ const card=document.createElement('div');card.setAttribute('data-testid','feedItem-by-${account}');
+ const profile=document.createElement('a');profile.href='/profile/${account}';profile.textContent='Owned QA @${account}';card.append(profile);
+ const permalink=document.createElement('a');permalink.href='/profile/${account}/post/3ownedqa';permalink.textContent='Now';card.append(permalink);
+ const authored=document.createElement('div');authored.setAttribute('data-word-wrap','1');authored.setAttribute('dir','auto');authored.textContent=payload.body;card.append(authored);
+ document.querySelector('#timeline').append(card);
+});
+window.qaSnapshot=()=>({...qaSnapshotEditor(),publishEnabled:document.querySelector('#publish')?.getAttribute('aria-disabled')==='false',
+ dialogOpen:!!document.querySelector('#composer'),events:qaEvents,commands:qaCommands,feedChanges:qaFeedChanges,saved:qaSaved});
+</script>`;
+
+const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-bluesky-composer-mv3-'));
+try {
+ const extension = path.join(profile, 'extension'); await fs.cp(path.resolve('src/chrome'), extension, { recursive: true });
+ await fs.appendFile(path.join(extension, 'src/background.js'), '\nglobalThis.blueskyFixtureAgent = agent;\n');
+ context = await chromium.launchPersistentContext(profile, { headless: true, channel: 'chromium', viewport: { width: 1280, height: 1000 },
+ args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'] });
+ await context.route('**/*', async route => {
+ const request = route.request(), requested = new URL(request.url());
+ if (requested.hostname === '127.0.0.1' && requested.port === String(server.address().port)) return route.continue();
+ if (requested.origin === 'https://bsky.app') {
+ if (request.isNavigationRequest() && requested.href === fixtureUrl && request.method() === 'GET')
+ return route.fulfill({ contentType: 'text/html', body: html });
+ if (requested.pathname === '/owned-fixture/editor.js' && request.method() === 'GET')
+ return route.fulfill({ contentType: 'text/javascript', body: editorBundle });
+ if (requested.pathname === '/owned-fixture/post' && request.method() === 'POST') {
+ submissions.push({ scenario: current.scenario, tool: current.tool, payload: request.postDataJSON() });
+ return route.fulfill({ status: 201, contentType: 'application/json', body: '{"saved":true}' });
+ }
+ return route.fulfill({ status: 404, body: '' });
+ }
+ if (/^https?:$/.test(requested.protocol)) {
+ blockedRemote.push({ method: request.method(), origin: requested.origin }); return route.abort('blockedbyclient');
+ }
+ return route.continue();
+ });
+ const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30000 });
+ await worker.evaluate(() => {
+ const fetchOriginal=fetch.bind(globalThis), sendCommand=chrome.debugger.sendCommand.bind(chrome.debugger), sendMessage=chrome.tabs.sendMessage.bind(chrome.tabs);
+ globalThis.blueskyFixtureProbe={commands:[],transports:[],blocked:[]};
+ globalThis.fetch=(input,options)=>{
+ const target=new URL(typeof input==='string'?input:input.url);
+ if(target.hostname==='127.0.0.1'||['chrome-extension:','data:','blob:'].includes(target.protocol))return fetchOriginal(input,options);
+ blueskyFixtureProbe.blocked.push({method:options?.method||'GET',origin:target.origin});
+ return Promise.reject(new Error('The owned Bluesky composer fixture blocks external service requests.'));
+ };
+ chrome.debugger.sendCommand=(...args)=>{blueskyFixtureProbe.commands.push({method:args[1],params:args[2]});return sendCommand(...args);};
+ chrome.tabs.sendMessage=async(...args)=>{
+ const result=await sendMessage(...args),message=args[1];
+ if(/page_monitor|set_field|type_ax|click_ax/.test(message.action))blueskyFixtureProbe.transports.push({action:message.action,
+ tool:message.params?.tool,ref:message.params?.ref_id,result});
+ return result;
+ };
+ });
+ const harness=await context.newPage();await harness.goto(`chrome-extension://${new URL(worker.url()).host}/src/ui/settings.html`);
+ const message=(action,data={})=>harness.evaluate(({action,data})=>chrome.runtime.sendMessage({target:'background',action,...data}),{action,data});
+ await harness.evaluate(()=>{
+ window.blueskyRuns={};chrome.runtime.onMessage.addListener(event=>{
+ if(event.action==='agent_update'&&blueskyRuns[event.requestId])blueskyRuns[event.requestId].push({type:event.type,data:event.data});
+ });
+ return chrome.storage.local.set({helpImproveWebBrain:false,tracingEnabled:false,autoScreenshot:false,screenshotFallback:false,
+ planBeforeActMode:'off',planBeforeAct:false,planReviewMode:'never',maxAgentSteps:10,systemOneEnabled:false,agentAllowLocalNetwork:true,
+ askBeforeConsequentialActions:false,openaiAskStreamingEnabled:false});
+ });
+ assert.equal((await message('update_provider',{providerId:'openrouter',config:{apiKey:'owned-fixture-fake-key',
+ baseUrl:`http://127.0.0.1:${server.address().port}/v1`,model:'minimax/minimax-m3',enabled:true,contextWindow:1000000,supportsAskStreaming:false}})).ok,true);
+ assert.equal((await message('set_active_provider',{providerId:'openrouter'})).ok,true);
+ for(const {scenario,tool,body} of [
+ {scenario:'set_field',tool:'set_field',body:singleLineBody},
+ {scenario:'type_ax',tool:'type_ax',body:singleLineBody},
+ {scenario:'set_field_multiline',tool:'set_field',body:multilineBody},
+ ]){
+ const page=await context.newPage(),pageErrors=[];page.on('pageerror',error=>pageErrors.push(error.message));await page.goto(fixtureUrl);
+ await page.waitForSelector('.ProseMirror');
+ const initial=await page.evaluate(()=>qaSnapshot());
+ assert.equal(initial.model,'');assert.equal(initial.editorName,null);assert.equal(initial.placeholder,"What's up?");assert.equal(initial.publishEnabled,false);
+ const tabId=await harness.evaluate(async url=>(await chrome.tabs.query({})).findLast(tab=>tab.url===url)?.id,fixtureUrl);assert.ok(tabId);
+ current={scenario,tool,body,page,marker:`Owned Bluesky regression path ${scenario}.`,requests:[],calls:[],steps:0,compilers:0,audits:0,judges:0,inferenceChanges:0};
+ const probeStart=await worker.evaluate(()=>({commands:blueskyFixtureProbe.commands.length,transports:blueskyFixtureProbe.transports.length}));
+ const requestId=`owned-bsky-${scenario}`;await harness.evaluate(id=>{blueskyRuns[id]=[];},requestId);
+ const task=`Publish exactly one plain-text post from the currently signed-in ${account} account in this intercepted owned local Bluesky QA fixture, with this exact body:\n${body}\n\nRe-observe Publish after writing, submit once, then verify the fresh authored native post and its stable permalink. ${current.marker}`;
+ const result=await message('chat',{tabId,text:task,mode:'act',requestId,locale:'en'});
+ const runEvents=await harness.evaluate(id=>blueskyRuns[id],requestId),state=await page.evaluate(()=>qaSnapshot());
+ const probe=await worker.evaluate(start=>({commands:blueskyFixtureProbe.commands.slice(start.commands),
+ transports:blueskyFixtureProbe.transports.slice(start.transports),blocked:blueskyFixtureProbe.blocked}),probeStart);
+ const completionEvidence=await worker.evaluate(tabId=>{
+ const guard=blueskyFixtureAgent._continuationExecutionEvidence.get(tabId);
+ return {verifiedSubmission:guard?.verifiedSubmissionEvidence,terminal:guard?.workflowTerminalEvidence,
+ outcomes:guard?.socialPublication?.outcomes,submit:blueskyFixtureAgent._completionSubmitStates.get(tabId)};
+ },tabId);
+ const tools=result.updates?.filter(event=>event.type==='tool_result').map(event=>event.data)||[],writes=tools.filter(item=>item.name===tool),clicks=tools.filter(item=>item.name==='click_ax');
+ const posts=submissions.filter(post=>post.scenario===scenario);
+ await fs.writeFile(path.join(out,`${scenario}-evidence.json`),JSON.stringify({initial,result,runEvents,state,probe,completionEvidence,pageErrors,posts,
+ provider:{...current,page:undefined},blockedRemote},(_key,value)=>typeof value==='string'&&value.startsWith('data:image/')?'[owned screenshot omitted]':value,2));
+ assert.equal(current.providerError,undefined,current.providerError);assert.deepEqual(pageErrors,[]);
+ assert.equal(writes.length,1);assert.equal(writes[0].result.success,true,JSON.stringify(writes));assert.equal(writes[0].result.verified,true);
+ assert.equal(current.afterWrite.model,body);assert.deepEqual(current.afterWrite.blocks,body.split('\n'));
+ assert.deepEqual(current.afterWrite.doc,{type:'doc',content:body.split('\n').map(text=>({type:'paragraph',content:[{type:'text',text}]}))});
+ assert.equal(current.afterWrite.publishEnabled,true);assert.deepEqual(current.afterWrite.commands,[]);
+ const insertions=probe.commands.filter(command=>command.method==='Input.insertText');assert.equal(insertions.length,1);assert.equal(insertions[0].params.text,body);
+ assert.ok(current.afterWrite.events.some(event=>['beforeinput','input'].includes(event.type)&&event.trusted));assert.ok(current.afterWrite.events.every(event=>event.trusted));
+ assert.equal(current.publishReobserved,true);assert.equal(clicks.length,1);
+ assert.ok(clicks[0].result.success===true||clicks[0].result.dispatched===true,JSON.stringify(clicks));
+ assert.equal(completionEvidence.submit?.dispatched,true,'The actual publication binding must record the native control activation.');
+ if(clicks[0].result.success!==true){assert.equal(clicks[0].result.outcomeUnknown,true);assert.equal(clicks[0].result.retryable,false);}
+ assert.deepEqual(posts,[{scenario,tool,payload:{account,body}}]);assert.deepEqual(state.saved,[{account,body}]);assert.equal(state.dialogOpen,false);
+ const fresh=tools.findLast(item=>item.name==='get_accessibility_tree')?.result?.pageContent||'';assert.ok(fresh.includes(`/profile/${account}/post/3ownedqa`));
+ assert.equal(state.feedChanges,2);assert.equal(current.inferenceChanges,2);
+ assert.ok(probe.transports.some(item=>item.action==='page_monitor_validate_model'&&item.result?.ready===true));
+ const doneCalls=tools.filter(item=>item.name==='done');assert.equal(doneCalls.length,1,'The first fresh completion must verify the exact native published body.');
+ const done=doneCalls[0]?.result;assert.equal(done?.done,true,JSON.stringify(done));assert.equal(done?.outcome,'success',JSON.stringify(done));assert.notEqual(done?.success,false);
+ assert.equal(runEvents.findLast(event=>event.type==='run_complete')?.data?.status,'completed');
+ assert.equal(completionEvidence.verifiedSubmission,true);assert.deepEqual(completionEvidence.outcomes?.p1,{status:'verified'});
+ assert.equal(completionEvidence.terminal?.source,'dispatch_bound_published_resource');
+ assert.equal(completionEvidence.submit?.workflowBinding?.publishedResourceIdentity,'bluesky:bsky.app/profile/owned.bsky.social/post/3ownedqa');
+ summaries.push({scenario,tool,paragraphs:body.split('\n').length,inputCommands:insertions.length,posts:posts.length,feedChanges:state.feedChanges,terminalOutcome:done.outcome,nativePublicationVerified:true});
+ await page.close();
+ }
+ assert.ok(blockedRemote.every(request=>['GET','HEAD','OPTIONS'].includes(request.method)));
+ const blockedBackground=await worker.evaluate(()=>blueskyFixtureProbe.blocked);assert.ok(blockedBackground.every(request=>['GET','HEAD','OPTIONS'].includes(request.method)));
+ await fs.writeFile(path.join(out,'summary.json'),JSON.stringify({passed:true,installedMV3:true,actualProseMirror:true,summaries,postUrl,externalPosts:0,blockedRemote,blockedBackground},null,2));
+ console.log(JSON.stringify({passed:true,installedMV3:true,actualProseMirror:true,cases:summaries,externalPosts:0}));
+}finally{
+ await context?.close();await new Promise(resolve=>server.close(resolve));
+ const resolved=path.resolve(profile);assert.ok(resolved.startsWith(path.resolve(os.tmpdir())+path.sep+'webbrain-bluesky-composer-mv3-'));
+ await fs.rm(resolved,{recursive:true,force:true});
+}
diff --git a/test/quality/inline-social-composer-mv3.mjs b/test/quality/inline-social-composer-mv3.mjs
new file mode 100644
index 000000000..dc9e50b75
--- /dev/null
+++ b/test/quality/inline-social-composer-mv3.mjs
@@ -0,0 +1,458 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import http from 'node:http';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { chromium } from 'playwright';
+
+// The actual installed MV3 background, monitor, Agent and CDP input operate on
+// React/DraftJS document nodes. Only inference and owned HTTP responses are
+// deterministic. No real X page, account, API or posting service is contacted.
+const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS
+ || 'ci/artifacts/quality-audit-2026-10-11/inline-social-composer-mv3');
+await fs.mkdir(out, { recursive: true });
+const require = createRequire(import.meta.url);
+const library = (name, file) => fs.readFile(path.join(path.dirname(require.resolve(`${name}/package.json`)), file), 'utf8');
+const libraryFiles = [
+ ['react.js', 'react', 'umd/react.development.js'],
+ ['react-dom.js', 'react-dom', 'umd/react-dom.development.js'],
+ ['immutable.js', 'immutable', 'dist/immutable.js'],
+ ['draft.js', 'draft-js', 'dist/Draft.js'],
+];
+const assets = new Map(await Promise.all(libraryFiles.map(async ([name, module, file]) => [name, await library(module, file)])));
+const draftCss = await library('draft-js', 'dist/Draft.css');
+const fixtureUrl = 'https://x.com/home';
+const account = 'ownedqa';
+const body = 'One owned inline draft: exact spaces and Turkish ıİşŞğĞüÜöÖçÇ 🧠.';
+const cases = [
+ { name: 'set_field', tool: 'set_field' },
+ { name: 'type_ax', tool: 'type_ax' },
+ { name: 'focus_expansion', tool: 'set_field', focusExpansion: true },
+ { name: 'owner_changed', tool: 'set_field', change: 'owner' },
+ { name: 'account_changed', tool: 'type_ax', change: 'account' },
+ { name: 'audience_changed', tool: 'set_field', change: 'audience' },
+ { name: 'composer_navigation_changed', tool: 'type_ax', change: 'navigation' },
+].filter(item => !process.env.WEBBRAIN_QUALITY_INLINE_CASE || item.name === process.env.WEBBRAIN_QUALITY_INLINE_CASE);
+assert.ok(cases.length, 'Select an existing owned inline regression case.');
+const textOf = value => typeof value === 'string' ? value : Array.isArray(value)
+ ? value.filter(part => part?.type === 'text').map(part => part.text || '').join('\n') : '';
+function toolObject(content) {
+ const text = textOf(content);
+ // Production results remain inside the nonce-bound untrusted-page envelope.
+ for (let start = text.indexOf('{'); start >= 0; start = text.indexOf('{', start + 1)) {
+ let depth = 0, quoted = false, escaped = false;
+ for (let cursor = start; cursor < text.length; cursor++) {
+ const char = text[cursor];
+ if (quoted) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === '"') quoted = false; }
+ else if (char === '"') quoted = true;
+ else if (char === '{') depth++;
+ else if (char === '}' && --depth === 0) {
+ try { return JSON.parse(text.slice(start, cursor + 1)); } catch { break; }
+ }
+ }
+ }
+ return null;
+}
+function latestTools(messages) {
+ const names = new Map();
+ for (const message of messages || []) for (const call of message.tool_calls || []) names.set(call.id, call.function?.name);
+ return (messages || []).filter(message => message.role === 'tool')
+ .map(message => ({ name: names.get(message.tool_call_id) || message.name, result: toolObject(message.content) }));
+}
+function references(tree) {
+ const lines = String(tree?.pageContent || '').split('\n');
+ const ref = expression => lines.find(line => expression.test(line))?.match(/\[(ref_\d+)\]/)?.[1];
+ return { editor: ref(/textbox "Post text"/), post: ref(/button "Post"/), tree: tree?.pageContent };
+}
+const intent = { request_kind: 'execute', scope_relation: 'new', requires_state_change: true,
+ requires_submission: true, messaging: null, deliverables: ['One exact owned local QA post, freshly verified.'],
+ allows_planner_shaped_result: false, allows_app_state_tool_evidence: false,
+ completion_requirements: { download: false }, read_scope: 'visible_page',
+ summary: 'Publish exactly one owned local QA post from the current ownedqa account and verify its confirmation.',
+ steps: [{ id: '1', action: 'Read the home composer, write the exact draft once, re-observe Post, publish once and verify the owned confirmation.' }],
+ memory: { use_progress_ledger: false, progress_action: null }, scheduling: null, risks: [] };
+let current, context;
+const blockedRemote = [], submissions = [], summaries = [], auxiliaryRequests = [];
+const server = http.createServer(async (request, response) => {
+ try {
+ if (request.url !== '/v1/chat/completions') { response.writeHead(404).end(); return; }
+ let raw = ''; for await (const part of request) raw += part;
+ const input = JSON.parse(raw);
+ const system = textOf(input.messages?.[0]?.content);
+ if (system.startsWith('Extract stable user preferences for WebBrain memory.')) {
+ auxiliaryRequests.push(input);
+ response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ id: 'owned-inline-memory',
+ choices: [{ message: { role: 'assistant', content: '{"memories":[]}' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 100, completion_tokens: 10 } }));
+ return;
+ }
+ current.requests.push(input);
+ assert.ok(current && JSON.stringify(input.messages).includes(current.marker), `Inference must retain this owned task authority: ${system.slice(0, 160)}`);
+ let completion;
+ if (system.startsWith("Compile the user's social-publication intent across languages.")) {
+ current.compilers = (current.compilers || 0) + 1;
+ completion = { role: 'assistant', content: JSON.stringify({ version: 1, status: 'ready',
+ actions: [{ id: 'p1', platform: 'twitter', account: { source: 'task', start: account, end: account },
+ posts: [{ body: { kind: 'exact', source: { source: 'task', start: body, end: body } },
+ media: { kind: 'count', type: 'any', format: null, min: 0, max: 0 }, context: { kind: 'post', target: null } }] }],
+ requirements: 'p1', prohibited: [], reason: 'The authentic task authorizes one exact local QA post.' }) };
+ } else if (system.startsWith('Independently check whether the authentic user request authorizes this concrete public dispatch.')) {
+ current.audits = (current.audits || 0) + 1;
+ const audit = JSON.parse(textOf(input.messages.find(message => message.role === 'user')?.content));
+ completion = { role: 'assistant', content: JSON.stringify({ key: audit.key, actionId: audit.action.id,
+ authorized: true, reason: 'The exact owned body, account and plain-post scope match the authentic task.' }) };
+ } else if (system.startsWith('Evaluate only the observable requirements of the genuine user task')) {
+ current.judges++;
+ completion = { role: 'assistant', content: JSON.stringify({ outcome: 'succeeded', reason: 'Fresh owned page confirmation records the exact authorized local post.' }) };
+ } else if (!input.tools?.length) completion = { role: 'assistant', content: JSON.stringify(intent) };
+ else {
+ const step = current.steps++;
+ const tools = latestTools(input.messages);
+ const last = tools.at(-1);
+ const observed = tools.findLast(tool => tool.name === 'get_accessibility_tree' && tool.result?.pageContent);
+ let call;
+ if (step === 0) call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ else if (step === 1) {
+ current.beforeWrite = references(observed?.result);
+ assert.ok(current.beforeWrite.editor && current.beforeWrite.post, JSON.stringify(observed));
+ // This external page activity occurs after the real pre-inference
+ // model capture and before the provider's response. It is never an
+ // agent-owned mutation or a mock monitor/dispatch acknowledgement.
+ await current.page.evaluate(change => {
+ qaChurnFeed();
+ if (change) qaChangeContext(change);
+ }, current.change || null);
+ current.inferenceChanges++;
+ await new Promise(resolve => setTimeout(resolve, 240));
+ call = { name: current.tool, args: { ref_id: current.beforeWrite.editor, text: body, clear: true } };
+ } else if (step === 2) {
+ current.writeResult = tools.findLast(tool => tool.name === current.tool)?.result;
+ current.afterWrite = await current.page.evaluate(() => qaSnapshot());
+ call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ } else if (step === 3 && current.focusExpansion) {
+ current.expansionResult = current.writeResult;
+ current.expansionState = current.afterWrite;
+ const fresh = references(observed?.result);
+ assert.ok(fresh.editor && last?.name === 'get_accessibility_tree', 'The focus expansion requires a new observed typing decision.');
+ call = { name: current.tool, args: { ref_id: fresh.editor, text: body, clear: true } };
+ } else if (step === 4 && current.focusExpansion) {
+ current.writeResult = tools.findLast(tool => tool.name === current.tool)?.result;
+ current.afterWrite = await current.page.evaluate(() => qaSnapshot());
+ call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ } else if (step === (current.focusExpansion ? 5 : 3) && !current.change && current.writeResult?.success === true) {
+ current.beforePost = references(observed?.result);
+ assert.ok(current.beforePost.post, JSON.stringify(observed));
+ current.postReobserved = last?.name === 'get_accessibility_tree';
+ await current.page.evaluate(() => qaChurnFeed());
+ current.inferenceChanges++;
+ await new Promise(resolve => setTimeout(resolve, 240));
+ call = { name: 'click_ax', args: { ref_id: current.beforePost.post } };
+ } else if (step === (current.focusExpansion ? 6 : 4) && !current.change && current.writeResult?.success === true)
+ call = { name: 'get_accessibility_tree', args: { filter: 'all' } };
+ else call = { name: 'done', args: { outcome: current.change || current.writeResult?.success !== true ? 'partial' : 'success',
+ summary: current.change ? 'The changed composer was left intact and unsubmitted.' : 'The owned local inline composer regression is finished.' } };
+ current.calls.push(call);
+ completion = { role: 'assistant', content: '', tool_calls: [{ id: `owned-inline-${current.name}-${step}`,
+ type: 'function', function: { name: call.name, arguments: JSON.stringify(call.args) } }] };
+ }
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(JSON.stringify({ id: `owned-inline-${current.name}-${current.requests.length}`, choices: [{ message: completion,
+ finish_reason: completion.tool_calls ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 100, completion_tokens: 30 } }));
+ } catch (error) {
+ if (current) current.providerError = error.stack;
+ response.writeHead(500, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: error.message }));
+ }
+});
+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+
+const html = `<!doctype html><html><head><meta charset="utf-8"><title>Owned home timeline</title>
+<style>${draftCss}
+body{margin:0;background:#fff;color:#111;font:17px system-ui}#app{display:flex;gap:24px;margin:20px}
+#account-nav{width:170px}a{color:inherit}main{width:660px}.tabs{height:55px;display:flex;gap:20px}
+#inline-owner{padding:16px;border:1px solid #bbb;display:flex;gap:15px;min-height:230px;box-sizing:border-box}
+.avatar{width:45px;height:45px;display:block;border-radius:50%;background:#456;color:white;text-align:center;line-height:45px}
+.compose-inner{width:560px}.public-DraftEditor-content{height:100px;overflow:auto}.DraftEditor-root{height:100px}
+button{font:inherit;padding:8px;margin:3px}.compose-actions{display:flex;align-items:center;justify-content:space-between}
+article{padding:16px;border:1px solid #ddd;height:120px}#confirmation{padding:12px}
+[data-testid="tweetText"]{white-space:pre-wrap}</style>
+${libraryFiles.map(([name]) => `<script src="/owned-fixture/${name}"></script>`).join('')}
+</head><body><div id="app"></div><script>
+window.qaEvents=[];window.qaCommands=[];window.qaFeedChanges=0;window.qaSaved=[];
+window.qaExpandOnFocus=!!window.qaExpandOnFocus;
+const root=ReactDOM.createRoot(document.querySelector('#app'));
+function App(){
+ const [editorState,setEditorState]=React.useState(()=>Draft.EditorState.createEmpty());
+ const [identity,setIdentity]=React.useState('${account}');
+ const [audience,setAudience]=React.useState(window.qaExpandOnFocus?null:'Everyone can reply');
+ const [ownerVersion,setOwnerVersion]=React.useState(0);
+ const [mediaLabel,setMediaLabel]=React.useState('Add photos or video');
+ const [feedRevision,setFeedRevision]=React.useState(0);
+ const [saved,setSaved]=React.useState(null);
+ window.qaEditorState=editorState;
+ window.qaChangeContext=kind=>ReactDOM.flushSync(()=>{
+ if(kind==='owner')setOwnerVersion(value=>value+1);
+ if(kind==='account')setIdentity('otherqa');
+ if(kind==='audience')setAudience('Only people you mention can reply');
+ if(kind==='navigation')setMediaLabel('Add private attachment');
+ });
+ window.qaChurnFeed=()=>ReactDOM.flushSync(()=>{window.qaFeedChanges++;setFeedRevision(value=>value+1);});
+ const onChange=next=>{window.qaEditorState=next;setEditorState(next);};
+ const value=editorState.getCurrentContent().getPlainText('\\n');
+ const post=async()=>{
+ const payload={account:identity,body:editorState.getCurrentContent().getPlainText('\\n'),audience};
+ const response=await fetch('/owned-fixture/post',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
+ if(response.ok){window.qaSaved.push(payload);setSaved(payload);setEditorState(Draft.EditorState.createEmpty());}
+ };
+ return React.createElement(React.Fragment,null,
+ React.createElement('nav',{id:'account-nav','aria-label':'Account navigation'},
+ React.createElement('a',{'data-testid':'AppTabBar_Profile_Link',href:'/'+identity},'Owned QA profile')),
+ React.createElement('main',{'aria-label':'Home timeline'},
+ React.createElement('nav',{className:'tabs','aria-label':'Home timeline tabs'},
+ React.createElement('button',{type:'button',role:'tab','aria-selected':'true'},'For you'),
+ React.createElement('button',{type:'button',role:'tab','aria-selected':'false'},'Following')),
+ React.createElement('div',{id:'inline-owner',key:ownerVersion},
+ React.createElement('a',{className:'avatar',href:'/'+identity,'aria-label':'Owned QA account avatar'},'QA'),
+ React.createElement('div',{className:'compose-inner',onFocus:()=>{if(window.qaExpandOnFocus&&!audience)ReactDOM.flushSync(()=>setAudience('Everyone can reply'));}},
+ React.createElement(Draft.Editor,{editorState,onChange,ariaLabel:'Post text',webDriverTestID:'tweetTextarea_0',placeholder:'What is happening?!'}),
+ audience?React.createElement('button',{id:'audience',type:'button'},audience):null,
+ React.createElement('div',{className:'compose-actions'},
+ React.createElement('nav',{'aria-label':'Composer tools'},
+ React.createElement('button',{type:'button','aria-label':mediaLabel},'Media'),
+ React.createElement('button',{type:'button','aria-label':'Add emoji'},'Emoji')),
+ React.createElement('button',{id:'post',type:'button','data-testid':'tweetButtonInline',disabled:!value,onClick:post},'Post')))),
+ React.createElement('div',{id:'confirmation',role:'status'},saved?'Owned local QA post recorded: '+saved.body:''),
+ saved?React.createElement('article',{'data-testid':'tweet'},
+ React.createElement('div',{'data-testid':'User-Name'},
+ React.createElement('a',{href:'/'+saved.account},'Owned QA account'),
+ React.createElement('a',{href:'/'+saved.account+'/status/900'},React.createElement('time',{dateTime:new Date().toISOString()},'Now'))),
+ React.createElement('div',{'data-testid':'tweetText'},saved.body)):null,
+ React.createElement('div',{id:'feed'},[0,1,2].map(index=>React.createElement('article',{key:feedRevision+'-'+index},
+ React.createElement('a',{href:'/feedqa/status/'+(feedRevision*10+index)},'Unrelated feed account'),
+ React.createElement('p',null,'Live feed record '+feedRevision+'-'+index),
+ React.createElement('button',{type:'button','aria-label':'Like feed item '+feedRevision+'-'+index},'Like'))))));
+}
+ReactDOM.flushSync(()=>root.render(React.createElement(App)));
+for(const type of ['beforeinput','input','paste'])document.querySelector('#app').addEventListener(type,event=>{
+ if(event.target.closest('[data-testid="tweetTextarea_0"]'))qaEvents.push({type,trusted:event.isTrusted,inputType:event.inputType,
+ data:type==='paste'?event.clipboardData?.getData('text/plain'):event.data});
+},true);
+const execCommand=document.execCommand.bind(document);
+document.execCommand=(command,showUI,value)=>{qaCommands.push({command,value});return execCommand(command,showUI,value);};
+window.qaSnapshot=()=>{
+ const editor=document.querySelector('[data-testid="tweetTextarea_0"]');
+ return {model:qaEditorState.getCurrentContent().getPlainText('\\n'),modelBlocks:qaEditorState.getCurrentContent().getBlocksAsArray().map(block=>block.getText()),
+ text:editor.textContent,blocks:[...editor.querySelectorAll('[data-block="true"]')].map(block=>block.textContent),
+ postEnabled:!document.querySelector('#post').disabled,audience:document.querySelector('#audience')?.textContent||null,
+ events:qaEvents,commands:qaCommands,feedChanges:qaFeedChanges,saved:qaSaved};
+};
+</script></body></html>`;
+
+const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-inline-social-mv3-'));
+try {
+ const extension = path.join(profile, 'extension');
+ await fs.cp(path.resolve('src/chrome'), extension, { recursive: true });
+ // Read-only diagnostics in the disposable clone leave every production
+ // permission, input, publication and completion decision intact.
+ await fs.appendFile(path.join(extension, 'src/background.js'), '\nglobalThis.inlineFixtureAgent = agent;\n');
+ context = await chromium.launchPersistentContext(profile, { headless: true, channel: 'chromium', viewport: { width: 1280, height: 1000 },
+ args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`,
+ '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'] });
+ await context.route('**/*', async route => {
+ const request = route.request(), requested = new URL(request.url());
+ if (requested.hostname === '127.0.0.1' && requested.port === String(server.address().port)) return route.continue();
+ if (requested.origin === 'https://x.com') {
+ if (request.isNavigationRequest() && requested.href === fixtureUrl && request.method() === 'GET')
+ return route.fulfill({ contentType: 'text/html', body: html });
+ if (requested.pathname.startsWith('/owned-fixture/') && assets.has(requested.pathname.split('/').at(-1)) && request.method() === 'GET')
+ return route.fulfill({ contentType: 'text/javascript', body: assets.get(requested.pathname.split('/').at(-1)) });
+ if (requested.pathname === '/owned-fixture/post' && request.method() === 'POST') {
+ const payload = request.postDataJSON(); submissions.push({ case: current.name, payload });
+ return route.fulfill({ status: 201, contentType: 'application/json', body: '{"owned":true}' });
+ }
+ return route.fulfill({ status: 404, body: '' });
+ }
+ if (/^https?:$/.test(requested.protocol)) {
+ blockedRemote.push({ method: request.method(), origin: requested.origin }); return route.abort('blockedbyclient');
+ }
+ return route.continue();
+ });
+ const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30000 });
+ await worker.evaluate(() => {
+ const fetchOriginal = fetch.bind(globalThis);
+ globalThis.inlineFixtureProbe = { commands: [], transports: [], feedback: [], blocked: [] };
+ globalThis.fetch = (input, options) => {
+ const requested = new URL(typeof input === 'string' ? input : input.url);
+ if (requested.hostname === '127.0.0.1' || ['chrome-extension:', 'data:', 'blob:'].includes(requested.protocol))
+ return fetchOriginal(input, options);
+ inlineFixtureProbe.blocked.push({ origin: requested.origin, method: options?.method || 'GET' });
+ return Promise.reject(new Error('The owned inline composer fixture blocks external service requests.'));
+ };
+ const sendCommand = chrome.debugger.sendCommand.bind(chrome.debugger);
+ chrome.debugger.sendCommand = (...args) => {
+ inlineFixtureProbe.commands.push({ method: args[1], params: args[2] }); return sendCommand(...args);
+ };
+ const sendMessage = chrome.tabs.sendMessage.bind(chrome.tabs);
+ chrome.tabs.sendMessage = async (...args) => {
+ const result = await sendMessage(...args), message = args[1];
+ if (/page_monitor|set_field|type_ax|click_ax/.test(message.action)) inlineFixtureProbe.transports.push({ tabId: args[0],
+ action: message.action, params: { tool: message.params?.tool, ref_id: message.params?.ref_id,
+ expectedModelSnapshot: !!message.params?.expectedModelSnapshot, fenceOnly: message.params?.fenceOnly }, result });
+ return result;
+ };
+ chrome.runtime.onMessage.addListener(message => {
+ if (message.action === 'page_feedback') inlineFixtureProbe.feedback.push(message.feedback);
+ });
+ });
+ const harness = await context.newPage();
+ await harness.goto(`chrome-extension://${new URL(worker.url()).host}/src/ui/settings.html`);
+ const message = (action, data = {}) => harness.evaluate(({ action, data }) =>
+ chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data });
+ await harness.evaluate(() => {
+ window.inlineRunEvents = {};
+ chrome.runtime.onMessage.addListener(event => {
+ if (event.action === 'agent_update' && inlineRunEvents[event.requestId])
+ inlineRunEvents[event.requestId].push({ type: event.type, data: event.data });
+ });
+ return chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false,
+ autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false,
+ planReviewMode: 'never', maxAgentSteps: 10, systemOneEnabled: false, agentAllowLocalNetwork: true,
+ askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false });
+ });
+ assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key',
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'minimax/minimax-m3', enabled: true,
+ contextWindow: 1000000, supportsAskStreaming: false } })).ok, true);
+ assert.equal((await message('set_active_provider', { providerId: 'openrouter' })).ok, true);
+
+ for (const specification of cases) {
+ const page = await context.newPage(), pageErrors = [];
+ page.on('pageerror', error => pageErrors.push(error.message));
+ if (specification.focusExpansion) await page.addInitScript(() => { window.qaExpandOnFocus = true; });
+ await page.goto(fixtureUrl);
+ await page.waitForSelector('[data-testid="tweetTextarea_0"]');
+ const initial = await page.evaluate(() => ({ state: qaSnapshot(), headings: document.querySelectorAll('h1,h2,h3,h4,h5,h6,[role="heading"]').length,
+ formsOrDialogs: document.querySelectorAll('form,dialog,[role="form"],[role="dialog"]').length }));
+ assert.equal(initial.state.model, ''); assert.equal(initial.state.postEnabled, false);
+ if (specification.focusExpansion) assert.equal(initial.state.audience, null);
+ assert.equal(initial.headings, 0); assert.equal(initial.formsOrDialogs, 0);
+ const tabId = await harness.evaluate(async url => (await chrome.tabs.query({})).findLast(tab => tab.url === url)?.id, fixtureUrl);
+ assert.ok(tabId);
+ current = { ...specification, page, marker: `Owned inline regression case ${specification.name}.`, requests: [], calls: [],
+ steps: 0, judges: 0, inferenceChanges: 0 };
+ const probeStart = await worker.evaluate(() => ({ commands: inlineFixtureProbe.commands.length,
+ transports: inlineFixtureProbe.transports.length, feedback: inlineFixtureProbe.feedback.length }));
+ const task = `In this intercepted owned local QA fixture, publish exactly one post from the active ${account} account with exact text ${JSON.stringify(body)}.
+Re-observe the Post button after writing, click it once, then verify the owned local confirmation. Do not post if the composer owner, account, audience or local controls change. ${current.marker}`;
+ const requestId = `owned-inline-${specification.name}`;
+ await harness.evaluate(id => { inlineRunEvents[id] = []; }, requestId);
+ const result = await message('chat', { tabId, text: task, mode: 'act', requestId, locale: 'en' });
+ const runEvents = await harness.evaluate(id => inlineRunEvents[id], requestId);
+ const completionEvidence = await worker.evaluate(tabId => {
+ const guard = inlineFixtureAgent._continuationExecutionEvidence.get(tabId);
+ return { verifiedSubmission: guard?.verifiedSubmissionEvidence, terminal: guard?.workflowTerminalEvidence,
+ publicationOutcomes: guard?.socialPublication?.outcomes,
+ submit: inlineFixtureAgent._completionSubmitStates.get(tabId) };
+ }, tabId);
+ const state = await page.evaluate(() => qaSnapshot());
+ const probe = await worker.evaluate(start => ({ commands: inlineFixtureProbe.commands.slice(start.commands),
+ transports: inlineFixtureProbe.transports.slice(start.transports), feedback: inlineFixtureProbe.feedback.slice(start.feedback),
+ blocked: inlineFixtureProbe.blocked }), probeStart);
+ const tools = result.updates?.filter(event => event.type === 'tool_result').map(event => event.data) || [];
+ const writes = tools.filter(tool => tool.name === specification.tool), clicks = tools.filter(tool => tool.name === 'click_ax');
+ const localPosts = submissions.filter(post => post.case === specification.name);
+ const evidence = { specification, initial, result, runEvents, completionEvidence, tools, state, probe, pageErrors, localPosts,
+ provider: { ...current, page: undefined }, blockedRemote };
+ await fs.writeFile(path.join(out, `${specification.name}-evidence.json`), JSON.stringify(evidence,
+ (_key, value) => typeof value === 'string' && value.startsWith('data:image/') ? '[owned fixture screenshot omitted]' : value, 2));
+ assert.equal(current.providerError, undefined, current.providerError);
+ assert.deepEqual(pageErrors, [], 'Real React/DraftJS reconciliation must remain valid.');
+ if (specification.change) {
+ assert.equal(current.calls.filter(call => call.name === specification.tool).length, 1, 'The provider must actually attempt the stale write once.');
+ assert.ok(writes.length <= 1, 'Never retry a vetoed context change.');
+ if (writes.length) {
+ assert.equal(writes[0].result.success, false, JSON.stringify(writes));
+ assert.equal(writes[0].result.noDispatch, true, JSON.stringify(writes));
+ assert.equal(writes[0].result.dispatched, false, JSON.stringify(writes));
+ } else {
+ // A stale decision can be discarded by the pre-dispatch batch fence,
+ // before Agent emits a tool_result. The real failed model validation
+ // and absence of native input prove the veto independently.
+ assert.ok(probe.transports.some(item => item.action === 'page_monitor_validate_model'
+ && item.params.tool === specification.tool && item.params.ref_id === current.beforeWrite.editor && item.result?.ready === false),
+ 'The production model certificate must reject the stale local owner.');
+ }
+ assert.equal(state.model, ''); assert.deepEqual(state.saved, []);
+ assert.deepEqual(localPosts, []); assert.equal(clicks.length, 0);
+ assert.equal(probe.commands.filter(command => command.method === 'Input.insertText').length, 0);
+ assert.deepEqual(state.events, [], 'A stale owner must be rejected before page input.');
+ } else {
+ assert.equal(writes.length, specification.focusExpansion ? 2 : 1, 'Only an explicit fresh decision may retry a positively undispatched write.');
+ if (specification.focusExpansion) {
+ assert.equal(current.expansionResult.success, false, JSON.stringify(writes));
+ assert.equal(current.expansionResult.noDispatch, true, JSON.stringify(writes));
+ assert.equal(current.expansionResult.dispatched, false, JSON.stringify(writes));
+ assert.equal(current.expansionState.model, '', 'Focus may reveal local controls, but must not insert stale-decision text.');
+ assert.equal(current.expansionState.audience, 'Everyone can reply', 'Trusted preparation must exercise a real focus-triggered expansion.');
+ assert.deepEqual(current.expansionState.events, []);
+ }
+ assert.equal(writes.at(-1).result.success, true, JSON.stringify(writes));
+ assert.equal(writes.at(-1).result.verified, true, JSON.stringify(writes));
+ assert.equal(current.afterWrite.model, body, 'Compare the real application EditorState before submitting.');
+ assert.deepEqual(current.afterWrite.modelBlocks, [body]);
+ assert.deepEqual(current.afterWrite.blocks, [body], 'React-rendered blocks must match the application document exactly.');
+ assert.equal(current.afterWrite.text, body, 'No unmanaged duplicate text may exist outside DraftJS blocks.');
+ assert.equal(current.afterWrite.postEnabled, true, 'The application must enable Post from its own editor state.');
+ assert.deepEqual(current.afterWrite.commands, [], 'No execCommand wrapper or HTML mutation may enter framework-owned DOM.');
+ const insertions = probe.commands.filter(command => command.method === 'Input.insertText');
+ assert.equal(insertions.length, 1, 'Dispatch the exact text through CDP once.');
+ assert.equal(insertions[0].params.text, body);
+ assert.ok(current.afterWrite.events.some(event => ['beforeinput', 'input'].includes(event.type) && event.trusted));
+ assert.ok(current.afterWrite.events.every(event => event.trusted), 'This single-line draft uses browser-trusted input.');
+ assert.equal(current.postReobserved, true, 'Post must receive an independent current AX read after typing.');
+ assert.equal(clicks.length, 1);
+ assert.equal(clicks[0].result.dispatched, true, JSON.stringify(clicks));
+ if (clicks[0].result.success !== true) {
+ assert.equal(clicks[0].result.outcomeUnknown, true, JSON.stringify(clicks));
+ assert.equal(clicks[0].result.retryable, false, 'An acknowledged Post must never be retried after observation is interrupted.');
+ }
+ const confirmation = tools.findLast(tool => tool.name === 'get_accessibility_tree')?.result?.pageContent || '';
+ assert.match(confirmation, /Owned local QA post recorded:/, 'A fresh installed-extension read must observe the owned save confirmation.');
+ assert.match(confirmation, /\/ownedqa\/status\/900/, 'A fresh native record must independently expose the saved owned post.');
+ assert.deepEqual(localPosts, [{ case: specification.name, payload: { account, body, audience: 'Everyone can reply' } }],
+ 'The owned local POST must contain exactly the application draft, once.');
+ assert.deepEqual(state.saved, [{ account, body, audience: 'Everyone can reply' }]);
+ assert.equal(state.model, ''); assert.equal(state.postEnabled, false);
+ assert.equal(current.inferenceChanges, 2, 'Live feed must churn independently during both write and Post inference.');
+ assert.equal(state.feedChanges, 2);
+ assert.ok(probe.transports.some(item => item.action === 'page_monitor_validate_model' && item.result?.ready === true),
+ 'The production model monitor must validate a real document certificate.');
+ const done = tools.findLast(tool => tool.name === 'done')?.result;
+ assert.equal(done?.done, true, JSON.stringify(done));
+ assert.equal(done?.outcome, 'success', JSON.stringify(done));
+ assert.notEqual(done?.success, false, JSON.stringify(done));
+ assert.equal(runEvents.findLast(event => event.type === 'run_complete')?.data?.status, 'completed');
+ assert.equal(completionEvidence.verifiedSubmission, true, 'A model verdict alone cannot verify the social submission.');
+ assert.deepEqual(completionEvidence.publicationOutcomes?.p1, { status: 'verified' });
+ assert.equal(completionEvidence.terminal?.source, 'dispatch_bound_published_resource');
+ assert.equal(completionEvidence.submit?.workflowBinding?.publishedResourceIdentity, 'twitter:status:900');
+ }
+ summaries.push({ case: specification.name, inputCommands: probe.commands.filter(command => command.method === 'Input.insertText').length,
+ posts: localPosts.length, noDispatch: specification.change ? true : writes[0].result.noDispatch === true, feedChanges: state.feedChanges,
+ postOutcomeUnknown: clicks[0]?.result?.outcomeUnknown === true,
+ terminalOutcome: tools.findLast(tool => tool.name === 'done')?.result?.outcome,
+ nativePublicationVerified: completionEvidence.publicationOutcomes?.p1?.status === 'verified' });
+ await page.close();
+ }
+ assert.ok(blockedRemote.every(request => ['GET', 'HEAD', 'OPTIONS'].includes(request.method)), 'No external mutation may be attempted.');
+ const network = await worker.evaluate(() => inlineFixtureProbe.blocked);
+ assert.ok(network.every(request => ['GET', 'HEAD', 'OPTIONS'].includes(request.method)), 'No background external mutation may be attempted.');
+ await fs.writeFile(path.join(out, 'summary.json'), JSON.stringify({ passed: true, installedMV3: true,
+ framework: { react: require('react/package.json').version, draftJS: require('draft-js/package.json').version },
+ summaries, externalPosts: 0, blockedRemote, blockedBackground: network, auxiliaryRequests }, null, 2));
+ console.log(JSON.stringify({ passed: true, installedMV3: true, actualReactDraftJS: true, cases: summaries, externalPosts: 0 }));
+} finally {
+ await context?.close(); await new Promise(resolve => server.close(resolve));
+ const resolved = path.resolve(profile);
+ assert.ok(resolved.startsWith(path.resolve(os.tmpdir()) + path.sep + 'webbrain-inline-social-mv3-'));
+ await fs.rm(resolved, { recursive: true, force: true });
+}
diff --git a/test/quality/whatsapp-contact-mv3.mjs b/test/quality/whatsapp-contact-mv3.mjs
index 50b40ec3f..03f96bcbb 100644
--- a/test/quality/whatsapp-contact-mv3.mjs
+++ b/test/quality/whatsapp-contact-mv3.mjs
@@ -59,7 +59,7 @@ const fixture = `<!doctype html><html><head><title>Owned native WhatsApp contact
<div id="main" data-testid="conversation-panel-wrapper"><header data-testid="conversation-header"><div style="display:flex;align-items:center;flex:1"><div role="button" tabindex="0" aria-label="Avatar QA" data-qa-forbidden="true"><span>Avatar</span></div><div role="button" tabindex="0" data-testid="conversation-info-header" data-tab="6"><div><div><div data-testid="conversation-info-header-chat-title-name"><div><div><span data-testid="conversation-info-header-chat-title" dir="auto">${peer}</span></div></div></div></div></div></div></div><div style="display:flex">${['Voice call', 'Video call', 'Search', 'Menu'].map(label => `<button type="button" aria-label="${label}" data-qa-forbidden="true"><span>${label}</span></button>`).join('')}</div></header>
<div data-testid="conversation-panel-body"><div data-testid="conversation-panel-messages"></div></div><footer><div data-testid="conversation-compose-box-input" contenteditable="true" role="textbox" aria-placeholder="Type a message" data-tab="10" data-lexical-editor="true"></div><div id="qa-action-wrap"><button aria-label="${scenario === 'postwrite_debt' ? 'Voice message' : 'Send'}">${scenario === 'postwrite_debt' ? 'Voice' : 'Send'}</button></div></footer></div>
<script>
-window.qaReplies=JSON.parse(sessionStorage.getItem('owned-qa-replies')||'[]');window.qaDrawer={opened:0,closed:0,avatarUpdates:0,hoverEvents:0,focusEvents:0,pressEvents:0,identityStable:true};window.qaDeliveryDelay=120;window.qaRemoveFloor=false;window.qaUnrelatedClicks=0;window.qaForbiddenClicks=0;window.qaEditor={handled:0,rerenders:0,enter:0,sendClicks:0};
+window.qaReplies=JSON.parse(sessionStorage.getItem('owned-qa-replies')||'[]');window.qaDrawer={opened:0,closed:0,avatarUpdates:0,hoverEvents:0,focusEvents:0,pressEvents:0,identityStable:true};window.qaDeliveryDelay=120;window.qaRemoveFloor=false;window.qaUnrelatedClicks=0;window.qaForbiddenClicks=0;window.qaEditor={handled:0,rerenders:0,enter:0,sendClicks:0};window.qaNativeInputs=[];
const transcript=document.querySelector('[data-testid="conversation-panel-messages"]'),composer=document.querySelector('[contenteditable]');
window.qaRow=(id,text,direction,tail=true)=>{const outer=document.createElement('div');outer.setAttribute('role','row');const row=document.createElement('div');row.dataset.id=id;row.dataset.testid='conv-msg-'+id;const container=document.createElement('div');container.dataset.testid='msg-container';const authored=document.createElement('div');authored.setAttribute('data-pre-plain-text','[10:00, 10/8/2026] '+(direction==='incoming'?'${peer}':'Owned QA')+': ');const body=document.createElement('span');body.dataset.testid='selectable-text';body.textContent=text;authored.append(body);container.append(authored);if(tail){const icon=document.createElement('span');icon.dataset.icon=direction==='incoming'?'tail-in':'tail-out';container.append(icon);}const meta=document.createElement('div');meta.dataset.testid='msg-meta';if(direction==='outgoing'){const delivered=document.createElement('span');delivered.setAttribute('aria-label','Delivered');delivered.textContent='✓✓';meta.append(delivered);}container.append(meta);row.append(container);outer.append(row);return outer;};
${latestCase ? "for(let index=0;index<46;index++)transcript.append(qaRow('QA'+String(index).padStart(18,'0'),'Earlier owned QA note '+index,'outgoing'));" : ''}
@@ -71,7 +71,7 @@ document.querySelector('#qa-unrelated')?.addEventListener('click',()=>qaUnrelate
document.querySelectorAll('[data-qa-forbidden]').forEach(node=>node.addEventListener('click',()=>qaForbiddenClicks++));
window.qaSend=()=>{const text=composer.innerText.trim();if(!text)return;qaReplies.push(text);sessionStorage.setItem('owned-qa-replies',JSON.stringify(qaReplies));composer.replaceChildren();composer.dispatchEvent(new InputEvent('input',{bubbles:true,inputType:'deleteContentBackward'}));if(qaRemoveFloor)transcript.replaceChildren(qaRow('opaque_history_Q',text,'outgoing'));setTimeout(()=>{transcript.append(qaRow('opaque_new_B_'+qaReplies.length,text,'outgoing'));transcript.scrollTop=transcript.scrollHeight;setTimeout(()=>{transcript.append(qaRow('opaque_terminal_C','QA dialogue complete: the generated reply was recorded.','incoming'));transcript.scrollTop=transcript.scrollHeight;},140);},qaDeliveryDelay);};
composer.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){qaEditor.enter++;e.preventDefault();qaSend();}});document.querySelector('#qa-action-wrap').onclick=e=>{if(e.target.closest('button')?.getAttribute('aria-label')==='Send'){qaEditor.sendClicks++;qaSend();}};
-${scenario === 'postwrite_debt' ? `composer.addEventListener('beforeinput',e=>{if(e.inputType!=='insertText'||qaEditor.handled)return;e.preventDefault();qaEditor.handled++;composer.textContent=e.data;setTimeout(()=>{qaEditor.rerenders++;document.querySelector('#qa-action-wrap').innerHTML='<button aria-label="Send">Send</button>';},15);});` : ''}
+${scenario === 'postwrite_debt' ? `composer.addEventListener('beforeinput',e=>{qaNativeInputs.push({trusted:e.isTrusted,inputType:e.inputType,data:e.data});if(e.inputType!=='insertText'||qaEditor.handled)return;e.preventDefault();qaEditor.handled++;composer.textContent=e.data;setTimeout(()=>{qaEditor.rerenders++;document.querySelector('#qa-action-wrap').innerHTML='<button aria-label="Send">Send</button>';},15);});` : ''}
</script></body></html>`;
const intent = { request_kind: 'execute', scope_relation: 'new', requires_state_change: true, requires_submission: true,
messaging: { target_kind: 'named', recipients: [peer] }, deliverables: ['One generated reply answering both QA questions and independently verified delivery.'],
@@ -380,12 +380,22 @@ const server = http.createServer(async (request, response) => {
stage = 'bound'; name = 'chat_observe';
} else if (stage === 'sent') {
if (scenario === 'postwrite_debt' && !metrics.postwriteAttempt) {
- const native = await page.evaluate(() => ({ editor: qaEditor, replies: qaReplies.length, draft: composer.innerText }));
+ const native = await page.evaluate(() => ({ editor: qaEditor, replies: qaReplies.length, draft: composer.innerText, inputs: qaNativeInputs }));
assert.equal(native.editor.handled, 1); assert.equal(native.editor.rerenders, 1);
assert.equal(native.editor.enter, 0); assert.equal(native.editor.sendClicks, 0); assert.equal(native.replies, 0);
assert.equal(native.draft, reply, 'A readonly certificate must preserve the exact page-owned native draft.');
assert.equal(last.name, 'chat_send'); assert.equal(last.result?.dispatch?.verified, true, last.content);
- assert.equal(last.result?.dispatch?.pageHandledBeforeInput, true, last.content);
+ assert.deepEqual(native.inputs, [{ trusted: true, inputType: 'insertText', data: reply }],
+ 'The controlled editor must receive one real browser input, without synthetic transport provenance.');
+ assert.equal(last.result?.dispatch?.trusted, true, last.content);
+ assert.equal(last.result?.dispatch?.method, 'set_field_cdp_fallback', last.content);
+ assert.equal(last.result?.dispatch?.pageHandledBeforeInput, undefined, last.content);
+ assert.equal(last.result?.dispatch?.submitted, false, last.content);
+ assert.equal(last.result?.dispatch?.submissionDispatched, false, last.content);
+ assert.equal(last.result?.dispatch?.submissionBlockedBeforeDispatch, true, last.content);
+ assert.equal(last.result?.dispatch?.submissionOutcomeUnknown, false, last.content);
+ assert.equal(last.result?.dispatch?.outcomeUnknown, true, last.content);
+ assert.equal(last.result?.dispatch?.retryable, false, last.content);
assert.equal(last.result?.chatWorkflow?.pendingOutbound, true, last.content);
metrics.postwriteAttempt = { verifiedDraft: true, entered: false, clicked: false, pending: true };
stage = 'postwrite_read'; name = 'get_accessibility_tree'; args = { filter: 'visible' };
@@ -476,6 +486,8 @@ try {
metrics.sourceSha256 = Object.fromEntries(await Promise.all(['agent/agent.js', 'agent/completion-invariant.js', 'content/chat-observation.js', 'content/content.js'].map(async name =>
[name, createHash('sha256').update(await fs.readFile(path.join(extension, 'src', name))).digest('hex')])));
await fs.appendFile(path.join(extension, 'src/background.js'), '\nglobalThis.__ownedWhatsAppBoot = crypto.randomUUID();\n');
+ if (scenario === 'postwrite_debt') await fs.appendFile(path.join(extension, 'src/background.js'),
+ '\nimport { cdpClient as ownedClearCdp } from "./cdp/cdp-client.js"; globalThis.__ownedClearCdp = ownedClearCdp;\n');
if (scenario === 'postwrite_debt') await fs.appendFile(path.join(extension, 'src/ui/sidepanel.js'), `
// Owned installed test access to the shipped module's actual card renderer.
globalThis.__ownedWhatsAppRenderPending = async (tabId, prompt) => {
@@ -547,6 +559,26 @@ for (const [object, name, doneOnly] of [[agent, '_executeToolImpl', true], [agen
const url = new URL(typeof input === 'string' ? input : input.url);
return url.hostname === '127.0.0.1' || ['chrome-extension:', 'data:', 'blob:'].includes(url.protocol)
? native(input, options) : Promise.reject(new Error('Owned lab blocks external worker requests.')); }; });
+ if (scenario === 'postwrite_debt') await worker.evaluate(async () => {
+ globalThis.__ownedClearTransport = [];
+ const send = chrome.tabs.sendMessage.bind(chrome.tabs);
+ chrome.tabs.sendMessage = async (...args) => {
+ const result = await send(...args), action = args[1]?.action;
+ if (['ax_prepare_native_chat_clear', 'ax_verify_native_chat_clear', 'ax_release_native_chat_clear'].includes(action))
+ __ownedClearTransport.push({ action, success: result?.success, hasToken: !!result?.token });
+ return result;
+ };
+ const cdpClient = __ownedClearCdp;
+ const capture = cdpClient.captureTextClearReceipt.bind(cdpClient);
+ cdpClient.captureTextClearReceipt = async (...args) => {
+ const receipt = await capture(...args);
+ __ownedClearTransport.push({ action: 'captureTextClearReceipt', captured: !!receipt });
+ return receipt && { ...receipt, async verify() {
+ const verified = await receipt.verify();
+ __ownedClearTransport.push({ action: 'verifyTextClearReceipt', verified }); return verified;
+ } };
+ };
+ });
if (latestCase) await worker.evaluate(() => {
globalThis.__ownedLatestTransport = { records: [] };
let owner = '', monitorDocument = '', axDocument = '', runToken = '';
@@ -760,6 +792,7 @@ for (const [object, name, doneOnly] of [[agent, '_executeToolImpl', true], [agen
if (process.env.WEBBRAIN_QUALITY_WA_DIAGNOSTIC === '1') metrics.diagnostics = await worker.evaluate(tabId => ({
events: globalThis.__ownedWhatsAppDiagnostics || [], final: globalThis.__ownedWhatsAppSnapshot?.(tabId) || null,
}), tabId);
+ if (scenario === 'postwrite_debt') metrics.clearTransport = await worker.evaluate(() => __ownedClearTransport);
if (latestCase) {
metrics.latestTransport = await worker.evaluate(() => __ownedLatestTransport);
metrics.nativeLatestDocumentAfter = await page.evaluate(() => ({ url: location.href, timeOrigin: performance.timeOrigin,
@@ -799,6 +832,13 @@ for (const [object, name, doneOnly] of [[agent, '_executeToolImpl', true], [agen
assert.deepEqual(metrics.postwriteAttempt, { verifiedDraft: true, entered: false, clicked: false, pending: true,
freshSendBlocked: true, manualCardClicked: true, manuallyReconciled: true });
assert.deepEqual(native.editor, { handled: 1, rerenders: 1, enter: 1, sendClicks: 0 });
+ assert.deepEqual(metrics.clearTransport, [
+ { action: 'ax_prepare_native_chat_clear', success: true, hasToken: true },
+ { action: 'captureTextClearReceipt', captured: true },
+ { action: 'verifyTextClearReceipt', verified: true },
+ { action: 'ax_verify_native_chat_clear', success: true, hasToken: false },
+ { action: 'ax_release_native_chat_clear', success: true, hasToken: false },
+ ], 'One genuine native clear must pass both the CDP event receipt and the same-conversation private proof.');
assert.equal(durableChat.pendingOutbound, null);
}
if (scenario === 'bootstrap_native') {
diff --git a/test/trusted-field-preparation.mjs b/test/trusted-field-preparation.mjs
index 66f31f339..ec07f4fde 100644
--- a/test/trusted-field-preparation.mjs
+++ b/test/trusted-field-preparation.mjs
@@ -72,6 +72,9 @@ async function scenario({ before = unchanged, after = unchanged, failure = 'rese
if (message.action === 'ax_verify_field_value') {
return { success: true, verified: failure !== 'verification', fieldMeta: unchanged.fieldMeta };
}
+ if (message.action === 'ax_prepare_native_chat_clear') {
+ return { success: false, error: 'This generic editor has no native conversation context.' };
+ }
throw new Error(`Unexpected message ${message.action}`);
};
cdpClient.attach = async () => ({});