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: bind background checks to their run and cancel superseded audits
Barack Sokulluc1cb82b39100
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 27c6336c9..c031203c1 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -23746,7 +23746,8 @@ 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.+ // installed after it, so its request is cancelled too.+ this._socialPublicationContractPrefetches?.get(guard)?.abort?.controller.abort();this._socialPublicationContractPrefetches?.delete(guard);const social = guard.socialPublication;if (!social) return;@@ -23897,7 +23898,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// that would compile awaits it and installs it only when it compiled exactly// the input that caller would compile from now: the same sources, context,// task and prior state. Anything else compiles as before.- async _ensureSocialPublicationContract(tabId, provider = this._activeProvider(tabId), { background = false, wait = true } = {}) {+ async _ensureSocialPublicationContract(tabId, provider = this._activeProvider(tabId), { background = false, wait = true, binding = null } = {}) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled) return null;// The app-owned guard is new for every user revision. A trusted Continue@@ -23909,7 +23910,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!wait) return null;await running.catch(() => {});if (this._planExecutionGuards.get(tabId) !== guard) return null;- return this._ensureSocialPublicationContract(tabId, provider, { background, wait });+ return this._ensureSocialPublicationContract(tabId, provider, { background, wait, binding });}if (previous && (!previous.needsRecompile || Object.keys(previous.outcomes || {}).length)) return previous;const sources = this._socialPublicationSources(tabId);@@ -23929,7 +23930,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait prefetch.done;if (this._planExecutionGuards.get(tabId) !== guard) return null;// Checked again: the sources may have changed while it ran.- return this._ensureSocialPublicationContract(tabId, provider, { background, wait });+ return this._ensureSocialPublicationContract(tabId, provider, { background, wait, binding });}prefetches.delete(guard);if (prefetch.compiled && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId)) {@@ -23937,20 +23938,26 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn prefetch.compiled;}} else if (prefetch && !background) {- // A background compile of another input is never installed.+ // A background compile of another input is never installed: cancel it.+ prefetch.abort?.controller.abort();prefetches.delete(guard);}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;- const entry = { previous, state, settled: false, compiled: null, done: 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();+ const abort = this._socialPublicationBackgroundAbort(binding);+ const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);+ const entry = { previous, state, settled: false, compiled: null, done: null, abort };prefetches.set(guard, entry);- entry.done = this._socialPublicationCompile(tabId, provider, guard, state, previous, true)- .catch(() => null)+ entry.done = this._socialPublicationBackgroundSettle(abort,+ this._socialPublicationCompile(tabId, provider, guard, state, previous, true, call).catch(() => null), null).then(compiled => {entry.settled = true;- entry.compiled = compiled || null;- if (!compiled && prefetches.get(guard) === entry) prefetches.delete(guard);+ entry.compiled = abort.signal.aborted ? null : (compiled || null);+ if (!entry.compiled && prefetches.get(guard) === entry) prefetches.delete(guard);return entry.compiled;});return entry.done;@@ -23975,7 +23982,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// moved on, or 'recompile' when a correction arrived meanwhile. A background// compile stops once the run's state or its own slot moved on, and leaves// the click its own attempts when it cannot finish.- async _socialPublicationCompile(tabId, provider, guard, state, previous, background) {+ async _socialPublicationCompile(tabId, provider, guard, state, previous, background, call = null) {const { sources, context } = state;const replaced = () => (background? guard.socialPublication !== previous || this._socialPublicationContractPrefetches?.get(guard)?.state !== state@@ -23991,8 +23998,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtry {await this._tracePlannerAttemptRequest(runId, 0, provider, requestMessages,'social_publication_contract', attempt + 1, this._effectiveRunMode(tabId), options);- const response = await this._chatWithCostAllowance(provider, requestMessages, options,- this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_contract' });+ // In the background, checked again right before inference: the run+ // that started the compile may have stopped or been replaced while+ // the request was traced. Its request carries that run's signal and+ // allowance, never a later run's.+ if (background && (call.signal.aborted || !call.current() || replaced())) return null;+ const response = await this._chatWithCostAllowance(provider, requestMessages,+ background ? { ...options, signal: call.signal } : options,+ background ? call.costState : (this.currentCostState.get(tabId) || null),+ { tabId, generationName: 'social_publication_contract' });received = true;await this._tracePlannerAttemptResponse(runId, 0, provider, response,'social_publication_contract', attempt + 1, startedAt, options);@@ -24012,6 +24026,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dstate.error = '';return state;} catch (error) {+ // Cancelled: its run stopped, or a newer compile replaced it.+ if (background && call.signal.aborted) return null;if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) {if (background) return null;throw error;@@ -24388,8 +24404,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// background prefetch. `record` (the click) records each outcome on the// publication state as it goes; the prefetch records nothing here.// `isCurrent` tells whether `social` is still the run's publication state.+ // `background` (the prefetch) binds the request to the run that started it:+ // its signal, allowance and liveness check.async _socialPublicationAuditRun(tabId, provider, guard, social, action, snapshot, key, taskKey,- { record = false, isCurrent = () => guard.socialPublication === social } = {}) {+ { record = false, isCurrent = () => guard.socialPublication === social, background = null } = {}) {const messages = publicationAuditMessages(social.sources, social.contract, action, snapshot, key, social.context);let portable = false;let failure = null;@@ -24402,8 +24420,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtry {await this._tracePlannerAttemptRequest(runId, 0, provider, requestMessages,'social_publication_authorization', attempt + 1, this._effectiveRunMode(tabId), options);- const response = await this._chatWithCostAllowance(provider, requestMessages, options,- this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_authorization' });+ // In the background, checked again right before inference (see+ // _socialPublicationCompile).+ if (background && (background.signal.aborted || !background.current() || !isCurrent())) return { status: 'changed' };+ const response = await this._chatWithCostAllowance(provider, requestMessages,+ background ? { ...options, signal: background.signal } : options,+ background ? background.costState : (this.currentCostState.get(tabId) || null),+ { tabId, generationName: 'social_publication_authorization' });received = true;await this._tracePlannerAttemptResponse(runId, 0, provider, response,'social_publication_authorization', attempt + 1, startedAt, options);@@ -24427,6 +24450,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}return { status: 'authorized', reason: verdict.reason };} catch (error) {+ // Cancelled: its run stopped, or an audit of a newer draft replaced it.+ if (background?.signal.aborted) return { status: 'changed' };if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;await this._socialPublicationCheckerFailure(tabId, 'social_publication_authorization', attempt + 1, error, received);if (this._planExecutionGuards.get(tabId) !== guard || !isCurrent()@@ -24541,8 +24566,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst startedAt = Date.now();const runId = this.currentRunId.get(tabId);const taskKey = guard.taskKey;+ // The run that started the prefetch: its Stop cancels the background+ // requests, they are charged to its allowance, and they stop mattering+ // once another run owns the tab.+ const runSignal = this._runAbortSignal(tabId);const current = () => this._planExecutionGuards.get(tabId) === guard && guard.taskKey === taskKey- && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId);+ && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId)+ && this._runAbortSignal(tabId) === runSignal && !runSignal?.aborted;+ const binding = { signal: runSignal, costState: this.currentCostState.get(tabId) || null, current };let status = 'skipped';try {const pageUrl = await this._currentUrl(tabId);@@ -24553,10 +24584,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!current() || detected?.isSubmit !== true || detected.publicationControl !== true) return status;const readings = this._socialPublicationPrefetchReadings(tabId, detected.publicationPrefetchCaptions, pageUrl);try {- const social = await this._ensureSocialPublicationContract(tabId, provider, { background: true });+ const social = await this._ensureSocialPublicationContract(tabId, provider, { background: true, binding });status = contractOnly? (social?.contract && this._socialPublicationStateCurrent(guard, social) ? 'contract_ready' : 'skipped')- : await this._socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, current);+ : await this._socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, binding);} finally {await readings;}@@ -24574,7 +24605,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}- async _socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, current) {+ async _socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, binding) {+ const { current } = binding;const isCurrent = () => this._socialPublicationStateCurrent(guard, social);if (!current() || !isCurrent() || social.needsRecompile|| social.contract?.status !== 'ready' || social.retryBypass) return 'skipped';@@ -24592,11 +24624,21 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl, documentIdentity, frameId }));if (social.dispatch?.key === key || social.deniedAuditKey === key || social.prefetchedAudit?.key === key) return 'cached';const audits = this._socialPublicationAuditPrefetches ||= new WeakMap();- const entry = { key, done: null };+ const running = audits.get(social);+ // The same draft is already being audited for this run: join it. An+ // audit of an older draft is superseded: cancel its request, so it+ // 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();+ const abort = this._socialPublicationBackgroundAbort(binding);+ const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);+ const entry = { key, done: null, abort, runSignal: binding.signal };audits.set(social, entry);- entry.done = (async () => {+ entry.done = this._socialPublicationBackgroundSettle(abort, (async () => {try {- const outcome = await this._socialPublicationAuditRun(tabId, provider, guard, social, action, snapshot, key, taskKey, { isCurrent });+ const outcome = await this._socialPublicationAuditRun(tabId, provider, guard, social, action, snapshot, key, taskKey,+ { isCurrent, background: call });if (outcome.status !== 'authorized' && outcome.status !== 'denied') return outcome.status;// Stored only while nothing moved on: the same run, task, contract// and page, no newer prefetch, and no click that already decided.@@ -24612,10 +24654,50 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d} finally {if (audits.get(social) === entry) audits.delete(social);}- })();+ })(), 'changed');return entry.done;}+ // A background publication check's own abort: the Stop of the run that+ // started it, or a newer check that supersedes it.+ _socialPublicationBackgroundAbort(binding) {+ const controller = new AbortController();+ const runSignal = binding?.signal || null;+ const onAbort = () => {+ if (!controller.signal.aborted) controller.abort(runSignal?.reason);+ };+ if (runSignal?.aborted) onAbort();+ else runSignal?.addEventListener?.('abort', onAbort, { once: true });+ return {+ controller,+ signal: controller.signal,+ dispose: () => {+ try { runSignal?.removeEventListener?.('abort', onAbort); } catch {}+ },+ };+ }++ // What a background model call is bound to: its abort, the allowance of the+ // run that started it, and that run's liveness check.+ _socialPublicationBackgroundCall(tabId, guard, binding, abort) {+ return {+ signal: abort.signal,+ costState: binding ? binding.costState : (this.currentCostState.get(tabId) || null),+ current: binding?.current || (() => this._planExecutionGuards.get(tabId) === guard && !this._checkAbort(tabId)),+ };+ }++ // A cancelled check settles at once with `cancelled`, even when its provider+ // cannot cancel the request (an in-browser model's queue): nothing waits+ // behind it, and its late result can no longer be stored.+ _socialPublicationBackgroundSettle(abort, work, cancelled) {+ const stopped = new Promise(resolve => {+ if (abort.signal.aborted) resolve(cancelled);+ else abort.signal.addEventListener('abort', () => resolve(cancelled), { once: true });+ });+ return Promise.race([work, stopped]).finally(() => abort.dispose());+ }+// The readings the click's own checks ask for, asked now: what the publish// control and the controls beside it do (the submit probe), and, on a page// whose sends the recipient guard checks, whether activating them sends adiff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex 826e39c71..d4e2fd48a 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -20929,7 +20929,8 @@ 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.+ // installed after it, so its request is cancelled too.+ this._socialPublicationContractPrefetches?.get(guard)?.abort?.controller.abort();this._socialPublicationContractPrefetches?.delete(guard);const social = guard.socialPublication;if (!social) return;@@ -21080,7 +21081,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// that would compile awaits it and installs it only when it compiled exactly// the input that caller would compile from now: the same sources, context,// task and prior state. Anything else compiles as before.- async _ensureSocialPublicationContract(tabId, provider = this._activeProvider(tabId), { background = false, wait = true } = {}) {+ async _ensureSocialPublicationContract(tabId, provider = this._activeProvider(tabId), { background = false, wait = true, binding = null } = {}) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled) return null;// The app-owned guard is new for every user revision. A trusted Continue@@ -21092,7 +21093,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!wait) return null;await running.catch(() => {});if (this._planExecutionGuards.get(tabId) !== guard) return null;- return this._ensureSocialPublicationContract(tabId, provider, { background, wait });+ return this._ensureSocialPublicationContract(tabId, provider, { background, wait, binding });}if (previous && (!previous.needsRecompile || Object.keys(previous.outcomes || {}).length)) return previous;const sources = this._socialPublicationSources(tabId);@@ -21112,7 +21113,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait prefetch.done;if (this._planExecutionGuards.get(tabId) !== guard) return null;// Checked again: the sources may have changed while it ran.- return this._ensureSocialPublicationContract(tabId, provider, { background, wait });+ return this._ensureSocialPublicationContract(tabId, provider, { background, wait, binding });}prefetches.delete(guard);if (prefetch.compiled && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId)) {@@ -21120,20 +21121,26 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn prefetch.compiled;}} else if (prefetch && !background) {- // A background compile of another input is never installed.+ // A background compile of another input is never installed: cancel it.+ prefetch.abort?.controller.abort();prefetches.delete(guard);}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;- const entry = { previous, state, settled: false, compiled: null, done: 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();+ const abort = this._socialPublicationBackgroundAbort(binding);+ const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);+ const entry = { previous, state, settled: false, compiled: null, done: null, abort };prefetches.set(guard, entry);- entry.done = this._socialPublicationCompile(tabId, provider, guard, state, previous, true)- .catch(() => null)+ entry.done = this._socialPublicationBackgroundSettle(abort,+ this._socialPublicationCompile(tabId, provider, guard, state, previous, true, call).catch(() => null), null).then(compiled => {entry.settled = true;- entry.compiled = compiled || null;- if (!compiled && prefetches.get(guard) === entry) prefetches.delete(guard);+ entry.compiled = abort.signal.aborted ? null : (compiled || null);+ if (!entry.compiled && prefetches.get(guard) === entry) prefetches.delete(guard);return entry.compiled;});return entry.done;@@ -21158,7 +21165,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// moved on, or 'recompile' when a correction arrived meanwhile. A background// compile stops once the run's state or its own slot moved on, and leaves// the click its own attempts when it cannot finish.- async _socialPublicationCompile(tabId, provider, guard, state, previous, background) {+ async _socialPublicationCompile(tabId, provider, guard, state, previous, background, call = null) {const { sources, context } = state;const replaced = () => (background? guard.socialPublication !== previous || this._socialPublicationContractPrefetches?.get(guard)?.state !== state@@ -21174,8 +21181,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtry {await this._tracePlannerAttemptRequest(runId, 0, provider, requestMessages,'social_publication_contract', attempt + 1, this._effectiveRunMode(tabId), options);- const response = await this._chatWithCostAllowance(provider, requestMessages, options,- this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_contract' });+ // In the background, checked again right before inference: the run+ // that started the compile may have stopped or been replaced while+ // the request was traced. Its request carries that run's signal and+ // allowance, never a later run's.+ if (background && (call.signal.aborted || !call.current() || replaced())) return null;+ const response = await this._chatWithCostAllowance(provider, requestMessages,+ background ? { ...options, signal: call.signal } : options,+ background ? call.costState : (this.currentCostState.get(tabId) || null),+ { tabId, generationName: 'social_publication_contract' });received = true;await this._tracePlannerAttemptResponse(runId, 0, provider, response,'social_publication_contract', attempt + 1, startedAt, options);@@ -21195,6 +21209,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dstate.error = '';return state;} catch (error) {+ // Cancelled: its run stopped, or a newer compile replaced it.+ if (background && call.signal.aborted) return null;if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) {if (background) return null;throw error;@@ -21571,8 +21587,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// background prefetch. `record` (the click) records each outcome on the// publication state as it goes; the prefetch records nothing here.// `isCurrent` tells whether `social` is still the run's publication state.+ // `background` (the prefetch) binds the request to the run that started it:+ // its signal, allowance and liveness check.async _socialPublicationAuditRun(tabId, provider, guard, social, action, snapshot, key, taskKey,- { record = false, isCurrent = () => guard.socialPublication === social } = {}) {+ { record = false, isCurrent = () => guard.socialPublication === social, background = null } = {}) {const messages = publicationAuditMessages(social.sources, social.contract, action, snapshot, key, social.context);let portable = false;let failure = null;@@ -21585,8 +21603,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtry {await this._tracePlannerAttemptRequest(runId, 0, provider, requestMessages,'social_publication_authorization', attempt + 1, this._effectiveRunMode(tabId), options);- const response = await this._chatWithCostAllowance(provider, requestMessages, options,- this.currentCostState.get(tabId) || null, { tabId, generationName: 'social_publication_authorization' });+ // In the background, checked again right before inference (see+ // _socialPublicationCompile).+ if (background && (background.signal.aborted || !background.current() || !isCurrent())) return { status: 'changed' };+ const response = await this._chatWithCostAllowance(provider, requestMessages,+ background ? { ...options, signal: background.signal } : options,+ background ? background.costState : (this.currentCostState.get(tabId) || null),+ { tabId, generationName: 'social_publication_authorization' });received = true;await this._tracePlannerAttemptResponse(runId, 0, provider, response,'social_publication_authorization', attempt + 1, startedAt, options);@@ -21610,6 +21633,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}return { status: 'authorized', reason: verdict.reason };} catch (error) {+ // Cancelled: its run stopped, or an audit of a newer draft replaced it.+ if (background?.signal.aborted) return { status: 'changed' };if (this._isCostAllowanceError(error) || this._checkAbort(tabId)) throw error;await this._socialPublicationCheckerFailure(tabId, 'social_publication_authorization', attempt + 1, error, received);if (this._planExecutionGuards.get(tabId) !== guard || !isCurrent()@@ -21724,8 +21749,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst startedAt = Date.now();const runId = this.currentRunId.get(tabId);const taskKey = guard.taskKey;+ // The run that started the prefetch: its Stop cancels the background+ // requests, they are charged to its allowance, and they stop mattering+ // once another run owns the tab.+ const runSignal = this._runAbortSignal(tabId);const current = () => this._planExecutionGuards.get(tabId) === guard && guard.taskKey === taskKey- && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId);+ && !this._checkAbort(tabId) && !this._hasPendingSteering(tabId)+ && this._runAbortSignal(tabId) === runSignal && !runSignal?.aborted;+ const binding = { signal: runSignal, costState: this.currentCostState.get(tabId) || null, current };let status = 'skipped';try {const pageUrl = await this._currentUrl(tabId);@@ -21736,10 +21767,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!current() || detected?.isSubmit !== true || detected.publicationControl !== true) return status;const readings = this._socialPublicationPrefetchReadings(tabId, detected.publicationPrefetchCaptions, pageUrl);try {- const social = await this._ensureSocialPublicationContract(tabId, provider, { background: true });+ const social = await this._ensureSocialPublicationContract(tabId, provider, { background: true, binding });status = contractOnly? (social?.contract && this._socialPublicationStateCurrent(guard, social) ? 'contract_ready' : 'skipped')- : await this._socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, current);+ : await this._socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, binding);} finally {await readings;}@@ -21757,7 +21788,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}- async _socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, current) {+ async _socialPublicationPrefetchAudit(tabId, guard, provider, social, detected, pageUrl, taskKey, binding) {+ const { current } = binding;const isCurrent = () => this._socialPublicationStateCurrent(guard, social);if (!current() || !isCurrent() || social.needsRecompile|| social.contract?.status !== 'ready' || social.retryBypass) return 'skipped';@@ -21775,11 +21807,21 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst key = this._sha256TextSync(JSON.stringify({ contract: social.key, action, snapshot, pageUrl, documentIdentity, frameId }));if (social.dispatch?.key === key || social.deniedAuditKey === key || social.prefetchedAudit?.key === key) return 'cached';const audits = this._socialPublicationAuditPrefetches ||= new WeakMap();- const entry = { key, done: null };+ const running = audits.get(social);+ // The same draft is already being audited for this run: join it. An+ // audit of an older draft is superseded: cancel its request, so it+ // 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();+ const abort = this._socialPublicationBackgroundAbort(binding);+ const call = this._socialPublicationBackgroundCall(tabId, guard, binding, abort);+ const entry = { key, done: null, abort, runSignal: binding.signal };audits.set(social, entry);- entry.done = (async () => {+ entry.done = this._socialPublicationBackgroundSettle(abort, (async () => {try {- const outcome = await this._socialPublicationAuditRun(tabId, provider, guard, social, action, snapshot, key, taskKey, { isCurrent });+ const outcome = await this._socialPublicationAuditRun(tabId, provider, guard, social, action, snapshot, key, taskKey,+ { isCurrent, background: call });if (outcome.status !== 'authorized' && outcome.status !== 'denied') return outcome.status;// Stored only while nothing moved on: the same run, task, contract// and page, no newer prefetch, and no click that already decided.@@ -21795,10 +21837,50 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d} finally {if (audits.get(social) === entry) audits.delete(social);}- })();+ })(), 'changed');return entry.done;}+ // A background publication check's own abort: the Stop of the run that+ // started it, or a newer check that supersedes it.+ _socialPublicationBackgroundAbort(binding) {+ const controller = new AbortController();+ const runSignal = binding?.signal || null;+ const onAbort = () => {+ if (!controller.signal.aborted) controller.abort(runSignal?.reason);+ };+ if (runSignal?.aborted) onAbort();+ else runSignal?.addEventListener?.('abort', onAbort, { once: true });+ return {+ controller,+ signal: controller.signal,+ dispose: () => {+ try { runSignal?.removeEventListener?.('abort', onAbort); } catch {}+ },+ };+ }++ // What a background model call is bound to: its abort, the allowance of the+ // run that started it, and that run's liveness check.+ _socialPublicationBackgroundCall(tabId, guard, binding, abort) {+ return {+ signal: abort.signal,+ costState: binding ? binding.costState : (this.currentCostState.get(tabId) || null),+ current: binding?.current || (() => this._planExecutionGuards.get(tabId) === guard && !this._checkAbort(tabId)),+ };+ }++ // A cancelled check settles at once with `cancelled`, even when its provider+ // cannot cancel the request (an in-browser model's queue): nothing waits+ // behind it, and its late result can no longer be stored.+ _socialPublicationBackgroundSettle(abort, work, cancelled) {+ const stopped = new Promise(resolve => {+ if (abort.signal.aborted) resolve(cancelled);+ else abort.signal.addEventListener('abort', () => resolve(cancelled), { once: true });+ });+ return Promise.race([work, stopped]).finally(() => abort.dispose());+ }+// The readings the click's own checks ask for, asked now: what the publish// control and the controls beside it do (the submit probe), and, on a page// whose sends the recipient guard checks, whether activating them sends adiff --git a/test/publication-prefetch.mjs b/test/publication-prefetch.mjsindex 9cf1b1bfb..d70c7b231 100644--- a/test/publication-prefetch.mjs+++ b/test/publication-prefetch.mjs@@ -28,6 +28,16 @@ const until = async (predicate, message) => {}assert.fail(message);};+// A promise that must settle soon: a hang fails the test instead of the run.+const within = async (promise, message, ms = 2000) => {+ let timer;+ const late = new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error(`timed out: ${message}`)), ms); });+ try {+ return await Promise.race([promise, late]);+ } finally {+ clearTimeout(timer);+ }+};for (const browser of ['chrome', 'firefox']) {const { Agent } = await import(`../src/${browser}/src/agent/agent.js`);@@ -45,21 +55,33 @@ for (const browser of ['chrome', 'firefox']) {agent._currentUrl = async () => f.pageUrl;agent.conversations.set(tabId, [{ role: 'system', content: 'system' }, { role: 'user', content: request }]);f.guard = agent._startPlanExecutionGuard(tabId, 'act', { requestKind: 'execute', requiresStateChange: true, requiresSubmission: true });- agent._chatWithCostAllowance = async (usedProvider, messages, _options, _cost, meta) => {+ agent._chatWithCostAllowance = async (usedProvider, messages, options, cost, meta) => {assert.equal(usedProvider, provider);- const call = { name: meta.generationName, startedAt: Date.now(), endedAt: null, done: false };+ const signal = options?.signal || null;+ const call = { name: meta.generationName, startedAt: Date.now(), endedAt: null, done: false, cost, signal, aborted: false };f.calls.push(call);+ // Like a provider that honors its request's signal.+ const aborted = () => {+ call.aborted = true;+ const error = new Error('The request was aborted.');+ error.name = 'AbortError';+ return error;+ };+ const input = JSON.parse(messages[1].content);+ if (meta.generationName === 'social_publication_authorization') call.key = input.key;+ if (signal?.aborted) throw aborted();const hold = f.holds[meta.generationName];if (hold) {delete f.holds[meta.generationName];hold.started = true;- await hold.promise;+ await new Promise((resolve, reject) => {+ hold.promise.then(resolve);+ if (f.honorAbort !== false) signal?.addEventListener('abort', () => reject(aborted()), { once: true });+ });}call.endedAt = Date.now();call.done = true;- const input = JSON.parse(messages[1].content);if (meta.generationName === 'social_publication_authorization') {- call.key = input.key;const authorized = f.authorize(input);return { content: JSON.stringify({ key: input.key, actionId: input.action.id, authorized,reason: authorized ? 'The draft matches the request.' : 'The draft does not match the request.' }) };@@ -72,7 +94,13 @@ for (const browser of ['chrome', 'firefox']) {// The same probe answers the prefetch (its publish-control hint) and the click.agent._detectLikelySubmitAction = async (_tabId, name, args, options = {}) => {f.probes.push({ name, args: structuredClone(args), captionPass: options.captionPass || 'collect' });- return structuredClone(f.detected);+ const detected = structuredClone(f.detected);+ // One probe can see a changed composer while later ones do not.+ if (f.probeOnce) {+ Object.assign(detected, f.probeOnce);+ f.probeOnce = null;+ }+ return detected;};agent._readPageTexts = async (_tabId, kind, texts) => { f.readings.push({ kind, texts: [...texts] }); };f.hold = name => { const gate = deferred(); f.holds[name] = gate; return gate; };@@ -271,6 +299,159 @@ for (const browser of ['chrome', 'firefox']) {}});+ test(`${browser}: a background check sends nothing for a run that stopped or was replaced, and never charges the next run`, async () => {+ for (const stage of ['social_publication_contract', 'social_publication_authorization']) {+ const f = setup();+ const { agent, tabId } = f;+ const startingRun = new AbortController();+ agent._runAbortStates.set(tabId, { controller: startingRun, dispose() {} });+ agent.currentCostState.set(tabId, { run: 'the run that wrote the draft' });+ // Hold the check where it awaits trace persistence: after its last+ // liveness check, before inference.+ const tracing = deferred();+ const traced = agent._tracePlannerAttemptRequest;+ let held = false;+ agent._tracePlannerAttemptRequest = async (...args) => {+ if (!held && args[4] === stage) {+ held = true;+ await tracing.promise;+ }+ return traced.apply(agent, args);+ };+ const prefetch = f.write();+ await until(() => held, `${stage}: the background check reached trace persistence`);+ const sent = f.calls.length;+ // Stop, then the next run starts on the tab with its own guard, signal+ // and allowance.+ agent.abort(tabId);+ agent._runAbortStates.set(tabId, { controller: new AbortController(), dispose() {} });+ agent.abortFlags.delete(tabId);+ const nextCost = { run: 'the next run' };+ agent.currentCostState.set(tabId, nextCost);+ agent._startPlanExecutionGuard(tabId, 'act', { requestKind: 'execute', requiresStateChange: true, requiresSubmission: true });+ tracing.release();+ assert.equal(await within(prefetch, `${stage}: the stale prefetch ends`),+ stage === 'social_publication_contract' ? 'skipped' : 'changed', stage);+ assert.equal(f.calls.length, sent, `${stage}: the stale check was never sent`);+ assert(f.calls.every(call => call.cost !== nextCost), `${stage}: the next run was not charged`);+ }+ });++ test(`${browser}: a background check carries the signal and allowance of the run that started it`, async () => {+ const f = setup();+ const { agent, tabId } = f;+ const startingRun = new AbortController();+ const startingCost = { run: 'the run that wrote the draft' };+ agent._runAbortStates.set(tabId, { controller: startingRun, dispose() {} });+ agent.currentCostState.set(tabId, startingCost);+ const audit = f.hold('social_publication_authorization');+ const prefetch = f.write();+ await until(() => audit.started, 'the background audit started');+ const [compile] = f.named('social_publication_contract');+ const [request] = f.named('social_publication_authorization');+ assert.equal(compile.cost, startingCost, 'the compile is charged to the run that started it');+ assert.equal(request.cost, startingCost, 'the audit is charged to the run that started it');+ // Stopping that run cancels the request in flight.+ startingRun.abort();+ await settle();+ audit.release();+ assert.equal(await within(prefetch, 'the stopped prefetch ends'), 'changed');+ assert.equal(request.aborted, true, 'the request in flight was cancelled');+ assert.equal(f.pending()?.compiled?.prefetchedAudit, undefined, 'a cancelled audit stores no verdict');+ });++ test(`${browser}: a newer draft cancels the background audit of the older one, and a click awaiting it audits on its own`, async () => {+ const f = setup();+ const audit = f.hold('social_publication_authorization');+ const first = f.write();+ await until(() => audit.started, 'the first background audit started');+ const [stale] = f.named('social_publication_authorization');+ // The click on Post awaits the audit of its own draft.+ let clicked = false;+ const click = f.click().then(result => { clicked = true; return result; });+ await settle();+ assert.equal(clicked, false, 'the click awaits the audit in flight');+ // Another write changes the composer: its audit supersedes the first.+ f.probeOnce = { frameDocumentIdentity: 'https://x.com/compose/post|fixture-document-2' };+ const second = f.write();+ try {+ assert.equal(await within(first, 'the superseded audit settles'), 'changed');+ assert.equal(stale.aborted, true, 'its request was cancelled');+ assert.equal(await within(click, 'the click goes on without the superseded audit'), null);+ assert.equal(await within(second, 'the newer audit ends'), 'authorized');+ } finally {+ audit.release();+ }+ const audits = f.named('social_publication_authorization');+ assert.equal(audits.length, 3, 'the cancelled audit, the newer draft\'s and the click\'s own');+ const own = audits.filter(call => call !== stale && call.key === stale.key);+ assert.equal(own.length, 1, 'the click audited the draft it probed');+ assert.equal(f.guard.socialPublication.dispatch.key, stale.key);+ assert.notEqual(f.guard.socialPublication.prefetchedAudit?.key, stale.key, 'the cancelled audit stored no verdict');+ // With a provider that cannot cancel its request, the superseded audit+ // still settles at once, and its late verdict is not stored.+ const stuck = setup();+ stuck.honorAbort = false;+ const blocked = stuck.hold('social_publication_authorization');+ const older = stuck.write();+ await until(() => blocked.started, 'the background audit started');+ const [late] = stuck.named('social_publication_authorization');+ stuck.probeOnce = { frameDocumentIdentity: 'https://x.com/compose/post|fixture-document-2' };+ const newer = stuck.write();+ try {+ assert.equal(await within(older, 'the superseded audit settles without its provider'), 'changed');+ assert.equal(await within(newer, 'the newer audit ends'), 'authorized');+ } finally {+ blocked.release();+ }+ await settle();+ assert.equal(late.done, true);+ assert.notEqual(stuck.guard.socialPublication?.prefetchedAudit?.key ?? stuck.pending()?.compiled?.prefetchedAudit?.key, late.key,+ 'the late verdict of the superseded audit is not stored');+ // The same draft written again joins the audit already running for it.+ const again = setup();+ const held = again.hold('social_publication_authorization');+ const one = again.write();+ await until(() => held.started, 'the background audit started');+ const two = again.write();+ await settle();+ held.release();+ assert.equal(await within(one, 'the first prefetch ends'), 'authorized');+ assert.equal(await within(two, 'the joined prefetch ends'), 'authorized');+ assert.equal(again.named('social_publication_authorization').length, 1, 'one audit for the same draft');+ });++ 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');+ const prefetch = f.write();+ await until(() => contract.started, 'the background compile started');+ const [stale] = f.named('social_publication_contract');+ f.applySteering('Actually post Goodbye instead');+ try {+ assert.equal(await within(prefetch, 'the corrected prefetch ends'), 'skipped');+ } finally {+ contract.release();+ }+ assert.equal(stale.aborted, true, 'the correction cancelled the compile request');+ // A click whose sources differ from a background compile cancels it and+ // compiles its own.+ const g = setup();+ const held = g.hold('social_publication_contract');+ const background = g.write();+ await until(() => held.started, 'the background compile started');+ const [other] = g.named('social_publication_contract');+ g.agent.conversations.get(g.tabId).push({ role: 'assistant', content: 'Draft: Hello' });+ try {+ assert.equal(await within(g.click(), 'the click compiles its own contract'), null);+ assert.equal(await within(background, 'the cancelled prefetch ends'), 'skipped');+ } finally {+ held.release();+ }+ assert.equal(other.aborted, true, 'the background compile of other sources was cancelled');+ assert.equal(g.guard.socialPublication.sources.draft0, 'Draft: Hello');+ });+test(`${browser}: a failed background compile leaves the click its own two attempts`, async () => {const f = setup();let failures = 2;@@ -515,7 +696,8 @@ test('Chrome and Firefox share the publication prefetch', async () => {'_socialPublicationPrefetchAllowed', '_socialPublicationStateCurrent', '_socialPublicationPrefetchRun', '_socialPublicationPrefetchAudit','_socialPublicationPrefetchReadings', '_socialPublicationPrefetchedVerdict', '_socialPublicationAuditRun','_socialPublicationCompile', '_ensureSocialPublicationContract', '_predispatchTimer', '_predispatchStage',- '_recordPredispatchTiming']) {+ '_recordPredispatchTiming', '_socialPublicationBackgroundAbort', '_socialPublicationBackgroundCall',+ '_socialPublicationBackgroundSettle', '_invalidateSocialPublicationContract']) {assert.equal(typeof Chrome.prototype[name], 'function', name);assert.equal(Chrome.prototype[name].toString(), Firefox.prototype[name].toString(), name);}