Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Scope social publication guards and defer intent compilation
Emre Sokullu195b4ab48fc5
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex fa5b67bca..4e897c3d3 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -17938,9 +17938,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn progress.missing.map(id => social.contract.actions.find(a => a.id === id)?.platform || id);}- async _adoptLiveSocialPublishWorkflow(tabId, provider) {+ async _adoptLiveSocialPublishWorkflow(tabId, provider, detected = null) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled) return false;+ const knownWorkflow = SOCIAL_PLATFORMS.includes(guard.siteWorkflow?.adapterName)+ && guard.siteWorkflow?.job?.id === 'publish-post';+ // A domain match alone says nothing about the task: settings, messages,+ // and ordinary forms also live on social sites. Compile only for a bound+ // publication workflow or an observed composer submission. Once compiled,+ // the contract can carry a multi-platform task across navigation.+ if (!knownWorkflow && !guard.socialPublication && detected?.publicationControl !== true) return false;+ if (guard.siteWorkflow?.job && !knownWorkflow) return false;const liveUrl = await this._currentUrl(tabId);const live = resolveAdapterWorkflowJob(liveUrl, 'publish-post');if (!SOCIAL_PLATFORMS.includes(live?.adapterName)) return false;@@ -17951,7 +17959,6 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst action = social.contract.actions.find(a => a.platform === live.adapterName && eligible.includes(a.id));if (!action) return false;if (social.actionId === action.id && this._sameAdapterWorkflowBinding(guard.siteWorkflow, live)) return false;- if (guard.siteWorkflow?.job && !SOCIAL_PLATFORMS.includes(guard.siteWorkflow.adapterName)) return false;guard.siteWorkflow = live;guard.siteWorkflowUrl = liveUrl;guard.requiresSubmission = true;@@ -18015,6 +18022,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst live = resolveAdapterWorkflowJob(pageUrl, 'publish-post');if (!SOCIAL_PLATFORMS.includes(live?.adapterName)) return null;if (detected?.resolvedEditableTarget || detected?.resolvedNavigationTarget || detected?.resolvedNonSubmitTarget) return null;+ // An observed ordinary form still goes through the generic submission+ // guards. Absent evidence is not a negative: opaque callbacks, failed+ // probes, and unresolved controls cannot claim this exemption.+ if (detected?.isSubmit === true && detected.publicationControl === false+ && ['click', 'click_ax', 'iframe_click', 'set_field', 'press_keys'].includes(name)) return null;const blocked = error => ({ success: false, dispatched: false, noDispatch: true, repeatBlocked: true,workflowJob: 'publish-post', error,publicationContract: guard.socialPublication?.contract || null,@@ -18022,7 +18034,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});if (detected?.isSubmit !== true) return blocked('Publication-capable action could not be identified. Use a resolved page control; do not run arbitrary JavaScript or bundle editing and submission.');if (!['click', 'click_ax', 'iframe_click'].includes(name)) return blocked('Write and verify the draft first, then activate its publish control in a separate click.');- await this._adoptLiveSocialPublishWorkflow(tabId, provider);+ if (detected.publicationControl !== true) return blocked('Publication composer ownership could not be observed. Read the current page and use its resolved publish control.');+ await this._adoptLiveSocialPublishWorkflow(tabId, provider, detected);const social = await this._ensureSocialPublicationContract(tabId, provider);const action = this._socialPublicationAction(guard);if (!action || action.platform !== live.adapterName@@ -18059,7 +18072,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// The semantic check can take time. Re-read the same target afterward;// neither a changed draft/account nor a navigated document inherits it.const fresh = await this._detectLikelySubmitAction(tabId, name, args);- if (fresh?.isSubmit !== true || fresh.publicationResourceUrlsComplete !== true+ if (fresh?.isSubmit !== true || fresh.publicationControl !== true || fresh.publicationResourceUrlsComplete !== true|| JSON.stringify(this._socialPublicationSnapshot(guard, fresh.publicationSnapshot)) !== JSON.stringify(snapshot)|| this._normalizeUrl(await this._currentUrl(tabId)) !== this._normalizeUrl(pageUrl)) {social.dispatch = null;@@ -22216,6 +22229,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dgithubCommitDialogLauncher: detected.githubCommitDialogLauncher === true,...(Array.isArray(detected.publicationResourceUrls) ? { publicationResourceUrls: detected.publicationResourceUrls.slice(0, 200) } : {}),publicationResourceUrlsComplete: detected.publicationResourceUrlsComplete === true,+ ...(typeof detected.publicationControl === 'boolean' ? { publicationControl: detected.publicationControl } : {}),publicationSnapshot: detected.publicationSnapshot || null,publicationAccountIdentity: String(detected.publicationAccountIdentity || '').slice(0, 300),publicationAccountIdentityComplete: detected.publicationAccountIdentityComplete === true,@@ -22740,8 +22754,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst pageOrders = transactionOrderSite? transactionOrderScan(doc.body || doc.documentElement): { ids: [], complete: false };- const publicationAccount = publicationAccountEvidence(submitControl);- const publicationBaseline = publicationResourceUrls();+ const publicationControl = socialPublicationControlFor(form, submitControl);+ const publicationAccount = publicationControl === true+ ? publicationAccountEvidence(submitControl) : { identity: '', complete: false };+ const publicationBaseline = publicationControl === true+ ? publicationResourceUrls() : { urls: [], complete: false };const formSummary = summarizeForm(form, pendingEl, pendingValue);const control = labelControlFor(submitControl) || submitControl;const controlLabel = compact(@@ -22785,7 +22802,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dvalidationSubmitEvidence,publicationResourceUrls: publicationBaseline.urls,publicationResourceUrlsComplete: publicationBaseline.complete,- publicationSnapshot: publicationComposerSnapshot(form, publicationAccount),+ ...(typeof publicationControl === 'boolean' ? { publicationControl } : {}),+ publicationSnapshot: publicationControl === true ? publicationComposerSnapshot(form, publicationAccount) : null,publicationAccountIdentity: publicationAccount.identity,publicationAccountIdentityComplete: publicationAccount.complete,transactionOrderIds: formOrders.ids,@@ -22881,6 +22899,28 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d? { isSubmit: true, strong: publishTestId }: { isSubmit: false, strong: false };};+ const socialPublicationControlFor = (root, el) => {+ if (!socialPublishAdapterName() || !el) return undefined;+ const target = labelControlFor(el) || el;+ const control = target.closest?.('button,input,[role="button"],[onclick],[data-action]') || target;+ if (socialPublishControlEvidence(control).isSubmit) return true;+ // The app's composer markers also cover localized/unnamed submit+ // controls and implicit Enter/set_field submissions. Inspect only the+ // target's own form/root; a separate composer elsewhere on the page+ // cannot turn a settings form into a publication.+ const markers = socialPublishAdapterName() === 'twitter'+ ? '[data-testid="tweetButton"],[data-testid="tweetButtonInline"],[data-testid^="tweetTextarea_"]'+ : '[data-testid="composerPublishBtn"],[data-testid="composerPublishButton"],[data-testid="composerTextInput"]';+ if (control.matches?.(markers) || root?.matches?.(markers) || root?.querySelector?.(markers)) return true;+ // Implicit submission acts on the form, not its focused editor. Include+ // unnamed publish buttons and externally associated HTML controls too.+ const controls = new Set([...(root?.elements || []),+ ...(root?.querySelectorAll?.('button,input,[role="button"]') || [])]);+ if ([...controls].some(candidate => socialPublishControlEvidence(candidate).isSubmit)) return true;+ // Only a resolved HTML form establishes the ordinary-form exemption.+ // Missing roots and arbitrary callbacks retain unknown classification.+ return String(root?.tagName || '').toUpperCase() === 'FORM' ? false : undefined;+ };const submitControlEvidence = (el) => {const target = labelControlFor(el) || el;if (!target || target.nodeType !== 1) return { isSubmit: false, strong: false };@@ -27238,8 +27278,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dasync _ensureProgressSessionForCurrentTask(tabId, opts = {}) {const publicationGuard = this._planExecutionGuards.get(tabId);- if (publicationGuard?.enabled && publicationGuard.requiresSubmission === true) {- await this._ensureSocialPublicationContract(tabId, opts.provider);+ if (publicationGuard?.enabled && publicationGuard.requiresSubmission === true+ && SOCIAL_PLATFORMS.includes(publicationGuard.siteWorkflow?.adapterName)+ && publicationGuard.siteWorkflow?.job?.id === 'publish-post') {await this._adoptLiveSocialPublishWorkflow(tabId, opts.provider);}const expectedItems = this._normalizeExpectedItems(opts.expectedItems);diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex f8dfe2823..619bc08df 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -15737,9 +15737,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn progress.missing.map(id => social.contract.actions.find(a => a.id === id)?.platform || id);}- async _adoptLiveSocialPublishWorkflow(tabId, provider) {+ async _adoptLiveSocialPublishWorkflow(tabId, provider, detected = null) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled) return false;+ const knownWorkflow = SOCIAL_PLATFORMS.includes(guard.siteWorkflow?.adapterName)+ && guard.siteWorkflow?.job?.id === 'publish-post';+ // A domain match alone says nothing about the task: settings, messages,+ // and ordinary forms also live on social sites. Compile only for a bound+ // publication workflow or an observed composer submission. Once compiled,+ // the contract can carry a multi-platform task across navigation.+ if (!knownWorkflow && !guard.socialPublication && detected?.publicationControl !== true) return false;+ if (guard.siteWorkflow?.job && !knownWorkflow) return false;const liveUrl = await this._currentUrl(tabId);const live = resolveAdapterWorkflowJob(liveUrl, 'publish-post');if (!SOCIAL_PLATFORMS.includes(live?.adapterName)) return false;@@ -15750,7 +15758,6 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst action = social.contract.actions.find(a => a.platform === live.adapterName && eligible.includes(a.id));if (!action) return false;if (social.actionId === action.id && this._sameAdapterWorkflowBinding(guard.siteWorkflow, live)) return false;- if (guard.siteWorkflow?.job && !SOCIAL_PLATFORMS.includes(guard.siteWorkflow.adapterName)) return false;guard.siteWorkflow = live;guard.siteWorkflowUrl = liveUrl;guard.requiresSubmission = true;@@ -15814,6 +15821,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst live = resolveAdapterWorkflowJob(pageUrl, 'publish-post');if (!SOCIAL_PLATFORMS.includes(live?.adapterName)) return null;if (detected?.resolvedEditableTarget || detected?.resolvedNavigationTarget || detected?.resolvedNonSubmitTarget) return null;+ // An observed ordinary form still goes through the generic submission+ // guards. Absent evidence is not a negative: opaque callbacks, failed+ // probes, and unresolved controls cannot claim this exemption.+ if (detected?.isSubmit === true && detected.publicationControl === false+ && ['click', 'click_ax', 'iframe_click', 'set_field', 'press_keys'].includes(name)) return null;const blocked = error => ({ success: false, dispatched: false, noDispatch: true, repeatBlocked: true,workflowJob: 'publish-post', error,publicationContract: guard.socialPublication?.contract || null,@@ -15821,7 +15833,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});if (detected?.isSubmit !== true) return blocked('Publication-capable action could not be identified. Use a resolved page control; do not run arbitrary JavaScript or bundle editing and submission.');if (!['click', 'click_ax', 'iframe_click'].includes(name)) return blocked('Write and verify the draft first, then activate its publish control in a separate click.');- await this._adoptLiveSocialPublishWorkflow(tabId, provider);+ if (detected.publicationControl !== true) return blocked('Publication composer ownership could not be observed. Read the current page and use its resolved publish control.');+ await this._adoptLiveSocialPublishWorkflow(tabId, provider, detected);const social = await this._ensureSocialPublicationContract(tabId, provider);const action = this._socialPublicationAction(guard);if (!action || action.platform !== live.adapterName@@ -15858,7 +15871,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// The semantic check can take time. Re-read the same target afterward;// neither a changed draft/account nor a navigated document inherits it.const fresh = await this._detectLikelySubmitAction(tabId, name, args);- if (fresh?.isSubmit !== true || fresh.publicationResourceUrlsComplete !== true+ if (fresh?.isSubmit !== true || fresh.publicationControl !== true || fresh.publicationResourceUrlsComplete !== true|| JSON.stringify(this._socialPublicationSnapshot(guard, fresh.publicationSnapshot)) !== JSON.stringify(snapshot)|| this._normalizeUrl(await this._currentUrl(tabId)) !== this._normalizeUrl(pageUrl)) {social.dispatch = null;@@ -19963,6 +19976,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dgithubCommitDialogLauncher: detected.githubCommitDialogLauncher === true,...(Array.isArray(detected.publicationResourceUrls) ? { publicationResourceUrls: detected.publicationResourceUrls.slice(0, 200) } : {}),publicationResourceUrlsComplete: detected.publicationResourceUrlsComplete === true,+ ...(typeof detected.publicationControl === 'boolean' ? { publicationControl: detected.publicationControl } : {}),publicationSnapshot: detected.publicationSnapshot || null,publicationAccountIdentity: String(detected.publicationAccountIdentity || '').slice(0, 300),publicationAccountIdentityComplete: detected.publicationAccountIdentityComplete === true,@@ -20399,8 +20413,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst pageOrders = transactionOrderSite? transactionOrderScan(doc.body || doc.documentElement): { ids: [], complete: false };- const publicationAccount = publicationAccountEvidence(submitControl);- const publicationBaseline = publicationResourceUrls();+ const publicationControl = socialPublicationControlFor(form, submitControl);+ const publicationAccount = publicationControl === true+ ? publicationAccountEvidence(submitControl) : { identity: '', complete: false };+ const publicationBaseline = publicationControl === true+ ? publicationResourceUrls() : { urls: [], complete: false };const formSummary = summarizeForm(form, pendingEl, pendingValue);const control = labelControlFor(submitControl) || submitControl;const controlLabel = compact(@@ -20444,7 +20461,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dvalidationSubmitEvidence,publicationResourceUrls: publicationBaseline.urls,publicationResourceUrlsComplete: publicationBaseline.complete,- publicationSnapshot: publicationComposerSnapshot(form, publicationAccount),+ ...(typeof publicationControl === 'boolean' ? { publicationControl } : {}),+ publicationSnapshot: publicationControl === true ? publicationComposerSnapshot(form, publicationAccount) : null,publicationAccountIdentity: publicationAccount.identity,publicationAccountIdentityComplete: publicationAccount.complete,transactionOrderIds: formOrders.ids,@@ -20540,6 +20558,28 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d? { isSubmit: true, strong: publishTestId }: { isSubmit: false, strong: false };};+ const socialPublicationControlFor = (root, el) => {+ if (!socialPublishAdapterName() || !el) return undefined;+ const target = labelControlFor(el) || el;+ const control = target.closest?.('button,input,[role="button"],[onclick],[data-action]') || target;+ if (socialPublishControlEvidence(control).isSubmit) return true;+ // The app's composer markers also cover localized/unnamed submit+ // controls and implicit Enter/set_field submissions. Inspect only the+ // target's own form/root; a separate composer elsewhere on the page+ // cannot turn a settings form into a publication.+ const markers = socialPublishAdapterName() === 'twitter'+ ? '[data-testid="tweetButton"],[data-testid="tweetButtonInline"],[data-testid^="tweetTextarea_"]'+ : '[data-testid="composerPublishBtn"],[data-testid="composerPublishButton"],[data-testid="composerTextInput"]';+ if (control.matches?.(markers) || root?.matches?.(markers) || root?.querySelector?.(markers)) return true;+ // Implicit submission acts on the form, not its focused editor. Include+ // unnamed publish buttons and externally associated HTML controls too.+ const controls = new Set([...(root?.elements || []),+ ...(root?.querySelectorAll?.('button,input,[role="button"]') || [])]);+ if ([...controls].some(candidate => socialPublishControlEvidence(candidate).isSubmit)) return true;+ // Only a resolved HTML form establishes the ordinary-form exemption.+ // Missing roots and arbitrary callbacks retain unknown classification.+ return String(root?.tagName || '').toUpperCase() === 'FORM' ? false : undefined;+ };const submitControlEvidence = (el) => {const target = labelControlFor(el) || el;if (!target || target.nodeType !== 1) return { isSubmit: false, strong: false };@@ -24845,8 +24885,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dasync _ensureProgressSessionForCurrentTask(tabId, opts = {}) {const publicationGuard = this._planExecutionGuards.get(tabId);- if (publicationGuard?.enabled && publicationGuard.requiresSubmission === true) {- await this._ensureSocialPublicationContract(tabId, opts.provider);+ if (publicationGuard?.enabled && publicationGuard.requiresSubmission === true+ && SOCIAL_PLATFORMS.includes(publicationGuard.siteWorkflow?.adapterName)+ && publicationGuard.siteWorkflow?.job?.id === 'publish-post') {await this._adoptLiveSocialPublishWorkflow(tabId, opts.provider);}const expectedItems = this._normalizeExpectedItems(opts.expectedItems);diff --git a/test/social-publish-contract-dom.mjs b/test/social-publish-contract-dom.mjsindex a6f44e40d..d180afe4d 100644--- a/test/social-publish-contract-dom.mjs+++ b/test/social-publish-contract-dom.mjs@@ -25,6 +25,59 @@ try {},{source:Agent._submitActionProbe.toString(),selector});for(const platform of ['twitter','bluesky']){await page.goto(platform==='twitter'?'https://x.com/home':'https://bsky.app/');+ // Run the real probe wrapper and dispatch gate against ordinary forms+ // on social domains, including an unrelated composer on the same page.+ const publishId=platform==='twitter'?'tweetButtonInline':'composerPublishBtn';+ const providerScope={chat:async()=>({content:'{}'})};+ const scopeAgent=new Agent({getActive:()=>providerScope}),scopeTab=909;+ scopeAgent.useSiteAdapters=true;scopeAgent._persist=()=>{};scopeAgent._currentUrl=async()=>page.url();+ scopeAgent.conversations.set(scopeTab,[{role:'system',content:'system'},{role:'user',content:'Save my profile settings. Do not publish anything.'}]);+ const scopeGuard=scopeAgent._startPlanExecutionGuard(scopeTab,'act',{requestKind:'execute',requiresStateChange:true,requiresSubmission:true});+ let scopeCalls=0;+ scopeAgent._chatWithCostAllowance=async()=>{scopeCalls++;return {content:JSON.stringify({version:1,status:'none',actions:[],requirements:null,prohibited:[],reason:'Settings only.'})};};+ const previousChrome=globalThis.chrome;+ globalThis.chrome={scripting:{executeScript:async({func,args})=>[{result:await page.evaluate(({source,args})=>Function('return ('+source+')')()(...args),{source:func.toString(),args})}]}};+ try {+ await scopeAgent._ensureProgressSessionForCurrentTask(scopeTab,{provider:providerScope,taskText:'Save profile settings',progressLedgerPolicy:'disabled'});+ assert.equal(await scopeAgent._adoptLiveSocialPublishWorkflow(scopeTab,providerScope),false);+ for(const external of [false,true]){+ const save=`<button id="save" ${external?'form="settings"':''}><span>Kaydet</span></button>`;+ await page.setContent(`<main><form id="settings"><input id="name" value="Alice"><textarea id="bio">My profile</textarea>${external?'':save}</form>${external?save:''}<div id="other-composer"><div contenteditable="true" role="textbox">Unrelated draft</div><button data-testid="${publishId}">Post</button></div></main>`);+ for(const [name,args] of [['click',{selector:'#save span'}],['press_keys',{key:'Enter'}]]){+ await page.locator('#name').focus();+ const ordinary=await scopeAgent._detectLikelySubmitAction(scopeTab,name,args);+ assert.equal(ordinary.isSubmit,true);+ assert.equal(ordinary.publicationControl,false,'own form is distinct from the nearby composer');+ assert.equal(ordinary.publicationSnapshot,null);+ assert.equal(await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,name,args,ordinary,providerScope),null);+ assert.equal(scopeCalls,0);checked++;+ }+ }+ // A localized composer, an unnamed Post button, and an incomplete+ // composer all stay guarded. Implicit Enter must not become a bypass.+ for(const kind of ['localized','unnamed','incomplete']){+ await page.setContent(`<form id="composer">${kind==='incomplete'?'':'<textarea id="body">Hello</textarea>'}<button id="publish" ${kind==='unnamed'?'':`data-testid="${publishId}"`}>${kind==='unnamed'?'Post':'Yayınla'}</button></form>`);+ const detected=await scopeAgent._detectLikelySubmitAction(scopeTab,'click',{selector:'#publish'});+ assert.equal(detected.publicationControl,true,kind);+ assert((await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,'click',{selector:'#publish'},detected,providerScope)).noDispatch);+ if(kind!=='incomplete'){+ await page.locator('#body').focus();+ const implicit=await scopeAgent._detectLikelySubmitAction(scopeTab,'press_keys',{key:'Enter'});+ assert.equal(implicit.publicationControl,true,kind+' implicit submission');+ assert((await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,'press_keys',{key:'Enter'},implicit,providerScope)).noDispatch);+ }+ checked++;+ }+ assert.equal(scopeCalls,1,'one cached none contract, no authorization call');+ assert.equal(scopeGuard.siteWorkflow,null);+ // Cached none intent still permits a subsequent ordinary settings save.+ await page.setContent('<form><textarea>Bio</textarea><button id="save">Save</button></form>');+ const ordinary=await scopeAgent._detectLikelySubmitAction(scopeTab,'click',{selector:'#save'});+ assert.equal(await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,'click',{selector:'#save'},ordinary,providerScope),null);+ assert.equal(scopeCalls,1);checked++;+ const opaque=await scopeAgent._detectLikelySubmitAction(scopeTab,'execute_js',{code:'publish()'});+ assert((await scopeAgent._workflowPreSubmitDispatchBlock(scopeTab,'execute_js',{code:'publish()'},opaque,providerScope)).noDispatch);checked++;+ } finally {if(previousChrome===undefined) delete globalThis.chrome;else globalThis.chrome=previousChrome;}const body='Beginning ① A 👨👩👧\n\n'+ 'long exact body '.repeat(650)+'END';await page.setContent(`<nav><a ${platform==='twitter'?'data-testid="AppTabBar_Profile_Link" href="/alice"':'href="/profile/alice.bsky.social"'}>Profile</a></nav><main><div id="composer"><div contenteditable="true" role="textbox" id="body" style="white-space:pre-wrap"></div><button id="publish" data-testid="${platform==='twitter'?'tweetButtonInline':'composerPublishBtn'}">Post</button></div></main>`);await page.locator('#body').fill(body);diff --git a/test/social-publish-contract.mjs b/test/social-publish-contract.mjsindex 5eeb75b93..ec2f5322c 100644--- a/test/social-publish-contract.mjs+++ b/test/social-publish-contract.mjs@@ -101,17 +101,71 @@ for (const browser of ['chrome', 'firefox']) {}return {content:JSON.stringify(raw)};};- const detected = {isSubmit:true,publicationResourceUrls:[],publicationResourceUrlsComplete:true,+ const detected = {isSubmit:true,publicationControl:true,publicationResourceUrls:[],publicationResourceUrlsComplete:true,publicationAccountIdentity:'twitter:alice',publicationAccountIdentityComplete:true,publicationSnapshot:snapshot()};agent._detectLikelySubmitAction = async () => structuredClone(detected);return {agent,tabId,guard,provider,calls,detected};}+ test(`${browser}: unrelated submissions and social-site visits do not compile publication intent`, async () => {+ for (const url of ['https://shop.example/checkout', 'https://mail.example/inbox', 'https://example.com/form',+ 'https://x.com/settings/profile', 'https://bsky.app/settings', 'https://x.com/home']) {+ const f = setup('Save the requested changes');+ f.agent._currentUrl = async () => url;+ f.agent._chatWithCostAllowance = async () => { throw new Error('Unexpected publication provider call'); };+ await f.agent._ensureProgressSessionForCurrentTask(f.tabId, {+ provider:f.provider, taskText:'Save the requested changes', progressLedgerPolicy:'disabled',+ });+ assert.equal(await f.agent._adoptLiveSocialPublishWorkflow(f.tabId,f.provider),false);+ assert.equal(f.guard.socialPublication,null);+ assert.equal(f.guard.siteWorkflow,null);+ }+ });++ test(`${browser}: bound publication plans compile at initialization and lazy composer discovery still works`, async () => {+ const f = setup();+ f.guard.siteWorkflow = f.agent._resolvePlannerSiteWorkflow('https://x.com/home', {request_kind:'execute',site_job:'publish-post'});+ assert(f.guard.siteWorkflow);+ await f.agent._ensureProgressSessionForCurrentTask(f.tabId, {+ provider:f.provider, taskText:'Post Hello on X', progressLedgerPolicy:'disabled',+ });+ assert.equal(f.calls.length,1);+ assert.equal(f.guard.socialPublication.contract.status,'ready');+ const lazy = setup();+ assert.equal(await lazy.agent._adoptLiveSocialPublishWorkflow(lazy.tabId,lazy.provider),false);+ assert.equal(lazy.calls.length,0);+ assert.equal(await lazy.agent._workflowPreSubmitDispatchBlock(lazy.tabId,'click',{},lazy.detected,lazy.provider),null);+ assert.deepEqual(lazy.calls.map(c=>c.meta.generationName),['social_publication_contract','social_publication_authorization']);+ });++ test(`${browser}: ordinary forms stay outside publication authorization with absent, none, or ready intent`, async () => {+ for (const intent of ['absent','none','ready']) {+ const f = setup('Save settings after posting Hello on X', intent === 'none'+ ? {version:1,status:'none',actions:[],requirements:null,prohibited:[],reason:'Settings task.'} : rawContract());+ if (intent !== 'absent') {+ await f.agent._ensureSocialPublicationContract(f.tabId,f.provider);+ assert.equal(f.guard.socialPublication.contract.status,intent);+ }+ const before = f.calls.length;+ const ordinary = {isSubmit:true,publicationControl:false};+ for (const [name,args] of [['click',{}],['click_ax',{}],['iframe_click',{}],['press_keys',{key:'Enter'}],['set_field',{submit:true}]]) {+ assert.equal(await f.agent._workflowPreSubmitDispatchBlock(f.tabId,name,args,ordinary,f.provider),null);+ }+ assert.equal(f.calls.length,before);+ assert.equal(f.guard.siteWorkflow,null);+ // A missing snapshot/flag never supplies the ordinary-form exemption.+ const unresolved = {isSubmit:true,publicationSnapshot:null};+ assert((await f.agent._workflowPreSubmitDispatchBlock(f.tabId,'click',{},unresolved,f.provider)).noDispatch);+ assert((await f.agent._workflowPreSubmitDispatchBlock(f.tabId,'execute_js',{code:'publish()'},ordinary,f.provider)).noDispatch);+ assert.equal(f.calls.length,before);+ }+ });+test(`${browser}: selected provider compiles once and checks the concrete draft before dispatch`, async () => {const {agent,tabId,guard,provider,calls,detected} = setup();- assert(await agent._adoptLiveSocialPublishWorkflow(tabId,provider));+ assert(await agent._adoptLiveSocialPublishWorkflow(tabId,provider,detected));assert.equal(guard.siteWorkflow.adapterName,'twitter');- assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId,provider),false);+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId,provider,detected),false);assert.equal(calls.length,1);assert.equal(await agent._workflowPreSubmitDispatchBlock(tabId,'click_ax',{ref_id:'post'},detected,provider),null);assert.equal(calls.length,2);@@ -130,7 +184,7 @@ for (const browser of ['chrome', 'firefox']) {for (const request of ['Explain how brands publish on X effectively','The team will post on X tomorrow','Do not publish anything; open composer to inspect','Read posts on X and summarize them']) {const {agent,tabId,guard,provider,detected} = setup(request,{version:1,status:'none',actions:[],requirements:null,prohibited:['twitter'],reason:'No publication authorized.'});- assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId,provider),false);+ assert.equal(await agent._adoptLiveSocialPublishWorkflow(tabId,provider,detected),false);assert.deepEqual([...agent._trustedSocialPublishTargetAdapters(guard)],[]);assert((await agent._workflowPreSubmitDispatchBlock(tabId,'click_ax',{},detected,provider)).noDispatch);}@@ -138,13 +192,13 @@ for (const browser of ['chrome', 'firefox']) {test(`${browser}: malformed/partial intent and failed semantic audits block without deterministic fallback`, async () => {const state = setup('Post Hello with an image on X',{workflowFields:[{field:'body',value:'Hello'}]});- await state.agent._adoptLiveSocialPublishWorkflow(state.tabId,state.provider);+ await state.agent._adoptLiveSocialPublishWorkflow(state.tabId,state.provider,state.detected);assert.equal(state.calls.length,2);assert.equal(state.guard.socialPublication.contract,null);assert((await state.agent._workflowPreSubmitDispatchBlock(state.tabId,'click_ax',{},state.detected,state.provider)).noDispatch);assert.equal(state.calls.length,2);const other = setup();- await other.agent._adoptLiveSocialPublishWorkflow(other.tabId,other.provider);+ await other.agent._adoptLiveSocialPublishWorkflow(other.tabId,other.provider,other.detected);other.agent._chatWithCostAllowance = async()=>({content:'{"authorized":true}'});assert((await other.agent._workflowPreSubmitDispatchBlock(other.tabId,'click_ax',{},other.detected,other.provider)).noDispatch);assert.equal(other.guard.socialPublication.dispatch,null);@@ -170,7 +224,7 @@ for (const browser of ['chrome', 'firefox']) {const fixture = setup(request,raw);const {agent,tabId,provider,detected} = fixture;detected.publicationSnapshot=composer;- await agent._adoptLiveSocialPublishWorkflow(tabId,provider);+ await agent._adoptLiveSocialPublishWorkflow(tabId,provider,detected);assert.equal(await agent._workflowPreSubmitDispatchBlock(tabId,'click_ax',{},detected,provider),null);agent._beginCompletionInvariant(tabId);agent._recordCompletionToolResult(tabId,'click_ax',{}, {success:true,dispatched:true});@@ -235,7 +289,7 @@ for (const browser of ['chrome', 'firefox']) {const f=await dispatchedFixture(rawContract(actions,{kind,items:['p1','p2']}),'Post Hello on X and Bluesky');f.guard.workflowTerminalEvidence=f.terminal();f.agent._currentUrl=async()=> 'https://bsky.app/';- assert.equal(await f.agent._adoptLiveSocialPublishWorkflow(f.tabId,f.provider),kind==='all');+ assert.equal(await f.agent._adoptLiveSocialPublishWorkflow(f.tabId,f.provider,f.detected),kind==='all');assert.equal(f.guard.socialPublication.outcomes.p1.status,'verified');assert.deepEqual(f.agent._missingSocialPublishTargets(f.guard),kind==='all'?['bluesky']:[]);assert.equal(f.calls.filter(c=>c.meta.generationName==='social_publication_contract').length,1);