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
Publication prefetch: abort a mismatched audit before dropping it
Barack Sokullu4439bf23a6ca
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex c031203c1..fdf0210ad 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -23746,10 +23746,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_invalidateSocialPublicationContract(guard) {// A contract compiled in the background before a correction is never- // installed after it, so its request is cancelled too.- this._socialPublicationContractPrefetches?.get(guard)?.abort?.controller.abort();- this._socialPublicationContractPrefetches?.delete(guard);+ // installed after it, so its request is cancelled too, and so is a+ // background audit against the contract the correction replaces.+ this._dropSocialPublicationContractPrefetch(guard);const social = guard.socialPublication;+ this._dropSocialPublicationAuditPrefetch(social);if (!social) return;social.needsRecompile = true;// Never erase an attempted publication's outcomes to obtain a fresh set@@ -23932,22 +23933,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Checked again: the sources may have changed while it ran.return this._ensureSocialPublicationContract(tabId, provider, { background, wait, binding });}- prefetches.delete(guard);- if (prefetch.compiled && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId)) {+ // An audit of the compiled state stays only when that state is+ // installed as the run's own.+ const install = !!prefetch.compiled && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId);+ this._dropSocialPublicationContractPrefetch(guard, prefetch, { keepAudit: install });+ if (install) {guard.socialPublication = prefetch.compiled;return prefetch.compiled;}} else if (prefetch && !background) {// A background compile of another input is never installed: cancel it.- prefetch.abort?.controller.abort();- prefetches.delete(guard);+ this._dropSocialPublicationContractPrefetch(guard, prefetch);}const state = { key, sources, context, contract: null, outcomes: {}, actionId: null, dispatch: null, error: '' };if (background) {if (!provider?.chat || JSON.stringify(sources).length > 120000) return null;- // A background compile of another input still running can never be- // installed: cancel its request before this one starts.- if (prefetch && !prefetch.settled) prefetch.abort?.controller.abort();+ // A background compile of another input can never be installed:+ // cancel its request (and an audit of what it compiled) first.+ if (prefetch) this._dropSocialPublicationContractPrefetch(guard, prefetch);const abort = this._socialPublicationBackgroundAbort(binding);const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);const entry = { previous, state, settled: false, compiled: null, done: null, abort };@@ -23957,7 +23960,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d.then(compiled => {entry.settled = true;entry.compiled = abort.signal.aborted ? null : (compiled || null);- if (!entry.compiled && prefetches.get(guard) === entry) prefetches.delete(guard);+ if (!entry.compiled) this._dropSocialPublicationContractPrefetch(guard, entry);return entry.compiled;});return entry.done;@@ -24486,7 +24489,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawaited = true;await running.done;}- if (running && audits.get(social) === running) audits.delete(social);+ // An audit of another draft (the user edited it or switched accounts+ // since the last write) can no longer be used: cancel its request before+ // this click runs its own audit.+ if (running) this._dropSocialPublicationAuditPrefetch(social, running);const stored = social.prefetchedAudit?.key === key ? social.prefetchedAudit : null;delete social.prefetchedAudit;if (!stored) return null;@@ -24630,10 +24636,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// neither spends tokens nor holds a serialized provider queue ahead of// this one.if (running?.key === key && running.runSignal === binding.signal && !running.abort.signal.aborted) return running.done;- running?.abort.controller.abort();+ if (running) this._dropSocialPublicationAuditPrefetch(social, running);const abort = this._socialPublicationBackgroundAbort(binding);const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);- const entry = { key, done: null, abort, runSignal: binding.signal };+ const entry = { key, done: null, abort, runSignal: binding.signal, settled: false };audits.set(social, entry);entry.done = this._socialPublicationBackgroundSettle(abort, (async () => {try {@@ -24654,10 +24660,35 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d} finally {if (audits.get(social) === entry) audits.delete(social);}- })(), 'changed');+ })(), 'changed').finally(() => { entry.settled = true; });return entry.done;}+ // Drops the background audit kept for `social` (only `entry`, when given).+ // A request still running is cancelled first, so it neither spends the+ // run's allowance nor holds a serialized provider queue ahead of the+ // click's own audit. A settled one only leaves the map.+ _dropSocialPublicationAuditPrefetch(social, entry = null) {+ const audits = this._socialPublicationAuditPrefetches;+ const kept = social ? audits?.get(social) : null;+ if (!kept || (entry && kept !== entry)) return;+ audits.delete(social);+ if (!kept.settled && !kept.abort.signal.aborted) kept.abort.controller.abort();+ }++ // Drops the background contract compile kept for `guard` (only `entry`,+ // when given), cancelling it while it runs. An audit of the state it+ // compiled is dropped with it, unless that state is being installed as the+ // run's own (`keepAudit`).+ _dropSocialPublicationContractPrefetch(guard, entry = null, { keepAudit = false } = {}) {+ const prefetches = this._socialPublicationContractPrefetches;+ const kept = guard ? prefetches?.get(guard) : null;+ if (!kept || (entry && kept !== entry)) return;+ prefetches.delete(guard);+ if (!kept.settled && !kept.abort?.signal.aborted) kept.abort?.controller.abort();+ if (!keepAudit && kept.compiled) this._dropSocialPublicationAuditPrefetch(kept.compiled);+ }+// A background publication check's own abort: the Stop of the run that// started it, or a newer check that supersedes it._socialPublicationBackgroundAbort(binding) {diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex d4e2fd48a..fb0acf4be 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -20929,10 +20929,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_invalidateSocialPublicationContract(guard) {// A contract compiled in the background before a correction is never- // installed after it, so its request is cancelled too.- this._socialPublicationContractPrefetches?.get(guard)?.abort?.controller.abort();- this._socialPublicationContractPrefetches?.delete(guard);+ // installed after it, so its request is cancelled too, and so is a+ // background audit against the contract the correction replaces.+ this._dropSocialPublicationContractPrefetch(guard);const social = guard.socialPublication;+ this._dropSocialPublicationAuditPrefetch(social);if (!social) return;social.needsRecompile = true;// Never erase an attempted publication's outcomes to obtain a fresh set@@ -21115,22 +21116,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Checked again: the sources may have changed while it ran.return this._ensureSocialPublicationContract(tabId, provider, { background, wait, binding });}- prefetches.delete(guard);- if (prefetch.compiled && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId)) {+ // An audit of the compiled state stays only when that state is+ // installed as the run's own.+ const install = !!prefetch.compiled && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId);+ this._dropSocialPublicationContractPrefetch(guard, prefetch, { keepAudit: install });+ if (install) {guard.socialPublication = prefetch.compiled;return prefetch.compiled;}} else if (prefetch && !background) {// A background compile of another input is never installed: cancel it.- prefetch.abort?.controller.abort();- prefetches.delete(guard);+ this._dropSocialPublicationContractPrefetch(guard, prefetch);}const state = { key, sources, context, contract: null, outcomes: {}, actionId: null, dispatch: null, error: '' };if (background) {if (!provider?.chat || JSON.stringify(sources).length > 120000) return null;- // A background compile of another input still running can never be- // installed: cancel its request before this one starts.- if (prefetch && !prefetch.settled) prefetch.abort?.controller.abort();+ // A background compile of another input can never be installed:+ // cancel its request (and an audit of what it compiled) first.+ if (prefetch) this._dropSocialPublicationContractPrefetch(guard, prefetch);const abort = this._socialPublicationBackgroundAbort(binding);const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);const entry = { previous, state, settled: false, compiled: null, done: null, abort };@@ -21140,7 +21143,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d.then(compiled => {entry.settled = true;entry.compiled = abort.signal.aborted ? null : (compiled || null);- if (!entry.compiled && prefetches.get(guard) === entry) prefetches.delete(guard);+ if (!entry.compiled) this._dropSocialPublicationContractPrefetch(guard, entry);return entry.compiled;});return entry.done;@@ -21669,7 +21672,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawaited = true;await running.done;}- if (running && audits.get(social) === running) audits.delete(social);+ // An audit of another draft (the user edited it or switched accounts+ // since the last write) can no longer be used: cancel its request before+ // this click runs its own audit.+ if (running) this._dropSocialPublicationAuditPrefetch(social, running);const stored = social.prefetchedAudit?.key === key ? social.prefetchedAudit : null;delete social.prefetchedAudit;if (!stored) return null;@@ -21813,10 +21819,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// neither spends tokens nor holds a serialized provider queue ahead of// this one.if (running?.key === key && running.runSignal === binding.signal && !running.abort.signal.aborted) return running.done;- running?.abort.controller.abort();+ if (running) this._dropSocialPublicationAuditPrefetch(social, running);const abort = this._socialPublicationBackgroundAbort(binding);const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);- const entry = { key, done: null, abort, runSignal: binding.signal };+ const entry = { key, done: null, abort, runSignal: binding.signal, settled: false };audits.set(social, entry);entry.done = this._socialPublicationBackgroundSettle(abort, (async () => {try {@@ -21837,10 +21843,35 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d} finally {if (audits.get(social) === entry) audits.delete(social);}- })(), 'changed');+ })(), 'changed').finally(() => { entry.settled = true; });return entry.done;}+ // Drops the background audit kept for `social` (only `entry`, when given).+ // A request still running is cancelled first, so it neither spends the+ // run's allowance nor holds a serialized provider queue ahead of the+ // click's own audit. A settled one only leaves the map.+ _dropSocialPublicationAuditPrefetch(social, entry = null) {+ const audits = this._socialPublicationAuditPrefetches;+ const kept = social ? audits?.get(social) : null;+ if (!kept || (entry && kept !== entry)) return;+ audits.delete(social);+ if (!kept.settled && !kept.abort.signal.aborted) kept.abort.controller.abort();+ }++ // Drops the background contract compile kept for `guard` (only `entry`,+ // when given), cancelling it while it runs. An audit of the state it+ // compiled is dropped with it, unless that state is being installed as the+ // run's own (`keepAudit`).+ _dropSocialPublicationContractPrefetch(guard, entry = null, { keepAudit = false } = {}) {+ const prefetches = this._socialPublicationContractPrefetches;+ const kept = guard ? prefetches?.get(guard) : null;+ if (!kept || (entry && kept !== entry)) return;+ prefetches.delete(guard);+ if (!kept.settled && !kept.abort?.signal.aborted) kept.abort?.controller.abort();+ if (!keepAudit && kept.compiled) this._dropSocialPublicationAuditPrefetch(kept.compiled);+ }+// A background publication check's own abort: the Stop of the run that// started it, or a newer check that supersedes it._socialPublicationBackgroundAbort(binding) {diff --git a/test/publication-prefetch.mjs b/test/publication-prefetch.mjsindex d70c7b231..4cc577cb1 100644--- a/test/publication-prefetch.mjs+++ b/test/publication-prefetch.mjs@@ -421,6 +421,92 @@ for (const browser of ['chrome', 'firefox']) {assert.equal(again.named('social_publication_authorization').length, 1, 'one audit for the same draft');});+ test(`${browser}: a click on a draft changed without a new write cancels the old background audit before its own`, async () => {+ for (const change of ['draft', 'account']) {+ // A composed body lets the changed draft pass the click's preflight, so+ // only the binding key tells it apart from the draft being audited.+ let abortedWhenOwnAuditRan = null;+ const f = setup({ request: 'Tweet about my blog post',+ contract: rawContract([rawAction('p1', 'twitter', 'about my blog post', 'compose')]),+ authorize: input => {+ if (f.stale && input.key !== f.stale.key) abortedWhenOwnAuditRan = f.stale.aborted;+ return true;+ } });+ const audit = f.hold('social_publication_authorization');+ const prefetch = f.write();+ await until(() => audit.started, `${change}: the background audit started`);+ [f.stale] = f.named('social_publication_authorization');+ // The composer changes without another write (the user edited the draft+ // or switched accounts), so no newer prefetch supersedes the audit.+ if (change === 'draft') f.detected.publicationSnapshot.posts[0].bodyText = 'A different post about the blog';+ if (change === 'account') f.detected.publicationSnapshot.account = 'twitter:bob';+ let result;+ try {+ result = await within(f.click(), `${change}: the click runs its own audit`);+ } finally {+ audit.release();+ }+ assert.equal(result, null, change);+ assert.equal(abortedWhenOwnAuditRan, true, `${change}: the stale request was cancelled before the click audited`);+ assert.equal(f.stale.aborted, true, change);+ assert.equal(await within(prefetch, `${change}: the dropped prefetch settles`), 'changed', change);+ const audits = f.named('social_publication_authorization');+ assert.equal(audits.length, 2, `${change}: the cancelled audit and the click's own`);+ assert.notEqual(audits[1].key, f.stale.key, change);+ assert.equal(f.guard.socialPublication.dispatch.key, audits[1].key, `${change}: the click bound the draft it probed`);+ assert.equal(f.guard.socialPublication.prefetchedAudit, undefined, `${change}: no stale verdict was stored`);+ }+ // A correction replaces the contract the audit checks against: the audit+ // is cancelled with the background compile that produced that contract.+ const corrected = setup();+ const held = corrected.hold('social_publication_authorization');+ const prefetch = corrected.write();+ await until(() => held.started, 'the background audit started');+ const [stale] = corrected.named('social_publication_authorization');+ try {+ corrected.applySteering('Actually post Goodbye instead');+ assert.equal(stale.aborted, true, 'the correction cancelled the audit request');+ assert.equal(await within(prefetch, 'the corrected prefetch settles'), 'changed');+ } finally {+ held.release();+ }+ // So does a clarification, when the audit checks the run's own contract.+ const bound = setup();+ bound.guard.siteWorkflow = resolveAdapterWorkflowJob('https://x.com/compose/post', 'publish-post');+ bound.guard.siteWorkflowUrl = 'https://x.com/compose/post';+ const installed = await bound.agent._ensureSocialPublicationContract(bound.tabId, bound.provider);+ const boundHeld = bound.hold('social_publication_authorization');+ const boundPrefetch = bound.write();+ await until(() => boundHeld.started, 'the background audit of the run\'s contract started');+ const [boundStale] = bound.named('social_publication_authorization');+ try {+ bound.agent._recordSocialPublicationClarification(bound.tabId, bound.guard, 'Which account?', 'alice', 'user');+ assert.equal(installed.needsRecompile, true);+ assert.equal(boundStale.aborted, true, 'the clarification cancelled the audit of the replaced contract');+ assert.equal(await within(boundPrefetch, 'the prefetch settles'), 'changed');+ } finally {+ boundHeld.release();+ }+ // A click whose sources differ from a settled background compile drops it+ // and compiles its own: an audit still running against the dropped+ // contract is cancelled with it.+ const g = setup();+ const audit = g.hold('social_publication_authorization');+ const background = g.write();+ await until(() => audit.started, 'the background audit of the prefetched contract started');+ const [orphan] = g.named('social_publication_authorization');+ assert.ok(g.pending()?.compiled, 'the background compile settled');+ g.agent.conversations.get(g.tabId).push({ role: 'assistant', content: 'Draft: Hello' });+ try {+ assert.equal(await within(g.click(), 'the click compiles and audits its own'), null);+ assert.equal(orphan.aborted, true, 'the audit of the dropped contract was cancelled');+ assert.equal(await within(background, 'the dropped prefetch settles'), 'changed');+ } finally {+ audit.release();+ }+ assert.equal(g.guard.socialPublication.sources.draft0, 'Draft: Hello');+ });+test(`${browser}: a correction or a compile of other sources cancels a background compile in flight`, async () => {const f = setup();const contract = f.hold('social_publication_contract');