Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Bind upload_file approval to the exact local file
Barack Sokullu74d95e3e29bc
diff --git a/docs/security-model.md b/docs/security-model.mdindex 1bc3e8090..328372d9b 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -213,6 +213,7 @@ The primary threat: a malicious page crafts content that, when read by the agent|---|---|| **Untrusted-content wrapping** | Page-derived tool results are wrapped in `<untrusted_page_content>` markers (`_wrapUntrusted` + `UNTRUSTED_CONTENT_TOOLS`) so the model treats them as data, not instructions. See [prompt-injection-defense.md](prompt-injection-defense.md). || **Capability × origin gate** | Before a consequential tool runs (click/type/navigate/execute_js/network/download/…), the agent requires a `(capability, host)` grant — Allow once / Always / Deny. Language-agnostic, deterministic, human-in-the-loop (`permission-gate.js`). |+| **Upload file binding** | `upload_file` puts a local file into a page's file input, and the page can read it as soon as it lands, so the approval names the exact file and host instead of the host alone. The card shows the file name, its saved path and, for a download, the web address it came from, with Allow once / Don't allow and no Always; a host-wide "always" upload grant no longer approves a file, while a standing deny still refuses. A file the user attached to the run, or one the run's own download tools saved, follows the normal gate: the approval covers that file on that host until the next turn, and with prompts off it attaches without a card. Any other local file (an older download, or a Chrome `filePath` that is not a download of this run) gets its own card on every call, even with prompts off or after `/dangerously-skip-permissions`, and a scheduled run that does not ask for confirmation refuses it. The handler attaches nothing if the file it resolves is not the one approved. Both builds (Firefox has no `filePath`). || **Tool result cap** | Individual tool results truncated at 8,000 chars (`_limitToolResult`). Injected text beyond that is silently dropped. || **Ask/Act/Dev mode** | Ask mode exposes only semantic read-only tools. Clicks/types/navigation need an action mode, which only the user's own request grants (see **Automatic mode selection**). Act exposes the selected provider tier's normal tools. Dev requires Mid/Full tier and adds source/style/page-inspection tools for developer debugging. || **Automatic mode selection** | Always on; the side panel has no mode toggle. The user's own request takes the place of the toggle as the action authorization: a turn enters Act or Dev only on a sure decision-model answer to `run_mode` about the user's words and run state, or on a `request_action_mode` call from a read-only Ask turn that quotes the user's latest message exactly (for Retry or Continue of a read-only run, the continued task's own words; WebBrain's continuation text never counts) and that the page-free `run_mode` question, asked again, confirms. Page text, titles and addresses never reach the route, and an unsure, slow or failed route starts read-only. A selected-text scope, the standalone window, Cloud runs, context-menu prompts and messages that carry page text always stay in Ask. The action run's planner gate, permission gates and confirmation cards apply as in a mode the user chose, except that in Try planning a turn that the same decision request is sure is a short, direct task (`plan_need`) runs the gate's compact intent check instead of the full planner. |diff --git a/package.json b/package.jsonindex 9e53890ff..ea5fb082a 100644--- a/package.json+++ b/package.json@@ -70,7 +70,7 @@"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/publication-prefetch.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/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.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-pre-enter-veto.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/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/guard-reading-carry-over.mjs test/trusted-retry-readings.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/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-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/run-ui-hidden-panel.mjs test/clarify-timeout-policy.mjs test/guard-ask-cards.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/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.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/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.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/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/guard-policy.mjs test/lean-mode.mjs test/prompt-unverified-pages.mjs test/prompt-missing-values.mjs test/lifecycle-planner-digest.mjs test/planner-clarify-loop.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/sidepanel-permission-gate-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.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/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/slash-command-timeline-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.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/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.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 test/message-control-readings.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/ask-person-activity-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-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-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: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/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.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-pre-enter-veto.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/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/guard-reading-carry-over.mjs test/trusted-retry-readings.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/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-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/run-ui-hidden-panel.mjs test/clarify-timeout-policy.mjs test/guard-ask-cards.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/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.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/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.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/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/guard-policy.mjs test/lean-mode.mjs test/prompt-unverified-pages.mjs test/prompt-missing-values.mjs test/lifecycle-planner-digest.mjs test/planner-clarify-loop.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/sidepanel-permission-gate-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.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/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/slash-command-timeline-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.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/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.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/upload-file-source-approval.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.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/ask-person-activity-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-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-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/guard-advisory-writes.mjs test/draftjs-text.mjs test/codemirror-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/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.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/x-compose-trusted-typing.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/page-monitor-feed-items.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-scroll-churn.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-native-button-route.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/page-feedback-held-time.mjs test/page-monitor-held-observation.mjs","test:history-recovery": "node --test test/history-recovery.mjs test/history-recovery-ui.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/conversation-persistence.mjs","test:chat-steering": "node --test test/chat-steering.mjs test/chat-steering-ui.mjs test/recipient-confirmation-ui.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs",@@ -106,7 +106,7 @@"test:upload-owner": "node --test test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs","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/guard-policy.mjs 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/cookie-banner-host.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/slash-command-tab-ownership.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:settings-pages:ui && npm run test:openrouter-capabilities && npm run test:anthropic && npm run test:browser-batch && 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/skill-download-wait.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-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-pre-enter-veto.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/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/guard-reading-carry-over.mjs test/trusted-retry-readings.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/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-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/run-ui-hidden-panel.mjs test/clarify-timeout-policy.mjs test/guard-ask-cards.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/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/auto-mode.mjs test/plan-when-needed.mjs test/model-picker-icon.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.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/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.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/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/lean-mode.mjs test/prompt-unverified-pages.mjs test/prompt-missing-values.mjs test/lifecycle-planner-digest.mjs test/planner-clarify-loop.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/improver-providers.mjs test/improver-providers-agent.mjs test/improver-guards-ledger.mjs test/improver-guards-tools.mjs test/improver-clarify.mjs test/improver-clarify-scheduler.mjs test/improver-misc.mjs test/improver-forms.mjs test/improver-forms-strict-secrets.mjs test/improver-content-press-keys-hint.mjs && npm run test:plan-notifications",- "test:shard:browser-a": "node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs && 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/sidepanel-permission-gate-ui.mjs test/model-picker-status-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.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/activity-brain-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/slash-command-timeline-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.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/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.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-scroll-churn.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-native-button-route.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/submit-probe-readings.mjs test/declined-submission-identity.mjs test/improver-content-account-chrome.mjs test/improver-content-recipient.mjs test/improver-content-truncated-replacement.mjs test/improver-forms-probe.mjs test/improver-misc-trace-browser.mjs test/page-feedback-held-time.mjs test/page-monitor-held-observation.mjs",+ "test:shard:browser-a": "node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs && 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/sidepanel-permission-gate-ui.mjs test/model-picker-status-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.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/activity-brain-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/slash-command-timeline-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.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/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.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/upload-file-source-approval.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.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-native-button-route.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/submit-probe-readings.mjs test/declined-submission-identity.mjs test/improver-content-account-chrome.mjs test/improver-content-recipient.mjs test/improver-content-truncated-replacement.mjs test/improver-forms-probe.mjs test/improver-misc-trace-browser.mjs test/page-feedback-held-time.mjs test/page-monitor-held-observation.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 test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/integration-mv3.mjs --batch && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-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/upload-release-binding-mv3.mjs --selector-recovery && node test/quality/upload-release-binding-mv3.mjs --sequential-assets && 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 && node --test test/iframe-probe-match-index.mjs","test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-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 && npm run test:vision-mode",diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 8ddfe71de..726f6e6ae 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -134,7 +134,7 @@ import {normalizeCloudflareManagedChallengeState,} from './cloudflare-managed-challenge.js';import { getRecordingStateFresh as recorderStateFresh } from '../recorder/host.js';-import { Capability, CAPABILITY_LABEL, SubmitRisk, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, requiredHosts, frameHostMatches, urlFilterHostHint, isNetworkMutation, normalizeHost, registrableHost, PermissionManager, submitActionKey, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';+import { Capability, CAPABILITY_LABEL, SubmitRisk, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, requiredHosts, frameHostMatches, urlFilterHostHint, isNetworkMutation, normalizeHost, registrableHost, PermissionManager, submitActionKey, uploadApprovalCard, uploadApprovalKey, uploadApprovalQuestion, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';import {buildPlannerMessages,buildPlannerAlignmentMessages,@@ -1311,6 +1311,11 @@ export class Agent extends LoopDetector {// Handles exist only while one agent run is active and let upload_file// reuse the exact bytes already supplied through the side panel.this._userAttachmentHandles = new Map();+ // tabId -> downloadIds this run's own download tools saved. Like the+ // attachment handles above, they are files the run itself provided, so+ // upload_file may attach them under the ordinary upload gate; any other+ // local file needs the user's approval for that file each time.+ this._runDownloadIds = new Map();// A waited clarify timeout is not user authorization. Keep that fact in// trusted app state instead of relying on the model to obey prose in the// tool result. Consequential actions stay blocked until a direct clarify@@ -17129,6 +17134,37 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}predispatch.lap('submitConfirmationMs');+ // upload_file hands a local file to a page that can read it at once, so+ // its approval names the exact file instead of the host-wide upload+ // grant, and a file outside this run is asked about even with prompts+ // off (_authorizeUploadFileSource). The handler re-checks the source.+ let uploadSourceKey = null;+ if (fnName === 'upload_file' && capabilities.includes(Capability.UPLOAD)) {+ capabilities = capabilities.filter(capability => capability !== Capability.UPLOAD);+ const uploadGate = await this._authorizeUploadFileSource(tabId, fnArgs, onUpdate, {+ promptTier,+ gateBypassed: bypassesConsequentialGates,+ unattended: scheduledBypassesGate,+ });+ if (uploadGate.aborted || (uploadGate.prompted && this._hasPendingSteering(tabId))) {+ if (this._hasPendingSteering(tabId) && !this._checkAbort(tabId)) return skipSteeredPermissionWait(toolIndex);+ const value = '[Stopped by user before executing requested tool calls.]';+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({+ success: false,+ cancelled: true,+ error: value,+ }));+ onUpdate('warning', { message: 'Stopped by user.' });+ return { action: 'abort', value };+ }+ if (!uploadGate.allowed) {+ messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(uploadGate.result) });+ predispatchBlocked('permissionMs');+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }+ continue;+ }+ uploadSourceKey = uploadGate.sourceKey;+ }if (capabilities.length && !bypassesConsequentialGates) {await this.permissions.hydrate();const curUrl = await this._currentUrl(tabId);@@ -17649,6 +17685,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// The typing target's ref, for a write by selector or focus.typingTargetRef: String(pipelineToolbarPreflight.probe?.refId || ''),...messageRecipientExecutionContext,+ ...(uploadSourceKey != null ? { uploadSourceKey } : {}),taskClickLockRelease: callState.taskClickLockRelease || null,iframeTargetUnresolved: pipelineToolbarPreflight.iframeTargetUnresolved === true,richTextToolbarWrongTargetAdvised: pipelineToolbarPreflight.wrongTargetAdvised === true,@@ -17883,6 +17920,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// upload/read survives context compaction even if the model never calls// scratchpad_write itself — the failure that made it invent file paths.this._pinDownloadHandles(tabId, fnName, toolResult);+ this._rememberRunDownloads(tabId, fnName, toolResult);const replayTracking = this._trackBulkApiReplayResult(tabId, fnName, fnArgs, toolResult);let progressObserved = null;@@ -30321,8 +30359,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d* Returns 'once' | 'always' | 'deny', or null (aborted/cancelled).* Fails safe: anything that isn't a clear allow is treated as 'deny'.*/- async _promptPermission(tabId, capability, host, onUpdate) {+ async _promptPermission(tabId, capability, host, onUpdate, upload = null) {const clarifyId = `perm_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;+ // An upload card names the exact file (_authorizeUploadFileSource) and has+ // no "always": a host-wide grant would approve every other file too.+ const uploadCard = capability === Capability.UPLOAD && upload && typeof upload === 'object'+ ? uploadApprovalCard(upload)+ : null;const tabPending = this._pendingClarifications.get(tabId) || new Map();this._pendingClarifications.set(tabId, tabPending);@@ -30340,9 +30383,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout donUpdate('clarify', {promptKind: 'permission',clarifyId,- permission: { capability, host },- question: `WebBrain wants to ${CAPABILITY_LABEL[capability] || 'act on'} ${host}. Allow it?`,- options: ['once', 'always', 'deny'],+ permission: uploadCard ? { capability, host, upload: uploadCard } : { capability, host },+ question: uploadCard+ ? uploadApprovalQuestion(host, uploadCard)+ : `WebBrain wants to ${CAPABILITY_LABEL[capability] || 'act on'} ${host}. Allow it?`,+ options: uploadCard ? ['once', 'deny'] : ['once', 'always', 'deny'],});} catch { /* UI emit must never break the run */ }}@@ -30353,7 +30398,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (response && response.cancelled) return null;const v = String(response?.answer || '').trim().toLowerCase();- if (v === 'always') return 'always';+ if (v === 'always') return uploadCard ? 'deny' : 'always';if (v === 'once') return 'once';return 'deny'; // 'deny', or anything unexpected → fail safe}@@ -38113,6 +38158,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._queueCloudflareManagedChallengeCleanup(tabId).catch(() => {});}this._userAttachmentHandles.delete(tabId);+ this._runDownloadIds.delete(tabId);this._clearResearchEscalationAuthorizations(tabId);this._runUpdateCallbacks.delete(tabId);if (!preserveRunGuard) this.persistenceDegradedTabs.delete(tabId);@@ -39690,6 +39736,33 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}} catch { /* best-effort */ }}++ /**+ * Remember the downloads this run's own download tools saved, so upload_file+ * can tell them from any other file on the disk (_uploadFileSource). The ids+ * come from chrome.downloads through WebBrain's own tool code, never from+ * the page or the model.+ */+ _rememberRunDownloads(tabId, name, result) {+ try {+ if (!result || result.error || result.success === false) return;+ const ids = [];+ if (name === 'download_files' || name === 'download_file') {+ for (const d of (result.downloads || [])) if (d && d.success && d.downloadId != null) ids.push(d.downloadId);+ } else if (name === 'download_resource_from_page'+ || this._activeSkillToolForName(tabId, name)?.requiresDownloadPermission) {+ ids.push(result.downloadId);+ } else if (name === 'download_social_media') {+ ids.push(result.savedFile?.downloadId);+ }+ for (const raw of ids) {+ const id = Number(raw);+ if (raw == null || !Number.isSafeInteger(id) || id < 0) continue;+ if (!this._runDownloadIds.has(tabId)) this._runDownloadIds.set(tabId, new Set());+ this._runDownloadIds.get(tabId).add(id);+ }+ } catch { /* best-effort: an unremembered download is only asked about */ }+ }// ─────────────────────────────────────────────────────────────────────// App-owned progress ledger projected into the prompt.@@ -44813,6 +44886,100 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d};}+ async _uploadDownloadItem(id) {+ if (!Number.isSafeInteger(id) || id < 0 || typeof globalThis.chrome?.downloads?.search !== 'function') return null;+ try {+ const items = await new Promise((resolve, reject) => {+ const pending = chrome.downloads.search({ id }, (res) => {+ if (chrome.runtime?.lastError) reject(new Error(chrome.runtime.lastError.message));+ else resolve(res);+ });+ if (pending && typeof pending.then === 'function') pending.then(resolve, reject);+ });+ return (items && items[0]) || null;+ } catch {+ return null;+ }+ }++ /**+ * The file an upload_file call would attach, resolved in the handler's own+ * order: attachmentId, then a complete downloadId, then filePath. runOwned+ * marks a file the user attached to this run or one this run's download+ * tools saved (a path counts only when it is such a download's saved path);+ * anything else could be any file on the disk. Kind "none" means the handler+ * has nothing it could read and will fail on its own.+ */+ async _uploadFileSource(tabId, args = {}, promptTier = this._resolvePromptTier()) {+ args = args || {};+ const given = key => args[key] != null && !(typeof args[key] === 'string' && !args[key].trim());+ if (given('attachmentId')) {+ const id = String(args.attachmentId).trim();+ const attachment = this._userAttachmentHandles.get(tabId)?.get(id);+ return { kind: 'attachment', key: `attachment:${id}`, runOwned: true,+ name: attachment ? this._sanitizeAttachmentName(attachment.name) : '' };+ }+ const none = { kind: 'none', key: 'none', runOwned: true };+ if (promptTier === 'compact') return none;+ const runIds = this._runDownloadIds.get(tabId);+ if (args.downloadId != null) {+ const id = Number(args.downloadId);+ const item = await this._uploadDownloadItem(id);+ if (item && item.state === 'complete' && item.filename) {+ return { kind: 'download', key: `download:${id}`, downloadId: id, runOwned: !!runIds?.has(id),+ path: String(item.filename), sourceUrl: String(item.finalUrl || item.url || '') };+ }+ }+ if (!given('filePath')) return none;+ const filePath = String(args.filePath);+ let runOwned = false;+ for (const id of runIds || []) {+ if ((await this._uploadDownloadItem(id))?.filename === filePath) { runOwned = true; break; }+ }+ return { kind: 'path', key: `path:${filePath}`, runOwned, path: filePath };+ }++ /**+ * The permission gate for upload_file. A page can read a File the moment it+ * lands in its input, so the approval names the exact file and the page+ * host: a host-wide upload grant no longer approves a file, though a+ * standing deny still refuses. A file the user attached to this run or one+ * this run downloaded keeps the ordinary gate (skipped when prompts are off)+ * and its approval lasts for the turn. Any other local file is approved on+ * the card one call at a time, with prompts on or off; a run that cannot+ * show the card refuses it. Returns { allowed, sourceKey } for the handler+ * to re-check, { aborted }, or { allowed: false, result }.+ */+ async _authorizeUploadFileSource(tabId, args, onUpdate, { promptTier, gateBypassed = false, unattended = false } = {}) {+ const source = await this._uploadFileSource(tabId, args, promptTier);+ const allowed = { allowed: true, sourceKey: source.key };+ if (source.kind === 'none' || (gateBypassed && source.runOwned)) return allowed;+ const refused = error => ({ allowed: false,+ result: { success: false, denied: true, dispatched: false, noDispatch: true, permissionRequired: true, error } });+ const host = requiredHosts(Capability.UPLOAD, args, await this._currentUrl(tabId), 'upload_file')[0] || '';+ if (!host) return refused('Cannot run upload_file: the page host could not be identified, so the file cannot be approved for it.');+ const file = source.kind === 'download' ? `downloadId ${source.downloadId}`+ : source.kind === 'path' ? 'the given filePath' : 'this file';+ if (!source.runOwned && (unattended || typeof onUpdate !== 'function')) {+ return refused(`Nothing was attached: ${file} is neither a file the user attached nor one this run downloaded, so the user must approve this exact file, and this run cannot ask. Use a file the user attached or one this run downloaded, or report that the upload needs the user.`);+ }+ const denied = refused(`The user did not allow attaching ${file} to a page on ${host}. Do NOT retry it. If the task needs a file, ask the user to attach it in the chat.`);+ await this.permissions.hydrate();+ const standing = this.permissions.check(host, Capability.UPLOAD, tabId);+ if (!standing.needsPrompt && !standing.allowed) return denied;+ const key = uploadApprovalKey(host, source.key);+ const prior = this.permissions.checkIntent(key, tabId, Capability.UPLOAD);+ if (!prior.needsPrompt) return prior.allowed ? allowed : denied;+ const choice = await this._promptPermission(tabId, Capability.UPLOAD, host, onUpdate, source);+ if (choice === null) return { allowed: false, aborted: true };+ if (choice !== 'once') {+ this.permissions.recordIntent(key, [Capability.UPLOAD], 'deny', tabId);+ return { ...denied, prompted: true };+ }+ if (source.runOwned) this.permissions.recordIntent(key, [Capability.UPLOAD], 'allow', tabId);+ return { ...allowed, prompted: true };+ }+_userAttachmentNotice(attachments, options = {}) {const entries = (attachments || []).map(att => ({attachmentId: String(att?.attachmentId || '').trim(),@@ -51233,6 +51400,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// id to an otherwise valid absolute path; that extra bad id must not make// the path-based upload fail.let uploadSourceUrl = '';+ let resolvedDownloadId = null;const suppliedFilePath = typeof args.filePath === 'string' && args.filePath.trim()? args.filePath: null;@@ -51255,6 +51423,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d} else {args.filePath = it.filename;uploadSourceUrl = String(it.finalUrl || it.url || '');+ resolvedDownloadId = Number(args.downloadId);}} catch (e) {if (!suppliedFilePath) return { success: false, error: `Could not resolve downloadId ${args.downloadId}: ${e.message}` };@@ -51263,6 +51432,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!attachmentPayload && !args.filePath) {return { success: false, error: 'upload_file needs attachmentId (from the current user-attachment notice), downloadId (from download_files / list_downloads), or filePath (absolute local path).' };}+ // The permission gate approved one exact source (_authorizeUploadFileSource).+ // A download that finished or vanished since then would make this call+ // read another file than the one the user saw, so it attaches nothing.+ if (typeof dispatchContext.uploadSourceKey === 'string') {+ const sourceKey = attachmentPayload ? `attachment:${String(args.attachmentId).trim()}`+ : resolvedDownloadId != null ? `download:${resolvedDownloadId}` : `path:${args.filePath}`;+ if (sourceKey !== dispatchContext.uploadSourceKey) {+ return { success: false, dispatched: false, noDispatch: true, denied: true,+ error: 'Nothing was attached: the file this call resolves to changed after it was approved. Call upload_file again so the file it now names can be approved.' };+ }+ }if (recipientUpload.protected) {let payload = attachmentPayload;if (!payload) {@@ -56430,6 +56610,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}await this._restoreCapturePolicyAfterRun(tabId, previousForegroundCapture);this._userAttachmentHandles.delete(tabId);+ this._runDownloadIds.delete(tabId);this._runUpdateCallbacks.delete(tabId);this._clearRunLoopState(tabId);this._resetChromeProtectedGalleryRunState(tabId);@@ -58502,6 +58683,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}await this._restoreCapturePolicyAfterRun(tabId, previousForegroundCapture);this._userAttachmentHandles.delete(tabId);+ this._runDownloadIds.delete(tabId);this._runUpdateCallbacks.delete(tabId);this._clearRunLoopState(tabId);this._resetChromeProtectedGalleryRunState(tabId);diff --git a/src/chrome/src/agent/guard-policy.js b/src/chrome/src/agent/guard-policy.jsindex 63a8ff2fb..23aececef 100644--- a/src/chrome/src/agent/guard-policy.js+++ b/src/chrome/src/agent/guard-policy.js@@ -162,7 +162,7 @@ export const GUARDS = Object.freeze({"browser-control-handoff-stale-batch": { class: "user_control", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",summary: "Browser control changed hands (manual takeover or cloud handoff) after the batch was planned: every remaining call is skipped and a fresh app-owned tree is injected." },"capability-host-permission": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",- summary: "Capability x host permission gate: a standing deny or a Deny on the capability card (navigate, click, type, execute_js, dev_patch, network, download, upload, window, schedule) refuses the call on that host." },+ summary: "Capability x host permission gate: a standing deny or a Deny on the capability card (navigate, click, type, execute_js, dev_patch, network, download, upload, window, schedule) refuses the call on that host. upload_file is approved for its exact file; a file from outside the run is asked about every call, even with prompts off, and refused in an unattended run." },"captcha-gate-action-block": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",summary: "A supported verification challenge is active (solve_required) or its one solve has not been confirmed cleared (verification_pending): page mutations, network mutations and done(success)/done_json are refused until solve_captcha runs once / a read confirms clearance." },"captcha-gate-manual-required": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",diff --git a/src/chrome/src/agent/permission-gate.js b/src/chrome/src/agent/permission-gate.jsindex ac2b0772d..c0bc82296 100644--- a/src/chrome/src/agent/permission-gate.js+++ b/src/chrome/src/agent/permission-gate.js@@ -732,6 +732,52 @@ export function requiredHosts(capability, args, currentUrlOrHost, toolName) {return h ? [h] : [];}+/**+ * upload_file puts a local file into a page's file input, and the page can+ * read that File the moment it lands. Its approval therefore names the exact+ * file and the page host, never the host alone. `sourceKey` is the source the+ * handler will read: attachment:<id>, download:<id>, path:<path> or picker+ * (Firefox's own file picker, where the user chooses the file).+ */+export function uploadApprovalKey(host, sourceKey) {+ const h = normalizeHost(host);+ const source = String(sourceKey || '');+ return h && source ? `upload_file\n${h}\n${source}` : '';+}++/**+ * What the upload card shows about the file, bounded and stripped of control+ * characters. A download's address is shown only when it is a web address+ * (staged downloads have blob: or data: addresses that tell the user nothing).+ */+export function uploadApprovalCard(upload = {}) {+ const text = (value, max) => String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max);+ const kind = ['attachment', 'download', 'path', 'picker'].includes(upload?.kind) ? upload.kind : 'path';+ const path = text(upload?.path, 500);+ const sourceUrl = text(upload?.sourceUrl, 500);+ return {+ kind,+ runOwned: upload?.runOwned === true,+ name: text(upload?.name || path.split(/[\\/]/).pop(), 200),+ path,+ sourceUrl: /^https?:\/\//i.test(sourceUrl) ? sourceUrl : '',+ };+}++/** English wording of the upload card, also kept by scheduled pending cards. */+export function uploadApprovalQuestion(host, upload = {}) {+ const card = uploadApprovalCard(upload);+ const file = card.kind === 'picker'+ ? 'a file you choose in WebBrain\'s file picker'+ : card.kind === 'attachment'+ ? `the file you attached${card.name ? ` ("${card.name}")` : ''}`+ : card.kind === 'download'+ ? `the downloaded file ${card.path || card.name}${card.sourceUrl ? ` (from ${card.sourceUrl})` : ''}`+ : `the local file ${card.path}`;+ const origin = card.runOwned ? '' : ' You did not attach this file and this task did not download it.';+ return `WebBrain wants to attach ${file} to a page on ${normalizeHost(host) || 'this site'}. The page can read the file as soon as it is attached.${origin} Allow it?`;+}+/*** Stores and evaluates (capability, host) grants. Pure logic — storage is* injected via async load/save hooks so this stays Node-testable. `skipAll`diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.jsindex c15220b80..8aee19bf4 100644--- a/src/chrome/src/agent/tools.js+++ b/src/chrome/src/agent/tools.js@@ -1170,14 +1170,14 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'upload_file',- description: 'Attach a file directly to an existing file input without opening the page or OS file-picker dialog. The actual file bytes must match the input’s accepted types. A file_type_mismatch is known no-dispatch: obtain the underlying asset (use an observed sourceResolution raw URL when returned), download it under normal permissions, and use the new downloadId; do not retry the viewer HTML. This proves only that the page input received or consumed the file; it does NOT prove a remote upload, form submission, or repository commit. A page_consumed attachment may clear its file input and show a preview/crop instead of a filename. Inspect the staged preview/crop or status and the current task-authorized Save/Submit/Commit controls; local attachment does not prove a remote upload or remote submission. Do not re-open the chooser or re-upload solely because the filename is absent or not rendered. Retry only if the file is genuinely missing or the user explicitly requests a new file. Do NOT click "Choose file", "Select a file", an upload drop zone, or the input first when the input already exists. Provide ONE source: attachmentId from the current user-attachment notice, downloadId from download_files/list_downloads, or an absolute filePath. Never guess an id. attachmentId is valid only during the current run and reuses the exact file the user already attached. If both downloadId and filePath are accidentally provided, a valid downloadId is preferred and filePath is the fallback. If the selector is ambiguous, call get_interactive_elements and use the exact selector on the intended file-input record before retrying. If no file input exists because the widget creates it lazily, one guarded click on its add-files control may initialize it; then retry upload_file with the exact selector returned or discovered.',+ description: 'Attach a file directly to an existing file input without opening the page or OS file-picker dialog. The actual file bytes must match the input’s accepted types. A file_type_mismatch is known no-dispatch: obtain the underlying asset (use an observed sourceResolution raw URL when returned), download it under normal permissions, and use the new downloadId; do not retry the viewer HTML. This proves only that the page input received or consumed the file; it does NOT prove a remote upload, form submission, or repository commit. A page_consumed attachment may clear its file input and show a preview/crop instead of a filename. Inspect the staged preview/crop or status and the current task-authorized Save/Submit/Commit controls; local attachment does not prove a remote upload or remote submission. Do not re-open the chooser or re-upload solely because the filename is absent or not rendered. Retry only if the file is genuinely missing or the user explicitly requests a new file. Do NOT click "Choose file", "Select a file", an upload drop zone, or the input first when the input already exists. Provide ONE source: attachmentId from the current user-attachment notice, downloadId from download_files/list_downloads, or an absolute filePath. Never guess an id. A downloadId this run did not download, or a filePath that is not a download of this run, asks the user to approve that exact file every time, so prefer attachmentId or a downloadId from this run. attachmentId is valid only during the current run and reuses the exact file the user already attached. If both downloadId and filePath are accidentally provided, a valid downloadId is preferred and filePath is the fallback. If the selector is ambiguous, call get_interactive_elements and use the exact selector on the intended file-input record before retrying. If no file input exists because the widget creates it lazily, one guarded click on its add-files control may initialize it; then retry upload_file with the exact selector returned or discovered.',parameters: {type: 'object',properties: {selector: { type: 'string', description: 'CSS selector for the file input element' },attachmentId: { type: 'string', description: 'Opaque id from the current [UNTRUSTED USER ATTACHMENTS] notice. Reuses that exact user-selected file without another picker. Valid only during the current agent run.' },downloadId: { type: 'number', description: 'Id of a previously downloaded file (from download_files or list_downloads). Preferred over filePath: it resolves to the real saved path automatically, so you never have to remember it. Survives context compaction via the scratchpad.' },- filePath: { type: 'string', description: 'Absolute path to the local file. Optional if downloadId is given.' },+ filePath: { type: 'string', description: 'Absolute path to the local file. Optional if downloadId is given. Unless it is a file this run downloaded, the user must approve this exact file each time.' },},required: ['selector'],},diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex ea69d4146..d3cd435c6 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -14,7 +14,7 @@ import { mountActivityBrain } from './activity-brain.js';import { createComposerModePins } from './composer-mode-pin.js';import { reportSidePanelPresence } from '../sidepanel-presence.js';import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';-import { CAPABILITY_LABEL } from '../agent/permission-gate.js';+import { CAPABILITY_LABEL, uploadApprovalCard } from '../agent/permission-gate.js';import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';import { installChatLinkIcons } from './chat-link-icons.js';import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';@@ -9416,6 +9416,9 @@ function resolvePendingPermissionPromptForContext(context) {if (targetTabId == null || !targetClarifyId) return false;for (const card of document.querySelectorAll('.clarify-card[data-permission="1"]')) {if (card.classList.contains('clarify-answered')) continue;+ // A card for a local file from outside the run is answered only by a+ // click on it: turning prompts off does not approve that file.+ if (card.dataset.uploadExactFile === '1') continue;if (String(card.dataset.tabId || '') !== String(targetTabId)) continue;if (String(card.dataset.clarifyId || '') !== targetClarifyId) continue;submitClarify(card, targetTabId, targetClarifyId, 'once', 'slash-command');@@ -9430,6 +9433,7 @@ function resolvePendingPermissionPromptsForTab(tabId) {let resolved = 0;for (const card of document.querySelectorAll('.clarify-card[data-permission="1"]')) {if (card.classList.contains('clarify-answered')) continue;+ if (card.dataset.uploadExactFile === '1') continue;if (String(card.dataset.tabId || '') !== targetTabId) continue;const clarifyId = String(card.dataset.clarifyId || '');if (!clarifyId) continue;@@ -12093,20 +12097,50 @@ function renderClarifyCard(data) {// carry their own translation under the key.const resolvedVerb = verb === verbKey ? (CAPABILITY_LABEL[cap] || cap) : verb;const grouped = data.permission.grouped === true;+ // An upload card names the exact file the page would receive and has no+ // "always". Its name, path and address are data, set as text only. Like+ // the grouped-search card, its copy is English for now.+ const upload = !grouped && data.permission.upload && typeof data.permission.upload === 'object'+ ? uploadApprovalCard(data.permission.upload)+ : null;+ if (upload && !upload.runOwned) card.dataset.uploadExactFile = '1';qEl.textContent = grouped? String(data.question || `WebBrain wants to run a task-scoped low-risk search on ${host}.`).slice(0, 600)- : t('sp.perm.question', { verb: resolvedVerb, host });+ : upload+ ? `WebBrain wants to attach a local file to a page on ${host}. The page can read the file as soon as it is attached. Allow it?`+ : t('sp.perm.question', { verb: resolvedVerb, host });++ const fileLines = !upload ? []+ : upload.kind === 'picker'+ ? ["File: the one you choose next in WebBrain's file picker."]+ : [+ upload.name ? `File: ${upload.name}` : '',+ upload.path ? `Local path: ${upload.path}` : '',+ upload.sourceUrl ? `Downloaded from: ${upload.sourceUrl}` : '',+ ].filter(Boolean);+ for (const line of fileLines) {+ const fileEl = document.createElement('div');+ fileEl.className = 'clarify-reason';+ fileEl.textContent = line;+ card.appendChild(fileEl);+ }const reasonEl = document.createElement('div');reasonEl.className = 'clarify-reason';reasonEl.textContent = grouped? 'This one-time approval covers only this unchanged search on this tab. It does not allow passwords, payments, mutations, JavaScript, or future tasks.'- : t('sp.perm.reason');+ : upload+ ? (!upload.runOwned+ ? 'You did not attach this file and this task did not download it. WebBrain asks each time it attaches such a file, even with permission prompts off. Allow only if you asked for this exact file.'+ : upload.kind === 'picker'+ ? `Allowing covers only files you choose for ${host} until the task ends.`+ : `You attached this file, or this task downloaded it. Allowing covers only this file on ${host} until the task ends.`)+ : t('sp.perm.reason');card.appendChild(reasonEl);const optionsEl = document.createElement('div');optionsEl.className = 'clarify-options';- const choices = grouped+ const choices = grouped || upload? [['once', t('sp.perm.allow_once')],['deny', t('sp.perm.dont_allow')],@@ -12127,7 +12161,8 @@ function renderClarifyCard(data) {}card.appendChild(optionsEl);content.appendChild(card);- void maybeShowPermissionEducationHint(card);+ // The hint offers "Always allow", which an upload card does not have.+ if (!upload) void maybeShowPermissionEducationHint(card);scrollToBottom({ force: true });return;}diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex a175c03d3..4696ca19a 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -126,7 +126,7 @@ import {cloudflareManagedChallengeStorageKey,normalizeCloudflareManagedChallengeState,} from './cloudflare-managed-challenge.js';-import { Capability, CAPABILITY_LABEL, SubmitRisk, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, requiredHosts, frameHostMatches, urlFilterHostHint, isNetworkMutation, normalizeHost, registrableHost, PermissionManager, submitActionKey, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';+import { Capability, CAPABILITY_LABEL, SubmitRisk, capabilitiesFor, classifySearchNavigation, classifySubmitRisk, requiredHosts, frameHostMatches, urlFilterHostHint, isNetworkMutation, normalizeHost, registrableHost, PermissionManager, submitActionKey, uploadApprovalCard, uploadApprovalKey, uploadApprovalQuestion, UNTRUSTED_CONTENT_TOOLS } from './permission-gate.js';import {buildPlannerMessages,buildPlannerAlignmentMessages,@@ -962,6 +962,11 @@ export class Agent extends LoopDetector {// Handles exist only while one agent run is active and let upload_file// reuse the exact bytes already supplied through the side panel.this._userAttachmentHandles = new Map();+ // tabId -> downloadIds this run's own download tools saved. Like the+ // attachment handles above, they are files the run itself provided, so+ // upload_file may attach them under the ordinary upload gate; any other+ // download needs the user's approval for that file each time.+ this._runDownloadIds = new Map();// Deterministic capability × origin permission gate. "Always" grants are// persisted in extension storage; "once" grants live for the current turn.this.permissions = new PermissionManager({@@ -15276,6 +15281,37 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}predispatch.lap('submitConfirmationMs');+ // upload_file hands a file to a page that can read it at once, so its+ // approval names the exact file instead of the host-wide upload grant,+ // and a download from outside this run is asked about even with prompts+ // off (_authorizeUploadFileSource). The handler re-checks the source.+ let uploadSourceKey = null;+ if (fnName === 'upload_file' && capabilities.includes(Capability.UPLOAD)) {+ capabilities = capabilities.filter(capability => capability !== Capability.UPLOAD);+ const uploadGate = await this._authorizeUploadFileSource(tabId, fnArgs, onUpdate, {+ promptTier,+ gateBypassed: this._skipPermissionGate || scheduledBypassesGate,+ unattended: scheduledBypassesGate,+ });+ if (uploadGate.aborted || (uploadGate.prompted && this._hasPendingSteering(tabId))) {+ if (this._hasPendingSteering(tabId) && !this._checkAbort(tabId)) return skipSteeredPermissionWait(toolIndex);+ const value = '[Stopped by user before executing requested tool calls.]';+ this._appendSyntheticToolResults(tabId, toolCalls, toolIndex, messages, onUpdate, step, () => ({+ success: false,+ cancelled: true,+ error: value,+ }));+ onUpdate('warning', { message: 'Stopped by user.' });+ return { action: 'abort', value };+ }+ if (!uploadGate.allowed) {+ messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(uploadGate.result) });+ predispatchBlocked('permissionMs');+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }+ continue;+ }+ uploadSourceKey = uploadGate.sourceKey;+ }if (capabilities.length && !this._skipPermissionGate && !scheduledBypassesGate) {await this.permissions.hydrate();const curUrl = await this._currentUrl(tabId);@@ -15782,6 +15818,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// The typing target's ref, for a write by selector or focus.typingTargetRef: String(pipelineToolbarPreflight.probe?.refId || ''),...messageRecipientExecutionContext,+ ...(uploadSourceKey != null ? { uploadSourceKey } : {}),iframeTargetUnresolved: pipelineToolbarPreflight.iframeTargetUnresolved === true,richTextToolbarWrongTargetAdvised: pipelineToolbarPreflight.wrongTargetAdvised === true,imageGenConfig,@@ -16007,6 +16044,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// read survives context compaction even if the model never calls// scratchpad_write itself — the failure that made it invent file paths.this._pinDownloadHandles(tabId, fnName, toolResult);+ this._rememberRunDownloads(tabId, fnName, toolResult);const replayTracking = this._trackBulkApiReplayResult(tabId, fnName, fnArgs, toolResult);let progressObserved = null;@@ -27102,8 +27140,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d* Returns 'once' | 'always' | 'deny', or null (aborted/cancelled).* Fails safe: anything that isn't a clear allow is treated as 'deny'.*/- async _promptPermission(tabId, capability, host, onUpdate) {+ async _promptPermission(tabId, capability, host, onUpdate, upload = null) {const clarifyId = `perm_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;+ // An upload card names the exact file (_authorizeUploadFileSource) and has+ // no "always": a host-wide grant would approve every other file too.+ const uploadCard = capability === Capability.UPLOAD && upload && typeof upload === 'object'+ ? uploadApprovalCard(upload)+ : null;const tabPending = this._pendingClarifications.get(tabId) || new Map();this._pendingClarifications.set(tabId, tabPending);@@ -27121,9 +27164,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout donUpdate('clarify', {promptKind: 'permission',clarifyId,- permission: { capability, host },- question: `WebBrain wants to ${CAPABILITY_LABEL[capability] || 'act on'} ${host}. Allow it?`,- options: ['once', 'always', 'deny'],+ permission: uploadCard ? { capability, host, upload: uploadCard } : { capability, host },+ question: uploadCard+ ? uploadApprovalQuestion(host, uploadCard)+ : `WebBrain wants to ${CAPABILITY_LABEL[capability] || 'act on'} ${host}. Allow it?`,+ options: uploadCard ? ['once', 'deny'] : ['once', 'always', 'deny'],});} catch { /* UI emit must never break the run */ }}@@ -27134,7 +27179,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (response && response.cancelled) return null;const v = String(response?.answer || '').trim().toLowerCase();- if (v === 'always') return 'always';+ if (v === 'always') return uploadCard ? 'deny' : 'always';if (v === 'once') return 'once';return 'deny'; // 'deny', or anything unexpected → fail safe}@@ -35819,6 +35864,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._queueCloudflareManagedChallengeCleanup(tabId).catch(() => {});}this._userAttachmentHandles.delete(tabId);+ this._runDownloadIds.delete(tabId);this._clearResearchEscalationAuthorizations(tabId);this._runUpdateCallbacks.delete(tabId);if (!preserveRunGuard) this.persistenceDegradedTabs.delete(tabId);@@ -36133,6 +36179,33 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}} catch { /* best-effort */ }}++ /**+ * Remember the downloads this run's own download tools saved, so upload_file+ * can tell them from any other download (_uploadFileSource). The ids come+ * from browser.downloads through WebBrain's own tool code, never from the+ * page or the model.+ */+ _rememberRunDownloads(tabId, name, result) {+ try {+ if (!result || result.error || result.success === false) return;+ const ids = [];+ if (name === 'download_files' || name === 'download_file') {+ for (const d of (result.downloads || [])) if (d && d.success && d.downloadId != null) ids.push(d.downloadId);+ } else if (name === 'download_resource_from_page'+ || this._activeSkillToolForName(tabId, name)?.requiresDownloadPermission) {+ ids.push(result.downloadId);+ } else if (name === 'download_social_media') {+ ids.push(result.savedFile?.downloadId);+ }+ for (const raw of ids) {+ const id = Number(raw);+ if (raw == null || !Number.isSafeInteger(id) || id < 0) continue;+ if (!this._runDownloadIds.has(tabId)) this._runDownloadIds.set(tabId, new Set());+ this._runDownloadIds.get(tabId).add(id);+ }+ } catch { /* best-effort: an unremembered download is only asked about */ }+ }_isCompressionPlaceholderResponse(text) {const normalized = String(text || '').trim().toLowerCase();return normalized === '[compressed]' || normalized === '[context compressed]';@@ -41238,6 +41311,86 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d};}+ async _uploadDownloadItem(id) {+ if (!Number.isSafeInteger(id) || id < 0 || typeof globalThis.browser?.downloads?.search !== 'function') return null;+ try {+ const items = await browser.downloads.search({ id });+ return (items && items[0]) || null;+ } catch {+ return null;+ }+ }++ /**+ * The file an upload_file call would attach, resolved in the handler's own+ * order: a filePath is refused before anything is read, then attachmentId,+ * then a complete downloadId, else WebBrain's file picker, where the user+ * chooses the file. runOwned marks a file the user attached or chooses, or+ * one this run's download tools saved; any other download could be any+ * file the browser ever saved. Kind "none" means the handler has nothing it+ * could read and will fail on its own.+ */+ async _uploadFileSource(tabId, args = {}, promptTier = this._resolvePromptTier()) {+ args = args || {};+ const given = key => args[key] != null && !(typeof args[key] === 'string' && !args[key].trim());+ const none = { kind: 'none', key: 'none', runOwned: true };+ if (given('filePath')) return none;+ if (promptTier === 'compact' && (given('selector') || args.downloadId != null)) return none;+ if (given('attachmentId')) {+ const id = String(args.attachmentId).trim();+ const attachment = this._userAttachmentHandles.get(tabId)?.get(id);+ return { kind: 'attachment', key: `attachment:${id}`, runOwned: true,+ name: attachment ? this._sanitizeAttachmentName(attachment.name) : '' };+ }+ if (args.downloadId == null) return { kind: 'picker', key: 'picker', runOwned: true };+ const id = Number(args.downloadId);+ const item = await this._uploadDownloadItem(id);+ if (!item || !item.url || item.state !== 'complete') return none;+ return { kind: 'download', key: `download:${id}`, downloadId: id, runOwned: !!this._runDownloadIds.get(tabId)?.has(id),+ path: String(item.filename || ''), sourceUrl: String(item.url || '') };+ }++ /**+ * The permission gate for upload_file. A page can read a File the moment it+ * lands in its input, so the approval names the exact file and the page+ * host: a host-wide upload grant no longer approves a file, though a+ * standing deny still refuses. A file the user attached or chooses, or one+ * this run downloaded, keeps the ordinary gate (skipped when prompts are+ * off) and its approval lasts for the turn. Any other download is approved+ * on the card one call at a time, with prompts on or off; a run that cannot+ * show the card refuses it. Returns { allowed, sourceKey } for the handler+ * to re-check, { aborted }, or { allowed: false, result }.+ */+ async _authorizeUploadFileSource(tabId, args, onUpdate, { promptTier, gateBypassed = false, unattended = false } = {}) {+ const source = await this._uploadFileSource(tabId, args, promptTier);+ const allowed = { allowed: true, sourceKey: source.key };+ if (source.kind === 'none' || (gateBypassed && source.runOwned)) return allowed;+ const refused = error => ({ allowed: false,+ result: { success: false, denied: true, dispatched: false, noDispatch: true, permissionRequired: true, error } });+ const host = requiredHosts(Capability.UPLOAD, args, await this._currentUrl(tabId), 'upload_file')[0] || '';+ if (!host) return refused('Cannot run upload_file: the page host could not be identified, so the file cannot be approved for it.');+ const file = source.kind === 'download' ? `downloadId ${source.downloadId}`+ : source.kind === 'picker' ? 'a file the user chooses' : 'this file';+ if (!source.runOwned && (unattended || typeof onUpdate !== 'function')) {+ return refused(`Nothing was attached: ${file} is neither a file the user attached nor one this run downloaded, so the user must approve this exact file, and this run cannot ask. Use a file the user attached or one this run downloaded, or report that the upload needs the user.`);+ }+ const denied = refused(`The user did not allow attaching ${file} to a page on ${host}. Do NOT retry it. If the task needs a file, ask the user to attach it in the chat.`);+ await this.permissions.hydrate();+ const standing = this.permissions.check(host, Capability.UPLOAD, tabId);+ if (!standing.needsPrompt && !standing.allowed) return denied;+ const key = uploadApprovalKey(host, source.key);+ const prior = this.permissions.checkIntent(key, tabId, Capability.UPLOAD);+ if (!prior.needsPrompt) return prior.allowed ? allowed : denied;+ const choice = await this._promptPermission(tabId, Capability.UPLOAD, host, onUpdate, source);+ if (choice === null) return { allowed: false, aborted: true };+ if (choice !== 'once') {+ this.permissions.recordIntent(key, [Capability.UPLOAD], 'deny', tabId);+ return { ...denied, prompted: true };+ }+ if (source.runOwned) this.permissions.recordIntent(key, [Capability.UPLOAD], 'allow', tabId);+ return { ...allowed, prompted: true };+ }+_userAttachmentNotice(attachments, options = {}) {const entries = (attachments || []).map(att => ({attachmentId: String(att?.attachmentId || '').trim(),@@ -44512,10 +44665,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (recipientUpload.block) return recipientUpload.block;let base64, filename, mimeType;+ // The permission gate approved one exact source (_authorizeUploadFileSource).+ // A download that finished or vanished since then would make this call+ // read another file than the one the user saw, so it attaches nothing.+ const sourceChanged = key => typeof dispatchContext.uploadSourceKey === 'string'+ && dispatchContext.uploadSourceKey !== key+ ? { success: false, dispatched: false, noDispatch: true, denied: true,+ error: 'Nothing was attached: the file this call resolves to changed after it was approved. Call upload_file again so the file it now names can be approved.' }+ : null;if (args.attachmentId != null) {if (args.downloadId != null) {return { success: false, error: 'upload_file accepts only one source. Remove downloadId and retry with the current attachmentId.' };}+ const changed = sourceChanged(`attachment:${String(args.attachmentId).trim()}`);+ if (changed) return changed;const resolved = compactAttachmentPayload|| this._resolveUserAttachment(tabId, args.attachmentId, UPLOAD_MAX_BYTES);if (!resolved.ok) return { success: false, error: resolved.error };@@ -44531,6 +44694,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout derror: `Download is in state: ${dl[0].state}, not complete. Wait for it to finish (wait_for_stable / list_downloads) then retry.`,};}+ const changed = sourceChanged(`download:${Number(args.downloadId)}`);+ if (changed) return changed;// The bytes the browser saved, read by the companion when this run// has one; otherwise the file is fetched again from its address.const saved = await this._firefoxSavedDownloadBytes(tabId, dl[0]);@@ -44641,6 +44806,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dmimeType = dl[0].mime || res.headers.get('content-type') || 'application/octet-stream';}} else {+ const changed = sourceChanged('picker');+ if (changed) return changed;const pickerId = `upk_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;const tabPending = this._pendingUploadPickers.get(tabId) || new Map();this._pendingUploadPickers.set(tabId, tabPending);@@ -47693,6 +47860,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout delse this.cloudRunContexts.delete(tabId);}this._userAttachmentHandles.delete(tabId);+ this._runDownloadIds.delete(tabId);this._runUpdateCallbacks.delete(tabId);this._clearRunLoopState(tabId);this._clearCompletionInvariant(tabId, completionRunToken);@@ -49558,6 +49726,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout delse this.cloudRunContexts.delete(tabId);}this._userAttachmentHandles.delete(tabId);+ this._runDownloadIds.delete(tabId);this._runUpdateCallbacks.delete(tabId);this._clearRunLoopState(tabId);this._clearCompletionInvariant(tabId, completionRunToken);diff --git a/src/firefox/src/agent/guard-policy.js b/src/firefox/src/agent/guard-policy.jsindex 63a8ff2fb..23aececef 100644--- a/src/firefox/src/agent/guard-policy.js+++ b/src/firefox/src/agent/guard-policy.js@@ -162,7 +162,7 @@ export const GUARDS = Object.freeze({"browser-control-handoff-stale-batch": { class: "user_control", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",summary: "Browser control changed hands (manual takeover or cloud handoff) after the batch was planned: every remaining call is skipped and a fresh app-owned tree is injected." },"capability-host-permission": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",- summary: "Capability x host permission gate: a standing deny or a Deny on the capability card (navigate, click, type, execute_js, dev_patch, network, download, upload, window, schedule) refuses the call on that host." },+ summary: "Capability x host permission gate: a standing deny or a Deny on the capability card (navigate, click, type, execute_js, dev_patch, network, download, upload, window, schedule) refuses the call on that host. upload_file is approved for its exact file; a file from outside the run is asked about every call, even with prompts off, and refused in an unattended run." },"captcha-gate-action-block": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",summary: "A supported verification challenge is active (solve_required) or its one solve has not been confirmed cleared (verification_pending): page mutations, network mutations and done(success)/done_json are refused until solve_captcha runs once / a read confirms clearance." },"captcha-gate-manual-required": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",diff --git a/src/firefox/src/agent/permission-gate.js b/src/firefox/src/agent/permission-gate.jsindex cc60c20aa..7f5b16dea 100644--- a/src/firefox/src/agent/permission-gate.js+++ b/src/firefox/src/agent/permission-gate.js@@ -717,6 +717,52 @@ export function requiredHosts(capability, args, currentUrlOrHost, toolName) {return h ? [h] : [];}+/**+ * upload_file puts a local file into a page's file input, and the page can+ * read that File the moment it lands. Its approval therefore names the exact+ * file and the page host, never the host alone. `sourceKey` is the source the+ * handler will read: attachment:<id>, download:<id>, path:<path> or picker+ * (Firefox's own file picker, where the user chooses the file).+ */+export function uploadApprovalKey(host, sourceKey) {+ const h = normalizeHost(host);+ const source = String(sourceKey || '');+ return h && source ? `upload_file\n${h}\n${source}` : '';+}++/**+ * What the upload card shows about the file, bounded and stripped of control+ * characters. A download's address is shown only when it is a web address+ * (staged downloads have blob: or data: addresses that tell the user nothing).+ */+export function uploadApprovalCard(upload = {}) {+ const text = (value, max) => String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max);+ const kind = ['attachment', 'download', 'path', 'picker'].includes(upload?.kind) ? upload.kind : 'path';+ const path = text(upload?.path, 500);+ const sourceUrl = text(upload?.sourceUrl, 500);+ return {+ kind,+ runOwned: upload?.runOwned === true,+ name: text(upload?.name || path.split(/[\\/]/).pop(), 200),+ path,+ sourceUrl: /^https?:\/\//i.test(sourceUrl) ? sourceUrl : '',+ };+}++/** English wording of the upload card, also kept by scheduled pending cards. */+export function uploadApprovalQuestion(host, upload = {}) {+ const card = uploadApprovalCard(upload);+ const file = card.kind === 'picker'+ ? 'a file you choose in WebBrain\'s file picker'+ : card.kind === 'attachment'+ ? `the file you attached${card.name ? ` ("${card.name}")` : ''}`+ : card.kind === 'download'+ ? `the downloaded file ${card.path || card.name}${card.sourceUrl ? ` (from ${card.sourceUrl})` : ''}`+ : `the local file ${card.path}`;+ const origin = card.runOwned ? '' : ' You did not attach this file and this task did not download it.';+ return `WebBrain wants to attach ${file} to a page on ${normalizeHost(host) || 'this site'}. The page can read the file as soon as it is attached.${origin} Allow it?`;+}+/*** Stores and evaluates (capability, host) grants. Pure logic — storage is* injected via async load/save hooks so this stays Node-testable. `skipAll`diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.jsindex 132e23401..38f830adc 100644--- a/src/firefox/src/agent/tools.js+++ b/src/firefox/src/agent/tools.js@@ -1017,7 +1017,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'upload_file',- description: 'Attach a file directly to an existing <input type="file"> without clicking the page upload control. The actual file bytes must match the input’s accepted types. A file_type_mismatch is known no-dispatch: obtain the underlying asset (use an observed sourceResolution raw URL when returned), download it under normal permissions, and use the new downloadId; do not retry the viewer HTML. This proves only that the page input received or consumed the file; it does NOT prove a remote upload, form submission, or repository commit. A page_consumed attachment may clear its file input and show a preview/crop instead of a filename. Inspect the staged preview/crop or status and the current task-authorized Save/Submit/Commit controls; local attachment does not prove a remote upload or remote submission. Do not re-open the chooser or re-upload solely because the filename is absent or not rendered. Retry only if the file is genuinely missing or the user explicitly requests a new file. Do NOT click "Choose file", "Select a file", an upload drop zone, or the input first when the input already exists. Provide attachmentId from the current user-attachment notice to reuse that exact file, provide downloadId to re-fetch a prior download, or omit both only when the user must pick a new local file through WebBrain\'s own picker. Never guess an id. If the selector is ambiguous, call get_interactive_elements and use the exact selector on the intended file-input record before retrying. If no file input exists because the widget creates it lazily, one guarded click on its add-files control may initialize it; then retry upload_file with the exact selector returned or discovered. NOTE: Firefox cannot set arbitrary local file paths (no CDP).',+ description: 'Attach a file directly to an existing <input type="file"> without clicking the page upload control. The actual file bytes must match the input’s accepted types. A file_type_mismatch is known no-dispatch: obtain the underlying asset (use an observed sourceResolution raw URL when returned), download it under normal permissions, and use the new downloadId; do not retry the viewer HTML. This proves only that the page input received or consumed the file; it does NOT prove a remote upload, form submission, or repository commit. A page_consumed attachment may clear its file input and show a preview/crop instead of a filename. Inspect the staged preview/crop or status and the current task-authorized Save/Submit/Commit controls; local attachment does not prove a remote upload or remote submission. Do not re-open the chooser or re-upload solely because the filename is absent or not rendered. Retry only if the file is genuinely missing or the user explicitly requests a new file. Do NOT click "Choose file", "Select a file", an upload drop zone, or the input first when the input already exists. Provide attachmentId from the current user-attachment notice to reuse that exact file, provide downloadId to re-fetch a prior download, or omit both only when the user must pick a new local file through WebBrain\'s own picker. Never guess an id. A downloadId this run did not download asks the user to approve that exact file every time. If the selector is ambiguous, call get_interactive_elements and use the exact selector on the intended file-input record before retrying. If no file input exists because the widget creates it lazily, one guarded click on its add-files control may initialize it; then retry upload_file with the exact selector returned or discovered. NOTE: Firefox cannot set arbitrary local file paths (no CDP).',parameters: {type: 'object',properties: {diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex 54ab3e2c3..5c15d4c3d 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -13,7 +13,7 @@ import { createTimeoutRing, updateTimeoutRing } from './timeout-ring.js';import { mountActivityBrain } from './activity-brain.js';import { createComposerModePins } from './composer-mode-pin.js';import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';-import { CAPABILITY_LABEL } from '../agent/permission-gate.js';+import { CAPABILITY_LABEL, uploadApprovalCard } from '../agent/permission-gate.js';import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';import { installChatLinkIcons } from './chat-link-icons.js';import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';@@ -9190,6 +9190,9 @@ function resolvePendingPermissionPromptForContext(context) {if (targetTabId == null || !targetClarifyId) return false;for (const card of document.querySelectorAll('.clarify-card[data-permission="1"]')) {if (card.classList.contains('clarify-answered')) continue;+ // A card for a local file from outside the run is answered only by a+ // click on it: turning prompts off does not approve that file.+ if (card.dataset.uploadExactFile === '1') continue;if (String(card.dataset.tabId || '') !== String(targetTabId)) continue;if (String(card.dataset.clarifyId || '') !== targetClarifyId) continue;submitClarify(card, targetTabId, targetClarifyId, 'once', 'slash-command');@@ -9204,6 +9207,7 @@ function resolvePendingPermissionPromptsForTab(tabId) {let resolved = 0;for (const card of document.querySelectorAll('.clarify-card[data-permission="1"]')) {if (card.classList.contains('clarify-answered')) continue;+ if (card.dataset.uploadExactFile === '1') continue;if (String(card.dataset.tabId || '') !== targetTabId) continue;const clarifyId = String(card.dataset.clarifyId || '');if (!clarifyId) continue;@@ -11586,20 +11590,50 @@ function renderClarifyCard(data) {// carry their own translation under the key.const resolvedVerb = verb === verbKey ? (CAPABILITY_LABEL[cap] || cap) : verb;const grouped = data.permission.grouped === true;+ // An upload card names the exact file the page would receive and has no+ // "always". Its name, path and address are data, set as text only. Like+ // the grouped-search card, its copy is English for now.+ const upload = !grouped && data.permission.upload && typeof data.permission.upload === 'object'+ ? uploadApprovalCard(data.permission.upload)+ : null;+ if (upload && !upload.runOwned) card.dataset.uploadExactFile = '1';qEl.textContent = grouped? String(data.question || `WebBrain wants to run a task-scoped low-risk search on ${host}.`).slice(0, 600)- : t('sp.perm.question', { verb: resolvedVerb, host });+ : upload+ ? `WebBrain wants to attach a local file to a page on ${host}. The page can read the file as soon as it is attached. Allow it?`+ : t('sp.perm.question', { verb: resolvedVerb, host });++ const fileLines = !upload ? []+ : upload.kind === 'picker'+ ? ["File: the one you choose next in WebBrain's file picker."]+ : [+ upload.name ? `File: ${upload.name}` : '',+ upload.path ? `Local path: ${upload.path}` : '',+ upload.sourceUrl ? `Downloaded from: ${upload.sourceUrl}` : '',+ ].filter(Boolean);+ for (const line of fileLines) {+ const fileEl = document.createElement('div');+ fileEl.className = 'clarify-reason';+ fileEl.textContent = line;+ card.appendChild(fileEl);+ }const reasonEl = document.createElement('div');reasonEl.className = 'clarify-reason';reasonEl.textContent = grouped? 'This one-time approval covers only this unchanged search on this tab. It does not allow passwords, payments, mutations, JavaScript, or future tasks.'- : t('sp.perm.reason');+ : upload+ ? (!upload.runOwned+ ? 'You did not attach this file and this task did not download it. WebBrain asks each time it attaches such a file, even with permission prompts off. Allow only if you asked for this exact file.'+ : upload.kind === 'picker'+ ? `Allowing covers only files you choose for ${host} until the task ends.`+ : `You attached this file, or this task downloaded it. Allowing covers only this file on ${host} until the task ends.`)+ : t('sp.perm.reason');card.appendChild(reasonEl);const optionsEl = document.createElement('div');optionsEl.className = 'clarify-options';- const choices = grouped+ const choices = grouped || upload? [['once', t('sp.perm.allow_once')],['deny', t('sp.perm.dont_allow')],@@ -11620,7 +11654,8 @@ function renderClarifyCard(data) {}card.appendChild(optionsEl);content.appendChild(card);- void maybeShowPermissionEducationHint(card);+ // The hint offers "Always allow", which an upload card does not have.+ if (!upload) void maybeShowPermissionEducationHint(card);scrollToBottom({ force: true });return;}diff --git a/test/upload-file-source-approval.mjs b/test/upload-file-source-approval.mjsnew file mode 100644index 000000000..e0c5f0808--- /dev/null+++ b/test/upload-file-source-approval.mjs@@ -0,0 +1,299 @@+// upload_file puts a local file into a page input, and the page can read the+// File the moment it lands. The permission gate therefore approves the exact+// file and host: a file the user attached or this run downloaded keeps the+// ordinary gate, any other local file is asked about one call at a time, even+// with permission prompts off, and a run that cannot show the card refuses it.+import assert from 'node:assert/strict';+import fs from 'node:fs';+import { test } from 'node:test';+import { chromium, firefox } from 'playwright';++const PAGE = 'https://forms.example.test/apply';+const HOST = 'forms.example.test';+const TAB = 4410;+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+const downloads = new Map();+const search = (query, callback) => {+ const items = downloads.has(query?.id) ? [downloads.get(query.id)] : [];+ if (typeof callback === 'function') { callback(items); return undefined; }+ return Promise.resolve(items);+};+globalThis.chrome = globalThis.browser = {+ storage: { local: area, session: area },+ runtime: { getURL: value => `extension://test/${value}` },+ tabs: { get: async id => ({ id, url: PAGE }), sendMessage: async () => ({}) },+ scripting: { executeScript: async () => [{ result: null }] },+ downloads: { search },+};++// 7 is this run's own download; 41 is an older download the user once saved.+downloads.set(7, { id: 7, state: 'complete', filename: '/home/user/Downloads/report.pdf', url: 'https://files.example.test/report.pdf' });+downloads.set(41, { id: 41, state: 'complete', filename: '/home/user/Downloads/tax-return.pdf', url: 'https://bank.example.test/statement.pdf' });++for (const build of ['chrome', 'firefox']) {+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);+ const { Capability, uploadApprovalCard } = await import(`../src/${build}/src/agent/permission-gate.js`);++ function harness({ gateOff = false, unattended = false } = {}) {+ const provider = { promptTier: 'full', supportsVision: false };+ const agent = new Agent({ getActive: () => provider, getVisionProvider: async () => null });+ agent._skipPermissionGate = gateOff; agent._ensureGateSetting = async () => gateOff;+ agent._chromeProtectedPageFailure = async () => null;+ agent._captchaMutationPreflight = async () => null;+ agent._adoptLiveSocialPublishWorkflow = async () => false;+ agent._workflowPreSubmitDispatchBlock = async () => null;+ agent._messageRecipientGuardBlock = async () => null;+ agent._detectLikelySubmitAction = async () => null;+ agent._isFormValidationCandidate = () => false;+ agent._preflightRichTextToolbarTarget = async () => ({ block: null });+ agent._socialPublicationPreSubmitBlock = async () => null;+ agent._auditRichTextToolbarTarget = async () => {};+ agent._shouldAutoScreenshot = () => false;+ agent._persist = () => {};+ agent._currentUrl = async () => PAGE;+ agent._refreshPageFeedbackForCall = async () => false;+ if (unattended) agent.scheduledRunPolicies.set(TAB, { requireConsequentialConfirmation: false });+ agent._rememberRunDownloads?.(TAB, 'download_files', { success: true, downloads: [{ success: true, downloadId: 7 }] });+ const state = { prompts: [], dispatched: [], messages: [], answer: 'once' };+ agent._promptPermission = async (_tab, capability, host, _update, upload) => {+ state.prompts.push({ capability, host, upload });+ return state.answer;+ };+ agent.executeTool = async (_tab, name, args, _update, context) => {+ state.dispatched.push({ name, args, uploadSourceKey: context?.uploadSourceKey });+ return { success: true, attached: { name: 'file', size: 1 }, attachmentState: 'input_attached', verified: false, remoteStateVerified: false };+ };+ let sequence = 0;+ state.upload = args => agent._executeToolBatch(TAB, [{ id: `upload-${++sequence}`,+ function: { name: 'upload_file', arguments: JSON.stringify({ selector: '#resume', ...args }) } }],+ state.messages, () => {}, provider, null, new Set(['upload_file']), sequence, {});+ state.lastResult = () => JSON.parse(state.messages.filter(message => message.role === 'tool').at(-1).content);+ state.agent = agent;+ return state;+ }++ test(`${build}: with permission prompts off, an older download still needs approval of that exact file`, async () => {+ const h = harness({ gateOff: true });+ h.answer = 'deny';+ await h.upload({ downloadId: 41 });+ assert.equal(h.prompts.length, 1, 'turning prompts off does not approve a file from outside the run');+ assert.equal(h.prompts[0].capability, Capability.UPLOAD);+ assert.equal(h.prompts[0].host, HOST);+ assert.equal(h.prompts[0].upload.kind, 'download');+ assert.equal(h.prompts[0].upload.path, '/home/user/Downloads/tax-return.pdf');+ assert.equal(h.prompts[0].upload.sourceUrl, 'https://bank.example.test/statement.pdf');+ assert.equal(h.prompts[0].upload.runOwned, false);+ assert.equal(h.dispatched.length, 0, 'a declined file never reaches the page');+ assert.equal(h.lastResult().denied, true);+ assert.equal(h.lastResult().noDispatch, true);++ await h.upload({ downloadId: 41 });+ assert.equal(h.prompts.length, 1, 'the same declined file is refused again without a new card this turn');+ assert.equal(h.dispatched.length, 0);++ h.agent.permissions.beginTurn(TAB);+ h.answer = 'once';+ await h.upload({ downloadId: 41 });+ await h.upload({ downloadId: 41 });+ assert.equal(h.prompts.length, 3, 'an approval of a file from outside the run covers one call');+ assert.deepEqual(h.dispatched.map(item => item.uploadSourceKey), ['download:41', 'download:41']);+ });++ test(`${build}: the run's own downloads keep the ordinary gate`, async () => {+ const off = harness({ gateOff: true });+ await off.upload({ downloadId: 7 });+ assert.equal(off.prompts.length, 0, 'with prompts off the run\'s own download attaches as before');+ assert.deepEqual(off.dispatched.map(item => item.uploadSourceKey), ['download:7']);++ const on = harness();+ await on.upload({ downloadId: 7 });+ await on.upload({ downloadId: 7 });+ assert.equal(on.prompts.length, 1, 'one approval covers the same run download for the turn');+ assert.equal(on.prompts[0].upload.runOwned, true);+ await on.upload({ downloadId: 41 });+ assert.equal(on.prompts.length, 2, 'another file asks again');+ assert.equal(on.dispatched.length, 3);+ });++ test(`${build}: a host-wide upload grant no longer approves a file, but a standing deny still refuses`, async () => {+ const h = harness();+ await h.agent.permissions.record(HOST, Capability.UPLOAD, 'allow', 'always', TAB);+ await h.upload({ downloadId: 41 });+ assert.equal(h.prompts.length, 1, 'an "always allow upload" grant for the host does not choose the file');+ assert.equal(h.dispatched.length, 1);++ const denied = harness();+ await denied.agent.permissions.record(HOST, Capability.UPLOAD, 'deny', 'always', TAB);+ await denied.upload({ downloadId: 7 });+ assert.equal(denied.prompts.length, 0);+ assert.equal(denied.dispatched.length, 0);+ assert.equal(denied.lastResult().denied, true);+ });++ test(`${build}: an unattended run refuses a file from outside the run without a card`, async () => {+ const h = harness({ unattended: true });+ await h.upload({ downloadId: 41 });+ assert.equal(h.prompts.length, 0);+ assert.equal(h.dispatched.length, 0);+ assert.match(h.lastResult().error, /must approve this exact file/);+ await h.upload({ downloadId: 7 });+ assert.deepEqual(h.dispatched.map(item => item.uploadSourceKey), ['download:7'], 'the run\'s own download still attaches');+ });++ test(`${build}: a user attachment keeps the ordinary gate`, async () => {+ const h = harness({ gateOff: true });+ const [attachment] = h.agent._registerUserAttachments(TAB, [{ name: 'cv.pdf', mimeType: 'application/pdf', dataUrl: 'data:application/pdf;base64,JVBERi0=' }]);+ await h.upload({ attachmentId: attachment.attachmentId });+ assert.equal(h.prompts.length, 0);+ assert.deepEqual(h.dispatched.map(item => item.uploadSourceKey), [`attachment:${attachment.attachmentId}`]);+ });++ test(`${build}: the upload card names the file and offers no "always"`, async () => {+ const agent = new Agent({ getVisionProvider: async () => null });+ const updates = [];+ const choice = agent._promptPermission(TAB, Capability.UPLOAD, HOST, (type, data) => updates.push({ type, data }),+ { kind: 'download', path: '/home/user/Downloads/tax-return.pdf', sourceUrl: 'https://bank.example.test/statement.pdf', runOwned: false });+ const card = updates[0].data;+ assert.deepEqual(card.options, ['once', 'deny']);+ assert.equal(card.permission.upload.path, '/home/user/Downloads/tax-return.pdf');+ assert.match(card.question, /tax-return\.pdf/);+ assert.match(card.question, /forms\.example\.test/);+ assert.match(card.question, /did not attach this file/);+ agent.submitClarifyResponse(TAB, card.clarifyId, 'always', 'test');+ assert.equal(await choice, 'deny', '"always" fails closed on an upload card');++ const staged = uploadApprovalCard({ kind: 'download', path: '/d/a.png', sourceUrl: 'blob:chrome-extension://id/1', runOwned: true });+ assert.equal(staged.sourceUrl, '', 'a staged blob address tells the user nothing and is not shown');+ assert.equal(staged.name, 'a.png');+ });++ test(`${build}: the handler attaches nothing when the approved source no longer matches`, async () => {+ const agent = new Agent({ getActive: () => ({ promptTier: 'full', supportsVision: false }) });+ agent._resolvePromptTier = () => 'full';+ agent._currentUrl = async () => PAGE;+ // The gate saw nothing it could read (say, an unfinished download); by+ // dispatch the download finished. That file was never shown to the user.+ const result = await agent.executeTool(TAB, 'upload_file', { selector: '#resume', downloadId: 41 }, null, { uploadSourceKey: 'none' });+ assert.equal(result.success, false);+ assert.equal(result.noDispatch, true);+ assert.match(result.error, /changed after it was approved/);+ });++ if (build === 'chrome') {+ test('chrome: a filePath outside the run needs approval each call; the run download\'s own path does not', async () => {+ const h = harness({ gateOff: true });+ h.answer = 'deny';+ await h.upload({ filePath: '/home/user/.ssh/id_ed25519' });+ assert.equal(h.prompts.length, 1);+ assert.equal(h.prompts[0].upload.kind, 'path');+ assert.equal(h.prompts[0].upload.path, '/home/user/.ssh/id_ed25519');+ assert.equal(h.dispatched.length, 0);++ await h.upload({ filePath: '/home/user/Downloads/report.pdf' });+ assert.equal(h.prompts.length, 1, 'the saved path of this run\'s download is the run\'s own file');+ assert.deepEqual(h.dispatched.map(item => item.uploadSourceKey), ['path:/home/user/Downloads/report.pdf']);++ // A run-owned downloadId that cannot be read falls back to filePath in+ // the handler, so the gate judges the path, not the id.+ downloads.set(8, { id: 8, state: 'in_progress', filename: '' });+ h.agent._rememberRunDownloads(TAB, 'download_resource_from_page', { success: true, downloadId: 8 });+ await h.upload({ downloadId: 8, filePath: '/etc/shadow' });+ assert.equal(h.prompts.length, 2);+ assert.equal(h.prompts[1].upload.path, '/etc/shadow');+ assert.equal(h.dispatched.length, 1);+ downloads.delete(8);+ });+ }+}++// The side panel card of both builds, run in Chromium and Firefox: the real+// renderClarifyCard, submitClarify and /dangerously-skip-permissions resolver.+const read = (build, file) => fs.readFileSync(new URL(`../src/${build}/${file}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');+function extract(source, name) {+ const start = source.search(new RegExp(`^(?:export )?(?:async )?function ${name}\\(`, 'm'));+ assert.ok(start >= 0, `Missing function: ${name}`);+ return source.slice(start, source.indexOf('\n}', start) + 2).replace(/^export /, '');+}++async function panel(build, engine) {+ const source = read(build, 'src/ui/sidepanel.js');+ const english = (await import(`../src/${build}/src/ui/locales/en.js`)).default;+ const content = `(() => {+ const STRINGS = ${JSON.stringify(english)};+ const t = (key, params) => String(STRINGS[key] ?? key).replace(/\\{(\\w+)\\}/g, (_, name) => params?.[name] ?? '{' + name + '}');+ let currentTabId = 9;+ let currentAssistantEl = document.querySelector('.message.assistant');+ const submittedClarificationIds = new Set();+ const sent = [];+ function clarificationSubmissionKey(tabId, requestId, clarifyId) { return JSON.stringify([Number(tabId), String(requestId || ''), String(clarifyId || '')]); }+ function hideActivity() {} function playClarifySound() {} function scrollToBottom() {} function hideRecommendedActions() {}+ function resetChatNavigation() {} function addMessage() { return currentAssistantEl; } function applyClarifyTimeoutExtension() {}+ function clearClarifyCountdown() {} function placeAnsweredClarifyCardInTimeline() {} function startClarifyCountdown() {}+ function maybeShowPermissionEducationHint() { sent.push(['education_hint']); }+ function workflowHealingTargetLabel(value) { return String(value || ''); }+ function sameTabId(a, b) { return Number(a) === Number(b); } function restoreActiveRunState() {}+ const CAPABILITY_LABEL = {};+ async function sendToBackground(action, payload) { sent.push([action, payload]); return { matched: true }; }+ ${extract(read(build, 'src/agent/permission-gate.js'), 'uploadApprovalCard')}+ ${extract(source, 'renderClarifyCard')}+ ${extract(source, 'submitClarify')}+ ${extract(source, 'resolvePendingPermissionPromptsForTab')}+ window.panel = { render: renderClarifyCard, skipAll: resolvePendingPermissionPromptsForTab, sent };+ })();`;+ const browser = await engine.launch({ headless: true });+ try {+ const page = await browser.newPage({ viewport: { width: 380, height: 700 } });+ await page.setContent(`<style>${read(build, 'styles/sidepanel.css')}</style>+ <div class="message assistant" data-run-request-id="request-1"><div class="message-content"></div></div>`);+ await page.addScriptTag({ content });+ return { browser, page };+ } catch (error) {+ await browser.close();+ throw error;+ }+}++const uploadCard = (clarifyId, upload) => ({ clarifyId, tabId: 9, promptKind: 'permission',+ permission: { capability: 'upload', host: HOST, upload }, question: 'fallback', options: ['once', 'deny'] });+const view = (page, id) => page.evaluate(clarifyId => {+ const card = document.querySelector(`.clarify-card[data-clarify-id="${clarifyId}"]`);+ return { question: card.querySelector('.clarify-question').textContent,+ lines: [...card.querySelectorAll('.clarify-reason')].map(element => element.textContent),+ buttons: [...card.querySelectorAll('.clarify-option')].map(button => [button.dataset.value, button.textContent]),+ exactFile: card.dataset.uploadExactFile || '', images: card.querySelectorAll('img').length };+}, id);++for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {+ test(`${build}: the side panel upload card shows the exact file, and only a click answers a file from outside the run`, async () => {+ const { browser, page } = await panel(build, engine);+ try {+ await page.evaluate(data => window.panel.render(data), uploadCard('upload_other', { kind: 'download', runOwned: false,+ path: 'C:\\Users\\me\\Downloads\\tax <img src=x>.pdf', sourceUrl: 'https://bank.example.test/statement.pdf' }));+ const other = await view(page, 'upload_other');+ assert.match(other.question, /attach a local file to a page on forms\.example\.test/);+ assert.deepEqual(other.lines.slice(0, 3), ['File: tax <img src=x>.pdf', 'Local path: C:\\Users\\me\\Downloads\\tax <img src=x>.pdf',+ 'Downloaded from: https://bank.example.test/statement.pdf']);+ assert.match(other.lines[3], /did not attach this file/);+ assert.deepEqual(other.buttons.map(([value]) => value), ['once', 'deny'], 'no "always" on an upload card');+ assert.equal(other.exactFile, '1');+ assert.equal(other.images, 0, 'file names are text, never markup');++ await page.evaluate(data => window.panel.render(data), uploadCard('upload_run', { kind: 'download', runOwned: true,+ path: '/home/user/Downloads/report.pdf', sourceUrl: 'blob:chrome-extension://id/1' }));+ const own = await view(page, 'upload_run');+ assert.deepEqual(own.lines.slice(0, 2), ['File: report.pdf', 'Local path: /home/user/Downloads/report.pdf']);+ assert.match(own.lines[2], /this task downloaded it/);+ assert.equal(own.exactFile, '');++ // /dangerously-skip-permissions answers the run's own file, never the other one.+ assert.equal(await page.evaluate(() => window.panel.skipAll(9)), 1);+ const answered = await page.evaluate(() => window.panel.sent.filter(([action]) => action === 'clarify_response').map(([, payload]) => [payload.clarifyId, payload.answer]));+ assert.deepEqual(answered, [['upload_run', 'once']]);+ await page.click('.clarify-card[data-clarify-id="upload_other"] button[data-value="deny"]');+ const after = await page.evaluate(() => window.panel.sent.filter(([action]) => action === 'clarify_response').map(([, payload]) => [payload.clarifyId, payload.answer]));+ assert.deepEqual(after, [['upload_run', 'once'], ['upload_other', 'deny']]);+ assert.equal(await page.evaluate(() => window.panel.sent.some(([action]) => action === 'education_hint')), false,+ 'the "always allow" hint is not offered on an upload card');+ } finally { await browser.close(); }+ });+}