Skip to content

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

Approve a message recipient from the first matching confirmation

Claudee6d73d78155c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8f9026133..c6e88a293 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ This changelog was generated from the repository Git history and release tags. V
- Ordinary controls (filter chips, folder links, menus, tabs, toggles, draft attachment and media removal, composer tools) work before and after a correction; X and Bluesky no longer reject them as unidentified publication actions. After a correction, identical resubmissions are reported as already done, a corrected in-place save or a requested post on another platform is allowed once the earlier result is known, and requests to remove characters or hashtags are no longer treated as deleting the post. A submit-probe exception that left real publish controls unresolved is fixed.
- A correction sent while a run is working is no longer lost when the extension background restarts before the run uses it. The resumed run applies it first, once, in the order it was sent; if the run does not resume, the correction returns to the queue marked as paused, as after Stop. Clearing the conversation or closing the tab discards it.
- Buttons that animate when the pointer reaches them (a hover lift, scale or border transition) are no longer refused once before working: the click waits up to 0.6 seconds, without sending anything, until the button stops moving, then presses it once at its new centre. A button that keeps moving, is covered or replaced, or any input or Stop during that wait still cancels the click. Hover, drag and drop, and checkbox actions refused before any input are reported as not sent.
+- Confirming a message recipient now works the first time. When the open conversation's name differs from the name in your request ("gamze" and "Gamze Çömlekçi"), picking that exact name in the confirmation approves it, however the question is worded, including a question asked before the first send; Firefox now shows the same confirmation question as Chrome. A reply that refuses or corrects ("No, not Gamze Çömlekçi", "Cancel all") is never taken as approval, and a reply that does not pick the name ("that's the right person") approves nothing and is explained instead of being treated as consent.
## [40.3.0] - 2026-10-12
diff --git a/docs/page-feedback-monitor.md b/docs/page-feedback-monitor.md
index 89cf3d4ab..97bcfe26a 100644
--- a/docs/page-feedback-monitor.md
+++ b/docs/page-feedback-monitor.md
@@ -296,6 +296,16 @@ Steer or grant authorization. Enter and Alt+Enter retain their existing behavior
another approval question cannot repair missing evidence. Recipient
clarifications report `recipientBinding` separately from general user
authorization and suppress repeated questions for known technical blockers.
+- A recipient clarification approves the recipients the page addresses when
+ its question names each of them and asks about sending to them (or declares
+ a recipient purpose), and the user's answer picks those exact names; the
+ wording "instead" is not required. A question asked before any send was
+ blocked binds to a fresh read-only observation of the open conversation, and
+ the send itself is still checked against the page. A question that hides the
+ recipient, a reply that does not name it, and a refusal or redirect ("No, not
+ …", "Cancel all") approve nothing, and the clarify result tells the model why.
+ Only an affirmative grant ("Send all remaining messages…", "send all")
+ approves every remaining send.
- A cancelled `beforeinput` handled by a native chat editor can receive an
exact read-only draft certificate while its original operation, document,
identity nodes, editor, focus and selection remain current. The certificate
diff --git a/package.json b/package.json
index 85ff10f71..8adcd09ba 100644
--- a/package.json
+++ b/package.json
@@ -59,8 +59,8 @@
"benchmark:relevance": "node scripts/benchmark-offline-relevance.mjs --verbose",
"test:social-contract": "node --test test/social-publish-contract.mjs test/publication-quote-markup.mjs",
"test:social-contract:dom": "node test/social-publish-contract-dom.mjs",
- "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/lifecycle-steering-restart.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/lifecycle-planner-digest.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",
- "test:page-feedback": "node --test test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/delivery-click-ax-response-loss.mjs test/delivery-stop-compound.mjs test/delivery-cdp-input.mjs test/delivery-click-locks.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-dispatch-boundary.mjs && node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs",
+ "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/lifecycle-steering-restart.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/lifecycle-planner-digest.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",
+ "test:page-feedback": "node --test test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/delivery-click-ax-response-loss.mjs test/delivery-stop-compound.mjs test/delivery-cdp-input.mjs test/delivery-click-locks.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-dispatch-boundary.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs",
"test:chat-steering": "node --test test/chat-steering.mjs test/chat-steering-ui.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs",
"test:rich-text-dom": "node test/ui-content-lifecycle.mjs --dom",
"test:firefox-bidi": "node --test test/firefox-bidi.mjs test/firefox-full-page-screenshot.mjs",
@@ -93,9 +93,9 @@
"test:shard:quick": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-bridge-registration.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:provider-instances:ui && npm run test:openrouter-capabilities && npm run test:anthropic && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs",
"test:shard:runtime-unit": "node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-click-guard.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/completion-current-execution-evidence.mjs test/video-upload-attachment.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/lifecycle-planner-digest.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-vision-fallback.mjs test/delivery-click-locks.mjs test/guards-steering-receipts.mjs test/terminal-user-messages.mjs",
"test:shard:browser-a": "node test/bot-memory-dom.mjs && node test/bot-memory-click-dom.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/native-button-preparation.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs test/delivery-cdp-input.mjs test/delivery-click-ax-response-loss.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs",
- "test:shard:browser-b1": "node test/message-recipient-upload.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs",
+ "test:shard:browser-b1": "node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs",
"test:shard:browser-b2": "node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/shared-action-guards-mv3.mjs && node test/quality/video-upload-attachment-mv3.mjs",
- "test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",
+ "test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",
"test:shard:tail": "node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",
"test:composer-context": "node --test test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs",
"test:bot-memory": "node --test test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs && node test/bot-memory-dom.mjs && node test/quality/cloud-bot-memory-mv3.mjs",
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 3de7ae356..72aabdb3c 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -69,7 +69,7 @@ import {
workflowControlLabelIsRequested,
workflowRequiredRowsAreProcessed,
} from './adapter-workflow-evidence.js';
-import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, messageRecipientUploadSourceKey, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity, resolveClarifiedRecipients } from './message-recipient-guard.js';
+import { answerGrantsAllRemainingSends, answerNamesAllObservedRecipients, answerNamesIdentity, answerRefusesRecipient, messageTargetMatchesObservedIdentities, messageRecipientUploadSourceKey, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity, questionAsksAboutRecipient, questionPresentsObservedRecipients, resolveClarifiedRecipients } from './message-recipient-guard.js';
import { advanceChatSession, chatRunEndedNotice, createOwnedNativeChatReadRepair, createChatSession, decideChatSend, markChatSendPending, normalizeChatSession, normalizeChatSnapshot, normalizeNativeOpaqueBaseline, serializeChatSession } from './chat-workflow.js';
import {
fetchUrl,
@@ -28607,19 +28607,33 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: inconclusive
? 'Message action blocked: WebBrain could not conclusively resolve the target control and active composer. Re-read the page and retry with an exact visible control or fresh ref_id.'
: target
- ? `Message send blocked: this send would go to ${observedRecipientLabel ? `"${observedRecipientLabel}"` : 'a recipient'} which is not the recipient authorized for this task, so nothing was dispatched. Do NOT click Send again, and do not retry with different targeting.
-Ask the user to authorize it — one clarify, then act on their answer. The options must carry the address/identity text itself, because authorization binds to what the page shows and a bare "yes" cannot authorize a send. Include the multi-send option when the task sends more than one message:
-clarify({ question: "Send to ${observedRecipientLabel || '<observed address>'} instead?", options: ["${observedRecipientLabel || '<observed address>'}", "Send all remaining emails in this task without asking again", "Cancel"] })
-- If they pick the address: that recipient is authorized for the rest of this task, so retry the Send and continue normally.
-- If they pick "send all remaining": every remaining send in this task is authorized, so keep going without asking again.
-- If they pick "Cancel": stop and report that the send was not authorized.
-If the user has already named or confirmed this exact recipient, do NOT ask again — treat it as authorized, retry the Send once, and continue.`
+ ? this._recipientMismatchGuidance(observedRecipientLabel, target)
: (guard?.requiresSubmission === false || guard?.requiresStateChange === false || !target
? 'Message send blocked: the current plan does not authorize sending or submitting messages. Return the draft in chat or ask the user to authorize sending before attempting delivery.'
: 'Message send blocked: the current task has no structured recipient authorization. Ask the user to name the recipient or explicitly authorize the currently open conversation before retrying.'),
};
}
+ /**
+ * Model guidance for a send whose page-observed recipient is not the one
+ * the task authorized. It names both, prescribes one clarify that shows the
+ * exact observed name, and never suggests retrying without the user's pick:
+ * the guard only accepts a bound answer, so a bare retry is blocked again.
+ */
+ _recipientMismatchGuidance(observedRecipientLabel, target) {
+ const planned = normalizeMessageTarget(target)?.target_kind === 'named'
+ ? normalizeMessageTarget(target).recipients.map(recipient => recipient.identity).slice(0, 3).join(', ')
+ : '';
+ const name = observedRecipientLabel || '<observed address>';
+ return `Message send blocked: this send would go to ${observedRecipientLabel ? `"${observedRecipientLabel}"` : 'a recipient'}, which is not ${planned ? `exactly the recipient named for this task ("${planned}")` : 'the conversation authorized for this task'}, so nothing was dispatched. Do not retry with different targeting.
+Ask the user once whether to send it there. Put that exact name in the question and as an option, because authorization binds to what the page shows and a bare "yes" cannot authorize a send:
+clarify({ question: "Send it to ${name} instead?", options: ["${name}", "Cancel"] })
+If the task sends more than one message, also offer "Send all remaining messages in this task without asking again".
+- If they pick the name: that recipient is authorized for the rest of this task, so retry the send and continue normally.
+- If they pick "Send all remaining messages": every remaining send in this task is authorized, so keep going without asking again.
+- If they pick "Cancel": stop and report that the send was not authorized.`;
+ }
+
_isRecipientClarification(context, pendingType = 'message_recipient', observedCandidates = []) {
if (!context || typeof context !== 'object') return false;
const purpose = String(context.purpose || '').trim();
@@ -28633,7 +28647,13 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
if (pendingType === 'recipient_change') {
const changeWord = /(change|switch|different|instead|update|replace|another|new|更改|更换|切换|替换|换成)/i.test(questionText);
const targetWord = /(recipient|conversation|contact|send to|person|address|target|someone else|\b(?:to|cc|bcc|role|field)\b|收件人|联系人|发送)/i.test(questionText);
- return changeWord && targetWord;
+ if (changeWord && targetWord) return true;
+ // The user has to see where the message goes, not a particular wording.
+ // A question that names the recipients the page addresses and asks about
+ // sending to them ("Send the photo to Gamze Çömlekçi?") shows exactly
+ // that; the answer must still name the same page-observed recipients.
+ return questionPresentsObservedRecipients(context.question, observedCandidates,
+ purpose === 'message_recipient' || purpose === 'recipient_change');
}
// Check if the clarify question, reason, or options explicitly mention any observed candidate identity or alias
@@ -28679,9 +28699,15 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
* messaging (requiresSubmission=true and requiresStateChange=true) and must
* match the specific clarification purpose or question.
*/
- _bindClarifiedMessageRecipient(tabId, answer, source = 'user', clarifyContext = null) {
+ _bindClarifiedMessageRecipient(tabId, answer, source = 'user', clarifyContext = null, outcome = null) {
+ // `outcome`, when given, receives why nothing was bound so the clarify
+ // result can tell the model what the user actually needs to see.
+ const unbound = reason => {
+ if (outcome && typeof outcome === 'object') outcome.reason = reason;
+ return false;
+ };
const guard = this._planExecutionGuards.get(tabId);
- if (!guard) return false;
+ if (!guard) return unbound('no_pending_recipient');
// Read and clear together. The consent the guard staged belongs to exactly
// one clarify, the one its own error told the model to ask; every later
// question is a different question and must not inherit it. Clearing on
@@ -28700,31 +28726,36 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
: [];
guard.pendingRecipientAuthorization = false;
guard.observedRecipientCandidates = null;
- if (!pending || !pendingType || observed.length === 0) return false;
- if (!answer || source === 'timeout' || source === 'auto') return false;
+ if (outcome && typeof outcome === 'object') outcome.observed = observed.slice(0, 16);
+ if (!pending || !pendingType || observed.length === 0) return unbound('no_pending_recipient');
+ if (!answer || source === 'timeout' || source === 'auto') return unbound('no_user_answer');
if (pendingType === 'recipient_change') {
if (!clarifyContext || !this._isRecipientClarification(clarifyContext, 'recipient_change', observed)) {
- return false;
+ return unbound('recipient_not_presented');
}
} else if (clarifyContext && !this._isRecipientClarification(clarifyContext, 'message_recipient', observed)) {
- return false;
+ return unbound('recipient_not_presented');
}
const normalizedAnswer = normalizeRecipientAnswer(answer);
- if (!normalizedAnswer) return false;
+ if (!normalizedAnswer) return unbound('no_user_answer');
+ // A refusal or redirect is never approval, even when it names the
+ // recipient ("No, not Mallory") or says "all" ("Cancel all").
+ if (answerRefusesRecipient(answer, observed)) return unbound('answer_refused');
// A user may authorize the rest of the task in one answer instead of one
// recipient at a time (multi-email / multi-recipient runs). This is still
// the USER's grant: it can only arrive as a real clarify answer, never as
// model text, and it still requires a page-observed recipient to exist.
- const allowAllSends = /(?:^|[^\p{L}])(?:all|everything|any|every|allow\s+all|send\s+all)(?:[^\p{L}]|$)/iu
- .test(normalizedAnswer);
- if (!allowAllSends && !answerNamesAllObservedRecipients(normalizedAnswer, observed)) return false;
+ const allowAllSends = answerGrantsAllRemainingSends(normalizedAnswer);
+ if (!allowAllSends && !answerNamesAllObservedRecipients(normalizedAnswer, observed)) {
+ return unbound('answer_does_not_name_recipient');
+ }
const resolvedRecipients = allowAllSends
? observed
.map(item => ({ identity: item?.identity || item, role: item?.role || 'to' }))
.filter(recipient => recipient.identity)
: resolveClarifiedRecipients(observed, guard.messaging, clarifyContext, answer);
const target = normalizeMessageTarget({ target_kind: 'named', recipients: resolvedRecipients });
- if (!target) return false;
+ if (!target) return unbound('answer_does_not_name_recipient');
guard.messaging = target;
// Remember the grant for the rest of this task: a multi-email run must not
// re-ask for an address the user already authorized, and an explicit
@@ -28739,6 +28770,71 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
return true;
}
+ /**
+ * Stage recipient consent for a clarification that shows the recipients the
+ * page addresses right now. The guard normally stages consent when it blocks
+ * a send, and each clarify uses it up; without this, a recipient question
+ * asked before the first send (or asked again after a vague reply) could
+ * never bind, so the user was asked the same thing again and again. Only a
+ * read-only observation runs, only under a plan that already permits this
+ * message, and the send itself is still checked against the page.
+ */
+ async _stageRecipientConsentForQuestion(tabId, context) {
+ const guard = this._planExecutionGuards.get(tabId);
+ const target = normalizeMessageTarget(guard?.messaging);
+ if (!guard || !target || guard.pendingRecipientAuthorization
+ || guard.requiresSubmission !== true || guard.requiresStateChange !== true) return false;
+ const declared = context?.purpose === 'message_recipient' || context?.purpose === 'recipient_change';
+ if (!declared && !questionAsksAboutRecipient(context?.question)) return false;
+ let policy = null;
+ try { policy = getMessageRecipientGuardPolicy(await this._currentUrl(tabId)); } catch {}
+ if (!policy?.verifyActiveRecipient) return false;
+ const probe = await this._messageRecipientContentProbe(tabId, {
+ tool: 'observe_active_conversation',
+ args: {},
+ adapterName: policy.adapterName,
+ supportsRecipientSets: policy.supportsRecipientSets === true,
+ });
+ if (probe?.success !== true || probe?.conclusive !== true) return false;
+ const candidates = this._messageRecipientCandidates(probe);
+ const identityCountAccepted = policy.supportsRecipientSets === true ? candidates.length > 0 : candidates.length === 1;
+ if (!identityCountAccepted || !questionPresentsObservedRecipients(context?.question, candidates, declared)) return false;
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.pendingRecipientAuthorization) return false;
+ guard.observedRecipientCandidates = candidates;
+ guard.pendingRecipientAuthorization = target.target_kind === 'named' ? 'recipient_change' : true;
+ return true;
+ }
+
+ /**
+ * What the model must do after a reply that did not approve the recipient
+ * a blocked send would reach. Without this the generic "treat it as
+ * authoritative" note reads as approval, the retry is blocked again and the
+ * user is asked the same question until the run gives up.
+ */
+ _unboundRecipientClarificationNote(outcome = {}) {
+ const names = (Array.isArray(outcome?.observed) ? outcome.observed : [])
+ .map(item => String(item?.identity || item?.name || item || '').trim())
+ .filter(Boolean)
+ .slice(0, 3);
+ const label = names.join(', ');
+ const named = label ? ` ("${label}")` : '';
+ const example = label
+ ? ` For example: clarify({ question: "Send it to ${label}?", options: ["${label}", "Cancel"] }).`
+ : '';
+ switch (outcome?.reason) {
+ case 'answer_refused':
+ return `The reply reads as declining or correcting the recipient this send would reach${named}, so nothing was authorized or sent. If the user named someone else, open that conversation and continue there. If it is unclear whether they meant that recipient, ask once more with the exact name as an option.${example} Otherwise stop and report that the send was not authorized.`;
+ case 'answer_does_not_name_recipient':
+ return `The reply did not choose the recipient this send would reach${named}, so nothing was authorized or sent. Only an answer that picks that exact name approves it; a reply such as "yes" or "that's the right person" cannot. If the user meant that recipient, ask once more with the exact name in the question and as an option.${example} Otherwise stop and report that the send was not authorized.`;
+ case 'recipient_not_presented':
+ return `The question did not ask the user to approve sending to the recipient this send would reach${named}, so the reply cannot approve it and nothing was sent. Ask once with that exact name in the question and as an option.${example}`;
+ case 'no_pending_recipient':
+ return 'This is a direct reply from the user; continue the task with it in mind. It did not approve a recipient by itself: approval is recorded only when the question shows the exact recipient name the open conversation has, so if a send is blocked, ask then with the exact name the block reports.';
+ default:
+ return '';
+ }
+ }
+
_fallbackSubmitConfirmationInfo(host, tool, reason, summary = '') {
const normalizedHost = normalizeHost(host || '') || String(host || '').trim() || 'this site';
return {
@@ -40761,12 +40857,6 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
? 'recipient_change'
: (args?.purpose === 'message_recipient' ? 'message_recipient' : null));
const explicitRecipientQuestion = purpose === 'message_recipient' || purpose === 'recipient_change';
- const recipientBindingRequired = explicitRecipientQuestion
- || (!!clarificationGuard?.pendingRecipientAuthorization
- && this._isRecipientClarification({ question, options, reason, purpose },
- typeof clarificationGuard.pendingRecipientAuthorization === 'string'
- ? clarificationGuard.pendingRecipientAuthorization : 'message_recipient',
- clarificationGuard.observedRecipientCandidates || []));
const technicalRecipientReasons = new Set(['recipient_identity_unavailable', 'message_body_unverified',
'message_body_baseline_unavailable', 'recipient_dispatch_binding_unavailable']);
const technicalRecipientReason = technicalRecipientReasons.has(clarificationGuard?.messageRecipientTechnicalBlock)
@@ -40779,6 +40869,22 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
recipientBinding: { required: true, bound: false, reasonCode: technicalRecipientReason },
error: 'Recipient confirmation cannot repair the unresolved technical message guard. No clarification was shown. Re-read the active recipient and composer evidence; if it remains unavailable, report the blocker instead of requesting the same approval again.' };
}
+ // A question that shows the recipients the page addresses binds to what
+ // the page shows now, even before any send was blocked.
+ if (clarificationGuard && !clarificationGuard.pendingRecipientAuthorization) {
+ try { await this._stageRecipientConsentForQuestion(tabId, { question, options, reason, purpose }); } catch {}
+ }
+ const pendingRecipientCandidates = clarificationGuard?.observedRecipientCandidates || [];
+ const recipientBindingRequired = explicitRecipientQuestion
+ || (!!clarificationGuard?.pendingRecipientAuthorization
+ && (this._isRecipientClarification({ question, options, reason, purpose },
+ typeof clarificationGuard.pendingRecipientAuthorization === 'string'
+ ? clarificationGuard.pendingRecipientAuthorization : 'message_recipient',
+ pendingRecipientCandidates)
+ // A recipient question that cannot satisfy a pending recipient
+ // change must still report that it approved nothing.
+ || this._isRecipientClarification({ question, options, reason, purpose }, 'message_recipient',
+ pendingRecipientCandidates)));
const isResearchEscalation = purpose === 'research_escalation';
const requireExplicitAnswer = isResearchEscalation || args?.require_explicit_answer === true;
const researchRequest = isResearchEscalation ? repairClarifyText(normalizeResearchRequest(args?.research_request)) : '';
@@ -40899,8 +41005,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
// nothing, matching how research escalation treats those sources below.
// Every clarification outcome (human answer, timeout, auto) must consume
// the staged recipient consent so a later unrelated clarify does not inherit it.
+ const recipientOutcome = {};
const recipientBound = this._bindClarifiedMessageRecipient(tabId, answer, source,
- { question, options, reason, purpose, safeFirst: entrySafeFirst });
+ { question, options, reason, purpose, safeFirst: entrySafeFirst }, recipientOutcome);
const recipientBinding = recipientBindingRequired ? { required: true, bound: recipientBound,
...(!recipientBound ? { reasonCode: technicalRecipientReasons.has(clarificationGuard?.messageRecipientTechnicalBlock)
? clarificationGuard.messageRecipientTechnicalBlock : 'recipient_authorization_not_bound' } : {}) } : null;
@@ -40925,7 +41032,8 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
// Settings Instant auto-approve (headless / unattended). User policy — proceed.
note = 'This answer was auto-selected because Clarify timeout is set to Instant (source=auto). The user intentionally configured unattended auto-approve; treat this answer as the chosen default and continue the task. Do not re-ask the same question. Put the intended default first in options when Instant mode may be on.';
} else {
- note = 'This is a direct reply from the user. Treat it as authoritative for the question you asked; do not re-ask. Continue the task with this answer in mind.';
+ note = (recipientBinding && !recipientBound && this._unboundRecipientClarificationNote(recipientOutcome))
+ || 'This is a direct reply from the user. Treat it as authoritative for the question you asked; do not re-ask. Continue the task with this answer in mind.';
}
return {
success: true,
diff --git a/src/chrome/src/agent/message-recipient-guard.js b/src/chrome/src/agent/message-recipient-guard.js
index d1d31b44b..02ed63881 100644
--- a/src/chrome/src/agent/message-recipient-guard.js
+++ b/src/chrome/src/agent/message-recipient-guard.js
@@ -221,6 +221,112 @@ export function answerNamesAllObservedRecipients(normalizedAnswer, observedCandi
return search(0, []);
}
+// Words that make a displayed question about where a message goes: sending,
+// sharing or forwarding it, or which person, account or conversation gets it.
+// Stems match at a word start so inflected forms count; scripts written
+// without spaces between words match anywhere.
+const RECIPIENT_QUESTION_WORD = new RegExp(`(?<![\\p{L}\\p{N}])(?:${[
+ 'send', 'sent', 'messag', 'deliver', 'forward', 'shar(?:e|ing)', 'repl(?:y|ies|ying)', 'recipient', 'contact',
+ 'conversa', 'chat', 'dms?(?![\\p{L}])', 'e-?mail', 'mail', 'thread', 'inbox', 'person', 'people', 'user', 'account',
+ 'whom', 'address',
+ 'gönder', 'ilet', 'yolla', 'mesaj', 'paylaş', 'alıcı', 'kişi', 'kullanıcı', 'hesab', 'hesap', 'sohbet', 'konuşma',
+ 'schick', 'nachricht', 'empfänger', 'weiterleit', 'teilen',
+ 'envi[aáeéoó]', 'envoy', 'envoi', 'mensaj', 'mensag', 'messagg', 'destinat', 'compart', 'partag', 'partilh',
+ 'condivid', 'inoltr', 'reenv', 'transf[eé]r', 'invia', 'invio', 'pessoa', 'contatt',
+ 'stuur', 'verstuur', 'verzend', 'bericht', 'ontvanger', 'delen',
+ 'wyśl', 'wysł', 'wiadomo', 'odbiorc', 'udostępn', 'zpráv', 'příjemc',
+ 'отправ', 'посла', 'пошл', 'сообщен', 'пересла', 'получател', 'собеседник', 'надісл', 'повідомл', 'одержувач',
+ 'kirim', 'pesan', 'penerima', 'bagikan', 'gửi', 'tin nhắn', 'người nhận', 'chia sẻ',
+ 'أرسل', 'ارسل', 'إرسال', 'ارسال', 'رسالة', 'مستلم', 'المستلم', 'بفرست', 'پیام', 'گیرنده',
+ 'שלח', 'הודעה', 'נמען', 'भेज', 'संदेश', 'प्राप्तकर्ता',
+].join('|')})`, 'iu');
+const RECIPIENT_QUESTION_UNSPACED = /送|发|發|传|傳|消息|信息|訊息|收件|联系人|聯絡人|メッセージ|宛|보내|전송|메시지|받는|ส่ง|ข้อความ/u;
+
+/**
+ * Does a clarification question show the user the exact recipients the page
+ * addresses, and ask about them as recipients?
+ *
+ * A recipient is authorized only by an answer that names it, given to a
+ * question that showed it. The question must name every observed recipient
+ * itself (options alone do not show where the message goes) and either ask
+ * about sending to them or be declared a recipient question by its caller.
+ */
+export function questionPresentsObservedRecipients(question, observedCandidates, declaredRecipientQuestion = false) {
+ const text = String(question ?? '');
+ if (!text.trim() || text.length > 2000) return false;
+ if (!answerNamesAllObservedRecipients(text, observedCandidates)) return false;
+ return declaredRecipientQuestion === true || questionAsksAboutRecipient(text);
+}
+
+/** Does a question ask about sending a message or about who receives it? */
+export function questionAsksAboutRecipient(question) {
+ const normalized = normalizeRecipientAnswer(question).replace(/\u0307/g, '');
+ if (!normalized || normalized.length > 2000) return false;
+ return RECIPIENT_QUESTION_WORD.test(normalized) || RECIPIENT_QUESTION_UNSPACED.test(normalized);
+}
+
+// A reply that refuses, cancels or points somewhere else. Naming a recipient
+// inside such a reply ("No, not Mallory") is never approval of that recipient.
+const ANSWER_REFUSAL = new RegExp(`(?<![\\p{L}\\p{N}])(?:${[
+ 'no', 'nope', 'nah', 'not', 'never', 'none', 'nobody', 'no\\s*one', 'nothing', 'neither', 'nor',
+ "don[’']?t", "doesn[’']?t", "didn[’']?t", "won[’']?t", "wouldn[’']?t", "shouldn[’']?t", "can[’']?t", 'cannot',
+ "isn[’']?t", "wasn[’']?t", "aren[’']?t", 'stop', 'cancel\\p{L}*', 'abort\\p{L}*', 'reject\\p{L}*', 'refuse\\p{L}*', 'deny',
+ 'wrong', 'incorrect', 'mistake\\p{L}*', 'other', 'another', 'different', 'else',
+ 'hayır', 'hayir', 'değil', 'degil', 'yanlış', 'yanlis', 'iptal', 'vazgeç\\p{L}*', 'vazgec\\p{L}*', 'gönderme\\p{L}*',
+ 'gonderme\\p{L}*', 'yollama\\p{L}*', 'istemiyorum', 'olmaz', 'yok', 'başka', 'baska', 'diğer', 'diger',
+ 'nein', 'nicht', 'kein\\p{L}*', 'falsch', 'abbrechen', 'stopp', 'andere[mnrs]?',
+ 'não', 'nao', 'non', 'nunca', 'jamais', 'mai', 'ningun[oa]?', 'nadie', 'nada', 'nenhum\\p{L}*', 'nessun\\p{L}*',
+ 'aucun\\p{L}*', 'pas', 'cancelar', 'annuler', 'annulla', 'incorrect[oa]', 'equivocad[oa]', 'errad[oa]',
+ 'sbagliat[oa]', 'faux', 'otr[oa]', 'outr[oa]', 'altr[oa]', 'autre\\p{L}*',
+ 'nee', 'niet', 'geen', 'annuleren', 'verkeerd\\p{L}*',
+ 'nie', 'anuluj', 'inn[ya]', 'нет', 'не', 'ни', 'никому', 'никогда', 'отмен\\p{L}*', 'неправильн\\p{L}*', 'друг(?:ой|ому|ая|ие|ую|ого|им)',
+ 'ні', 'скасу\\p{L}*', 'tidak', 'bukan', 'jangan', 'batal\\p{L}*', 'salah', 'không', 'đừng', 'hủy', 'sai',
+ 'لا', 'ليس', 'إلغاء', 'الغاء', 'خطأ', 'לא', 'בטל', 'नहीं', 'मत', 'रद्द',
+].join('|')})(?![\\p{L}\\p{N}])`, 'iu');
+const ANSWER_REFUSAL_UNSPACED = /不要|不是|不对|不對|别|別|取消|错|錯|いいえ|違う|ちがう|キャンセル|ないで|아니|취소|마세요|말아/u;
+
+/**
+ * Does the user's reply refuse, cancel or redirect the send rather than
+ * approve it? The observed recipient names themselves are removed first, so a
+ * contact called "No Limits" is still approvable by name.
+ */
+export function answerRefusesRecipient(answer, observedCandidates = []) {
+ let text = normalizeRecipientAnswer(answer);
+ if (!text || text.length > 8192) return !!text;
+ const aliases = [];
+ for (const candidate of Array.isArray(observedCandidates) ? observedCandidates.slice(0, 16) : []) {
+ const identity = typeof candidate === 'string' ? candidate : (candidate?.identity ?? candidate?.recipient);
+ for (const alias of [identity, ...(Array.isArray(candidate?.aliases) ? candidate.aliases.slice(0, 16) : [])]) {
+ const normalized = normalizeRecipientIdentity(alias);
+ if (normalized && !aliases.includes(normalized)) aliases.push(normalized);
+ }
+ }
+ aliases.sort((left, right) => right.length - left.length);
+ for (const alias of aliases) {
+ for (const span of findCandidateAnswerSpans(text, alias).reverse()) {
+ text = `${text.slice(0, span.start)} ${text.slice(span.end)}`;
+ }
+ }
+ // A non-Turkish locale lowercases "İ" to "i" plus a combining dot.
+ text = text.replace(/\u0307/g, '');
+ return ANSWER_REFUSAL.test(text) || ANSWER_REFUSAL_UNSPACED.test(text);
+}
+
+/**
+ * Does the user's reply grant every remaining send of the task at once, as
+ * the "Send all remaining messages in this task without asking again" option
+ * does? A refusal ("Cancel all") is never a grant; check that first.
+ */
+export function answerGrantsAllRemainingSends(answer) {
+ const text = normalizeRecipientAnswer(answer);
+ if (!text || text.length > 2000) return false;
+ const bare = text.replace(/[\p{P}\p{S}\s]+/gu, ' ').trim();
+ return /(?<![\p{L}\p{N}])(?:send|allow|approve|authori[sz]e)\s+(?:(?:them|these|those|it)\s+)?all(?![\p{L}\p{N}])/u.test(text)
+ || /(?<![\p{L}\p{N}])all\s+(?:remaining|the\s+rest|of\s+them)(?![\p{L}\p{N}])/u.test(text)
+ || /(?<![\p{L}\p{N}])(?:hepsin[ei]|tümün[eü]|herkese)\s+(?:gönder|yolla|ilet)/u.test(text)
+ || /^(?:all|everything|everyone|all of them|hepsi|hepsine|hepsini|tümü|tümüne|alle|todos|todas|tous|tutti|все|全部|すべて|모두)$/u.test(bare);
+}
+
export function messageTargetMatchesObservedIdentities(target, candidates) {
const normalizedTarget = normalizeMessageTarget(target);
const recipients = new Map();
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 1f3415fe5..f5db36096 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -68,7 +68,7 @@ import {
workflowControlLabelIsRequested,
workflowRequiredRowsAreProcessed,
} from './adapter-workflow-evidence.js';
-import { answerNamesAllObservedRecipients, answerNamesIdentity, messageTargetMatchesObservedIdentities, messageRecipientUploadSourceKey, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity, resolveClarifiedRecipients } from './message-recipient-guard.js';
+import { answerGrantsAllRemainingSends, answerNamesAllObservedRecipients, answerNamesIdentity, answerRefusesRecipient, messageTargetMatchesObservedIdentities, messageRecipientUploadSourceKey, normalizeMessageTarget, normalizeRecipientAnswer, normalizeRecipientIdentity, questionAsksAboutRecipient, questionPresentsObservedRecipients, resolveClarifiedRecipients } from './message-recipient-guard.js';
import { advanceChatSession, chatRunEndedNotice, createOwnedNativeChatReadRepair, createChatSession, decideChatSend, markChatSendPending, normalizeChatSession, normalizeChatSnapshot, normalizeNativeOpaqueBaseline, serializeChatSession } from './chat-workflow.js';
import {
fetchUrl,
@@ -26003,28 +26003,65 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const missingLinkedInComposer = policy.adapterName === 'linkedin'
&& probe?.success === true && probe?.composerAvailable === false;
+ const inconclusive = probe?.success !== true || probe?.conclusive !== true || probe?.messageSend !== true;
+ // Human-readable view of who the page actually addresses, so a mismatch
+ // block can name the exact observed recipient instead of asking the user to
+ // re-confirm blindly.
+ const observedRecipientLabel = (() => {
+ try {
+ return (this._messageRecipientCandidates(probe) || [])
+ .map(item => String(item?.identity || item?.name || item || '').trim())
+ .filter(Boolean)
+ .slice(0, 3)
+ .join(', ');
+ } catch {
+ return '';
+ }
+ })();
return {
success: false,
blocked: true,
noDispatch: true,
dispatched: false,
messageRecipientGuard: true,
- ...(missingLinkedInComposer ? { retryable: false } : {}),
- reasonCode: probe?.success !== true || probe?.conclusive !== true || probe?.messageSend !== true
- ? 'message_send_classification_inconclusive'
+ ...((missingLinkedInComposer || (!inconclusive && target)) ? { retryable: false } : {}),
+ reasonCode: inconclusive
+ ? (probe?.reasonCode || 'message_send_classification_inconclusive')
: (target ? 'active_recipient_unverified' : 'authorized_recipient_missing'),
error: missingLinkedInComposer
- ? 'Message action blocked: no message composer is visible and this control is not a verified non-send action. Changing click targeting methods will not resolve this classification failure. Re-read the page to find a supported navigation or composer-opening control; if none is available, report the blocker instead of repeating the click.'
- : probe?.success !== true || probe?.conclusive !== true || probe?.messageSend !== true
+ ? (probe?.reasonCode === 'message_commit_without_composer'
+ ? 'Message send blocked: this control commits a message (for example "Send" / "Send without a note") but no active composer or recipient could be verified. Changing click targeting methods will not help; ask the user to confirm the recipient or open the intended conversation first.'
+ : 'Message send blocked: no message composer is visible, so this send cannot be verified. Changing click targeting methods will not resolve this classification failure. Re-read the page to find a supported navigation or composer-opening control; if none is available, report the blocker instead of repeating the click.')
+ : inconclusive
? 'Message action blocked: WebBrain could not conclusively resolve the target control and active composer. Re-read the page and retry with an exact visible control or fresh ref_id.'
: target
- ? 'Message send blocked: the active conversation does not exactly match the recipient authorized by the user. Select the intended conversation, re-read its visible header, then retry the send action.'
+ ? this._recipientMismatchGuidance(observedRecipientLabel, target)
: (guard?.requiresSubmission === false || guard?.requiresStateChange === false || !target
? 'Message send blocked: the current plan does not authorize sending or submitting messages. Return the draft in chat or ask the user to authorize sending before attempting delivery.'
: 'Message send blocked: the current task has no structured recipient authorization. Ask the user to name the recipient or explicitly authorize the currently open conversation before retrying.'),
};
}
+ /**
+ * Model guidance for a send whose page-observed recipient is not the one
+ * the task authorized. It names both, prescribes one clarify that shows the
+ * exact observed name, and never suggests retrying without the user's pick:
+ * the guard only accepts a bound answer, so a bare retry is blocked again.
+ */
+ _recipientMismatchGuidance(observedRecipientLabel, target) {
+ const planned = normalizeMessageTarget(target)?.target_kind === 'named'
+ ? normalizeMessageTarget(target).recipients.map(recipient => recipient.identity).slice(0, 3).join(', ')
+ : '';
+ const name = observedRecipientLabel || '<observed address>';
+ return `Message send blocked: this send would go to ${observedRecipientLabel ? `"${observedRecipientLabel}"` : 'a recipient'}, which is not ${planned ? `exactly the recipient named for this task ("${planned}")` : 'the conversation authorized for this task'}, so nothing was dispatched. Do not retry with different targeting.
+Ask the user once whether to send it there. Put that exact name in the question and as an option, because authorization binds to what the page shows and a bare "yes" cannot authorize a send:
+clarify({ question: "Send it to ${name} instead?", options: ["${name}", "Cancel"] })
+If the task sends more than one message, also offer "Send all remaining messages in this task without asking again".
+- If they pick the name: that recipient is authorized for the rest of this task, so retry the send and continue normally.
+- If they pick "Send all remaining messages": every remaining send in this task is authorized, so keep going without asking again.
+- If they pick "Cancel": stop and report that the send was not authorized.`;
+ }
+
_isRecipientClarification(context, pendingType = 'message_recipient', observedCandidates = []) {
if (!context || typeof context !== 'object') return false;
const purpose = String(context.purpose || '').trim();
@@ -26038,7 +26075,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (pendingType === 'recipient_change') {
const changeWord = /(change|switch|different|instead|update|replace|another|new|更改|更换|切换|替换|换成)/i.test(questionText);
const targetWord = /(recipient|conversation|contact|send to|person|address|target|someone else|\b(?:to|cc|bcc|role|field)\b|收件人|联系人|发送)/i.test(questionText);
- return changeWord && targetWord;
+ if (changeWord && targetWord) return true;
+ // The user has to see where the message goes, not a particular wording.
+ // A question that names the recipients the page addresses and asks about
+ // sending to them ("Send the photo to Gamze Çömlekçi?") shows exactly
+ // that; the answer must still name the same page-observed recipients.
+ return questionPresentsObservedRecipients(context.question, observedCandidates,
+ purpose === 'message_recipient' || purpose === 'recipient_change');
}
// Check if the clarify question, reason, or options explicitly mention any observed candidate identity or alias
@@ -26084,9 +26127,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
* messaging (requiresSubmission=true and requiresStateChange=true) and must
* match the specific clarification purpose or question.
*/
- _bindClarifiedMessageRecipient(tabId, answer, source = 'user', clarifyContext = null) {
+ _bindClarifiedMessageRecipient(tabId, answer, source = 'user', clarifyContext = null, outcome = null) {
+ // `outcome`, when given, receives why nothing was bound so the clarify
+ // result can tell the model what the user actually needs to see.
+ const unbound = reason => {
+ if (outcome && typeof outcome === 'object') outcome.reason = reason;
+ return false;
+ };
const guard = this._planExecutionGuards.get(tabId);
- if (!guard) return false;
+ if (!guard) return unbound('no_pending_recipient');
// Read and clear together. The consent the guard staged belongs to exactly
// one clarify, the one its own error told the model to ask; every later
// question is a different question and must not inherit it. Clearing on
@@ -26105,28 +26154,40 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: [];
guard.pendingRecipientAuthorization = false;
guard.observedRecipientCandidates = null;
- if (!pending || !pendingType || observed.length === 0) return false;
- if (!answer || source === 'timeout' || source === 'auto') return false;
+ if (outcome && typeof outcome === 'object') outcome.observed = observed.slice(0, 16);
+ if (!pending || !pendingType || observed.length === 0) return unbound('no_pending_recipient');
+ if (!answer || source === 'timeout' || source === 'auto') return unbound('no_user_answer');
if (pendingType === 'recipient_change') {
if (!clarifyContext || !this._isRecipientClarification(clarifyContext, 'recipient_change', observed)) {
- return false;
+ return unbound('recipient_not_presented');
}
} else if (clarifyContext && !this._isRecipientClarification(clarifyContext, 'message_recipient', observed)) {
- return false;
+ return unbound('recipient_not_presented');
}
const normalizedAnswer = normalizeRecipientAnswer(answer);
- if (!normalizedAnswer) return false;
- const allowAllSends = /(?:^|[^\p{L}])(?:all|everything|any|every|allow\s+all|send\s+all)(?:[^\p{L}]|$)/iu
- .test(normalizedAnswer);
- if (!allowAllSends && !answerNamesAllObservedRecipients(normalizedAnswer, observed)) return false;
+ if (!normalizedAnswer) return unbound('no_user_answer');
+ // A refusal or redirect is never approval, even when it names the
+ // recipient ("No, not Mallory") or says "all" ("Cancel all").
+ if (answerRefusesRecipient(answer, observed)) return unbound('answer_refused');
+ // A user may authorize the rest of the task in one answer instead of one
+ // recipient at a time (multi-email / multi-recipient runs). This is still
+ // the USER's grant: it can only arrive as a real clarify answer, never as
+ // model text, and it still requires a page-observed recipient to exist.
+ const allowAllSends = answerGrantsAllRemainingSends(normalizedAnswer);
+ if (!allowAllSends && !answerNamesAllObservedRecipients(normalizedAnswer, observed)) {
+ return unbound('answer_does_not_name_recipient');
+ }
const resolvedRecipients = allowAllSends
? observed
.map(item => ({ identity: item?.identity || item, role: item?.role || 'to' }))
.filter(recipient => recipient.identity)
: resolveClarifiedRecipients(observed, guard.messaging, clarifyContext, answer);
const target = normalizeMessageTarget({ target_kind: 'named', recipients: resolvedRecipients });
- if (!target) return false;
+ if (!target) return unbound('answer_does_not_name_recipient');
guard.messaging = target;
+ // Remember the grant for the rest of this task: a multi-email run must not
+ // re-ask for an address the user already authorized, and an explicit
+ // "send all remaining" answer covers the sends that come after it.
const approved = Array.isArray(guard.approvedRecipients) ? guard.approvedRecipients.slice() : [];
for (const recipient of target.recipients || []) {
const identity = normalizeRecipientIdentity(recipient?.identity || recipient);
@@ -26137,6 +26198,71 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return true;
}
+ /**
+ * Stage recipient consent for a clarification that shows the recipients the
+ * page addresses right now. The guard normally stages consent when it blocks
+ * a send, and each clarify uses it up; without this, a recipient question
+ * asked before the first send (or asked again after a vague reply) could
+ * never bind, so the user was asked the same thing again and again. Only a
+ * read-only observation runs, only under a plan that already permits this
+ * message, and the send itself is still checked against the page.
+ */
+ async _stageRecipientConsentForQuestion(tabId, context) {
+ const guard = this._planExecutionGuards.get(tabId);
+ const target = normalizeMessageTarget(guard?.messaging);
+ if (!guard || !target || guard.pendingRecipientAuthorization
+ || guard.requiresSubmission !== true || guard.requiresStateChange !== true) return false;
+ const declared = context?.purpose === 'message_recipient' || context?.purpose === 'recipient_change';
+ if (!declared && !questionAsksAboutRecipient(context?.question)) return false;
+ let policy = null;
+ try { policy = getMessageRecipientGuardPolicy(await this._currentUrl(tabId)); } catch {}
+ if (!policy?.verifyActiveRecipient) return false;
+ const probe = await this._messageRecipientContentProbe(tabId, {
+ tool: 'observe_active_conversation',
+ args: {},
+ adapterName: policy.adapterName,
+ supportsRecipientSets: policy.supportsRecipientSets === true,
+ });
+ if (probe?.success !== true || probe?.conclusive !== true) return false;
+ const candidates = this._messageRecipientCandidates(probe);
+ const identityCountAccepted = policy.supportsRecipientSets === true ? candidates.length > 0 : candidates.length === 1;
+ if (!identityCountAccepted || !questionPresentsObservedRecipients(context?.question, candidates, declared)) return false;
+ if (this._planExecutionGuards.get(tabId) !== guard || guard.pendingRecipientAuthorization) return false;
+ guard.observedRecipientCandidates = candidates;
+ guard.pendingRecipientAuthorization = target.target_kind === 'named' ? 'recipient_change' : true;
+ return true;
+ }
+
+ /**
+ * What the model must do after a reply that did not approve the recipient
+ * a blocked send would reach. Without this the generic "treat it as
+ * authoritative" note reads as approval, the retry is blocked again and the
+ * user is asked the same question until the run gives up.
+ */
+ _unboundRecipientClarificationNote(outcome = {}) {
+ const names = (Array.isArray(outcome?.observed) ? outcome.observed : [])
+ .map(item => String(item?.identity || item?.name || item || '').trim())
+ .filter(Boolean)
+ .slice(0, 3);
+ const label = names.join(', ');
+ const named = label ? ` ("${label}")` : '';
+ const example = label
+ ? ` For example: clarify({ question: "Send it to ${label}?", options: ["${label}", "Cancel"] }).`
+ : '';
+ switch (outcome?.reason) {
+ case 'answer_refused':
+ return `The reply reads as declining or correcting the recipient this send would reach${named}, so nothing was authorized or sent. If the user named someone else, open that conversation and continue there. If it is unclear whether they meant that recipient, ask once more with the exact name as an option.${example} Otherwise stop and report that the send was not authorized.`;
+ case 'answer_does_not_name_recipient':
+ return `The reply did not choose the recipient this send would reach${named}, so nothing was authorized or sent. Only an answer that picks that exact name approves it; a reply such as "yes" or "that's the right person" cannot. If the user meant that recipient, ask once more with the exact name in the question and as an option.${example} Otherwise stop and report that the send was not authorized.`;
+ case 'recipient_not_presented':
+ return `The question did not ask the user to approve sending to the recipient this send would reach${named}, so the reply cannot approve it and nothing was sent. Ask once with that exact name in the question and as an option.${example}`;
+ case 'no_pending_recipient':
+ return 'This is a direct reply from the user; continue the task with it in mind. It did not approve a recipient by itself: approval is recorded only when the question shows the exact recipient name the open conversation has, so if a send is blocked, ask then with the exact name the block reports.';
+ default:
+ return '';
+ }
+ }
+
_fallbackSubmitConfirmationInfo(host, tool, reason, summary = '') {
const normalizedHost = normalizeHost(host || '') || String(host || '').trim() || 'this site';
return {
@@ -37096,12 +37222,6 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? 'recipient_change'
: (args?.purpose === 'message_recipient' ? 'message_recipient' : null));
const explicitRecipientQuestion = purpose === 'message_recipient' || purpose === 'recipient_change';
- const recipientBindingRequired = explicitRecipientQuestion
- || (!!clarificationGuard?.pendingRecipientAuthorization
- && this._isRecipientClarification({ question, options, reason, purpose },
- typeof clarificationGuard.pendingRecipientAuthorization === 'string'
- ? clarificationGuard.pendingRecipientAuthorization : 'message_recipient',
- clarificationGuard.observedRecipientCandidates || []));
const technicalRecipientReasons = new Set(['recipient_identity_unavailable', 'message_body_unverified',
'message_body_baseline_unavailable', 'recipient_dispatch_binding_unavailable']);
const technicalRecipientReason = technicalRecipientReasons.has(clarificationGuard?.messageRecipientTechnicalBlock)
@@ -37114,6 +37234,22 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
recipientBinding: { required: true, bound: false, reasonCode: technicalRecipientReason },
error: 'Recipient confirmation cannot repair the unresolved technical message guard. No clarification was shown. Re-read the active recipient and composer evidence; if it remains unavailable, report the blocker instead of requesting the same approval again.' };
}
+ // A question that shows the recipients the page addresses binds to what
+ // the page shows now, even before any send was blocked.
+ if (clarificationGuard && !clarificationGuard.pendingRecipientAuthorization) {
+ try { await this._stageRecipientConsentForQuestion(tabId, { question, options, reason, purpose }); } catch {}
+ }
+ const pendingRecipientCandidates = clarificationGuard?.observedRecipientCandidates || [];
+ const recipientBindingRequired = explicitRecipientQuestion
+ || (!!clarificationGuard?.pendingRecipientAuthorization
+ && (this._isRecipientClarification({ question, options, reason, purpose },
+ typeof clarificationGuard.pendingRecipientAuthorization === 'string'
+ ? clarificationGuard.pendingRecipientAuthorization : 'message_recipient',
+ pendingRecipientCandidates)
+ // A recipient question that cannot satisfy a pending recipient
+ // change must still report that it approved nothing.
+ || this._isRecipientClarification({ question, options, reason, purpose }, 'message_recipient',
+ pendingRecipientCandidates)));
const isResearchEscalation = purpose === 'research_escalation';
const requireExplicitAnswer = isResearchEscalation || args?.require_explicit_answer === true;
const researchRequest = isResearchEscalation ? repairClarifyText(normalizeResearchRequest(args?.research_request)) : '';
@@ -37234,8 +37370,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// nothing, matching how research escalation treats those sources below.
// Every clarification outcome (human answer, timeout, auto) must consume
// the staged recipient consent so a later unrelated clarify does not inherit it.
+ const recipientOutcome = {};
const recipientBound = this._bindClarifiedMessageRecipient(tabId, answer, source,
- { question, options, reason, purpose, safeFirst: entrySafeFirst });
+ { question, options, reason, purpose, safeFirst: entrySafeFirst }, recipientOutcome);
const recipientBinding = recipientBindingRequired ? { required: true, bound: recipientBound,
...(!recipientBound ? { reasonCode: technicalRecipientReasons.has(clarificationGuard?.messageRecipientTechnicalBlock)
? clarificationGuard.messageRecipientTechnicalBlock : 'recipient_authorization_not_bound' } : {}) } : null;
@@ -37260,7 +37397,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// Settings Instant auto-approve (headless / unattended). User policy — proceed.
note = 'This answer was auto-selected because Clarify timeout is set to Instant (source=auto). The user intentionally configured unattended auto-approve; treat this answer as the chosen default and continue the task. Do not re-ask the same question. Put the intended default first in options when Instant mode may be on.';
} else {
- note = 'This is a direct reply from the user. Treat it as authoritative for the question you asked; do not re-ask. Continue the task with this answer in mind.';
+ note = (recipientBinding && !recipientBound && this._unboundRecipientClarificationNote(recipientOutcome))
+ || 'This is a direct reply from the user. Treat it as authoritative for the question you asked; do not re-ask. Continue the task with this answer in mind.';
}
return {
success: true,
diff --git a/src/firefox/src/agent/message-recipient-guard.js b/src/firefox/src/agent/message-recipient-guard.js
index d1d31b44b..02ed63881 100644
--- a/src/firefox/src/agent/message-recipient-guard.js
+++ b/src/firefox/src/agent/message-recipient-guard.js
@@ -221,6 +221,112 @@ export function answerNamesAllObservedRecipients(normalizedAnswer, observedCandi
return search(0, []);
}
+// Words that make a displayed question about where a message goes: sending,
+// sharing or forwarding it, or which person, account or conversation gets it.
+// Stems match at a word start so inflected forms count; scripts written
+// without spaces between words match anywhere.
+const RECIPIENT_QUESTION_WORD = new RegExp(`(?<![\\p{L}\\p{N}])(?:${[
+ 'send', 'sent', 'messag', 'deliver', 'forward', 'shar(?:e|ing)', 'repl(?:y|ies|ying)', 'recipient', 'contact',
+ 'conversa', 'chat', 'dms?(?![\\p{L}])', 'e-?mail', 'mail', 'thread', 'inbox', 'person', 'people', 'user', 'account',
+ 'whom', 'address',
+ 'gönder', 'ilet', 'yolla', 'mesaj', 'paylaş', 'alıcı', 'kişi', 'kullanıcı', 'hesab', 'hesap', 'sohbet', 'konuşma',
+ 'schick', 'nachricht', 'empfänger', 'weiterleit', 'teilen',
+ 'envi[aáeéoó]', 'envoy', 'envoi', 'mensaj', 'mensag', 'messagg', 'destinat', 'compart', 'partag', 'partilh',
+ 'condivid', 'inoltr', 'reenv', 'transf[eé]r', 'invia', 'invio', 'pessoa', 'contatt',
+ 'stuur', 'verstuur', 'verzend', 'bericht', 'ontvanger', 'delen',
+ 'wyśl', 'wysł', 'wiadomo', 'odbiorc', 'udostępn', 'zpráv', 'příjemc',
+ 'отправ', 'посла', 'пошл', 'сообщен', 'пересла', 'получател', 'собеседник', 'надісл', 'повідомл', 'одержувач',
+ 'kirim', 'pesan', 'penerima', 'bagikan', 'gửi', 'tin nhắn', 'người nhận', 'chia sẻ',
+ 'أرسل', 'ارسل', 'إرسال', 'ارسال', 'رسالة', 'مستلم', 'المستلم', 'بفرست', 'پیام', 'گیرنده',
+ 'שלח', 'הודעה', 'נמען', 'भेज', 'संदेश', 'प्राप्तकर्ता',
+].join('|')})`, 'iu');
+const RECIPIENT_QUESTION_UNSPACED = /送|发|發|传|傳|消息|信息|訊息|收件|联系人|聯絡人|メッセージ|宛|보내|전송|메시지|받는|ส่ง|ข้อความ/u;
+
+/**
+ * Does a clarification question show the user the exact recipients the page
+ * addresses, and ask about them as recipients?
+ *
+ * A recipient is authorized only by an answer that names it, given to a
+ * question that showed it. The question must name every observed recipient
+ * itself (options alone do not show where the message goes) and either ask
+ * about sending to them or be declared a recipient question by its caller.
+ */
+export function questionPresentsObservedRecipients(question, observedCandidates, declaredRecipientQuestion = false) {
+ const text = String(question ?? '');
+ if (!text.trim() || text.length > 2000) return false;
+ if (!answerNamesAllObservedRecipients(text, observedCandidates)) return false;
+ return declaredRecipientQuestion === true || questionAsksAboutRecipient(text);
+}
+
+/** Does a question ask about sending a message or about who receives it? */
+export function questionAsksAboutRecipient(question) {
+ const normalized = normalizeRecipientAnswer(question).replace(/\u0307/g, '');
+ if (!normalized || normalized.length > 2000) return false;
+ return RECIPIENT_QUESTION_WORD.test(normalized) || RECIPIENT_QUESTION_UNSPACED.test(normalized);
+}
+
+// A reply that refuses, cancels or points somewhere else. Naming a recipient
+// inside such a reply ("No, not Mallory") is never approval of that recipient.
+const ANSWER_REFUSAL = new RegExp(`(?<![\\p{L}\\p{N}])(?:${[
+ 'no', 'nope', 'nah', 'not', 'never', 'none', 'nobody', 'no\\s*one', 'nothing', 'neither', 'nor',
+ "don[’']?t", "doesn[’']?t", "didn[’']?t", "won[’']?t", "wouldn[’']?t", "shouldn[’']?t", "can[’']?t", 'cannot',
+ "isn[’']?t", "wasn[’']?t", "aren[’']?t", 'stop', 'cancel\\p{L}*', 'abort\\p{L}*', 'reject\\p{L}*', 'refuse\\p{L}*', 'deny',
+ 'wrong', 'incorrect', 'mistake\\p{L}*', 'other', 'another', 'different', 'else',
+ 'hayır', 'hayir', 'değil', 'degil', 'yanlış', 'yanlis', 'iptal', 'vazgeç\\p{L}*', 'vazgec\\p{L}*', 'gönderme\\p{L}*',
+ 'gonderme\\p{L}*', 'yollama\\p{L}*', 'istemiyorum', 'olmaz', 'yok', 'başka', 'baska', 'diğer', 'diger',
+ 'nein', 'nicht', 'kein\\p{L}*', 'falsch', 'abbrechen', 'stopp', 'andere[mnrs]?',
+ 'não', 'nao', 'non', 'nunca', 'jamais', 'mai', 'ningun[oa]?', 'nadie', 'nada', 'nenhum\\p{L}*', 'nessun\\p{L}*',
+ 'aucun\\p{L}*', 'pas', 'cancelar', 'annuler', 'annulla', 'incorrect[oa]', 'equivocad[oa]', 'errad[oa]',
+ 'sbagliat[oa]', 'faux', 'otr[oa]', 'outr[oa]', 'altr[oa]', 'autre\\p{L}*',
+ 'nee', 'niet', 'geen', 'annuleren', 'verkeerd\\p{L}*',
+ 'nie', 'anuluj', 'inn[ya]', 'нет', 'не', 'ни', 'никому', 'никогда', 'отмен\\p{L}*', 'неправильн\\p{L}*', 'друг(?:ой|ому|ая|ие|ую|ого|им)',
+ 'ні', 'скасу\\p{L}*', 'tidak', 'bukan', 'jangan', 'batal\\p{L}*', 'salah', 'không', 'đừng', 'hủy', 'sai',
+ 'لا', 'ليس', 'إلغاء', 'الغاء', 'خطأ', 'לא', 'בטל', 'नहीं', 'मत', 'रद्द',
+].join('|')})(?![\\p{L}\\p{N}])`, 'iu');
+const ANSWER_REFUSAL_UNSPACED = /不要|不是|不对|不對|别|別|取消|错|錯|いいえ|違う|ちがう|キャンセル|ないで|아니|취소|마세요|말아/u;
+
+/**
+ * Does the user's reply refuse, cancel or redirect the send rather than
+ * approve it? The observed recipient names themselves are removed first, so a
+ * contact called "No Limits" is still approvable by name.
+ */
+export function answerRefusesRecipient(answer, observedCandidates = []) {
+ let text = normalizeRecipientAnswer(answer);
+ if (!text || text.length > 8192) return !!text;
+ const aliases = [];
+ for (const candidate of Array.isArray(observedCandidates) ? observedCandidates.slice(0, 16) : []) {
+ const identity = typeof candidate === 'string' ? candidate : (candidate?.identity ?? candidate?.recipient);
+ for (const alias of [identity, ...(Array.isArray(candidate?.aliases) ? candidate.aliases.slice(0, 16) : [])]) {
+ const normalized = normalizeRecipientIdentity(alias);
+ if (normalized && !aliases.includes(normalized)) aliases.push(normalized);
+ }
+ }
+ aliases.sort((left, right) => right.length - left.length);
+ for (const alias of aliases) {
+ for (const span of findCandidateAnswerSpans(text, alias).reverse()) {
+ text = `${text.slice(0, span.start)} ${text.slice(span.end)}`;
+ }
+ }
+ // A non-Turkish locale lowercases "İ" to "i" plus a combining dot.
+ text = text.replace(/\u0307/g, '');
+ return ANSWER_REFUSAL.test(text) || ANSWER_REFUSAL_UNSPACED.test(text);
+}
+
+/**
+ * Does the user's reply grant every remaining send of the task at once, as
+ * the "Send all remaining messages in this task without asking again" option
+ * does? A refusal ("Cancel all") is never a grant; check that first.
+ */
+export function answerGrantsAllRemainingSends(answer) {
+ const text = normalizeRecipientAnswer(answer);
+ if (!text || text.length > 2000) return false;
+ const bare = text.replace(/[\p{P}\p{S}\s]+/gu, ' ').trim();
+ return /(?<![\p{L}\p{N}])(?:send|allow|approve|authori[sz]e)\s+(?:(?:them|these|those|it)\s+)?all(?![\p{L}\p{N}])/u.test(text)
+ || /(?<![\p{L}\p{N}])all\s+(?:remaining|the\s+rest|of\s+them)(?![\p{L}\p{N}])/u.test(text)
+ || /(?<![\p{L}\p{N}])(?:hepsin[ei]|tümün[eü]|herkese)\s+(?:gönder|yolla|ilet)/u.test(text)
+ || /^(?:all|everything|everyone|all of them|hepsi|hepsine|hepsini|tümü|tümüne|alle|todos|todas|tous|tutti|все|全部|すべて|모두)$/u.test(bare);
+}
+
export function messageTargetMatchesObservedIdentities(target, candidates) {
const normalizedTarget = normalizeMessageTarget(target);
const recipients = new Map();
diff --git a/test/message-recipient-clarify-binding.mjs b/test/message-recipient-clarify-binding.mjs
new file mode 100644
index 000000000..8af864c1b
--- /dev/null
+++ b/test/message-recipient-clarify-binding.mjs
@@ -0,0 +1,282 @@
+#!/usr/bin/env node
+// A user asked to send a photo to "gamze" on Instagram. The open conversation
+// was "Gamze Çömlekçi", so the recipient guard asked for confirmation, and the
+// user picked "Gamze Çömlekçi" twice. Both answers were discarded because the
+// model's question did not say "instead", and the run gave up. These cases run
+// the real content probe, guard, clarify tool and upload handler in both
+// builds: a question that shows the exact observed recipient binds the user's
+// pick, while refusals, vague replies and questions that hide the recipient
+// still authorize nothing.
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { chromium, firefox } from 'playwright';
+import { Agent as ChromeAgent } from '../src/chrome/src/agent/agent.js';
+import { Agent as FirefoxAgent } from '../src/firefox/src/agent/agent.js';
+import { cdpClient } from '../src/chrome/src/cdp/cdp-client.js';
+
+const tests = [];
+const bytes = Buffer.from('fixture photo bytes\n');
+const directory = await mkdtemp(path.join(tmpdir(), 'webbrain-recipient-clarify-'));
+const filePath = path.join(directory, 'photo.txt');
+await writeFile(filePath, bytes);
+const originalChrome = globalThis.chrome;
+const originalBrowser = globalThis.browser;
+const originalFetch = globalThis.fetch;
+const originalAttach = cdpClient.attach;
+const originalSend = cdpClient.sendCommand;
+const deliver = (page, message) => page.evaluate(message => new Promise(resolve => {
+ window.__wb_handler(message, {}, resolve);
+}), message);
+const call = (page, action, params) => deliver(page, { target: 'content', action, params });
+const RECIPIENT = 'Gamze Çömlekçi';
+
+async function setup(page, kind) {
+ await page.route('**/*', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html>' }));
+ await page.goto('https://www.instagram.com/direct/t/17848282661759097/');
+ await page.setContent(`<!doctype html><meta charset="utf-8"><style>
+ body{margin:0;font:16px sans-serif} #composer{position:fixed;left:340px;top:390px;width:430px;height:200px}
+ textarea{width:300px;height:90px} h2{position:fixed;left:350px;top:60px}
+ [role=button]{display:inline-block;width:32px;height:32px} svg{width:24px;height:24px}
+ </style><form id="composer"><h2 id="recipient">${RECIPIENT}</h2><textarea id="body" aria-label="Message"></textarea>
+ <input id="file" type="file" accept="audio/*,.mp4,.mov,.png,.jpg,.jpeg,.txt" multiple hidden>
+ <div role="button" tabindex="0" id="attach"><svg aria-label="Add Photo or Video" role="img"><path d="M0 0h24v24H0z"/></svg></div>
+ <div role="button" tabindex="0" id="titled"><svg role="img"><title>Choose an emoji</title><path d="M0 0h24v24H0z"/></svg></div>
+ <div role="button" tabindex="0" id="like"><svg aria-label="Like" role="img"><path d="M0 0h24v24H0z"/></svg></div>
+ <div role="button" tabindex="0" id="send-icon"><svg aria-label="Send" role="img"><path d="M0 0h24v24H0z"/></svg></div>
+ <div role="button" tabindex="0" id="mixed"><svg aria-label="Add Photo or Video" role="img"></svg><svg aria-label="Send" role="img"></svg></div>
+ <div role="button" tabindex="0" id="bare"><svg role="img"><path d="M0 0h24v24H0z"/></svg></div>
+ </form>`);
+ await page.evaluate(() => {
+ window.__wb_handlers = [];
+ const runtime = { onMessage: { addListener(fn) { window.__wb_handlers.push(fn); } }, getURL: path => path };
+ window.__wb_handler = (message, sender, response) => {
+ for (const handler of window.__wb_handlers) handler(message, sender, response);
+ };
+ window.chrome = { runtime }; window.browser = { runtime };
+ window.inputEvents = 0; window.changeEvents = 0; window.clicks = [];
+ document.querySelector('#file').addEventListener('input', () => window.inputEvents++);
+ document.querySelector('#file').addEventListener('change', () => window.changeEvents++);
+ for (const control of document.querySelectorAll('[role=button]')) {
+ control.addEventListener('click', () => window.clicks.push(control.id));
+ }
+ });
+ const sourceRoot = path.resolve('src', kind, 'src', 'content');
+ for (const file of ['file-upload-policy.js', 'rich-text-toolbar-heuristic.js', 'accessibility-tree.js', 'content.js']) {
+ await page.addScriptTag({ content: await readFile(path.join(sourceRoot, file), 'utf8') });
+ }
+ const api = {
+ runtime: {},
+ tabs: {
+ async get() { return { id: 71, url: page.url() }; },
+ async sendMessage(_, message) { return deliver(page, message); },
+ async executeScript(_, details) {
+ if (details.file) { await page.addScriptTag({ content: await readFile(path.resolve('src', kind, details.file), 'utf8') }); return []; }
+ return [await page.evaluate(source => window.eval(source), details.code)];
+ },
+ },
+ downloads: kind === 'chrome'
+ ? { async search(_, callback) { callback([{ id: 2073, state: 'complete', filename: filePath }]); } }
+ : { async search() {
+ return [{ id: 2073, state: 'complete', filename: filePath, url: 'https://assets.example.test/photo.txt', mime: 'text/plain' }];
+ } },
+ };
+ globalThis.chrome = api;
+ globalThis.browser = api;
+ globalThis.fetch = async () => new Response(bytes, { headers: { 'content-type': 'text/plain' } });
+ if (kind === 'chrome') {
+ const session = await page.context().newCDPSession(page);
+ cdpClient.attach = async () => {};
+ cdpClient.sendCommand = async (_, method, params = {}) => session.send(method, params);
+ }
+ const Agent = kind === 'chrome' ? ChromeAgent : FirefoxAgent;
+ const agent = new Agent({ getActive: () => ({ supportsVision: false }) });
+ agent._resolvePromptTier = () => 'full';
+ agent._currentUrl = async () => page.url();
+ // The planner kept the name the user typed: "gamze".
+ agent._planExecutionGuards.set(71, { messaging: { target_kind: 'named', recipients: [{ identity: 'gamze', role: 'to' }] },
+ requiresSubmission: true, requiresStateChange: true });
+ agent.clarifyTimeoutSec = -1;
+ agent._recordClarificationAuthorization = async () => true;
+ const args = { selector: 'input[type="file"][accept="audio/*,.mp4,.mov,.png,.jpg,.jpeg,.txt"][multiple]', downloadId: 2073 };
+ const bind = async () => {
+ const context = {};
+ const block = await agent._messageRecipientGuardBlock(71, 'upload_file', args, page.url(), context);
+ return { block, context };
+ };
+ // Shows one clarify card and answers it the way the user did.
+ const ask = async (clarifyArgs, answer, source = 'option') => {
+ const shown = [];
+ const result = await agent._executeToolImpl(71, 'clarify', clarifyArgs, (status, details) => {
+ if (status !== 'clarify') return;
+ shown.push(details);
+ agent._settleClarification(agent._pendingClarifications.get(71).get(details.clarifyId), { answer, source });
+ });
+ return { result, shown };
+ };
+ const state = () => page.evaluate(() => ({ inputs: window.inputEvents, changes: window.changeEvents,
+ count: document.querySelector('#file')?.files?.length || 0 }));
+ return { agent, args, bind, ask, state };
+}
+
+const traceQuestions = [
+ ['the first question from the trace', { options: [RECIPIENT, 'Cancel'], purpose: 'message_recipient',
+ question: `Send the photo to ${RECIPIENT} on Instagram?` }],
+ ['the second question from the trace', { purpose: 'recipient_change',
+ options: [RECIPIENT, 'Send all remaining emails in this task without asking again', 'Cancel'],
+ question: `Authorize sending the photo to ${RECIPIENT} on Instagram?` }],
+ ['the question the guard prescribes', { options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` }],
+ ['a Turkish question without a declared purpose', { options: [RECIPIENT, 'İptal'],
+ question: `Fotoğrafı ${RECIPIENT}'ye göndereyim mi?` }],
+ ['a declared recipient question in a language without listed send words', { options: [RECIPIENT, 'Ακύρωση'],
+ purpose: 'message_recipient', question: `${RECIPIENT}: σωστό άτομο;` }],
+];
+
+for (const kind of ['chrome', 'firefox']) {
+ const test = (name, fn) => tests.push({ kind, name: `${kind}: ${name}`, fn });
+
+ for (const [label, question] of traceQuestions) {
+ test(`${label} binds the picked recipient and the photo attaches`, async page => {
+ const f = await setup(page, kind);
+ const first = await f.bind();
+ assert.equal(first.block?.reasonCode, 'active_recipient_unverified', JSON.stringify(first.block));
+ assert.equal(first.block.retryable, false);
+ assert.match(first.block.error, new RegExp(`"${RECIPIENT}"`));
+ assert.match(first.block.error, /named for this task \("gamze"\)/);
+ assert.match(first.block.error, /clarify\(/);
+ assert.doesNotMatch(first.block.error, /emails|treat it as authorized/);
+ const { result, shown } = await f.ask(question, RECIPIENT);
+ assert.equal(shown.length, 1);
+ assert.deepEqual(result.recipientBinding, { required: true, bound: true }, JSON.stringify(result));
+ assert.match(result.note, /direct reply from the user/);
+ const second = await f.bind();
+ assert.equal(second.block, null, JSON.stringify(second.block));
+ assert.ok(second.context.messageRecipientDispatchBinding?.token);
+ const upload = await f.agent.executeTool(71, 'upload_file', f.args, null, second.context);
+ assert.equal(upload.success, true, JSON.stringify(upload));
+ assert.deepEqual(await f.state(), { inputs: 1, changes: 1, count: 1 });
+ // The approval holds for the rest of the task without asking again.
+ assert.equal((await f.bind()).block, null);
+ });
+ }
+
+ for (const [label, question, answer, source, reason] of [
+ ['a question that hides the recipient', { options: [RECIPIENT, 'Cancel'], question: 'Who should I send the photo to?' },
+ RECIPIENT, 'option', /did not ask the user to approve sending to the recipient[\s\S]*Gamze Çömlekçi/],
+ ['a question about something else', { options: [RECIPIENT, 'No'], question: `Is ${RECIPIENT} your colleague?` },
+ RECIPIENT, 'option', /did not ask the user to approve sending to the recipient/],
+ ['a reply that does not pick the name', { options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` },
+ "you're on the right user", 'text', /did not choose the recipient[\s\S]*ask once more with the exact name[\s\S]*Gamze Çömlekçi/],
+ ['a refusal that names the recipient', { options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` },
+ `No, not ${RECIPIENT}`, 'text', /declining or correcting/],
+ ['a Turkish refusal that names the recipient', { options: [RECIPIENT, 'İptal'], question: `${RECIPIENT}'ye göndereyim mi?` },
+ `Hayır, ${RECIPIENT} değil`, 'text', /declining or correcting/],
+ ['a cancellation that says "all"', { options: [RECIPIENT, 'Send all remaining messages in this task without asking again', 'Cancel'],
+ question: `Send it to ${RECIPIENT} instead?` }, 'Cancel all', 'text', /declining or correcting/],
+ ['an answer naming someone the page does not show', { options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` },
+ 'Gamze Yılmaz', 'text', /did not choose the recipient/],
+ ['a timed-out question', { options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` },
+ RECIPIENT, 'timeout', /AUTO-SELECTED|auto-selected/],
+ ]) {
+ test(`${label} authorizes nothing and attaches nothing`, async page => {
+ const f = await setup(page, kind);
+ assert.equal((await f.bind()).block?.reasonCode, 'active_recipient_unverified');
+ const { result } = await f.ask(question, answer, source);
+ assert.equal(result.recipientBinding?.bound, false, JSON.stringify(result));
+ assert.match(result.note, reason, result.note);
+ assert.equal(f.agent._planExecutionGuards.get(71).messageRecipientApprovedAll, undefined);
+ const retry = await f.bind();
+ assert.equal(retry.block?.reasonCode, 'active_recipient_unverified', JSON.stringify(retry.block));
+ const upload = await f.agent.executeTool(71, 'upload_file', f.args, null, retry.context);
+ assert.equal(upload.success, false, JSON.stringify(upload));
+ assert.deepEqual(await f.state(), { inputs: 0, changes: 0, count: 0 });
+ });
+ }
+
+ test('after a vague reply, asking again with the exact name binds without another blocked send', async page => {
+ const f = await setup(page, kind);
+ assert.equal((await f.bind()).block?.reasonCode, 'active_recipient_unverified');
+ const vague = await f.ask({ options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` }, 'yes', 'text');
+ assert.equal(vague.result.recipientBinding.bound, false);
+ // An unrelated question cannot pick up recipient consent.
+ const unrelated = await f.ask({ options: [RECIPIENT, 'Original size'], question: 'Which image size do you prefer?' }, RECIPIENT);
+ assert.equal(unrelated.result.recipientBinding, undefined);
+ assert.equal((await f.bind()).block?.reasonCode, 'active_recipient_unverified');
+ const picked = await f.ask({ options: [RECIPIENT, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` }, RECIPIENT);
+ assert.deepEqual(picked.result.recipientBinding, { required: true, bound: true });
+ assert.equal((await f.bind()).block, null);
+ });
+
+ test('a recipient question asked before the first send binds to the open conversation', async page => {
+ const f = await setup(page, kind);
+ const { result, shown } = await f.ask({ options: [RECIPIENT, 'Cancel'],
+ question: `Should I send the photo to ${RECIPIENT}?` }, RECIPIENT);
+ assert.equal(shown.length, 1);
+ assert.deepEqual(result.recipientBinding, { required: true, bound: true }, JSON.stringify(result));
+ const { block, context } = await f.bind();
+ assert.equal(block, null, JSON.stringify(block));
+ const upload = await f.agent.executeTool(71, 'upload_file', f.args, null, context);
+ assert.equal(upload.success, true, JSON.stringify(upload));
+ assert.deepEqual(await f.state(), { inputs: 1, changes: 1, count: 1 });
+ });
+
+ test('an early recipient question naming someone the page does not show binds nothing', async page => {
+ const f = await setup(page, kind);
+ const { result } = await f.ask({ options: ['Gamze Yılmaz', 'Cancel'], purpose: 'message_recipient',
+ question: 'Should I send the photo to Gamze Yılmaz?' }, 'Gamze Yılmaz');
+ assert.equal(result.recipientBinding.bound, false, JSON.stringify(result));
+ assert.equal((await f.bind()).block?.reasonCode, 'active_recipient_unverified');
+ assert.deepEqual(await f.state(), { inputs: 0, changes: 0, count: 0 });
+ });
+
+ test('an approved recipient does not cover a different conversation', async page => {
+ const f = await setup(page, kind);
+ await f.bind();
+ const { result } = await f.ask(traceQuestions[0][1], RECIPIENT);
+ assert.equal(result.recipientBinding.bound, true);
+ await page.evaluate(() => { document.querySelector('#recipient').textContent = 'Gamze Yılmaz'; });
+ const moved = await f.bind();
+ assert.equal(moved.block?.reasonCode, 'active_recipient_unverified', JSON.stringify(moved.block));
+ assert.match(moved.block.error, /"Gamze Yılmaz"/);
+ assert.deepEqual(await f.state(), { inputs: 0, changes: 0, count: 0 });
+ });
+
+ test('the send-all option approves the remaining sends; a refusal never does', async page => {
+ const f = await setup(page, kind);
+ await f.bind();
+ const all = 'Send all remaining messages in this task without asking again';
+ const { result } = await f.ask({ options: [RECIPIENT, all, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` }, all);
+ assert.equal(result.recipientBinding.bound, true);
+ assert.equal(f.agent._planExecutionGuards.get(71).messageRecipientApprovedAll, true);
+ for (const answer of ['Cancel all', "No, don't send it to any of them", 'Stop everything', 'all good']) {
+ f.agent._planExecutionGuards.set(71, { messaging: { target_kind: 'named', recipients: [{ identity: 'gamze', role: 'to' }] },
+ requiresSubmission: true, requiresStateChange: true });
+ await f.bind();
+ const refused = await f.ask({ options: [RECIPIENT, all, 'Cancel'], question: `Send it to ${RECIPIENT} instead?` }, answer, 'text');
+ assert.equal(refused.result.recipientBinding.bound, false, answer);
+ assert.equal(f.agent._planExecutionGuards.get(71).messageRecipientApprovedAll, undefined, answer);
+ }
+ });
+
+}
+
+let passed = 0, failed = 0;
+try {
+ for (const [kind, type] of [['chrome', chromium], ['firefox', firefox]]) {
+ const browser = await type.launch();
+ for (const t of tests.filter(t => t.kind === kind)) {
+ const page = await browser.newPage();
+ try { await t.fn(page); passed++; console.log(`✓ ${t.name}`); }
+ catch (error) { failed++; console.error(`✗ ${t.name}\n${error.stack}`); }
+ finally { await page.close(); }
+ }
+ await browser.close();
+ }
+} finally {
+ globalThis.chrome = originalChrome; globalThis.browser = originalBrowser; globalThis.fetch = originalFetch;
+ cdpClient.attach = originalAttach; cdpClient.sendCommand = originalSend;
+ await rm(directory, { recursive: true, force: true });
+}
+console.log(`${passed} passed, ${failed} failed`);
+process.exitCode = failed ? 1 : 0;
diff --git a/test/quality/recipient-clarify-mv3.mjs b/test/quality/recipient-clarify-mv3.mjs
new file mode 100644
index 000000000..36c3f7be9
--- /dev/null
+++ b/test/quality/recipient-clarify-mv3.mjs
@@ -0,0 +1,218 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import { chromium } from 'playwright';
+import { conformFixtureCompletionCall } from './completion-provider-contract.mjs';
+
+// The reported trace through the installed MV3 extension: the user asks to
+// send a photo to "gamze", the open direct thread is "Gamze Çömlekçi", the
+// recipient guard blocks the attachment and asks once, the user picks that
+// exact name, and the attachment is sent once. A second variant answers with
+// a refusal that names the recipient, which must send nothing. The thread,
+// photo and model are owned local fixtures; nothing leaves the host.
+const threadUrl = 'https://www.instagram.com/direct/t/17848282661759097/';
+const recipient = 'Gamze Çömlekçi';
+const question = `Send the photo to ${recipient} on Instagram?`;
+const selector = 'input[type="file"][accept="audio/*,.mp4,.mov,.png,.jpg,.jpeg"][multiple]';
+const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aS3kAAAAASUVORK5CYII=', 'base64');
+
+// Default settings advertise clarify without `purpose`; the trace's settings
+// (research escalation on) advertise it, and that model declared it.
+for (const [variant, answer, source, declared] of [['approved', recipient, 'option', false],
+ ['approved-declared-purpose', recipient, 'option', true], ['refused', `No, not ${recipient}`, 'user', false]]) {
+ await runVariant(variant, answer, source, declared);
+}
+
+async function runVariant(variant, answer, source, declared) {
+ const approved = variant.startsWith('approved');
+ const out = path.resolve(process.env.WEBBRAIN_QUALITY_ARTIFACTS
+ || `ci/artifacts/quality-audit-2026-10-07/recipient-clarify-mv3/${variant}`);
+ await fs.mkdir(out, { recursive: true });
+ const intent = { request_kind: 'execute', scope_relation: 'new', requires_state_change: true, requires_submission: true,
+ messaging: { target_kind: 'named', recipients: [{ identity: 'gamze', role: 'to' }] },
+ deliverables: ['Send the photo to Gamze via Instagram direct message'], completion_requirements: { download: false },
+ allows_planner_shaped_result: false, allows_app_state_tool_evidence: false, read_scope: 'visible_page',
+ summary: 'Attach the downloaded photo in the Gamze conversation.', steps: [{ id: '1', action: 'Attach the photo and verify it was sent.' }],
+ memory: { use_progress_ledger: false, progress_action: null }, scheduling: null, risks: [] };
+ const sends = [], providerRequests = [], clarifications = [];
+ let actionCalls = 0, judgeCalls = 0, blockedRemote = 0, base = '';
+ const completionRecovery = { reads: 0 };
+ const textOf = content => typeof content === 'string' ? content : Array.isArray(content)
+ ? content.filter(part => part?.type === 'text').map(part => part.text || '').join('\n') : '';
+ const downloadIdIn = input => {
+ for (const message of input.messages || []) {
+ if (message.role !== 'tool') continue;
+ const content = textOf(message.content);
+ try {
+ const data = JSON.parse(content.slice(content.indexOf('{'), content.lastIndexOf('}') + 1));
+ const id = data.downloads?.find(item => String(item.url || '').endsWith('/photo.png'))?.downloadId;
+ if (id != null) return id;
+ } catch {}
+ }
+ return undefined;
+ };
+ const steps = approved
+ ? ['download', 'list', 'upload', 'clarify', 'upload', 'tree', 'done']
+ : ['download', 'list', 'upload', 'clarify', 'upload', 'done'];
+ const server = http.createServer(async (request, response) => {
+ if (request.url === '/photo.png') {
+ response.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': png.length,
+ 'Content-Disposition': 'attachment; filename="photo.png"' });
+ response.end(png); return;
+ }
+ if (request.url !== '/v1/chat/completions') { response.writeHead(404).end(); return; }
+ let raw = ''; for await (const part of request) raw += part;
+ const input = JSON.parse(raw); providerRequests.push(input);
+ const system = textOf(input.messages?.[0]?.content);
+ let completion;
+ if (system.startsWith('Evaluate only the observable requirements of the genuine user task')) {
+ judgeCalls++;
+ completion = { role: 'assistant', content: JSON.stringify(approved
+ ? { outcome: 'succeeded', reason: 'The thread shows the new outgoing attachment.' }
+ : { outcome: 'failed', reason: 'The user declined the recipient; nothing was sent.' }) };
+ } else if (!input.tools?.length) completion = { role: 'assistant', content: JSON.stringify(intent) };
+ else {
+ const step = actionCalls++;
+ const kind = steps[Math.min(step, steps.length - 1)];
+ const call = kind === 'download' ? { name: 'download_files', args: { urls: [`${base}/photo.png`] } }
+ : kind === 'list' ? { name: 'list_downloads', args: { limit: 5 } }
+ : kind === 'upload' ? { name: 'upload_file', args: { selector, downloadId: downloadIdIn(input) } }
+ : kind === 'clarify' ? { name: 'clarify', args: { options: [recipient, 'Cancel'], question,
+ ...(declared ? { purpose: 'message_recipient' } : {}) } }
+ : kind === 'tree' ? { name: 'get_accessibility_tree', args: { filter: 'all' } }
+ : { name: 'done', args: approved
+ ? { outcome: 'success', summary: `Sent the photo to ${recipient}.` }
+ : { outcome: 'partial', summary: 'The photo was not sent because you declined the recipient.' } };
+ let emitted;
+ try { emitted = conformFixtureCompletionCall(input, call, completionRecovery); } catch (error) {
+ const tools = (input.tools || []).map(tool => tool.function || tool);
+ await fs.writeFile(path.join(out, 'provider-diagnostic.json'), JSON.stringify({ step, kind,
+ tools: tools.map(tool => tool.name), done: tools.find(tool => tool.name === 'done')?.parameters,
+ last: input.messages.slice(-4), toolMessages: input.messages.filter(item => item.role === 'tool')
+ .map(item => textOf(item.content).slice(0, 1500)) }, null, 2));
+ throw error;
+ }
+ completion = { role: 'assistant', content: '', tool_calls: [{ id: `owned-recipient-${step}`, type: 'function',
+ function: { name: emitted.name, arguments: JSON.stringify(emitted.args) } }] };
+ }
+ response.writeHead(200, { 'Content-Type': 'application/json' });
+ response.end(JSON.stringify({ id: `response-${providerRequests.length}`, choices: [{ message: completion,
+ finish_reason: completion.tool_calls ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 100, completion_tokens: 30 } }));
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ base = `http://127.0.0.1:${server.address().port}`;
+ const pageBody = `<!doctype html><meta charset="utf-8"><title>Owned direct thread</title>
+ <style>body{margin:0;font:16px sans-serif} nav{position:fixed;left:0;top:0;width:330px;height:700px}
+ header{position:fixed;left:350px;top:10px;width:600px;height:70px} #thread{position:fixed;left:350px;top:90px;width:600px;height:420px}
+ footer{position:fixed;left:350px;top:600px;width:600px;height:60px} [contenteditable]{display:inline-block;width:420px;height:40px;border:1px solid #888}
+ [role=button]{display:inline-block;width:32px;height:32px} svg{width:24px;height:24px}</style>
+ <nav aria-label="Thread list"><div role="button">Ungvb</div><div role="button">${recipient}</div></nav>
+ <main><header><a href="/dr.gamzec_/" aria-label="Open the profile page of dr.gamzec_"><h2>${recipient}</h2></a></header>
+ <div id="thread" role="log"><div data-message-direction="incoming">Merhaba!</div></div>
+ <footer><form id="composer" onsubmit="return false"><div role="textbox" contenteditable="true" aria-label="Message" id="body"></div>
+ <div role="button" id="attach"><svg role="img" aria-label="Add Photo or Video"><title>Add Photo or Video</title><path d="M0 0h24v24H0z"/></svg></div>
+ <input type="file" accept="audio/*,.mp4,.mov,.png,.jpg,.jpeg" multiple hidden></form></footer></main>
+ <script>
+ document.querySelector('input[type=file]').addEventListener('change', async event => {
+ const file = event.target.files[0]; if (!file) return;
+ const body = new FormData(); body.append('photo', file);
+ const result = await fetch('/api/v1/direct_v2/threads/17848282661759097/items/configure_photo/', { method: 'POST', body });
+ if (result.ok) {
+ const item = document.createElement('div'); item.dataset.messageDirection = 'outgoing'; item.textContent = 'You sent an attachment.';
+ document.querySelector('#thread').append(item);
+ }
+ });
+ </script>`;
+ const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-recipient-clarify-mv3-'));
+ let context;
+ try {
+ const extension = path.join(profile, 'extension'); await fs.cp(path.resolve('src/chrome'), extension, { recursive: true });
+ await fs.appendFile(path.join(extension, 'src/background.js'), '\nglobalThis.recipientFixtureAgent = agent;\n');
+ context = await chromium.launchPersistentContext(profile, { headless: true, channel: 'chromium', acceptDownloads: true,
+ args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`,
+ '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1'] });
+ await context.route('**/*', async route => {
+ const request = route.request(), requested = new URL(request.url());
+ if (requested.hostname === '127.0.0.1' && requested.port === String(server.address().port)) return route.continue();
+ if (requested.origin === 'https://www.instagram.com') {
+ if (requested.pathname === '/api/v1/direct_v2/threads/17848282661759097/items/configure_photo/' && request.method() === 'POST') {
+ const body = request.postDataBuffer() || Buffer.alloc(0);
+ sends.push({ method: request.method(), path: requested.pathname, containsPhoto: body.includes(png) });
+ return route.fulfill({ status: 200, contentType: 'application/json', body: '{"status":"ok"}' });
+ }
+ if (request.isNavigationRequest() && requested.href === threadUrl) return route.fulfill({ contentType: 'text/html', body: pageBody });
+ return route.fulfill({ status: 404, body: '' });
+ }
+ if (/^https?:$/.test(requested.protocol)) { blockedRemote++; return route.abort('blockedbyclient'); }
+ return route.continue();
+ });
+ const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker', { timeout: 30_000 });
+ // Keep the browser's own download name ("photo.png"), as a real profile
+ // does, instead of the test runner's extension-less artifact name.
+ const downloads = path.join(profile, 'downloads'); await fs.mkdir(downloads, { recursive: true });
+ const cdp = await context.newCDPSession(context.pages()[0] || await context.newPage());
+ await cdp.send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads, eventsEnabled: true });
+ const harness = await context.newPage(); await harness.goto(`chrome-extension://${new URL(worker.url()).host}/src/ui/settings.html`);
+ const message = (action, data = {}) => harness.evaluate(({ action, data }) => chrome.runtime.sendMessage({ target: 'background', action, ...data }), { action, data });
+ await harness.evaluate(() => chrome.storage.local.set({ helpImproveWebBrain: false, tracingEnabled: false,
+ autoScreenshot: false, screenshotFallback: false, planBeforeActMode: 'off', planBeforeAct: false,
+ planReviewMode: 'never', maxAgentSteps: 14, systemOneEnabled: false, agentAllowLocalNetwork: true,
+ askBeforeConsequentialActions: false, openaiAskStreamingEnabled: false }));
+ if (declared) await harness.evaluate(() => chrome.storage.local.set({ researchEscalationEnabled: true }));
+ assert.equal((await message('update_provider', { providerId: 'openrouter', config: { apiKey: 'owned-fixture-fake-key',
+ baseUrl: `${base}/v1`, model: 'minimax/minimax-m3', enabled: true,
+ contextWindow: 1000000, supportsAskStreaming: false } })).ok, true);
+ assert.equal((await message('set_active_provider', { providerId: 'openrouter' })).ok, true);
+ await worker.evaluate(() => { recipientFixtureAgent.clarifyTimeoutSec = -1; });
+ const page = await context.newPage(); await page.goto(threadUrl);
+ const tabId = await harness.evaluate(async url => (await chrome.tabs.query({})).find(tab => tab.url === url)?.id, threadUrl);
+ // Answer each clarification card the way the user did in the trace.
+ let answering = true;
+ const answerer = (async () => {
+ while (answering) {
+ const pending = await worker.evaluate(tabId => [...(recipientFixtureAgent._pendingClarifications.get(tabId)?.keys() || [])], tabId);
+ for (const clarifyId of pending) {
+ clarifications.push(clarifyId);
+ assert.equal((await message('clarify_response', { tabId, clarifyId, answer, source })).ok, true);
+ }
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ })();
+ const result = await message('chat', { tabId, text: 'send this photo to gamze on instagram', mode: 'act',
+ requestId: `owned-recipient-${variant}`, locale: 'en' });
+ answering = false; await answerer;
+ const toolResults = result.updates.filter(event => event.type === 'tool_result').map(event => ({ name: event.data?.name,
+ success: event.data?.result?.success, reasonCode: event.data?.result?.reasonCode || null,
+ recipientBinding: event.data?.result?.recipientBinding || null, note: event.data?.result?.note || null,
+ error: event.data?.result?.error || null }));
+ const questions = result.updates.filter(event => event.type === 'clarify').map(event => event.data?.question);
+ await fs.writeFile(path.join(out, 'evidence.json'), JSON.stringify({ toolResults, questions, clarifications, sends,
+ judgeCalls, blockedRemote }, null, 2));
+ const uploads = toolResults.filter(item => item.name === 'upload_file');
+ assert.equal(uploads[0]?.reasonCode, 'active_recipient_unverified', JSON.stringify(toolResults));
+ assert.equal(clarifications.length, 1, `Exactly one question: ${JSON.stringify(toolResults)}`);
+ const clarify = toolResults.find(item => item.name === 'clarify');
+ if (approved) {
+ assert.deepEqual(clarify?.recipientBinding, { required: true, bound: true }, JSON.stringify(clarify));
+ assert.equal(uploads[1]?.success, true, JSON.stringify(uploads[1]));
+ assert.deepEqual(sends, [{ method: 'POST', path: '/api/v1/direct_v2/threads/17848282661759097/items/configure_photo/', containsPhoto: true }]);
+ assert.equal(await page.locator('[data-message-direction="outgoing"]').count(), 1);
+ } else {
+ assert.equal(clarify?.recipientBinding?.bound, false, JSON.stringify(clarify));
+ assert.match(clarify?.note || '', /declining or correcting/);
+ assert.equal(uploads[1]?.reasonCode, 'active_recipient_unverified', JSON.stringify(uploads[1]));
+ assert.deepEqual(sends, []);
+ assert.equal(await page.locator('[data-message-direction="outgoing"]').count(), 0);
+ }
+ assert.match(uploads[0].error, /"Gamze Çömlekçi", which is not exactly the recipient named for this task \("gamze"\)/);
+ console.log(JSON.stringify({ passed: true, installedMV3: true, variant, questions: clarifications.length,
+ sends: sends.length, uploads: uploads.map(item => item.success === true ? 'sent' : item.reasonCode), judgeCalls, blockedRemote }));
+ } finally {
+ await context?.close(); await new Promise(resolve => server.close(resolve));
+ const resolved = path.resolve(profile);
+ if (!resolved.startsWith(path.resolve(os.tmpdir()) + path.sep + 'webbrain-recipient-clarify-mv3-')) throw new Error('Unexpected temporary profile path.');
+ await fs.rm(resolved, { recursive: true, force: true });
+ }
+}