Skip to content

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

fix(social-publish): verify reply parents from observed threads

Emre Sokullue2f1dc4630d7
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index a4f72077c..fa5b67bca 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -31,7 +31,7 @@ import { detectProgressAction, formatLedgerRow, formatLedgerSummary, isBlockedLe
import { buildGithubStargazerProgressItems } from './observers/github-stargazers.js';
import { analyzeMastodonPage, mastodonHandoffInstruction, mastodonProgressGuard } from './observers/mastodon.js';
import { isProgressActionAllowed, isProgressIntentActive, normalizeProgressAction, normalizeProgressIntent } from './progress-intent.js';
-import { classifyCompletionForm, completionDoneBlock, completionPlainFinalBlock, completionPlainFinalPartial, consumeCompletionObservation, consumeCompletionObservationResult, createCompletionInvariantState, hasUnconsumedCompletionObservation, hasUnconsumedCompletionObservationResult, publicationResourceRecordRoot, recordCompletionToolResult } from './completion-invariant.js';
+import { classifyCompletionForm, completionDoneBlock, completionPlainFinalBlock, completionPlainFinalPartial, consumeCompletionObservation, consumeCompletionObservationResult, createCompletionInvariantState, hasUnconsumedCompletionObservation, hasUnconsumedCompletionObservationResult, publicationReplyParent, publicationResourceRecordRoot, recordCompletionToolResult } from './completion-invariant.js';
import { cdpClient } from '../cdp/cdp-client.js';
import { findLastGmailResultPage, getActiveAdapter, getAdapterWorkflowRouting, getCarouselNavigationPolicy, getCarouselNavigationTarget, getFullPageCapturePolicy, getGmailResultCountPolicy, getGmailResultPageUrl, getMessageRecipientGuardPolicy, parseCarouselSlideCount, parseGmailPaginationRange, resolveAdapterWorkflowJob, UNIVERSAL_PREAMBLE } from './adapters.js';
import { formatAdapterWorkflowExecutionPolicy } from './adapter-workflow.js';
@@ -22613,6 +22613,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const profileNav = identitiesIn(doc, 'a[data-testid="AppTabBar_Profile_Link"][href]');
if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
}
+ // Navigation identifies the signed-in account before a reply target's
+ // profile link inside the composer can be mistaken for its author.
+ if (adapterName === 'bluesky') {
+ const profileNav = identitiesIn(doc, 'nav a[href^="/profile/"], [role="navigation"] a[href^="/profile/"]');
+ if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
+ }
let node = submitTarget;
for (let depth = 0; node && depth < 10; depth++, node = node.parentElement) {
let hasEditor = false;
@@ -22624,10 +22630,6 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (identities.length === 1) return { identity: identities[0], complete: true };
if (identities.length > 1) break;
}
- if (adapterName === 'bluesky') {
- const profileNav = identitiesIn(doc, 'nav a[href^="/profile/"], [role="navigation"] a[href^="/profile/"]');
- if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
- }
return { identity: '', complete: false };
};
const publicationEditorText = editor => {
@@ -33345,6 +33347,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const classifyForm = ${classifyCompletionForm.toString()};
const publicationRecordRoot = ${publicationResourceRecordRoot.toString()};
+ const publicationParent = ${publicationReplyParent.toString()};
+ const publicationParentCache = new Map();
const dialogs = Array.from(document.querySelectorAll('[role=dialog],[role=alertdialog],[aria-modal="true"],dialog[open]')).filter(visible);
const forms = Array.from(document.querySelectorAll('form')).filter(visible);
const primaryContent = document.querySelector('main,[role=main]');
@@ -33578,9 +33582,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
attachmentsComplete: record?.authorshipComplete === true && rawAttachments.length <= 20 && attachmentDataComplete,
links,
replyToUrl: (() => {
- const parent = best.querySelector?.('[data-testid="replyToPost"] a[href],a[data-testid="replyToPost"],a[rel="in-reply-to"]');
- const explicit = best.getAttribute?.('data-in-reply-to-url') || parent?.href || '';
- return publicationResourceIdentity(explicit) ? explicit : '';
+ if (!publicationParentCache.has(best)) publicationParentCache.set(best, new Map());
+ const parents = publicationParentCache.get(best);
+ if (!parents.has(identity)) parents.set(identity,
+ publicationParent(best, location.href, publicationResourceIdentity, identity));
+ return parents.get(identity);
})(),
contextUrls: Array.from(new Set((record?.excluded || []).filter(node => !node.matches?.('[data-testid="replyToPost"]') && !node.closest?.('[data-testid="replyToPost"]')).flatMap(node => Array.from(node.querySelectorAll?.('a[href]') || []))
.map(a => a.href).filter(href => publicationResourceIdentity(href)))),
diff --git a/src/chrome/src/agent/completion-invariant.js b/src/chrome/src/agent/completion-invariant.js
index dc79d5b50..cd4d5e2a3 100644
--- a/src/chrome/src/agent/completion-invariant.js
+++ b/src/chrome/src/agent/completion-invariant.js
@@ -483,6 +483,100 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
return { root: best, excluded: [], authored: [], attachments: authoredMediaNodesIn(best, []) };
}
+// Infer a published reply's parent only from the page's own thread structure.
+// Keep self-contained: Agent serializes this function into the completion probe.
+export function publicationReplyParent(card, pageUrl, publicationResourceIdentity, expectedIdentity) {
+ try {
+ const page = new URL(pageUrl);
+ const host = page.hostname.toLowerCase().replace(/^www\./, '');
+ const twitter = host === 'x.com' || host === 'twitter.com';
+ if (!twitter && host !== 'bsky.app') return '';
+ const cardSelector = twitter ? '[data-testid="tweet"]' : '[data-testid^="feedItem-by-"],[data-testid^="postThreadItem-by-"]';
+ const bodySelector = twitter ? '[data-testid="tweetText"]' : '[data-testid="postText"]';
+ const embeds = '[data-testid="quoteTweet"],[role="blockquote"],[data-testid*="quote"],[data-testid*="card.layout"],[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid^="embed-"]';
+ const hints = '[data-testid="replyingTo"],[data-testid="replyToPost"]';
+ if (!card?.matches?.(cardSelector) || card.parentElement?.closest(cardSelector + ',' + embeds)) return '';
+ const visible = node => {
+ const rect = node.getBoundingClientRect();
+ const style = window.getComputedStyle(node);
+ return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) !== 0;
+ };
+ const parse = value => {
+ if (!value) return null;
+ const parsed = new URL(value, pageUrl);
+ const candidateHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password || parsed.port
+ || (twitter ? !['x.com', 'twitter.com'].includes(candidateHost) : candidateHost !== 'bsky.app')) return null;
+ return parsed;
+ };
+ const permalink = value => {
+ try {
+ const parsed = parse(value);
+ if (!parsed) return '';
+ const url = parsed.origin + parsed.pathname.replace(/\/+$/, '');
+ return publicationResourceIdentity(url) ? url : '';
+ } catch { return ''; }
+ };
+ const profile = value => {
+ try {
+ const parsed = parse(value);
+ if (!parsed) return '';
+ const match = parsed.pathname.replace(/\/+$/, '').match(twitter ? /^\/([A-Za-z0-9_]{1,15})$/ : /^\/profile\/([^/]+)$/);
+ return match ? match[1].toLowerCase() : '';
+ } catch { return ''; }
+ };
+ const owner = value => {
+ try {
+ const parsed = parse(value);
+ const match = parsed?.pathname.match(twitter ? /^\/([^/]+)\/status\/\d+\/?$/ : /^\/profile\/([^/]+)\/post\/[^/]+\/?$/);
+ return match ? match[1].toLowerCase() : '';
+ } catch { return ''; }
+ };
+ const owned = (node, root) => node.closest(cardSelector) === root && !node.closest(bodySelector + ',' + embeds);
+ const ownPermalink = root => {
+ const urls = new Map(Array.from(root.querySelectorAll('a[href]')).filter(a => visible(a) && owned(a, root) && !a.closest(hints))
+ .map(a => permalink(a.getAttribute('href'))).filter(Boolean).map(url => [publicationResourceIdentity(url), url]));
+ return urls.size === 1 ? [...urls.values()][0] : '';
+ };
+ const childUrl = ownPermalink(card), childId = publicationResourceIdentity(childUrl);
+ if (!childId || childId !== expectedIdentity) return '';
+ const explicit = new Map([
+ card.getAttribute('data-in-reply-to-url'),
+ ...Array.from(card.querySelectorAll('[data-testid="replyToPost"] a[href],a[data-testid="replyToPost"],a[rel="in-reply-to"]'))
+ .filter(a => visible(a) && owned(a, card)).map(a => a.getAttribute('href')),
+ ].map(permalink).filter(Boolean).map(url => [publicationResourceIdentity(url), url]));
+ if (explicit.size) return explicit.size === 1 && !explicit.has(childId) ? [...explicit.values()][0] : '';
+ if (card.hasAttribute('data-in-reply-to-url')) return '';
+
+ const threadUrl = permalink(pageUrl), threadId = publicationResourceIdentity(threadUrl);
+ const scope = card.closest('[data-testid="primaryColumn"],main,[role="main"]');
+ if (!threadId || !scope || card.closest('dialog,[role="dialog"],aside,[role="complementary"]')) return '';
+ const cards = Array.from(scope.querySelectorAll(cardSelector)).filter(node => visible(node)
+ && !node.parentElement?.closest(cardSelector + ',' + embeds)
+ && !node.closest('dialog,[role="dialog"],aside,[role="complementary"]'));
+ if (cards.length > 200) return '';
+ const items = cards.map(root => ({ root, url: ownPermalink(root) })).filter(item => item.url);
+ const current = items.findIndex(item => item.root === card);
+ if (current <= 0 || items.filter(item => publicationResourceIdentity(item.url) === threadId).length !== 1
+ || items.filter(item => publicationResourceIdentity(item.url) === childId).length !== 1) return '';
+ const parent = items[current - 1], parentId = publicationResourceIdentity(parent.url);
+ // The active permalink must be one endpoint of this adjacent thread pair.
+ // A grandparent route, a feed, or mere page co-occurrence is insufficient.
+ if (threadId !== childId && threadId !== parentId) return '';
+ if (items.filter(item => publicationResourceIdentity(item.url) === parentId).length !== 1) return '';
+ const parentCell = parent.root.closest('[data-testid="cellInnerDiv"]') || parent.root;
+ const childCell = card.closest('[data-testid="cellInnerDiv"]') || card;
+ if (parentCell.parentElement !== childCell.parentElement || parentCell.nextElementSibling !== childCell) return '';
+ const markedHints = Array.from(card.querySelectorAll(hints)).filter(visible);
+ const profileLinks = markedHints.length
+ ? markedHints.flatMap(node => Array.from(node.querySelectorAll('a[href]')))
+ : Array.from(card.querySelectorAll('a[href]')).filter(a => !a.closest('[data-testid="User-Name"],[data-testid*="Avatar"],[data-testid*="avatar"],button,[role="button"]')
+ && profile(a.getAttribute('href')) !== owner(childUrl));
+ const recipients = new Set(profileLinks.filter(a => visible(a) && owned(a, card)).map(a => profile(a.getAttribute('href'))).filter(Boolean));
+ return recipients.size === 1 && recipients.has(owner(parent.url)) ? parent.url : '';
+ } catch { return ''; }
+}
+
export function isCompletionActionTool(name, args = {}) {
if (name === 'execute_webmcp_tool') return true;
if (
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 6fbefa52f..f8dfe2823 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -31,7 +31,7 @@ import { detectProgressAction, formatLedgerRow, formatLedgerSummary, isBlockedLe
import { buildGithubStargazerProgressItems } from './observers/github-stargazers.js';
import { analyzeMastodonPage, mastodonHandoffInstruction, mastodonProgressGuard } from './observers/mastodon.js';
import { isProgressActionAllowed, isProgressIntentActive, normalizeProgressAction, normalizeProgressIntent } from './progress-intent.js';
-import { classifyCompletionForm, completionDoneBlock, completionPlainFinalBlock, completionPlainFinalPartial, consumeCompletionObservation, consumeCompletionObservationResult, createCompletionInvariantState, hasUnconsumedCompletionObservation, hasUnconsumedCompletionObservationResult, publicationResourceRecordRoot, recordCompletionToolResult } from './completion-invariant.js';
+import { classifyCompletionForm, completionDoneBlock, completionPlainFinalBlock, completionPlainFinalPartial, consumeCompletionObservation, consumeCompletionObservationResult, createCompletionInvariantState, hasUnconsumedCompletionObservation, hasUnconsumedCompletionObservationResult, publicationReplyParent, publicationResourceRecordRoot, recordCompletionToolResult } from './completion-invariant.js';
import { findLastGmailResultPage, getActiveAdapter, getAdapterWorkflowRouting, getCarouselNavigationPolicy, getCarouselNavigationTarget, getGmailResultCountPolicy, getGmailResultPageUrl, getMessageRecipientGuardPolicy, parseCarouselSlideCount, parseGmailPaginationRange, resolveAdapterWorkflowJob, UNIVERSAL_PREAMBLE } from './adapters.js';
import { formatAdapterWorkflowExecutionPolicy } from './adapter-workflow.js';
import {
@@ -20272,6 +20272,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const profileNav = identitiesIn(doc, 'a[data-testid="AppTabBar_Profile_Link"][href]');
if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
}
+ // Navigation identifies the signed-in account before a reply target's
+ // profile link inside the composer can be mistaken for its author.
+ if (adapterName === 'bluesky') {
+ const profileNav = identitiesIn(doc, 'nav a[href^="/profile/"], [role="navigation"] a[href^="/profile/"]');
+ if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
+ }
let node = submitTarget;
for (let depth = 0; node && depth < 10; depth++, node = node.parentElement) {
let hasEditor = false;
@@ -20283,10 +20289,6 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (identities.length === 1) return { identity: identities[0], complete: true };
if (identities.length > 1) break;
}
- if (adapterName === 'bluesky') {
- const profileNav = identitiesIn(doc, 'nav a[href^="/profile/"], [role="navigation"] a[href^="/profile/"]');
- if (profileNav.length === 1) return { identity: profileNav[0], complete: true };
- }
return { identity: '', complete: false };
};
const publicationEditorText = editor => {
@@ -29824,6 +29826,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const classifyForm = ${classifyCompletionForm.toString()};
const publicationRecordRoot = ${publicationResourceRecordRoot.toString()};
+ const publicationParent = ${publicationReplyParent.toString()};
+ const publicationParentCache = new Map();
const dialogs = Array.from(document.querySelectorAll('[role=dialog],[role=alertdialog],[aria-modal="true"],dialog[open]')).filter(visible);
const forms = Array.from(document.querySelectorAll('form')).filter(visible);
const primaryContent = document.querySelector('main,[role=main]');
@@ -30057,9 +30061,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
attachmentsComplete: record?.authorshipComplete === true && rawAttachments.length <= 20 && attachmentDataComplete,
links,
replyToUrl: (() => {
- const parent = best.querySelector?.('[data-testid="replyToPost"] a[href],a[data-testid="replyToPost"],a[rel="in-reply-to"]');
- const explicit = best.getAttribute?.('data-in-reply-to-url') || parent?.href || '';
- return publicationResourceIdentity(explicit) ? explicit : '';
+ if (!publicationParentCache.has(best)) publicationParentCache.set(best, new Map());
+ const parents = publicationParentCache.get(best);
+ if (!parents.has(identity)) parents.set(identity,
+ publicationParent(best, location.href, publicationResourceIdentity, identity));
+ return parents.get(identity);
})(),
contextUrls: Array.from(new Set((record?.excluded || []).filter(node => !node.matches?.('[data-testid="replyToPost"]') && !node.closest?.('[data-testid="replyToPost"]')).flatMap(node => Array.from(node.querySelectorAll?.('a[href]') || []))
.map(a => a.href).filter(href => publicationResourceIdentity(href)))),
diff --git a/src/firefox/src/agent/completion-invariant.js b/src/firefox/src/agent/completion-invariant.js
index dc79d5b50..cd4d5e2a3 100644
--- a/src/firefox/src/agent/completion-invariant.js
+++ b/src/firefox/src/agent/completion-invariant.js
@@ -483,6 +483,100 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
return { root: best, excluded: [], authored: [], attachments: authoredMediaNodesIn(best, []) };
}
+// Infer a published reply's parent only from the page's own thread structure.
+// Keep self-contained: Agent serializes this function into the completion probe.
+export function publicationReplyParent(card, pageUrl, publicationResourceIdentity, expectedIdentity) {
+ try {
+ const page = new URL(pageUrl);
+ const host = page.hostname.toLowerCase().replace(/^www\./, '');
+ const twitter = host === 'x.com' || host === 'twitter.com';
+ if (!twitter && host !== 'bsky.app') return '';
+ const cardSelector = twitter ? '[data-testid="tweet"]' : '[data-testid^="feedItem-by-"],[data-testid^="postThreadItem-by-"]';
+ const bodySelector = twitter ? '[data-testid="tweetText"]' : '[data-testid="postText"]';
+ const embeds = '[data-testid="quoteTweet"],[role="blockquote"],[data-testid*="quote"],[data-testid*="card.layout"],[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid^="embed-"]';
+ const hints = '[data-testid="replyingTo"],[data-testid="replyToPost"]';
+ if (!card?.matches?.(cardSelector) || card.parentElement?.closest(cardSelector + ',' + embeds)) return '';
+ const visible = node => {
+ const rect = node.getBoundingClientRect();
+ const style = window.getComputedStyle(node);
+ return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) !== 0;
+ };
+ const parse = value => {
+ if (!value) return null;
+ const parsed = new URL(value, pageUrl);
+ const candidateHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password || parsed.port
+ || (twitter ? !['x.com', 'twitter.com'].includes(candidateHost) : candidateHost !== 'bsky.app')) return null;
+ return parsed;
+ };
+ const permalink = value => {
+ try {
+ const parsed = parse(value);
+ if (!parsed) return '';
+ const url = parsed.origin + parsed.pathname.replace(/\/+$/, '');
+ return publicationResourceIdentity(url) ? url : '';
+ } catch { return ''; }
+ };
+ const profile = value => {
+ try {
+ const parsed = parse(value);
+ if (!parsed) return '';
+ const match = parsed.pathname.replace(/\/+$/, '').match(twitter ? /^\/([A-Za-z0-9_]{1,15})$/ : /^\/profile\/([^/]+)$/);
+ return match ? match[1].toLowerCase() : '';
+ } catch { return ''; }
+ };
+ const owner = value => {
+ try {
+ const parsed = parse(value);
+ const match = parsed?.pathname.match(twitter ? /^\/([^/]+)\/status\/\d+\/?$/ : /^\/profile\/([^/]+)\/post\/[^/]+\/?$/);
+ return match ? match[1].toLowerCase() : '';
+ } catch { return ''; }
+ };
+ const owned = (node, root) => node.closest(cardSelector) === root && !node.closest(bodySelector + ',' + embeds);
+ const ownPermalink = root => {
+ const urls = new Map(Array.from(root.querySelectorAll('a[href]')).filter(a => visible(a) && owned(a, root) && !a.closest(hints))
+ .map(a => permalink(a.getAttribute('href'))).filter(Boolean).map(url => [publicationResourceIdentity(url), url]));
+ return urls.size === 1 ? [...urls.values()][0] : '';
+ };
+ const childUrl = ownPermalink(card), childId = publicationResourceIdentity(childUrl);
+ if (!childId || childId !== expectedIdentity) return '';
+ const explicit = new Map([
+ card.getAttribute('data-in-reply-to-url'),
+ ...Array.from(card.querySelectorAll('[data-testid="replyToPost"] a[href],a[data-testid="replyToPost"],a[rel="in-reply-to"]'))
+ .filter(a => visible(a) && owned(a, card)).map(a => a.getAttribute('href')),
+ ].map(permalink).filter(Boolean).map(url => [publicationResourceIdentity(url), url]));
+ if (explicit.size) return explicit.size === 1 && !explicit.has(childId) ? [...explicit.values()][0] : '';
+ if (card.hasAttribute('data-in-reply-to-url')) return '';
+
+ const threadUrl = permalink(pageUrl), threadId = publicationResourceIdentity(threadUrl);
+ const scope = card.closest('[data-testid="primaryColumn"],main,[role="main"]');
+ if (!threadId || !scope || card.closest('dialog,[role="dialog"],aside,[role="complementary"]')) return '';
+ const cards = Array.from(scope.querySelectorAll(cardSelector)).filter(node => visible(node)
+ && !node.parentElement?.closest(cardSelector + ',' + embeds)
+ && !node.closest('dialog,[role="dialog"],aside,[role="complementary"]'));
+ if (cards.length > 200) return '';
+ const items = cards.map(root => ({ root, url: ownPermalink(root) })).filter(item => item.url);
+ const current = items.findIndex(item => item.root === card);
+ if (current <= 0 || items.filter(item => publicationResourceIdentity(item.url) === threadId).length !== 1
+ || items.filter(item => publicationResourceIdentity(item.url) === childId).length !== 1) return '';
+ const parent = items[current - 1], parentId = publicationResourceIdentity(parent.url);
+ // The active permalink must be one endpoint of this adjacent thread pair.
+ // A grandparent route, a feed, or mere page co-occurrence is insufficient.
+ if (threadId !== childId && threadId !== parentId) return '';
+ if (items.filter(item => publicationResourceIdentity(item.url) === parentId).length !== 1) return '';
+ const parentCell = parent.root.closest('[data-testid="cellInnerDiv"]') || parent.root;
+ const childCell = card.closest('[data-testid="cellInnerDiv"]') || card;
+ if (parentCell.parentElement !== childCell.parentElement || parentCell.nextElementSibling !== childCell) return '';
+ const markedHints = Array.from(card.querySelectorAll(hints)).filter(visible);
+ const profileLinks = markedHints.length
+ ? markedHints.flatMap(node => Array.from(node.querySelectorAll('a[href]')))
+ : Array.from(card.querySelectorAll('a[href]')).filter(a => !a.closest('[data-testid="User-Name"],[data-testid*="Avatar"],[data-testid*="avatar"],button,[role="button"]')
+ && profile(a.getAttribute('href')) !== owner(childUrl));
+ const recipients = new Set(profileLinks.filter(a => visible(a) && owned(a, card)).map(a => profile(a.getAttribute('href'))).filter(Boolean));
+ return recipients.size === 1 && recipients.has(owner(parent.url)) ? parent.url : '';
+ } catch { return ''; }
+}
+
export function isCompletionActionTool(name, args = {}) {
if (name === 'execute_webmcp_tool') return true;
if (
diff --git a/test/run.js b/test/run.js
index 6db784607..4ba2529e4 100644
--- a/test/run.js
+++ b/test/run.js
@@ -94328,6 +94328,7 @@ test('the injected completion probe survives its own template literal', () => {
const injected = vm.runInNewContext('`' + raw + '`', {
classifyCompletionForm: invariant.classifyCompletionForm,
publicationResourceRecordRoot: invariant.publicationResourceRecordRoot,
+ publicationReplyParent: invariant.publicationReplyParent,
});
assert.doesNotThrow(
() => new vm.Script(`(${injected})`),
diff --git a/test/social-publish-contract-dom.mjs b/test/social-publish-contract-dom.mjs
index 6d2148558..a6f44e40d 100644
--- a/test/social-publish-contract-dom.mjs
+++ b/test/social-publish-contract-dom.mjs
@@ -120,6 +120,79 @@ try {
},bodyId);
published=(await readPublished()).workflowResourceRecords[0];
assert.equal(published.bodyTextComplete,false,'overflow cannot prove a complete body');checked++;
+ // Drive composer observation, simulated dispatch, actual completion DOM
+ // extraction, and terminal verification. No replyToUrl is hand-written.
+ const profile=name=>platform==='twitter'?`https://x.com/${name}`:`https://bsky.app/profile/${name}.bsky.social`;
+ const item=(id,who,href,text,hint='')=>`<div data-testid="cellInnerDiv" id="${id}-cell"><article data-testid="${card}" id="${id}"><div data-testid="User-Name"><a href="${profile(who)}">${who}</a><a href="${href}"><time>Today</time></a></div>${hint}<div data-testid="${bodyId}">${text}</div></article></div>`;
+ const parentItem=item('parent-post','bob',parent,'Parent body');
+ const hint=`<div data-testid="replyingTo" id="reply-hint">Replying to <a href="${profile('bob')}">@bob</a></div>`;
+ const replyItem=item('reply-post','alice',permalink,'Hello',hint);
+ const threadHtml=items=>`<nav><a ${platform==='twitter'?'data-testid="AppTabBar_Profile_Link"':''} href="${platform==='twitter'?'/alice':'/profile/alice.bsky.social'}">Profile</a></nav><main><div data-testid="primaryColumn"><div id="thread">${items}</div></div></main>`;
+ await page.evaluate(parent=>history.replaceState({},'',parent),parent);
+ await page.setContent(threadHtml(parentItem+`<div id="composer"><div data-testid="replyingTo">Replying to <a href="${profile('bob')}">@bob</a></div><div contenteditable="true" role="textbox">Hello</div><button id="publish" data-testid="${platform==='twitter'?'tweetButtonInline':'composerPublishBtn'}">Reply</button></div>`));
+ const provider={chat:async()=>({content:'{}'})},agent=new Agent({getActive:()=>provider}),tabId=910;
+ const request=`Reply exactly Hello to ${parent} on ${platform==='twitter'?'X':'Bluesky'} without attachments.`;
+ agent.useSiteAdapters=true;agent._persist=()=>{};agent._currentUrl=async()=>page.url();
+ agent.conversations.set(tabId,[{role:'system',content:'system'},{role:'user',content:request}]);
+ agent._startPlanExecutionGuard(tabId,'act',{requestKind:'execute',requiresStateChange:true,requiresSubmission:true});
+ const reference=text=>({source:'request',start:text,end:text});
+ const raw={version:1,status:'ready',actions:[{id:'p1',platform,account:null,posts:[{body:{kind:'exact',source:reference('Hello')},media:{kind:'count',type:'any',format:null,min:0,max:0},context:{kind:'reply',target:reference(parent)}}]}],requirements:'p1',prohibited:[],reason:'Fixture request.'};
+ agent._chatWithCostAllowance=async(_p,messages,_o,_c,meta)=>{
+ const input=JSON.parse(messages[1].content);
+ return {content:JSON.stringify(meta.generationName==='social_publication_authorization'?{key:input.key,actionId:input.action.id,authorized:true,reason:'Fixture authorization.'}:raw)};
+ };
+ agent._detectLikelySubmitAction=async()=>probe();
+ const detected=await probe();
+ assert.equal(detected.publicationSnapshot.account,platform==='twitter'?'twitter:alice':'bluesky:alice.bsky.social','reply recipient cannot become the publishing account');
+ assert.equal(await agent._workflowPreSubmitDispatchBlock(tabId,'click',{selector:'#publish'},detected,provider),null);
+ agent._beginCompletionInvariant(tabId);
+ agent._recordCompletionToolResult(tabId,'click',{selector:'#publish'},{success:true,dispatched:true});
+ agent._recordCompletionSubmitAttempt(tabId,detected,'click',{selector:'#publish'},parent,parent,{success:true,dispatched:true});
+ await page.setContent(threadHtml(parentItem+replyItem));
+ const verify=async()=>{
+ const state=await readPublished();
+ agent._recordCompletionToolResult(tabId,'read_page',{}, {success:true,url:page.url(),content:'Observed thread.'});
+ return {state,record:state.workflowResourceRecords.find(r=>r.url===permalink),terminal:agent._workflowTerminalEvidenceFromDone(tabId,state,page.url(),agent._completionSubmissionEvidence(tabId,state,page.url()))};
+ };
+ let verified=await verify();
+ assert.equal(verified.record.replyToUrl,parent,'published reply profile hint resolves through surrounding thread');
+ assert(verified.terminal,`${build}/${platform}: actual extracted reply relationship completes the submitted contract`);checked++;
+ await page.evaluate(permalink=>history.replaceState({},'',permalink+'?s=20#reply'),permalink);
+ verified=await verify();assert.equal(verified.record.replyToUrl,parent);assert(verified.terminal);checked++;
+ // Native profile-only reply UI may have no reply-specific test ID.
+ await page.locator('#reply-hint').evaluate(el=>el.removeAttribute('data-testid'));
+ verified=await verify();assert.equal(verified.record.replyToUrl,parent);assert(verified.terminal);checked++;
+ for(const variation of ['feed','wrong-profile','missing-parent','reordered','gap','duplicate-parent','quoted-parent','body-mention']){
+ await page.evaluate(permalink=>history.replaceState({},'',permalink),permalink);
+ await page.setContent(threadHtml(parentItem+replyItem));
+ if(variation==='feed') await page.evaluate(()=>history.replaceState({},'','/home'));
+ if(variation==='wrong-profile') await page.locator('#reply-hint a').evaluate((el,href)=>el.href=href,profile('carol'));
+ if(variation==='missing-parent') await page.locator('#parent-post-cell').evaluate(el=>el.remove());
+ if(variation==='reordered') await page.locator('#thread').evaluate(el=>el.prepend(el.lastElementChild));
+ if(variation==='gap') await page.locator('#parent-post-cell').evaluate(el=>{const gap=document.createElement('div');gap.dataset.testid='cellInnerDiv';gap.textContent='Show more';el.after(gap);});
+ if(variation==='duplicate-parent') await page.locator('#parent-post-cell').evaluate(el=>el.before(el.cloneNode(true)));
+ if(variation==='quoted-parent') await page.locator('#reply-post').evaluate(el=>{const quote=document.createElement('div');quote.dataset.testid='quoteTweet';quote.append(document.querySelector('#parent-post-cell'));el.append(quote);});
+ if(variation==='body-mention') await page.locator('#reply-hint').evaluate((el,bodyId)=>{el.removeAttribute('data-testid');document.querySelector(`#reply-post [data-testid="${bodyId}"]`).append(el);},bodyId);
+ verified=await verify();assert.equal(verified.record.replyToUrl,'',variation);assert.equal(verified.terminal,null,variation);checked++;
+ }
+ // Explicit app-provided parent metadata also works outside a thread,
+ // but invalid metadata cannot be repaired by the background page URL.
+ await page.evaluate(()=>history.replaceState({},'','/home'));
+ await page.setContent(threadHtml(replyItem));
+ await page.locator('#reply-post').evaluate((el,parent)=>el.setAttribute('data-in-reply-to-url',parent),parent);
+ verified=await verify();assert.equal(verified.record.replyToUrl,parent);assert(verified.terminal);checked++;
+ await page.locator('#reply-post').evaluate(el=>el.setAttribute('data-in-reply-to-url','https://example.com/bob/status/1111111111111111111'));
+ verified=await verify();assert.equal(verified.record.replyToUrl,'');assert.equal(verified.terminal,null);checked++;
+ await page.evaluate(permalink=>history.replaceState({},'',permalink),permalink);
+ await page.setContent(threadHtml(parentItem+replyItem));
+ const mentioned=platform==='twitter'?'https://x.com/alice/status/5555555555555555555':'https://bsky.app/profile/alice.bsky.social/post/3mentioned';
+ await page.locator(`#reply-post [data-testid="${bodyId}"]`).evaluate((el,href)=>{const link=document.createElement('a');link.href=href;link.textContent=href;el.append(link);},mentioned);
+ verified=await verify();
+ assert.equal(verified.state.workflowResourceRecords.find(r=>r.url===mentioned)?.replyToUrl,'','an authored permalink does not inherit the surrounding card relationship');
+ assert.equal(verified.record.replyToUrl,parent);assert.equal(verified.terminal,null);checked++;
+
+
+
}
}
diff --git a/test/social-publish-contract.mjs b/test/social-publish-contract.mjs
index fda5798de..5eeb75b93 100644
--- a/test/social-publish-contract.mjs
+++ b/test/social-publish-contract.mjs
@@ -368,4 +368,5 @@ test('Chrome and Firefox share the contract runtime and composer extraction', as
const chromeInvariant=await import('../src/chrome/src/agent/completion-invariant.js');
const firefoxInvariant=await import('../src/firefox/src/agent/completion-invariant.js');
assert.equal(chromeInvariant.publicationResourceRecordRoot.toString()===firefoxInvariant.publicationResourceRecordRoot.toString(),true,'publication record parity');
+ assert.equal(chromeInvariant.publicationReplyParent.toString()===firefoxInvariant.publicationReplyParent.toString(),true,'published reply parent parity');
});