Skip to content

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

fix: verify Bluesky publication details safely

Emre Sokullu56cf49f9b9b7
diff --git a/docs/social-publication-contract.md b/docs/social-publication-contract.md
index 86de214aa..5b5ad41a9 100644
--- a/docs/social-publication-contract.md
+++ b/docs/social-publication-contract.md
@@ -19,6 +19,9 @@ A ready contract is not sufficient permission to dispatch. Before a separate pub
- Require complete composer/account/media/context observations and a pre-dispatch permalink baseline. Unassigned or shared thread media makes the observation incomplete.
- Failed preflight reports `publicationValidation.issues`, distinguishing missing account/composer/baseline evidence from body, media, or context mismatches. Body mismatches include lengths and the first differing character position/code points without copying the observed draft into diagnostics.
- Verify a new, account-bound permalink with complete authored body and media evidence. Reply, quote, and ordered thread relationships need their own observed proof.
+- Bluesky detail pages can bind their current permalink to one visible matching-author thread card without a self-link. Conflicting permalinks, duplicate candidates, hidden cards, feeds, and embedded posts cannot supply that binding. Read native word-wrapped rich text within the owning card, excluding previews and controls, and preserve exact paragraphs and link destinations.
+- Include the current resource URL in the pre-dispatch baseline even when a composer hides the existing post. Keep the focused detail record ahead of neighboring records when applying completion limits, so long threads retain its verification evidence.
+- Exclude native Bluesky quote containers (`div[role="link"]`) from the owning post's body and media. A quote without an observed target, or a focused thread item with preceding cards but no verified parent, retains incomplete context and cannot satisfy publication. An empty parent URL alone is not proof of a standalone post.
- Track each contract action as pending, failed, or verified. Uncertain delivery never unlocks an alternative or fallback, and cannot authorize another publish attempt.
- Preserve the contract, authentic clarification pairs, and outcomes only across the existing trusted Continue boundary. A new user task gets a new contract. Clarification after an attempted publication retains its outcomes and blocks further dispatch under the stale instructions; it cannot reset delivery uncertainty or authorize a duplicate.
- Preserve bound upload evidence when clarification recompiles an unchanged, unattempted action in the same workflow. Changed action constraints or workflow bindings reset it; every refreshed contract still requires a fresh authorization audit.
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 6c0d55cf2..3bf76d8a5 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, publicationReplyParent, publicationResourceRecordRoot, recordCompletionToolResult } from './completion-invariant.js';
+import { classifyCompletionForm, completionDoneBlock, completionPlainFinalBlock, completionPlainFinalPartial, consumeCompletionObservation, consumeCompletionObservationResult, createCompletionInvariantState, hasUnconsumedCompletionObservation, hasUnconsumedCompletionObservationResult, publicationDetailResource, 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';
@@ -18467,8 +18467,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const author = this._workflowSocialPublicationAccountIdentity(guard.siteWorkflow, record.url);
if (author !== account && !this._workflowSocialAccountAliasProven(guard.siteWorkflow, account, author, record)) return false;
const mediaRecord = this._workflowSocialRecordWithUploadedAttachmentNames(record, binding);
- return record.bodyTextComplete === true && record.attachmentsComplete === true && typeof record.bodyText === 'string'
- && (expected.bodyText === '' ? record.bodyText === '' : this._workflowSocialPublishedBodyObserved({ field: 'body', value: expected.bodyText, rawValue: expected.bodyText }, record))
+ return record.contextComplete !== false && record.bodyTextComplete === true && record.attachmentsComplete === true && typeof record.bodyText === 'string'
+ && (expected.bodyText === '' ? record.bodyText === '' : record.bodyText !== '' && this._workflowSocialPublishedBodyObserved({ field: 'body', value: expected.bodyText, rawValue: expected.bodyText }, record))
&& publicationMediaMatches(post.media, mediaRecord)
&& (i > 0 ? !(record.contextUrls?.length) : post.context.kind === 'post'
? !(record.contextUrls?.length) && !record.replyToUrl
@@ -22930,11 +22930,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
const publicationResourceUrls = () => {
try {
- const urls = Array.from(doc.querySelectorAll('a[href]'))
+ // The current detail route already existed before this dispatch,
+ // even if its post has no self-link or a composer hides its card.
+ // Baseline exclusion needs no claim that the old post was published
+ // by this job; omitting it would let it appear new at completion.
+ const candidates = [url, ...Array.from(doc.querySelectorAll('a[href]'))
.map((link) => {
try { return new URL(link.getAttribute('href') || link.href || '', url).href; } catch { return ''; }
- })
- .filter((value) => {
+ })];
+ const urls = [...new Set(candidates.filter((value) => {
try {
const parsed = new URL(value);
const resourceHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
@@ -22947,8 +22951,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
} catch {
return false;
}
- })
- ;
+ }))];
return { urls: urls.slice(0, 200), complete: urls.length <= 200 };
} catch {
return { urls: [], complete: false };
@@ -33914,6 +33917,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const classifyForm = ${classifyCompletionForm.toString()};
const publicationRecordRoot = ${publicationResourceRecordRoot.toString()};
+ const publicationDetail = ${publicationDetailResource.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);
@@ -33981,7 +33985,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
} catch {}
return '';
};
- const workflowResourceLinks = Array.from(document.querySelectorAll('a[href]'))
+ let workflowResourceLinks = Array.from(document.querySelectorAll('a[href]'))
.slice(0, 2000)
.map(link => {
let url = '';
@@ -33989,6 +33993,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return { link, url, identity: publicationResourceIdentity(url) };
})
.filter(item => !!item.identity);
+ const detailResource = publicationDetail(document, location.href, publicationResourceIdentity);
+ if (detailResource) {
+ workflowResourceLinks = workflowResourceLinks.filter(item => item.identity !== detailResource.identity);
+ // Reserve the focused post before the URL, record, and
+ // candidate limits so a long thread cannot crowd it out.
+ workflowResourceLinks.unshift(detailResource);
+ }
// Commit pages expose changed files as blob links. They prove
// the commit's file scope without becoming published-resource
// records of their own.
@@ -34050,7 +34061,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
].filter(candidate => !isEmbedded(candidate)).slice(0, 100).map(candidate => {
let href = '';
try { href = new URL(candidate.getAttribute('href') || candidate.href || '', location.href).href; } catch {}
- const compact = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 1000);
+ const compact = value => String(value || '').replace(/\\s+/g, ' ').trim().slice(0, 1000);
let inAuthoredBody = false;
try {
inAuthoredBody = authoredNodes.some(node => node === candidate || node.contains?.(candidate));
@@ -34139,6 +34150,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
alt: String(alt || '').slice(0, 25000),
};
});
+ 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, detailResource));
+ const replyToUrl = parents.get(identity);
+ const contextComplete = record?.contextComplete !== false
+ && (best !== detailResource?.link || (identity === detailResource.identity
+ && (!!replyToUrl || detailResource.replyContextComplete === true)));
const prior = workflowResourceRecordMap.get(identity);
if (!prior || text.length > prior.text.length || (!prior.attachments?.length && attachments.length)) {
workflowResourceRecordMap.set(identity, {
@@ -34148,13 +34167,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
bodyTextComplete: record?.authorshipComplete === true && rawBodyText.length <= 25000,
attachmentsComplete: record?.authorshipComplete === true && rawAttachments.length <= 20 && attachmentDataComplete,
links,
- replyToUrl: (() => {
- 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);
- })(),
+ replyToUrl,
+ contextComplete,
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)))),
attachments: attachments.length ? attachments : (prior?.attachments || []),
diff --git a/src/chrome/src/agent/completion-invariant.js b/src/chrome/src/agent/completion-invariant.js
index cd4d5e2a3..e59ec1e12 100644
--- a/src/chrome/src/agent/completion-invariant.js
+++ b/src/chrome/src/agent/completion-invariant.js
@@ -274,12 +274,12 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
const bodySelector = value.startsWith('twitter:')
? '[data-testid="tweetText"]'
: value.startsWith('bluesky:')
- ? '[data-testid="postText"]'
+ ? '[data-testid="postText"],div[data-word-wrap="1"]'
: '';
const embedSelector = value.startsWith('twitter:')
? '[data-testid="quoteTweet"],[role="blockquote"],[data-testid*="quote"],[data-testid*="card.layout"]'
: value.startsWith('bluesky:')
- ? '[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid*="quote"],[data-testid^="embed-"]'
+ ? '[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid*="quote"],[data-testid^="embed-"],div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"])'
: '';
const identityOf = (candidate) => {
try {
@@ -324,7 +324,16 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
const embeddedResourcesIn = (card) => {
const links = linksIn(card);
if (!links) return [];
- const excluded = [];
+ // Native Bluesky quotes are pressable divs, often without either an
+ // embed test ID or a permalink anchor. Exclude the whole subtree even
+ // when its target cannot be established from DOM links.
+ const nativeQuoteSelector = 'div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"])';
+ const excluded = value.startsWith('bluesky:')
+ ? Array.from(card.querySelectorAll(nativeQuoteSelector))
+ .filter(node => node.matches?.(nativeQuoteSelector) && node.closest(cardSelector) === card)
+ .filter((node, _i, nodes) => !nodes.some(other => other !== node && other.contains(node)))
+ .slice(0, 9)
+ : [];
for (const candidate of links) {
if (excluded.length >= 9) break;
const found = identityOf(candidate);
@@ -362,7 +371,15 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
if (!bodySelector) return [];
try {
return Array.from(card.querySelectorAll(bodySelector))
- .filter(node => !excluded.some(entry => entry === node || entry.contains?.(node)))
+ .filter(node => !excluded.some(entry => entry === node || entry.contains?.(node) || node.contains?.(entry)))
+ .filter(node => {
+ // Bluesky's native rich text has no postText test ID. Its word-wrap
+ // div must belong to this card, not a preview, byline, or control.
+ if (!node.matches?.('div[data-word-wrap="1"]')) return true;
+ return node.closest(cardSelector) === card
+ && !node.closest(embedSelector + ',a[href],button,[role="button"],[data-testid="replyingTo"],[data-testid="replyToPost"]');
+ })
+ .filter((node, _index, nodes) => !nodes.some(other => other !== node && other.contains?.(node)))
.slice(0, 9);
} catch {
return [];
@@ -462,6 +479,13 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
// Keep one overflow sentinel; a truncated observation is not proof
// of the complete authored body or its embedded relationships.
authorshipComplete: excluded.length <= 8 && authored.length <= 8,
+ // A quote whose own permalink is unavailable is unknown context,
+ // not evidence that this is a standalone post. Body links inside
+ // that quote cannot stand in for its own identity.
+ contextComplete: excluded.filter(node => value.startsWith('bluesky:') && node.matches?.('div[role="link"]'))
+ .every(node => new Set((linksIn(node) || [])
+ .filter(candidate => !candidate.closest?.(bodySelector))
+ .map(identityOf).filter(identity => identity && identity !== value)).size === 1),
authored,
attachments: authoredMediaNodesIn(card, excluded),
};
@@ -483,17 +507,81 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
return { root: best, excluded: [], authored: [], attachments: authoredMediaNodesIn(best, []) };
}
+// The focused Bluesky thread item renders its timestamp as text, without a
+// self-permalink anchor. Bind the route only to one visible, matching author
+// card in the app's thread screen. Feed items, embeds, and cards that already
+// identify a different post cannot borrow the current URL.
+// Keep self-contained: Agent serializes this function into the page.
+export function publicationDetailResource(doc, pageUrl, publicationResourceIdentity) {
+ try {
+ const page = new URL(pageUrl);
+ if (!/^https?:$/.test(page.protocol) || page.hostname !== 'bsky.app'
+ || page.username || page.password || page.port) return null;
+ const match = page.pathname.match(/^\/profile\/([^/]+)\/post\/[^/]+\/?$/);
+ if (!match) return null;
+ const url = page.origin + page.pathname.replace(/\/+$/, '');
+ const identity = publicationResourceIdentity(url);
+ if (!identity) return null;
+ const owner = decodeURIComponent(match[1]).toLowerCase();
+ const cards = '[data-testid^="feedItem-by-"],[data-testid^="postThreadItem-by-"]';
+ const excluded = '[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid*="quote"],[data-testid^="embed-"],div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"]),dialog,[role="dialog"],aside,[role="complementary"]';
+ const body = '[data-testid="postText"],div[data-word-wrap="1"]';
+ const visible = node => {
+ const rect = node.getBoundingClientRect();
+ if (rect.width < 1 || rect.height < 1) return false;
+ for (let el = node; el; el = el.parentElement) {
+ const style = el.ownerDocument.defaultView.getComputedStyle(el);
+ if (el.hidden || el.getAttribute('aria-hidden') === 'true'
+ || style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
+ }
+ return true;
+ };
+ const candidates = Array.from(doc.querySelectorAll('[data-testid="postThreadScreen"] [data-testid^="postThreadItem-by-"]'));
+ if (candidates.length > 200) return null;
+ const matches = candidates.filter(card => {
+ if (!visible(card) || card.closest(excluded) || card.parentElement?.closest(cards)
+ || card.getAttribute('data-testid').toLowerCase() !== 'postthreaditem-by-' + owner) return false;
+ const links = Array.from(card.querySelectorAll('a[href]'));
+ if (links.length > 200) return false;
+ const owned = links.filter(a => a.closest(cards) === card && !a.closest(body + ',' + excluded));
+ // A non-focused thread item supplies its own permalink. Even a single
+ // conflicting identity is enough to reject route-based attribution.
+ const identities = owned.map(a => publicationResourceIdentity(a.href)).filter(Boolean);
+ if (identities.some(value => value !== identity)) return false;
+ return owned.some(a => {
+ const profile = new URL(a.href, pageUrl);
+ return visible(a) && profile.origin === page.origin
+ && decodeURIComponent(profile.pathname).replace(/\/+$/, '').toLowerCase() === '/profile/' + owner;
+ });
+ });
+ if (matches.length !== 1) return null;
+ const link = matches[0];
+ const screen = link.closest('[data-testid="postThreadScreen"]');
+ const threadCards = Array.from(screen.querySelectorAll(cards))
+ .filter(node => !node.closest(excluded) && !node.parentElement?.closest(cards));
+ // Earlier native thread cards are ancestors even when separate wrappers
+ // prevent the legacy parent matcher from identifying the exact parent.
+ // Preserve that uncertainty; an empty replyToUrl must not erase it.
+ const replyContextComplete = threadCards.length <= 200 && threadCards[0] === link
+ && !link.hasAttribute('data-in-reply-to-url')
+ && !link.querySelector('[data-testid="replyingTo"],[data-testid="replyToPost"],a[rel="in-reply-to"]')
+ && !screen.querySelector('[aria-busy="true"],[role="progressbar"]');
+ return { link, url, identity, replyContextComplete };
+ } catch { return null; }
+}
+
// 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) {
+export function publicationReplyParent(card, pageUrl, publicationResourceIdentity, expectedIdentity, detailResource = null) {
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 bodySelector = twitter ? '[data-testid="tweetText"]' : '[data-testid="postText"],div[data-word-wrap="1"]';
+ const embeds = '[data-testid="quoteTweet"],[role="blockquote"],[data-testid*="quote"],[data-testid*="card.layout"],[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid^="embed-"]'
+ + (twitter ? '' : ',div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"])');
const hints = '[data-testid="replyingTo"],[data-testid="replyToPost"]';
if (!card?.matches?.(cardSelector) || card.parentElement?.closest(cardSelector + ',' + embeds)) return '';
const visible = node => {
@@ -534,6 +622,7 @@ export function publicationReplyParent(card, pageUrl, publicationResourceIdentit
};
const owned = (node, root) => node.closest(cardSelector) === root && !node.closest(bodySelector + ',' + embeds);
const ownPermalink = root => {
+ if (root === detailResource?.link) return detailResource.url;
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] : '';
@@ -549,7 +638,7 @@ export function publicationReplyParent(card, pageUrl, publicationResourceIdentit
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"]');
+ const scope = card.closest('[data-testid="primaryColumn"],[data-testid="postThreadScreen"],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)
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 8def44b8a..e8b71e062 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, publicationReplyParent, publicationResourceRecordRoot, recordCompletionToolResult } from './completion-invariant.js';
+import { classifyCompletionForm, completionDoneBlock, completionPlainFinalBlock, completionPlainFinalPartial, consumeCompletionObservation, consumeCompletionObservationResult, createCompletionInvariantState, hasUnconsumedCompletionObservation, hasUnconsumedCompletionObservationResult, publicationDetailResource, 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 {
@@ -16266,8 +16266,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const author = this._workflowSocialPublicationAccountIdentity(guard.siteWorkflow, record.url);
if (author !== account && !this._workflowSocialAccountAliasProven(guard.siteWorkflow, account, author, record)) return false;
const mediaRecord = this._workflowSocialRecordWithUploadedAttachmentNames(record, binding);
- return record.bodyTextComplete === true && record.attachmentsComplete === true && typeof record.bodyText === 'string'
- && (expected.bodyText === '' ? record.bodyText === '' : this._workflowSocialPublishedBodyObserved({ field: 'body', value: expected.bodyText, rawValue: expected.bodyText }, record))
+ return record.contextComplete !== false && record.bodyTextComplete === true && record.attachmentsComplete === true && typeof record.bodyText === 'string'
+ && (expected.bodyText === '' ? record.bodyText === '' : record.bodyText !== '' && this._workflowSocialPublishedBodyObserved({ field: 'body', value: expected.bodyText, rawValue: expected.bodyText }, record))
&& publicationMediaMatches(post.media, mediaRecord)
&& (i > 0 ? !(record.contextUrls?.length) : post.context.kind === 'post'
? !(record.contextUrls?.length) && !record.replyToUrl
@@ -20589,11 +20589,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
const publicationResourceUrls = () => {
try {
- const urls = Array.from(doc.querySelectorAll('a[href]'))
+ // The current detail route already existed before this dispatch,
+ // even if its post has no self-link or a composer hides its card.
+ // Baseline exclusion needs no claim that the old post was published
+ // by this job; omitting it would let it appear new at completion.
+ const candidates = [url, ...Array.from(doc.querySelectorAll('a[href]'))
.map((link) => {
try { return new URL(link.getAttribute('href') || link.href || '', url).href; } catch { return ''; }
- })
- .filter((value) => {
+ })];
+ const urls = [...new Set(candidates.filter((value) => {
try {
const parsed = new URL(value);
const resourceHost = parsed.hostname.toLowerCase().replace(/^www\./, '');
@@ -20606,8 +20610,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
} catch {
return false;
}
- })
- ;
+ }))];
return { urls: urls.slice(0, 200), complete: urls.length <= 200 };
} catch {
return { urls: [], complete: false };
@@ -30391,6 +30394,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const classifyForm = ${classifyCompletionForm.toString()};
const publicationRecordRoot = ${publicationResourceRecordRoot.toString()};
+ const publicationDetail = ${publicationDetailResource.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);
@@ -30458,7 +30462,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
} catch {}
return '';
};
- const workflowResourceLinks = Array.from(document.querySelectorAll('a[href]'))
+ let workflowResourceLinks = Array.from(document.querySelectorAll('a[href]'))
.slice(0, 2000)
.map(link => {
let url = '';
@@ -30466,6 +30470,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return { link, url, identity: publicationResourceIdentity(url) };
})
.filter(item => !!item.identity);
+ const detailResource = publicationDetail(document, location.href, publicationResourceIdentity);
+ if (detailResource) {
+ workflowResourceLinks = workflowResourceLinks.filter(item => item.identity !== detailResource.identity);
+ // Reserve the focused post before the URL, record, and
+ // candidate limits so a long thread cannot crowd it out.
+ workflowResourceLinks.unshift(detailResource);
+ }
// Commit pages expose changed files as blob links. They prove
// the commit's file scope without becoming published-resource
// records of their own.
@@ -30527,7 +30538,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
].filter(candidate => !isEmbedded(candidate)).slice(0, 100).map(candidate => {
let href = '';
try { href = new URL(candidate.getAttribute('href') || candidate.href || '', location.href).href; } catch {}
- const compact = value => String(value || '').replace(/\s+/g, ' ').trim().slice(0, 1000);
+ const compact = value => String(value || '').replace(/\\s+/g, ' ').trim().slice(0, 1000);
let inAuthoredBody = false;
try {
inAuthoredBody = authoredNodes.some(node => node === candidate || node.contains?.(candidate));
@@ -30616,6 +30627,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
alt: String(alt || '').slice(0, 25000),
};
});
+ 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, detailResource));
+ const replyToUrl = parents.get(identity);
+ const contextComplete = record?.contextComplete !== false
+ && (best !== detailResource?.link || (identity === detailResource.identity
+ && (!!replyToUrl || detailResource.replyContextComplete === true)));
const prior = workflowResourceRecordMap.get(identity);
if (!prior || text.length > prior.text.length || (!prior.attachments?.length && attachments.length)) {
workflowResourceRecordMap.set(identity, {
@@ -30625,13 +30644,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
bodyTextComplete: record?.authorshipComplete === true && rawBodyText.length <= 25000,
attachmentsComplete: record?.authorshipComplete === true && rawAttachments.length <= 20 && attachmentDataComplete,
links,
- replyToUrl: (() => {
- 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);
- })(),
+ replyToUrl,
+ contextComplete,
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)))),
attachments: attachments.length ? attachments : (prior?.attachments || []),
diff --git a/src/firefox/src/agent/completion-invariant.js b/src/firefox/src/agent/completion-invariant.js
index cd4d5e2a3..e59ec1e12 100644
--- a/src/firefox/src/agent/completion-invariant.js
+++ b/src/firefox/src/agent/completion-invariant.js
@@ -274,12 +274,12 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
const bodySelector = value.startsWith('twitter:')
? '[data-testid="tweetText"]'
: value.startsWith('bluesky:')
- ? '[data-testid="postText"]'
+ ? '[data-testid="postText"],div[data-word-wrap="1"]'
: '';
const embedSelector = value.startsWith('twitter:')
? '[data-testid="quoteTweet"],[role="blockquote"],[data-testid*="quote"],[data-testid*="card.layout"]'
: value.startsWith('bluesky:')
- ? '[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid*="quote"],[data-testid^="embed-"]'
+ ? '[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid*="quote"],[data-testid^="embed-"],div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"])'
: '';
const identityOf = (candidate) => {
try {
@@ -324,7 +324,16 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
const embeddedResourcesIn = (card) => {
const links = linksIn(card);
if (!links) return [];
- const excluded = [];
+ // Native Bluesky quotes are pressable divs, often without either an
+ // embed test ID or a permalink anchor. Exclude the whole subtree even
+ // when its target cannot be established from DOM links.
+ const nativeQuoteSelector = 'div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"])';
+ const excluded = value.startsWith('bluesky:')
+ ? Array.from(card.querySelectorAll(nativeQuoteSelector))
+ .filter(node => node.matches?.(nativeQuoteSelector) && node.closest(cardSelector) === card)
+ .filter((node, _i, nodes) => !nodes.some(other => other !== node && other.contains(node)))
+ .slice(0, 9)
+ : [];
for (const candidate of links) {
if (excluded.length >= 9) break;
const found = identityOf(candidate);
@@ -362,7 +371,15 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
if (!bodySelector) return [];
try {
return Array.from(card.querySelectorAll(bodySelector))
- .filter(node => !excluded.some(entry => entry === node || entry.contains?.(node)))
+ .filter(node => !excluded.some(entry => entry === node || entry.contains?.(node) || node.contains?.(entry)))
+ .filter(node => {
+ // Bluesky's native rich text has no postText test ID. Its word-wrap
+ // div must belong to this card, not a preview, byline, or control.
+ if (!node.matches?.('div[data-word-wrap="1"]')) return true;
+ return node.closest(cardSelector) === card
+ && !node.closest(embedSelector + ',a[href],button,[role="button"],[data-testid="replyingTo"],[data-testid="replyToPost"]');
+ })
+ .filter((node, _index, nodes) => !nodes.some(other => other !== node && other.contains?.(node)))
.slice(0, 9);
} catch {
return [];
@@ -462,6 +479,13 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
// Keep one overflow sentinel; a truncated observation is not proof
// of the complete authored body or its embedded relationships.
authorshipComplete: excluded.length <= 8 && authored.length <= 8,
+ // A quote whose own permalink is unavailable is unknown context,
+ // not evidence that this is a standalone post. Body links inside
+ // that quote cannot stand in for its own identity.
+ contextComplete: excluded.filter(node => value.startsWith('bluesky:') && node.matches?.('div[role="link"]'))
+ .every(node => new Set((linksIn(node) || [])
+ .filter(candidate => !candidate.closest?.(bodySelector))
+ .map(identityOf).filter(identity => identity && identity !== value)).size === 1),
authored,
attachments: authoredMediaNodesIn(card, excluded),
};
@@ -483,17 +507,81 @@ export function publicationResourceRecordRoot(link, identity, publicationResourc
return { root: best, excluded: [], authored: [], attachments: authoredMediaNodesIn(best, []) };
}
+// The focused Bluesky thread item renders its timestamp as text, without a
+// self-permalink anchor. Bind the route only to one visible, matching author
+// card in the app's thread screen. Feed items, embeds, and cards that already
+// identify a different post cannot borrow the current URL.
+// Keep self-contained: Agent serializes this function into the page.
+export function publicationDetailResource(doc, pageUrl, publicationResourceIdentity) {
+ try {
+ const page = new URL(pageUrl);
+ if (!/^https?:$/.test(page.protocol) || page.hostname !== 'bsky.app'
+ || page.username || page.password || page.port) return null;
+ const match = page.pathname.match(/^\/profile\/([^/]+)\/post\/[^/]+\/?$/);
+ if (!match) return null;
+ const url = page.origin + page.pathname.replace(/\/+$/, '');
+ const identity = publicationResourceIdentity(url);
+ if (!identity) return null;
+ const owner = decodeURIComponent(match[1]).toLowerCase();
+ const cards = '[data-testid^="feedItem-by-"],[data-testid^="postThreadItem-by-"]';
+ const excluded = '[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid*="quote"],[data-testid^="embed-"],div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"]),dialog,[role="dialog"],aside,[role="complementary"]';
+ const body = '[data-testid="postText"],div[data-word-wrap="1"]';
+ const visible = node => {
+ const rect = node.getBoundingClientRect();
+ if (rect.width < 1 || rect.height < 1) return false;
+ for (let el = node; el; el = el.parentElement) {
+ const style = el.ownerDocument.defaultView.getComputedStyle(el);
+ if (el.hidden || el.getAttribute('aria-hidden') === 'true'
+ || style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return false;
+ }
+ return true;
+ };
+ const candidates = Array.from(doc.querySelectorAll('[data-testid="postThreadScreen"] [data-testid^="postThreadItem-by-"]'));
+ if (candidates.length > 200) return null;
+ const matches = candidates.filter(card => {
+ if (!visible(card) || card.closest(excluded) || card.parentElement?.closest(cards)
+ || card.getAttribute('data-testid').toLowerCase() !== 'postthreaditem-by-' + owner) return false;
+ const links = Array.from(card.querySelectorAll('a[href]'));
+ if (links.length > 200) return false;
+ const owned = links.filter(a => a.closest(cards) === card && !a.closest(body + ',' + excluded));
+ // A non-focused thread item supplies its own permalink. Even a single
+ // conflicting identity is enough to reject route-based attribution.
+ const identities = owned.map(a => publicationResourceIdentity(a.href)).filter(Boolean);
+ if (identities.some(value => value !== identity)) return false;
+ return owned.some(a => {
+ const profile = new URL(a.href, pageUrl);
+ return visible(a) && profile.origin === page.origin
+ && decodeURIComponent(profile.pathname).replace(/\/+$/, '').toLowerCase() === '/profile/' + owner;
+ });
+ });
+ if (matches.length !== 1) return null;
+ const link = matches[0];
+ const screen = link.closest('[data-testid="postThreadScreen"]');
+ const threadCards = Array.from(screen.querySelectorAll(cards))
+ .filter(node => !node.closest(excluded) && !node.parentElement?.closest(cards));
+ // Earlier native thread cards are ancestors even when separate wrappers
+ // prevent the legacy parent matcher from identifying the exact parent.
+ // Preserve that uncertainty; an empty replyToUrl must not erase it.
+ const replyContextComplete = threadCards.length <= 200 && threadCards[0] === link
+ && !link.hasAttribute('data-in-reply-to-url')
+ && !link.querySelector('[data-testid="replyingTo"],[data-testid="replyToPost"],a[rel="in-reply-to"]')
+ && !screen.querySelector('[aria-busy="true"],[role="progressbar"]');
+ return { link, url, identity, replyContextComplete };
+ } catch { return null; }
+}
+
// 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) {
+export function publicationReplyParent(card, pageUrl, publicationResourceIdentity, expectedIdentity, detailResource = null) {
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 bodySelector = twitter ? '[data-testid="tweetText"]' : '[data-testid="postText"],div[data-word-wrap="1"]';
+ const embeds = '[data-testid="quoteTweet"],[role="blockquote"],[data-testid*="quote"],[data-testid*="card.layout"],[data-testid^="postQuote-"],[data-testid="embeddedPost"],[data-testid^="embed-"]'
+ + (twitter ? '' : ',div[role="link"]:not([data-testid^="feedItem-by-"]):not([data-testid^="postThreadItem-by-"])');
const hints = '[data-testid="replyingTo"],[data-testid="replyToPost"]';
if (!card?.matches?.(cardSelector) || card.parentElement?.closest(cardSelector + ',' + embeds)) return '';
const visible = node => {
@@ -534,6 +622,7 @@ export function publicationReplyParent(card, pageUrl, publicationResourceIdentit
};
const owned = (node, root) => node.closest(cardSelector) === root && !node.closest(bodySelector + ',' + embeds);
const ownPermalink = root => {
+ if (root === detailResource?.link) return detailResource.url;
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] : '';
@@ -549,7 +638,7 @@ export function publicationReplyParent(card, pageUrl, publicationResourceIdentit
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"]');
+ const scope = card.closest('[data-testid="primaryColumn"],[data-testid="postThreadScreen"],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)
diff --git a/test/run.js b/test/run.js
index e042e2b8c..51d559a35 100644
--- a/test/run.js
+++ b/test/run.js
@@ -94720,6 +94720,7 @@ test('the injected completion probe survives its own template literal', () => {
const injected = vm.runInNewContext('`' + raw + '`', {
classifyCompletionForm: invariant.classifyCompletionForm,
publicationResourceRecordRoot: invariant.publicationResourceRecordRoot,
+ publicationDetailResource: invariant.publicationDetailResource,
publicationReplyParent: invariant.publicationReplyParent,
});
assert.doesNotThrow(
diff --git a/test/social-publish-contract-dom.mjs b/test/social-publish-contract-dom.mjs
index 41d78295c..ed22a6430 100644
--- a/test/social-publish-contract-dom.mjs
+++ b/test/social-publish-contract-dom.mjs
@@ -371,6 +371,156 @@ try {
},bodyId);
published=(await readPublished()).workflowResourceRecords[0];
assert.equal(published.bodyTextComplete,false,'overflow cannot prove a complete body');checked++;
+ if (platform === 'bluesky') {
+ // Current Bluesky detail markup: the timestamp is plain text and the
+ // rich-text div has data-word-wrap, not a postText test ID. Exercise
+ // real extraction through dispatch-bound completion, including the
+ // exact paragraphs and shortened changelog link from the failing run.
+ const body = announcement.replace('35.0.0', '36.0.0');
+ const changelog = 'https://github.com/webbrain-one/webbrain/blob/main/CHANGELOG.md';
+ const bodyHtml = escape(body).replace(changelog, `<a href="${changelog}">github.com/webbrain-one...</a>`);
+ const detailCard = `<div data-testid="postThreadItem-by-alice.bsky.social" id="detail"><div><a href="/profile/alice.bsky.social"><div>Alice</div><div>@alice.bsky.social</div></a></div><div><div data-word-wrap="1" dir="auto" style="white-space:pre-wrap" id="detail-body">${bodyHtml}</div><div>4:36 PM · Sep 9, 2026</div><button>Reply</button></div></div>`;
+ const detailHtml = `<main><div data-testid="postThreadScreen">${detailCard}</div></main>`;
+ const composerHtml = `<nav><a href="/profile/alice.bsky.social">Profile</a></nav><div role="dialog"><div class="ProseMirror" contenteditable="true" style="white-space:pre-wrap">${paragraphs(body)}</div><button id="publish" data-testid="composerPublishBtn">Post</button></div>`;
+ const verifyDetail = async (html, url = permalink, options = {}) => {
+ const origin = options.origin || 'https://bsky.app/profile/alice.bsky.social/post/deleted';
+ const dispatchResult = options.dispatchResult || {success:true,dispatched:true};
+ await page.evaluate(url => history.replaceState({}, '', url), origin);
+ await page.setContent(`${options.background || ''}${composerHtml}`);
+ const provider = {chat:async()=>({content:'{}'})}, agent = new Agent({getActive:()=>provider}), tab = 912;
+ agent.useSiteAdapters=true;agent._persist=()=>{};agent._currentUrl=async()=>page.url();
+ agent.conversations.set(tab,[{role:'system',content:'system'},{role:'user',content:`Post exactly ${body} on Bluesky without attachments.`}]);
+ const guard = agent._startPlanExecutionGuard(tab,'act',{requestKind:'execute',requiresStateChange:true,requiresSubmission:true});
+ const raw = {version:1,status:'ready',actions:[{id:'p1',platform,account:null,posts:[{body:{kind:'exact',source:{source:'request',start:body,end:body}},media:{kind:'count',type:'any',format:null,min:0,max:0},context:{kind:'post',target:null}}]}],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 audit.'}:raw)};
+ };
+ agent._detectLikelySubmitAction=async()=>probe();
+ const detected=await probe();
+ assert.equal(await agent._workflowPreSubmitDispatchBlock(tab,'click',{selector:'#publish'},detected,provider),null);
+ agent._beginCompletionInvariant(tab);
+ agent._recordCompletionToolResult(tab,'click',{selector:'#publish'},dispatchResult);
+ agent._recordCompletionSubmitAttempt(tab,detected,'click',{selector:'#publish'},origin,origin,dispatchResult);
+ await page.evaluate(url => history.replaceState({}, '', url), url);
+ await page.setContent(html);
+ const state=await readPublished();
+ agent._recordCompletionToolResult(tab,'read_page',{}, {success:true,url:page.url(),content:'Observed published post.'});
+ const terminal=agent._workflowTerminalEvidenceFromDone(tab,state,page.url(),agent._completionSubmissionEvidence(tab,state,page.url()));
+ if (terminal) guard.workflowTerminalEvidence=terminal;
+ return {state,terminal,missing:agent._missingSocialPublishTargets(guard),baseline:detected.publicationResourceUrls,baselineComplete:detected.publicationResourceUrlsComplete};
+ };
+ let result = await verifyDetail(detailHtml);
+ const detail = result.state.workflowResourceRecords.find(r=>r.url===permalink);
+ assert(detail, 'current permalink binds to the focused post without a self-link');
+ assert.equal(detail.bodyText,body.replace(changelog,'github.com/webbrain-one...'));
+ assert.equal(detail.bodyTextComplete,true);
+ assert.equal(detail.contextComplete,true,'a standalone detail retains complete context');
+ assert.equal(detail.links.find(l=>l.authored)?.href,changelog,'authored URL survives probe serialization');
+ assert(result.terminal,`${build}: real Bluesky detail markup completes the publication`);
+ assert.deepEqual(result.missing,[],'the social completion guard accepts the verified publication');checked++;
+ const nativeBody = `<div data-word-wrap="1" dir="auto" style="white-space:pre-wrap" id="detail-body">${bodyHtml}</div>`;
+ const nativeQuote = `<div role="link" tabindex="0"><a href="/profile/bob.bsky.social">Bob</a><div data-word-wrap="1" style="white-space:pre-wrap">${bodyHtml}</div></div>`;
+ for (const [label,html,expectedBody] of [
+ ['native quote-only',detailHtml.replace(nativeBody,nativeQuote),''],
+ ['native body plus quote',detailHtml.replace(nativeBody,nativeBody+nativeQuote),body.replace(changelog,'github.com/webbrain-one...')],
+ ['native quote with media',detailHtml.replace(nativeBody,nativeQuote.replace('</div>','<img src="https://cdn.example/quoted.png" width="30" height="30"></div>')),''],
+ ]) {
+ result=await verifyDetail(html);
+ const record=result.state.workflowResourceRecords.find(r=>r.url===permalink);
+ assert.equal(record?.bodyText,expectedBody,`${build}: ${label} excludes quoted text`);
+ assert.deepEqual(record?.attachments,[],`${build}: ${label} excludes quoted media`);
+ assert.equal(record?.contextComplete,false,'an unresolved native quote remains incomplete context');
+ assert.equal(result.terminal,null,`${build}: ${label} cannot fulfill a standalone post`);
+ assert.deepEqual(result.missing,['bluesky']);checked++;
+ }
+ const nativeParent='<div data-testid="postThreadItem-by-bob.bsky.social"><a href="/profile/bob.bsky.social">Bob</a><a href="/profile/bob.bsky.social/post/parent">Earlier</a><div data-word-wrap="1">Parent text</div></div>';
+ for (const [label,leading] of [
+ ['wrapped parent',`<div><div>${nativeParent}</div></div>`],
+ ['unresolved parent gap',`<div>${nativeParent}</div><div>Continue thread</div>`],
+ ]) {
+ result=await verifyDetail(detailHtml.replace(detailCard,leading+`<div><div>${detailCard}</div></div>`));
+ const record=result.state.workflowResourceRecords.find(r=>r.url===permalink);
+ assert.equal(record?.bodyText,body.replace(changelog,'github.com/webbrain-one...'),'the matching authored body is still observed');
+ assert.equal(record?.replyToUrl,'','unresolved native parent is not guessed');
+ assert.equal(record?.contextComplete,false,'missing parent URL does not mean standalone');
+ assert.equal(result.terminal,null,`${build}: native ${label} cannot fulfill a standalone post`);
+ assert.deepEqual(result.missing,['bluesky']);checked++;
+ }
+ // Opening and closing a composer over an existing identical post
+ // does not publish anything. Its anchorless route must be in the
+ // pre-dispatch baseline even when the modal hides the underlying UI.
+ for (const [label,dispatchResult] of [
+ ['acknowledged click without publication',{success:true,dispatched:true}],
+ ['uncertain dispatch',{success:false,outcomeUnknown:true}],
+ ]) {
+ for (const background of [detailHtml,detailHtml.replace('<main>','<main aria-hidden="true" style="display:none">')]) {
+ result=await verifyDetail(detailHtml,permalink,{
+ origin:permalink+'?view=thread#post',background,dispatchResult,
+ });
+ assert.equal(result.terminal,null,`${build}: ${label} cannot reuse an existing detail post`);
+ assert.equal(result.baselineComplete,true);
+ assert(result.baseline.some(url=>url.startsWith(permalink)),`${build}: current detail URL is captured before dispatch`);
+ assert.deepEqual(result.missing,['bluesky'],label);checked++;
+ }
+ }
+ // The added route counts toward the baseline bound; overflow must
+ // remain incomplete, and the route cannot be truncated out itself.
+ for (const count of [199,200]) {
+ await page.evaluate(url=>history.replaceState({},'',url),permalink);
+ const links=Array.from({length:count},(_,i)=>`<a href="/profile/bob.bsky.social/post/baseline${i}">${i}</a>`).join('');
+ await page.setContent(links+composerHtml);
+ const baseline=await probe();
+ assert.equal(baseline.publicationResourceUrls[0],permalink);
+ assert.equal(baseline.publicationResourceUrls.length,200);
+ assert.equal(baseline.publicationResourceUrlsComplete,count===199);checked++;
+ }
+ // The focused card is first in the DOM, but its route-derived record
+ // used to be appended after every neighbor and lost at the 40 cap.
+ for (const count of [39,40,60]) {
+ const neighbors=Array.from({length:count},(_,i)=>`<div data-testid="postThreadItem-by-bob.bsky.social"><a href="/profile/bob.bsky.social/post/neighbor${i}">Earlier ${i}</a><div data-word-wrap="1">Unrelated body ${i}</div></div>`).join('');
+ result=await verifyDetail(detailHtml.replace(detailCard,detailCard+neighbors));
+ assert(result.state.workflowResourceRecords.some(record=>record.url===permalink),`${build}: focused evidence survives ${count} neighboring records`);
+ assert(result.state.workflowResourceRecords.length<=40,'the resource-record bound is preserved');
+ assert(result.terminal,`${build}: focused publication completes with ${count} neighbors`);
+ assert.deepEqual(result.missing,[]);checked++;
+ }
+ for (const [label, html, url] of [
+ ['wrong author',detailHtml.replaceAll('alice.bsky.social','bob.bsky.social')],
+ ['conflicting permalink',detailHtml.replace('<div>4:36 PM', '<a href="/profile/alice.bsky.social/post/other">Earlier post</a><div>4:36 PM')],
+ ['duplicate focused card',detailHtml.replace(detailCard,detailCard+detailCard)],
+ ['hidden focused card',detailHtml.replace('<main>','<main style="display:none">')],
+ ['feed card',detailHtml.replace('postThreadItem-by-','feedItem-by-')],
+ ['missing thread screen',detailHtml.replace('postThreadScreen','profileScreen')],
+ ['quoted focused card',detailHtml.replace(detailCard,`<div data-testid="embeddedPost">${detailCard}</div>`)],
+ ['feed route',detailHtml,'https://bsky.app/'],
+ ['wrong body',detailHtml.replace('36.0.0','37.0.0')],
+ ['wrong link',detailHtml.replace(changelog,'https://example.com/wrong')],
+ ['reply instead of post',detailHtml.replace('id="detail"','id="detail" data-in-reply-to-url="https://bsky.app/profile/bob.bsky.social/post/parent"')],
+ ['quote instead of post',detailHtml.replace('</button>','</button><div data-testid="embeddedPost"><a href="/profile/bob.bsky.social/post/quoted">Quoted post</a></div>')],
+ ['body only in preview',detailHtml.replace(bodyHtml,`<a href="https://example.com/card"><div data-word-wrap="1">${escape(body)}</div></a>`).replace('data-word-wrap="1" dir="auto"','dir="auto"')],
+ ['body only in quote',detailHtml.replace(bodyHtml,`<div data-testid="embeddedPost"><div data-word-wrap="1">${bodyHtml}</div></div>`).replace('data-word-wrap="1" dir="auto"','dir="auto"')],
+ ]) {
+ result=await verifyDetail(html,url);
+ assert.equal(result.terminal,null,`${build}: ${label} cannot complete the publication`);
+ assert.deepEqual(result.missing,['bluesky'],label);checked++;
+ }
+ const preview = '<a href="https://example.com/preview"><div data-word-wrap="1">Preview title</div></a>';
+ result=await verifyDetail(detailHtml.replace('</main>',preview+'</main>').replace('</button>','</button>'+preview));
+ assert(result.terminal,'external preview text cannot contaminate the authored body');checked++;
+ const neighbor='<div data-testid="postThreadItem-by-alice.bsky.social"><a href="/profile/alice.bsky.social">Alice</a><a href="/profile/alice.bsky.social/post/older">Earlier</a><div data-word-wrap="1">Earlier body</div></div>';
+ result=await verifyDetail(detailHtml.replace(detailCard,neighbor+detailCard),permalink+'?view=thread#post');
+ assert.equal(result.terminal,null,'a preceding native thread card cannot be treated as absent reply context');
+ assert(result.state.workflowResourceRecords.some(record=>record.url===permalink),'the focused resource remains attributed to its route');checked++;
+ // The same body marker occurs in feeds. A mentioned permalink in
+ // native rich text must stay in the authored body, not become a quote.
+ await page.setContent(detailHtml.replace('postThreadItem-by-','feedItem-by-').replace('<div>4:36 PM',`<a href="${permalink}">timestamp</a><div>4:36 PM`));
+ assert.equal((await readPublished()).workflowResourceRecords.find(r=>r.url===permalink)?.bodyText,body.replace(changelog,'github.com/webbrain-one...'));checked++;
+ await page.locator('#detail-body a').evaluate(el=>el.href='https://bsky.app/profile/bob.bsky.social/post/mentioned');
+ const mentioned=(await readPublished()).workflowResourceRecords.find(r=>r.url===permalink);
+ assert.equal(mentioned.bodyText,body.replace(changelog,'github.com/webbrain-one...'));
+ assert.deepEqual(mentioned.contextUrls,[]);checked++;
+ }
// Link thumbnails have no dedicated container on Bluesky. Check the
// same media in the real composer and published-resource probes, then
// drive no-attachment authorization and completion for the preview case.
diff --git a/test/social-publish-contract.mjs b/test/social-publish-contract.mjs
index 5579be0b5..6ba09ea8b 100644
--- a/test/social-publish-contract.mjs
+++ b/test/social-publish-contract.mjs
@@ -813,6 +813,15 @@ for (const browser of ['chrome', 'firefox']) {
}
});
+ test(`${browser}: incomplete context cannot satisfy publication even with matching body and account`,async()=>{
+ const f=await dispatchedFixture();
+ const record=f.page.workflowResourceRecords[0];
+ record.contextComplete=true;
+ assert(f.terminal());
+ record.contextComplete=false;
+ assert.equal(f.terminal(),null,'unknown reply or quote context is not a standalone post');
+ });
+
test(`${browser}: fallback checks the specified failure cause`,()=>{
for(const trigger of ['unavailable','publish_failed','not_published']){
const c=normalize(rawContract([rawAction('p1','twitter'),rawAction('p2','bluesky')],{kind:'fallback',trigger,items:['p1','p2']}));
@@ -857,4 +866,5 @@ test('Chrome and Firefox share the contract runtime and composer extraction', as
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');
+ assert.equal(chromeInvariant.publicationDetailResource.toString()===firefoxInvariant.publicationDetailResource.toString(),true,'published detail resource parity');
});