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
Limit download tools to this conversation's files and ask before reading others
Barack Sokullu6be856447d05
diff --git a/docs/security-model.md b/docs/security-model.mdindex 1bc3e8090..dec13b7fd 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -35,7 +35,7 @@ see Firefox Differences below.)| `<all_urls>` | Content script injection anywhere — the agent can read and interact with any page the user visits | A turn needs an action mode (Act or Dev) before clicks/types/navigation, and only the user's own request grants one: in their own words or with `/act` or `/dev` (see **Automatic mode selection** below). Ask mode is read-only. General browser-tab creation, enumeration, activation, and run retargeting are not exposed as model-callable tools. The one OTP-skill-gated Mid/Full reader internally selects an already-open supported mailbox and returns only bounded service-matching content; it exposes no tab catalog. Candidate inspection is read-only, while opening a selected message requires Act/Dev and mailbox-host click permission because it may mark mail read. Its disposable inactive clone consumes exact message continuations to completion or fails closed. || `debugger` | CDP access provides trusted events and full DOM/network control on any tab | The debugger is attached only to the target tab while a CDP-backed run or mode-scoped Dev diagnostics own it. Run cleanup closes run-scoped WebMCP state and detaches unless Dev diagnostics remain active; conversation cleanup and tab removal drain all owners and detach. || `webRequest` | Can observe XHR/fetch metadata for requests made by the active page | API mutation observer is on by default; it keeps only a bounded in-memory per-tab buffer for repeated-click shortcut hints and opaque same-origin replay. |-| `downloads` | Can save files to the user's Downloads folder without prompting | Only the agent's explicit download-capable tool calls (`download_files`, `download_file`, `download_resource_from_page`, `download_social_media`, download-job skill tools) use this, and each is gated by the capability × origin permission prompt. |+| `downloads` | Can save files to the user's Downloads folder without prompting, and read the browser's download history | Only the agent's explicit download-capable tool calls (`download_files`, `download_file`, `download_resource_from_page`, `download_social_media`, download-job skill tools) use this, and each is gated by the capability × origin permission prompt. `list_downloads` and `read_downloaded_file` see only the conversation's own downloads: files those tools saved, and downloads that started while a WebBrain run was active on the tab (a download names no tab, so concurrent runs share one). Listed files carry their basename, not the local path. Reading any other file from the history needs the user's approval of that exact file on WebBrain's card ("Read this file once"); an unattended run cannot ask and reads nothing. || `alarms` | Can wake scheduled jobs in future browser sessions | `schedule_resume` / `schedule_task` are gated; the user-authored `/watch` slash command can also create a page-bound 30–120 second conditional poll. || `offscreen` | An offscreen document can make HTTP requests immune to user CSP, run local inference, or play audio without an open panel | Used for the localhost LLM proxy, the optional endpoint-free WebGPU text and vision providers, tab recording, validated download staging, the local controller bridge, and successful `/watch /beep` tones. The text provider receives the same bounded conversation and allowlisted tool schemas that would be sent to another active provider; dedicated local vision receives only its screenshot/prompt. Model files are downloaded from Hugging Face, while inference stays in the worker. Watch audio receives only a style selector, never page content or an arbitrary URL. || `sidePanel` | Opens the extension side panel UI | The panel is user-invoked (toolbar click / `Alt+Shift+W`). No model-callable tool opens it silently; it only hosts the chat UI the user already sees. |diff --git a/package.json b/package.jsonindex 9e53890ff..e8fdacb07 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/download-conversation-scope.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: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",@@ -105,7 +105,7 @@"test:chat-draft-recovery": "node --test test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs && node test/quality/native-chat-presubmit-mv3.mjs","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: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/download-conversation-scope.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-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",diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 8ddfe71de..e8fd4f761 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -89,6 +89,7 @@ import {researchUrl,listDownloads,readDownloadedFile,+ downloadBasename,downloadResourceFromPage,downloadFiles,} from '../network/network-tools.js';@@ -287,6 +288,8 @@ const PLAN_REVIEW_CONFIDENCE_DEFAULT = 0.75;// chain cannot grow the anchor without limit.const CLARIFICATION_ANSWER_CHARS = 400;const CLARIFICATION_ANSWER_LIMIT = 8;+// Download ids a conversation keeps (and saves); the oldest go first.+const CONVERSATION_DOWNLOAD_LIMIT = 200;// Planner history digest (_buildPlannerHistoryDigest). buildPlannerMessages and// the alignment check keep its first 2,000 characters, so it stays within that.const PLANNER_DIGEST_MAX_CHARS = 2000;@@ -1261,6 +1264,11 @@ export class Agent extends LoopDetector {this.autoScreenshotBursts = new Map();this.lastSeenAdapter = new Map(); // tabId -> adapter name from last enrichmentthis._huggingFaceSignupRecoveries = new Map(); // tabId -> task-bound, value-free signup checkpoint+ // tabId -> Set(downloadId): the downloads this conversation produced, the+ // only ones list_downloads shows and read_downloaded_file reads without+ // asking (see _rememberConversationDownload).+ this._conversationDownloads = new Map();+ this._runDownloadListener = null;this.pendingAdapterMatchTraces = new Map(); // tabId -> Map(adapter@revision -> content-free match metadata)this.adapterMatchTraceKeys = new Map(); // runId -> Map(adapter@revision -> OR-merged match metadata)// Per-tab opt-in: when true, the agent is allowed to use API mutations@@ -6359,6 +6367,7 @@ export class Agent extends LoopDetector {// Claim synchronously before awaiting the external guard so teacher-mode// startup cannot race a run whose persisted teacher-state check is pending.this._runningTabs.add(tabId);+ this._watchRunDownloads();const monitoringRetry = runOptions.trustedContinuation === true? this._failureRecovery.takeMonitoringRetry(this._failureRecoveryBinding(tabId), String(runOptions.detachedRequestId || '')): null;@@ -7850,6 +7859,9 @@ export class Agent extends LoopDetector {if (data.videoLengthConfirmation) {display.videoLengthConfirmation = record(data.videoLengthConfirmation, ['estimatedSeconds', 'totalSeconds', 'clipCount', 'maxSeconds']);}+ if (data.downloadReadConfirmation) {+ display.downloadReadConfirmation = record(data.downloadReadConfirmation, ['filename', 'host'], 300);+ }if (data.researchEscalation) display.researchEscalation = record(data.researchEscalation, ['engine', 'request'], 6000);if (data.workflowHealing) {const target = value => record(value, ['role', 'name', 'label', 'ariaLabel', 'placeholder',@@ -8240,6 +8252,7 @@ export class Agent extends LoopDetector {this.conversationModes.set(forkId, 'ask');this.conversationIds.set(forkId, `conv_${forkId}_${Date.now().toString(36)}_${secureRandomBase36Token(12)}`);this._latestWorkflowDrafts.delete(forkId);+ this._conversationDownloads.delete(forkId);this.selectionGroundingScopes.delete(forkId);this.selectionGroundingRestorationPendingTabs.delete(forkId);this.progressLedgers.delete(forkId);@@ -22222,6 +22235,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}this._restorePersistedRichTextToolbarAudit(tabId, entry.richTextToolbarAudit);this._restoreTaskAttemptLedger(tabId, entry.taskAttemptLedger, attemptStored?.[attemptKey]);+ const savedDownloads = entry.conversationDownloads;+ if (typeof entry.conversationId === 'string' && entry.conversationId+ && savedDownloads?.conversationId === entry.conversationId && Array.isArray(savedDownloads.ids)) {+ const ids = savedDownloads.ids.filter(id => Number.isSafeInteger(id) && id >= 0).slice(-CONVERSATION_DOWNLOAD_LIMIT);+ if (ids.length) this._conversationDownloads.set(tabId, new Set(ids));+ }const savedVideoObligation = entry.videoDurationObligation;const videoDurationContract = normalizeVideoDurationContract(savedVideoObligation?.contract);if (videoDurationContract && typeof entry.conversationId === 'string' && entry.conversationId@@ -22406,6 +22425,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// The sites the current task attempted, so a correction after a restart// still knows them; never authorization.taskAttemptLedger: this._persistedTaskAttemptLedger(tabId),+ // Restored only into this conversation (_rememberConversationDownload).+ conversationDownloads: conversationId && this._conversationDownloads.get(tabId)?.size+ ? { conversationId, ids: [...this._conversationDownloads.get(tabId)] }+ : null,captchaGateState: captchaGateState?.cloudflareManagedChallenge === true|| captchaGateState?.publicGate?.cloudflareManagedChallenge === true? null@@ -39347,6 +39370,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._cancelClarifications(tabId, 'conversation cleared');this._cancelPendingPlans(tabId, 'conversation cleared');this.conversations.delete(tabId);+ this._conversationDownloads.delete(tabId);this.plannerFollowUpSkipTabs.delete(tabId);this.progressLedgers.delete(tabId);this.progressPageScopes.delete(tabId);@@ -39662,6 +39686,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d*/_pinDownloadId(tabId, downloadId) {if (downloadId == null) return;+ this._rememberConversationDownload(tabId, downloadId);this._autoScratchpadNote(tabId, `[auto] Downloaded file (downloadId ${downloadId}) — details are in list_downloads. Attach with upload_file({downloadId: ${downloadId}, selector}); re-read with read_downloaded_file({downloadId: ${downloadId}}).`);}@@ -39684,12 +39709,125 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._pinDownloadId(tabId, result.downloadId);} else if (name === 'download_social_media') {const n = Number(result.completedCount || 0);- if (n > 0) this._autoScratchpadNote(tabId, `[auto] download_social_media saved ${n} file(s) — find their ids/paths via list_downloads.`);+ if (n > 0) this._autoScratchpadNote(tabId, `[auto] download_social_media saved ${n} file(s) — find their ids via list_downloads.`);} else if (this._activeSkillToolForName(tabId, name)?.requiresDownloadPermission) {this._pinDownloadId(tabId, result.downloadId);}} catch { /* best-effort */ }}++ /**+ * The downloads this tab's conversation produced: the ids WebBrain's own+ * download tools returned here (_pinDownloadId) and every download that+ * started while a run was active on this tab, such as a clicked "Export"+ * link or download_social_media's page-side saves (_watchRunDownloads).+ * Only these are listed by list_downloads and read by read_downloaded_file+ * without asking. The rest of the browser's download history is the user's+ * own: reading one of those files needs the user's approval of that exact+ * file (_authorizeDownloadRead). Saved with the conversation, so a worker+ * restart keeps them; a new, forked or cleared conversation starts empty.+ */+ _rememberConversationDownload(tabId, downloadId) {+ if (tabId == null || !Number.isSafeInteger(downloadId) || downloadId < 0) return;+ let ids = this._conversationDownloads.get(tabId);+ if (!ids) this._conversationDownloads.set(tabId, ids = new Set());+ if (ids.has(downloadId)) return;+ ids.add(downloadId);+ while (ids.size > CONVERSATION_DOWNLOAD_LIMIT) ids.delete(ids.values().next().value);+ this._persist(tabId);+ }++ _isConversationDownload(tabId, downloadId) {+ return this._conversationDownloads.get(tabId)?.has(downloadId) === true;+ }++ // Added with the first run and kept for the worker's lifetime; outside runs+ // nothing is recorded. A download names no tab, so one that starts while+ // several tabs run belongs to each of their conversations.+ _watchRunDownloads() {+ if (this._runDownloadListener) return;+ const listener = item => {+ for (const tabId of this._runningTabs) this._rememberConversationDownload(tabId, item?.id);+ };+ try {+ if (!chrome.downloads?.onCreated?.addListener) return;+ chrome.downloads.onCreated.addListener(listener);+ this._runDownloadListener = listener;+ } catch { /* without the event only tool-returned ids are kept */ }+ }++ /**+ * read_downloaded_file sends a local file's bytes to the model's provider.+ * A download this conversation produced is read as before. Any other+ * download is the user's own file: WebBrain names it on its own card and+ * reads it only on the user's "Read once". The model's arguments, page text+ * and an unattended run never approve it. Returns null when the read may go+ * ahead, otherwise the result for the model.+ */+ async _authorizeDownloadRead(tabId, downloadId, onUpdate = null) {+ // readDownloadedFile reports an invalid id itself.+ if (!Number.isSafeInteger(downloadId) || downloadId < 0 || this._isConversationDownload(tabId, downloadId)) return null;+ const refused = (error, extra = {}) => ({ success: false, code: 'download_not_from_conversation', ...extra, error });+ const find = async () => {+ try { return (await chrome.downloads.search({ id: downloadId })).find(item => item.id === downloadId) || null; }+ catch { return null; }+ };+ const item = await find();+ if (!item || item.state !== 'complete' || item.exists === false || !item.filename) {+ return refused(`Download #${downloadId} is not a file downloaded in this conversation. Use a downloadId from this conversation's download results or list_downloads; if the user wants another downloaded file read, ask them to attach it.`);+ }+ let host = '';+ try { host = new URL(item.finalUrl || item.url).hostname; } catch {}+ const choice = await this._promptDownloadReadConfirmation(tabId, { filename: downloadBasename(item.filename), host }, onUpdate);+ if (choice === null) return refused('The user stopped or corrected the task before approving this file, so nothing was read.', { cancelled: true });+ if (choice === 'unavailable') {+ return refused(`Download #${downloadId} is not a file downloaded in this conversation, and the user cannot be asked to approve reading it in this run, so nothing was read.`);+ }+ if (choice !== 'once') {+ return refused('The user did not approve reading this downloaded file, so nothing was read. Do not ask again; continue without it.', { readDeclined: true });+ }+ // The answer covers the file the card named.+ if ((await find())?.filename !== item.filename) return refused('The downloaded file changed while the user was deciding, so nothing was read.');+ return null;+ }++ /**+ * The card for _authorizeDownloadRead: the file's name (the download's own,+ * page-settable name, which the side panel shows as text only) and the site+ * it came from. Like a permission prompt it never times out and never+ * answers itself; an unattended scheduled run cannot ask. Returns 'once',+ * 'deny', 'unavailable', or null when Stop or a correction cancelled it.+ */+ async _promptDownloadReadConfirmation(tabId, details = {}, onUpdate = null) {+ const confirmation = {+ filename: String(details.filename || '').slice(0, 260),+ host: String(details.host || '').slice(0, 300),+ };+ if (this.scheduledRunPolicies.get(tabId)?.requireConsequentialConfirmation === false) return 'unavailable';+ if (typeof onUpdate !== 'function') return 'unavailable';+ const clarifyId = `download_read_${secureRandomBase36Token(12)}`;+ const tabPending = this._pendingClarifications.get(tabId) || new Map();+ this._pendingClarifications.set(tabId, tabPending);+ const responsePromise = new Promise((resolve) => {+ tabPending.set(clarifyId, { resolve, ts: Date.now(), timer: null, settled: false, timeoutSec: 0, deadlineTs: 0, onUpdate });+ });+ try {+ onUpdate('clarify', {+ promptKind: 'download_read',+ clarifyId,+ // English for traces and surfaces without the side panel's localized copy.+ question: `Let WebBrain read ${confirmation.filename || 'this file'} from your downloads? Its contents go to your AI provider.`,+ downloadReadConfirmation: confirmation,+ options: ['once', 'deny'],+ });+ } catch { /* UI emit must never break the run */ }+ const response = await responsePromise;+ tabPending.delete(clarifyId);+ if (tabPending.size === 0 && this._pendingClarifications.get(tabId) === tabPending) this._pendingClarifications.delete(tabId);+ if (response?.cancelled) return null;+ if (['timeout', 'auto'].includes(response?.source)) return 'deny';+ return String(response?.answer || '').trim().toLowerCase() === 'once' ? 'once' : 'deny';+ }// ─────────────────────────────────────────────────────────────────────// App-owned progress ledger projected into the prompt.@@ -49291,10 +49429,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn await researchUrl(args.url, { ...args, sourceTabId: tabId });}if (name === 'list_downloads') {- return await listDownloads(args);+ return await listDownloads(args, { downloadIds: this._conversationDownloads.get(tabId) || [] });}if (name === 'read_downloaded_file') {const readOwner = this._pageFeedbackOwnerScope?.(tabId) || '';+ const refused = await this._authorizeDownloadRead(tabId, args.downloadId, onUpdate);+ if (refused) return refused;return await readDownloadedFile(args.downloadId, { tabId, cdpClient,signal: executionContext?._contentActionAbortSignal,checkStillActive: () => {diff --git a/src/chrome/src/agent/guard-policy.js b/src/chrome/src/agent/guard-policy.jsindex 63a8ff2fb..228041957 100644--- a/src/chrome/src/agent/guard-policy.js+++ b/src/chrome/src/agent/guard-policy.js@@ -303,6 +303,9 @@ export const GUARDS = Object.freeze({summary: "A trusted click (native button or click_ax trusted fallback) on this exact document+ref earlier in the task may have landed and was never verified: the same target is not clicked again (one trusted fallback per ref per run)." },"clickax-trusted-retry-vetoes": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",summary: "WebBrain's automatic trusted retry of a click_ax that produced no visible change is skipped for concurrent tab/network/download activity, mutating captions, changed or ineligible targets." },+ "downloaded-file-conversation-scope": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "read_downloaded_file of a download this conversation did not produce (WebBrain's download tools, or a download that started during one of its runs) reads nothing unless the user approves that exact file on WebBrain's card; an unattended run cannot ask and reads nothing.",+ mustNotBlock: "test/download-conversation-scope.mjs#a download from this conversation is listed and read without asking" },"downloaded-file-task-changed": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",summary: "read_downloaded_file discards bytes when steering arrived, the page-feedback owner, the download or the pinned document changed during the read, or the reader/document cannot be pinned." },"iframe-target-binding": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",diff --git a/src/chrome/src/agent/scheduler.js b/src/chrome/src/agent/scheduler.jsindex 20fd87bfd..99ac989a5 100644--- a/src/chrome/src/agent/scheduler.js+++ b/src/chrome/src/agent/scheduler.js@@ -199,6 +199,14 @@ function normalizePendingClarify(data, now = Date.now()) {maxSeconds: whole(videoLength.maxSeconds),};}+ // WebBrain's card about reading a file from the user's downloads: its name.+ const downloadRead = asObject(obj.downloadReadConfirmation);+ if (downloadRead.filename) {+ pending.downloadReadConfirmation = {+ filename: String(downloadRead.filename).slice(0, 260),+ host: String(downloadRead.host || '').slice(0, 300),+ };+ }return pending;}diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.jsindex c15220b80..7c0f18b09 100644--- a/src/chrome/src/agent/tools.js+++ b/src/chrome/src/agent/tools.js@@ -1112,7 +1112,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'list_downloads',- description: 'List the user\'s most recent downloads with state, filename, source URL, and bytes received. Use this to verify a download you triggered actually completed.',+ description: 'List this conversation\'s downloads (files you downloaded, or that downloaded while you worked) with state, file name, source URL, and bytes received. Use this to verify a download you triggered actually completed. The user\'s other download history is not listed.',parameters: {type: 'object',properties: {@@ -1126,7 +1126,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'read_downloaded_file',- description: 'Read actual saved bytes of a completed browser download through an isolated local-file reader; never re-fetch its source URL. Returns at most 16k text characters, base64 for small binaries, or saved-file metadata for large binaries. Pass downloadId from list_downloads or download_files. A missing file or unavailable local reader returns an error.',+ description: 'Read actual saved bytes of a completed browser download through an isolated local-file reader; never re-fetch its source URL. Returns at most 16k text characters, base64 for small binaries, or saved-file metadata for large binaries. Pass downloadId from list_downloads or download_files. A missing file or unavailable local reader returns an error. A download from outside this conversation is read only if the user approves that exact file on WebBrain\'s card.',parameters: {type: 'object',properties: {diff --git a/src/chrome/src/network/network-tools.js b/src/chrome/src/network/network-tools.jsindex c9298234c..9c3b77b4d 100644--- a/src/chrome/src/network/network-tools.js+++ b/src/chrome/src/network/network-tools.js@@ -2363,21 +2363,32 @@ export async function researchUrl(url, opts = {}) {// ─── list_downloads ─────────────────────────────────────────────────────-export async function listDownloads(opts = {}) {+// The browser's download history is the user's own: unrelated files, their+// source URLs and full local paths (which name the OS account). The model+// sees only the downloads its conversation produced (`downloadIds`, kept by+// the agent), and each file only by its basename.+export function downloadBasename(filename) {+ return String(filename || '').split(/[\\/]/).pop() || '';+}++export async function listDownloads(opts = {}, { downloadIds = [] } = {}) {try {const limit = Math.min(opts.limit || 10, 50);- const items = await chrome.downloads.search({- orderBy: ['-startTime'],- limit,- exists: true,- });+ const ids = [...new Set(downloadIds)].filter(id => Number.isSafeInteger(id) && id >= 0).sort((a, b) => b - a);+ const items = [];+ for (const id of ids) {+ if (items.length >= limit) break;+ const found = (await chrome.downloads.search({ id })).find(item => item.id === id);+ if (found && found.exists !== false) items.push(found);+ }return {success: true,count: items.length,+ ...(items.length ? {} : { note: 'No downloads from this conversation. Only files WebBrain downloaded, or that downloaded while it was working, in this conversation are listed; the browser\'s download history is not. If the user wants another downloaded file read, ask them to attach it.' }),downloads: items.map(d => ({id: d.id,url: d.url,- filename: d.filename,+ filename: downloadBasename(d.filename),state: d.state,bytesReceived: d.bytesReceived,totalBytes: d.totalBytes,@@ -2426,7 +2437,7 @@ function downloadedFileContent(item, payload, contentSource, savedFileVerified)return { success: false, code: 'saved_download_read_incomplete', error: 'The downloaded-file byte window could not be verified.' };}const ct = String(item.mime || payload.mimeType || '').toLowerCase();- const common = { success: true, filename: item.filename, contentType: ct, sizeBytes: size,+ const common = { success: true, filename: downloadBasename(item.filename), contentType: ct, sizeBytes: size,contentSource, savedFileVerified, sourceRefetched: false, bytesRead: bytes.length };if (downloadedFileIsText(item, ct)) {// Do not invent the full character count of a bounded byte prefix. A@@ -2438,7 +2449,7 @@ function downloadedFileContent(item, payload, contentSource, savedFileVerified)}if (size > READ_FILE_BASE64_LIMIT * 0.75) {return { ...common, note: savedFileVerified- ? `Binary file too large to inline (${size} bytes). It is on disk at: ${item.filename}`+ ? `Binary file too large to inline (${size} bytes). It is saved as ${downloadBasename(item.filename)}.`: `Captured binary payload too large to inline (${size} bytes). Firefox cannot verify the current on-disk file.` };}if (payload.dataTruncated) return { success: false, code: 'saved_download_read_incomplete', error: 'The small binary payload was not read completely.' };diff --git a/src/chrome/src/ui/locales/ar.js b/src/chrome/src/ui/locales/ar.jsindex 1f9c542b4..ff33767a3 100644--- a/src/chrome/src/ui/locales/ar.js+++ b/src/chrome/src/ui/locales/ar.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "إنشاء نسخة {total}","sp.video_length.dont": "عدم الإنشاء","sp.video_length.seconds": "{seconds} ث",+ "sp.download_read.question": "هل تسمح لـ WebBrain بقراءة هذا الملف من التنزيلات؟",+ "sp.download_read.reason": "لم يقم WebBrain بتنزيله في هذه المحادثة. إذا سمحت بذلك، فسيُرسَل محتوى الملف إلى مزوّد الذكاء الاصطناعي.",+ "sp.download_read.file_from": "{filename} (من {host})",+ "sp.download_read.read": "قراءة هذا الملف مرة واحدة",+ "sp.download_read.dont": "عدم القراءة","sp.unverified.question.commit": "هل تريد إيداع هذا على {host}؟","sp.unverified.question.submit": "هل تريد إرسال هذا على {host}؟","sp.unverified.question.publish": "هل تريد نشر هذا على {host}؟",diff --git a/src/chrome/src/ui/locales/bn.js b/src/chrome/src/ui/locales/bn.jsindex 339bbd17d..d2dfe43d0 100644--- a/src/chrome/src/ui/locales/bn.js+++ b/src/chrome/src/ui/locales/bn.js@@ -465,6 +465,11 @@ export default {"sp.video_length.generate": "{total} সংস্করণ তৈরি করুন","sp.video_length.dont": "তৈরি করবেন না","sp.video_length.seconds": "{seconds} সে.",+ "sp.download_read.question": "WebBrain-কে আপনার ডাউনলোড থেকে এই ফাইলটি পড়তে দেবেন?",+ "sp.download_read.reason": "WebBrain এই চ্যাটে এটি ডাউনলোড করেনি। অনুমতি দিলে ফাইলের বিষয়বস্তু আপনার AI প্রদানকারীর কাছে পাঠানো হবে।",+ "sp.download_read.file_from": "{filename} ({host} থেকে)",+ "sp.download_read.read": "এই ফাইলটি একবার পড়ুন",+ "sp.download_read.dont": "পড়বেন না","sp.unverified.question.commit": "{host}-এ এটি কমিট করবেন?","sp.unverified.question.submit": "{host}-এ এটি জমা দেবেন?","sp.unverified.question.publish": "{host}-এ এটি প্রকাশ করবেন?",diff --git a/src/chrome/src/ui/locales/de.js b/src/chrome/src/ui/locales/de.jsindex 925da832c..e94748567 100644--- a/src/chrome/src/ui/locales/de.js+++ b/src/chrome/src/ui/locales/de.js@@ -483,6 +483,11 @@ export default {"sp.video_length.generate": "{total}-Version erstellen","sp.video_length.dont": "Nicht erstellen","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Darf WebBrain diese Datei aus den Downloads lesen?",+ "sp.download_read.reason": "WebBrain hat sie nicht in diesem Chat heruntergeladen. Bei Erlaubnis wird der Inhalt der Datei an den KI-Anbieter gesendet.",+ "sp.download_read.file_from": "{filename} (von {host})",+ "sp.download_read.read": "Diese Datei einmal lesen",+ "sp.download_read.dont": "Nicht lesen","sp.unverified.question.commit": "Das auf {host} committen?","sp.unverified.question.submit": "Das auf {host} absenden?","sp.unverified.question.publish": "Das auf {host} veröffentlichen?",diff --git a/src/chrome/src/ui/locales/en.js b/src/chrome/src/ui/locales/en.jsindex 39d885745..0955081fa 100644--- a/src/chrome/src/ui/locales/en.js+++ b/src/chrome/src/ui/locales/en.js@@ -470,6 +470,11 @@ export default {"sp.video_length.generate": "Generate {total} version","sp.video_length.dont": "Don’t generate","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Let WebBrain read this file from your downloads?",+ "sp.download_read.reason": "WebBrain did not download it in this chat. If you allow it, the file’s contents are sent to your AI provider.",+ "sp.download_read.file_from": "{filename} (from {host})",+ "sp.download_read.read": "Read this file once",+ "sp.download_read.dont": "Don’t read it","sp.unverified.question.commit": "Commit this on {host}?","sp.unverified.question.submit": "Submit this on {host}?","sp.unverified.question.publish": "Publish this on {host}?",diff --git a/src/chrome/src/ui/locales/es.js b/src/chrome/src/ui/locales/es.jsindex 62db780bb..20694825a 100644--- a/src/chrome/src/ui/locales/es.js+++ b/src/chrome/src/ui/locales/es.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Generar versión de {total}","sp.video_length.dont": "No generar","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "¿Permitir que WebBrain lea este archivo de tus descargas?",+ "sp.download_read.reason": "WebBrain no lo descargó en este chat. Si lo permites, el contenido del archivo se enviará a tu proveedor de IA.",+ "sp.download_read.file_from": "{filename} (de {host})",+ "sp.download_read.read": "Leer este archivo una vez",+ "sp.download_read.dont": "No leer","sp.unverified.question.commit": "¿Hacer commit de esto en {host}?","sp.unverified.question.submit": "¿Enviar esto en {host}?","sp.unverified.question.publish": "¿Publicar esto en {host}?",diff --git a/src/chrome/src/ui/locales/fa.js b/src/chrome/src/ui/locales/fa.jsindex 399ecf839..750a54354 100644--- a/src/chrome/src/ui/locales/fa.js+++ b/src/chrome/src/ui/locales/fa.js@@ -465,6 +465,11 @@ export default {"sp.video_length.generate": "ساخت نسخهٔ {total}","sp.video_length.dont": "نساز","sp.video_length.seconds": "{seconds} ثانیه",+ "sp.download_read.question": "اجازه میدهید WebBrain این فایل را از دانلودهای شما بخواند؟",+ "sp.download_read.reason": "WebBrain این فایل را در این گفتگو دانلود نکرده است. اگر اجازه دهید، محتوای فایل برای ارائهدهنده هوش مصنوعی شما ارسال میشود.",+ "sp.download_read.file_from": "{filename} (از {host})",+ "sp.download_read.read": "یک بار این فایل را بخوان",+ "sp.download_read.dont": "نخوان","sp.unverified.question.commit": "این در {host} کامیت شود؟","sp.unverified.question.submit": "این در {host} ارسال شود؟","sp.unverified.question.publish": "این در {host} منتشر شود؟",diff --git a/src/chrome/src/ui/locales/fr.js b/src/chrome/src/ui/locales/fr.jsindex 38de3e4d1..b48a01e86 100644--- a/src/chrome/src/ui/locales/fr.js+++ b/src/chrome/src/ui/locales/fr.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Générer la version de {total}","sp.video_length.dont": "Ne pas générer","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Autoriser WebBrain à lire ce fichier de vos téléchargements ?",+ "sp.download_read.reason": "WebBrain ne l’a pas téléchargé dans cette conversation. Si vous l’autorisez, le contenu du fichier est envoyé à votre fournisseur d’IA.",+ "sp.download_read.file_from": "{filename} (depuis {host})",+ "sp.download_read.read": "Lire ce fichier une fois",+ "sp.download_read.dont": "Ne pas lire","sp.unverified.question.commit": "Valider (commit) ceci sur {host} ?","sp.unverified.question.submit": "Envoyer ceci sur {host} ?","sp.unverified.question.publish": "Publier ceci sur {host} ?",diff --git a/src/chrome/src/ui/locales/he.js b/src/chrome/src/ui/locales/he.jsindex 57f414e2a..801594811 100644--- a/src/chrome/src/ui/locales/he.js+++ b/src/chrome/src/ui/locales/he.js@@ -456,6 +456,11 @@ export default {"sp.video_length.generate": "יצירת גרסה של {total}","sp.video_length.dont": "לא ליצור","sp.video_length.seconds": "{seconds} שנ׳",+ "sp.download_read.question": "לאפשר ל-WebBrain לקרוא את הקובץ הזה מההורדות שלך?",+ "sp.download_read.reason": "WebBrain לא הוריד אותו בצ׳אט הזה. אם תאפשר זאת, תוכן הקובץ יישלח לספק ה-AI שלך.",+ "sp.download_read.file_from": "{filename} (מ-{host})",+ "sp.download_read.read": "לקרוא את הקובץ הזה פעם אחת",+ "sp.download_read.dont": "לא לקרוא","sp.unverified.question.commit": "לבצע commit לזה ב-{host}?","sp.unverified.question.submit": "לשלוח את זה ב-{host}?","sp.unverified.question.publish": "לפרסם את זה ב-{host}?",diff --git a/src/chrome/src/ui/locales/hi.js b/src/chrome/src/ui/locales/hi.jsindex 1ba4480a0..c297eb8d0 100644--- a/src/chrome/src/ui/locales/hi.js+++ b/src/chrome/src/ui/locales/hi.js@@ -465,6 +465,11 @@ export default {"sp.video_length.generate": "{total} संस्करण बनाएँ","sp.video_length.dont": "न बनाएँ","sp.video_length.seconds": "{seconds} से.",+ "sp.download_read.question": "क्या WebBrain को आपके डाउनलोड से यह फ़ाइल पढ़ने दें?",+ "sp.download_read.reason": "WebBrain ने इसे इस चैट में डाउनलोड नहीं किया। अनुमति देने पर फ़ाइल की सामग्री आपके AI प्रदाता को भेजी जाएगी।",+ "sp.download_read.file_from": "{filename} ({host} से)",+ "sp.download_read.read": "यह फ़ाइल एक बार पढ़ें",+ "sp.download_read.dont": "न पढ़ें","sp.unverified.question.commit": "{host} पर इसे कमिट करें?","sp.unverified.question.submit": "{host} पर इसे सबमिट करें?","sp.unverified.question.publish": "{host} पर इसे प्रकाशित करें?",diff --git a/src/chrome/src/ui/locales/id.js b/src/chrome/src/ui/locales/id.jsindex 9e70412ef..91b28e354 100644--- a/src/chrome/src/ui/locales/id.js+++ b/src/chrome/src/ui/locales/id.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Buat versi {total}","sp.video_length.dont": "Jangan buat","sp.video_length.seconds": "{seconds} dtk",+ "sp.download_read.question": "Izinkan WebBrain membaca file ini dari unduhan Anda?",+ "sp.download_read.reason": "WebBrain tidak mengunduhnya di obrolan ini. Jika diizinkan, isi file akan dikirim ke penyedia AI Anda.",+ "sp.download_read.file_from": "{filename} (dari {host})",+ "sp.download_read.read": "Baca file ini sekali",+ "sp.download_read.dont": "Jangan baca","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Kirim ini di {host}?","sp.unverified.question.publish": "Publikasikan ini di {host}?",diff --git a/src/chrome/src/ui/locales/ja.js b/src/chrome/src/ui/locales/ja.jsindex 18f2e6d67..9686817fc 100644--- a/src/chrome/src/ui/locales/ja.js+++ b/src/chrome/src/ui/locales/ja.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "{total}版を作成","sp.video_length.dont": "作成しない","sp.video_length.seconds": "{seconds}秒",+ "sp.download_read.question": "ダウンロード済みのこのファイルを WebBrain に読み込ませますか?",+ "sp.download_read.reason": "このファイルは WebBrain がこのチャットでダウンロードしたものではありません。許可すると、ファイルの内容が AI プロバイダーに送信されます。",+ "sp.download_read.file_from": "{filename}({host} から)",+ "sp.download_read.read": "このファイルを 1 回読む",+ "sp.download_read.dont": "読まない","sp.unverified.question.commit": "{host} でこれをコミットしますか?","sp.unverified.question.submit": "{host} でこれを送信しますか?","sp.unverified.question.publish": "{host} でこれを公開しますか?",diff --git a/src/chrome/src/ui/locales/ko.js b/src/chrome/src/ui/locales/ko.jsindex fb7cda149..a78b8da0d 100644--- a/src/chrome/src/ui/locales/ko.js+++ b/src/chrome/src/ui/locales/ko.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "{total} 버전 만들기","sp.video_length.dont": "만들지 않기","sp.video_length.seconds": "{seconds}초",+ "sp.download_read.question": "WebBrain이 다운로드한 파일 중 이 파일을 읽도록 허용할까요?",+ "sp.download_read.reason": "WebBrain이 이 채팅에서 다운로드한 파일이 아닙니다. 허용하면 파일 내용이 AI 제공업체로 전송됩니다.",+ "sp.download_read.file_from": "{filename} ({host}에서)",+ "sp.download_read.read": "이 파일을 한 번 읽기",+ "sp.download_read.dont": "읽지 않기","sp.unverified.question.commit": "{host}에서 이 내용을 커밋할까요?","sp.unverified.question.submit": "{host}에서 이 내용을 제출할까요?","sp.unverified.question.publish": "{host}에서 이 내용을 게시할까요?",diff --git a/src/chrome/src/ui/locales/ms.js b/src/chrome/src/ui/locales/ms.jsindex 497352787..9f771cee8 100644--- a/src/chrome/src/ui/locales/ms.js+++ b/src/chrome/src/ui/locales/ms.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Jana versi {total}","sp.video_length.dont": "Jangan jana","sp.video_length.seconds": "{seconds} saat",+ "sp.download_read.question": "Benarkan WebBrain membaca fail ini daripada muat turun anda?",+ "sp.download_read.reason": "WebBrain tidak memuat turunnya dalam sembang ini. Jika dibenarkan, kandungan fail akan dihantar kepada penyedia AI anda.",+ "sp.download_read.file_from": "{filename} (dari {host})",+ "sp.download_read.read": "Baca fail ini sekali",+ "sp.download_read.dont": "Jangan baca","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Serahkan ini di {host}?","sp.unverified.question.publish": "Terbitkan ini di {host}?",diff --git a/src/chrome/src/ui/locales/nl.js b/src/chrome/src/ui/locales/nl.jsindex 76a138324..e7b6e5a29 100644--- a/src/chrome/src/ui/locales/nl.js+++ b/src/chrome/src/ui/locales/nl.js@@ -453,6 +453,11 @@ export default {"sp.video_length.generate": "Versie van {total} maken","sp.video_length.dont": "Niet maken","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Mag WebBrain dit bestand uit je downloads lezen?",+ "sp.download_read.reason": "WebBrain heeft het niet in deze chat gedownload. Als je het toestaat, wordt de inhoud van het bestand naar je AI-provider gestuurd.",+ "sp.download_read.file_from": "{filename} (van {host})",+ "sp.download_read.read": "Dit bestand één keer lezen",+ "sp.download_read.dont": "Niet lezen","sp.unverified.question.commit": "Dit committen op {host}?","sp.unverified.question.submit": "Dit versturen op {host}?","sp.unverified.question.publish": "Dit publiceren op {host}?",diff --git a/src/chrome/src/ui/locales/pl.js b/src/chrome/src/ui/locales/pl.jsindex df038e784..1fc6c76ac 100644--- a/src/chrome/src/ui/locales/pl.js+++ b/src/chrome/src/ui/locales/pl.js@@ -354,6 +354,11 @@ export default {"sp.video_length.generate": "Utwórz wersję {total}","sp.video_length.dont": "Nie twórz","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Pozwolić WebBrain odczytać ten plik z pobranych?",+ "sp.download_read.reason": "WebBrain nie pobrał go w tym czacie. Jeśli pozwolisz, zawartość pliku zostanie wysłana do Twojego dostawcy AI.",+ "sp.download_read.file_from": "{filename} (z {host})",+ "sp.download_read.read": "Odczytaj ten plik raz",+ "sp.download_read.dont": "Nie odczytuj","sp.unverified.question.commit": "Zatwierdzić (commit) to w {host}?","sp.unverified.question.submit": "Wysłać to w {host}?","sp.unverified.question.publish": "Opublikować to w {host}?",diff --git a/src/chrome/src/ui/locales/pt.js b/src/chrome/src/ui/locales/pt.jsindex d47f5f26c..8d3e547b5 100644--- a/src/chrome/src/ui/locales/pt.js+++ b/src/chrome/src/ui/locales/pt.js@@ -465,6 +465,11 @@ export default {"sp.video_length.generate": "Gerar versão de {total}","sp.video_length.dont": "Não gerar","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Permitir que o WebBrain leia este arquivo dos seus downloads?",+ "sp.download_read.reason": "O WebBrain não o baixou neste chat. Se você permitir, o conteúdo do arquivo será enviado ao seu provedor de IA.",+ "sp.download_read.file_from": "{filename} (de {host})",+ "sp.download_read.read": "Ler este arquivo uma vez",+ "sp.download_read.dont": "Não ler","sp.unverified.question.commit": "Fazer commit disto em {host}?","sp.unverified.question.submit": "Enviar isto em {host}?","sp.unverified.question.publish": "Publicar isto em {host}?",diff --git a/src/chrome/src/ui/locales/ru.js b/src/chrome/src/ui/locales/ru.jsindex f342a83d2..76f35c9d8 100644--- a/src/chrome/src/ui/locales/ru.js+++ b/src/chrome/src/ui/locales/ru.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Создать версию на {total}","sp.video_length.dont": "Не создавать","sp.video_length.seconds": "{seconds} с",+ "sp.download_read.question": "Разрешить WebBrain прочитать этот файл из загрузок?",+ "sp.download_read.reason": "WebBrain не скачивал его в этом чате. Если разрешить, содержимое файла будет отправлено вашему поставщику ИИ.",+ "sp.download_read.file_from": "{filename} (с {host})",+ "sp.download_read.read": "Прочитать этот файл один раз",+ "sp.download_read.dont": "Не читать","sp.unverified.question.commit": "Закоммитить это на {host}?","sp.unverified.question.submit": "Отправить это на {host}?","sp.unverified.question.publish": "Опубликовать это на {host}?",diff --git a/src/chrome/src/ui/locales/th.js b/src/chrome/src/ui/locales/th.jsindex 09a60f80e..2994ae935 100644--- a/src/chrome/src/ui/locales/th.js+++ b/src/chrome/src/ui/locales/th.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "สร้างเวอร์ชัน {total}","sp.video_length.dont": "ไม่สร้าง","sp.video_length.seconds": "{seconds} วินาที",+ "sp.download_read.question": "อนุญาตให้ WebBrain อ่านไฟล์นี้จากรายการดาวน์โหลดของคุณหรือไม่?",+ "sp.download_read.reason": "WebBrain ไม่ได้ดาวน์โหลดไฟล์นี้ในแชทนี้ หากอนุญาต เนื้อหาของไฟล์จะถูกส่งไปยังผู้ให้บริการ AI ของคุณ",+ "sp.download_read.file_from": "{filename} (จาก {host})",+ "sp.download_read.read": "อ่านไฟล์นี้หนึ่งครั้ง",+ "sp.download_read.dont": "ไม่อ่าน","sp.unverified.question.commit": "คอมมิตสิ่งนี้บน {host} ไหม?","sp.unverified.question.submit": "ส่งสิ่งนี้บน {host} ไหม?","sp.unverified.question.publish": "เผยแพร่สิ่งนี้บน {host} ไหม?",diff --git a/src/chrome/src/ui/locales/tl.js b/src/chrome/src/ui/locales/tl.jsindex 9855c98c4..b2c14a565 100644--- a/src/chrome/src/ui/locales/tl.js+++ b/src/chrome/src/ui/locales/tl.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Gumawa ng {total} na bersyon","sp.video_length.dont": "Huwag gumawa","sp.video_length.seconds": "{seconds} seg",+ "sp.download_read.question": "Payagan ang WebBrain na basahin ang file na ito mula sa iyong mga download?",+ "sp.download_read.reason": "Hindi ito na-download ng WebBrain sa chat na ito. Kapag pinayagan mo, ipapadala ang nilalaman ng file sa iyong AI provider.",+ "sp.download_read.file_from": "{filename} (mula sa {host})",+ "sp.download_read.read": "Basahin ang file na ito nang isang beses",+ "sp.download_read.dont": "Huwag basahin","sp.unverified.question.commit": "I-commit ito sa {host}?","sp.unverified.question.submit": "Isumite ito sa {host}?","sp.unverified.question.publish": "I-publish ito sa {host}?",diff --git a/src/chrome/src/ui/locales/tr.js b/src/chrome/src/ui/locales/tr.jsindex 16cedeaa4..860348378 100644--- a/src/chrome/src/ui/locales/tr.js+++ b/src/chrome/src/ui/locales/tr.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "{total} sürümünü üret","sp.video_length.dont": "Üretme","sp.video_length.seconds": "{seconds} sn",+ "sp.download_read.question": "WebBrain indirilenlerindeki bu dosyayı okusun mu?",+ "sp.download_read.reason": "WebBrain bu dosyayı bu sohbette indirmedi. İzin verirsen dosyanın içeriği yapay zekâ sağlayıcına gönderilir.",+ "sp.download_read.file_from": "{filename} ({host} kaynağından)",+ "sp.download_read.read": "Bu dosyayı bir kez oku",+ "sp.download_read.dont": "Okuma","sp.unverified.question.commit": "{host} üzerinde bu commit edilsin mi?","sp.unverified.question.submit": "{host} üzerinde bu gönderilsin mi?","sp.unverified.question.publish": "{host} üzerinde bu yayınlansın mı?",diff --git a/src/chrome/src/ui/locales/uk.js b/src/chrome/src/ui/locales/uk.jsindex 743c80cd1..a7ac8dd07 100644--- a/src/chrome/src/ui/locales/uk.js+++ b/src/chrome/src/ui/locales/uk.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Створити версію на {total}","sp.video_length.dont": "Не створювати","sp.video_length.seconds": "{seconds} с",+ "sp.download_read.question": "Дозволити WebBrain прочитати цей файл із завантажень?",+ "sp.download_read.reason": "WebBrain не завантажував його в цьому чаті. Якщо дозволити, вміст файлу буде надіслано вашому постачальнику ШІ.",+ "sp.download_read.file_from": "{filename} (з {host})",+ "sp.download_read.read": "Прочитати цей файл один раз",+ "sp.download_read.dont": "Не читати","sp.unverified.question.commit": "Закомітити це на {host}?","sp.unverified.question.submit": "Надіслати це на {host}?","sp.unverified.question.publish": "Опублікувати це на {host}?",diff --git a/src/chrome/src/ui/locales/vi.js b/src/chrome/src/ui/locales/vi.jsindex 8e1b92391..4affe6f45 100644--- a/src/chrome/src/ui/locales/vi.js+++ b/src/chrome/src/ui/locales/vi.js@@ -465,6 +465,11 @@ export default {"sp.video_length.generate": "Tạo bản {total}","sp.video_length.dont": "Không tạo","sp.video_length.seconds": "{seconds} giây",+ "sp.download_read.question": "Cho phép WebBrain đọc tệp này từ thư mục tải xuống của bạn?",+ "sp.download_read.reason": "WebBrain không tải tệp này xuống trong cuộc trò chuyện này. Nếu bạn cho phép, nội dung tệp sẽ được gửi đến nhà cung cấp AI của bạn.",+ "sp.download_read.file_from": "{filename} (từ {host})",+ "sp.download_read.read": "Đọc tệp này một lần",+ "sp.download_read.dont": "Không đọc","sp.unverified.question.commit": "Commit nội dung này trên {host}?","sp.unverified.question.submit": "Gửi nội dung này trên {host}?","sp.unverified.question.publish": "Đăng nội dung này trên {host}?",diff --git a/src/chrome/src/ui/locales/zh.js b/src/chrome/src/ui/locales/zh.jsindex cfa119106..312947dc1 100644--- a/src/chrome/src/ui/locales/zh.js+++ b/src/chrome/src/ui/locales/zh.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "生成 {total} 版本","sp.video_length.dont": "不生成","sp.video_length.seconds": "{seconds} 秒",+ "sp.download_read.question": "允许 WebBrain 读取你下载的这个文件吗?",+ "sp.download_read.reason": "这个文件不是 WebBrain 在本次对话中下载的。如果允许,文件内容会发送给你的 AI 服务提供商。",+ "sp.download_read.file_from": "{filename}(来自 {host})",+ "sp.download_read.read": "读取此文件一次",+ "sp.download_read.dont": "不读取","sp.unverified.question.commit": "要在 {host} 上提交(commit)这些内容吗?","sp.unverified.question.submit": "要在 {host} 上提交这些内容吗?","sp.unverified.question.publish": "要在 {host} 上发布这些内容吗?",diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex ea69d4146..3ba7ce90c 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -6736,7 +6736,7 @@ function rebindClarifyCards() {// the card. Skip permission/form-submit cards (they never auto-timeout).if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'|| card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'- || card.dataset.videoLengthConfirmation === '1') return;+ || card.dataset.videoLengthConfirmation === '1' || card.dataset.downloadReadConfirmation === '1') return;const deadlineTs = Number(card.dataset.deadlineTs);if (!Number.isFinite(deadlineTs) || deadlineTs <= 0) return;const firstOption = card.dataset.firstOption@@ -11758,6 +11758,7 @@ function renderClarifyCard(data) {? 'scheduled_clarification': data.workflowHealing || data.pendingReconciliation === true || data.recipientConfirmation|| data.mutationConfirmation || data.unverifiedStepConfirmation || data.videoLengthConfirmation+ || data.downloadReadConfirmation? '': data.submitConfirmation? 'form_confirmation'@@ -12022,6 +12023,44 @@ function renderClarifyCard(data) {return;}+ // Downloaded-file read: the model asked to read a file from the browser's+ // download history that WebBrain did not download in this chat. The name is+ // the download's own (page-settable) name, shown as text only. Fixed choices+ // return stable values ('once'/'deny'); the card never times out.+ if (data.downloadReadConfirmation) {+ card.dataset.downloadReadConfirmation = '1';+ const file = data.downloadReadConfirmation || {};+ const filename = String(file.filename || '').slice(0, 260);+ const host = String(file.host || '').slice(0, 300);+ qEl.textContent = t('sp.download_read.question');+ const reasonEl = document.createElement('div');+ reasonEl.className = 'clarify-reason';+ reasonEl.textContent = t('sp.download_read.reason');+ card.appendChild(reasonEl);+ const fileEl = document.createElement('div');+ fileEl.className = 'clarify-subject';+ fileEl.textContent = host ? t('sp.download_read.file_from', { filename, host }) : filename;+ card.appendChild(fileEl);+ const optionsEl = document.createElement('div');+ optionsEl.className = 'clarify-options';+ for (const [value, label] of [['once', t('sp.download_read.read')], ['deny', t('sp.download_read.dont')]]) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'clarify-option';+ b.textContent = String(label).slice(0, 200);+ b.dataset.value = value;+ b.addEventListener('click', () => {+ card.dataset.answerLabel = b.textContent;+ submitClarify(card, tabId, clarifyId, value, 'option');+ });+ optionsEl.appendChild(b);+ }+ card.appendChild(optionsEl);+ content.appendChild(card);+ scrollToBottom({ force: true });+ return;+ }+// Unverifiable step: one of WebBrain's checks could not verify a commit,// publish or submit, so it asks instead of refusing. The text is what the// page showed when WebBrain asked: page content, shown as text only@@ -12367,7 +12406,7 @@ function lockClarifyCardFromAuto(data) {const unverifiedStep = card.dataset.unverifiedStepConfirmation === '1';if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'|| card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'- || card.dataset.videoLengthConfirmation === '1') return;+ || card.dataset.videoLengthConfirmation === '1' || card.dataset.downloadReadConfirmation === '1') return;clearClarifyCountdown(card);card.classList.add('clarify-answered');for (const el of card.querySelectorAll('button, input')) {diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex a175c03d3..8471de645 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -87,6 +87,7 @@ import {researchUrl,listDownloads,readDownloadedFile,+ downloadBasename,downloadResourceFromPage,downloadFiles,registrableDomain,@@ -298,6 +299,8 @@ const PLAN_REVIEW_CONFIDENCE_DEFAULT = 0.75;// chain cannot grow the anchor without limit.const CLARIFICATION_ANSWER_CHARS = 400;const CLARIFICATION_ANSWER_LIMIT = 8;+// Download ids a conversation keeps (and saves); the oldest go first.+const CONVERSATION_DOWNLOAD_LIMIT = 200;// Planner history digest (_buildPlannerHistoryDigest). buildPlannerMessages and// the alignment check keep its first 2,000 characters, so it stays within that.const PLANNER_DIGEST_MAX_CHARS = 2000;@@ -898,6 +901,11 @@ export class Agent extends LoopDetector {this.autoScreenshotBursts = new Map();this.lastSeenAdapter = new Map();this._huggingFaceSignupRecoveries = new Map(); // tabId -> task-bound, value-free signup checkpoint+ // tabId -> Set(downloadId): the downloads this conversation produced, the+ // only ones list_downloads shows and read_downloaded_file reads without+ // asking (see _rememberConversationDownload).+ this._conversationDownloads = new Map();+ this._runDownloadListener = null;this.pendingAdapterMatchTraces = new Map(); // tabId -> Map(adapter@revision -> content-free match metadata)this.adapterMatchTraceKeys = new Map(); // runId -> Map(adapter@revision -> OR-merged match metadata)this.apiAllowedTabs = new Set();@@ -5879,6 +5887,7 @@ export class Agent extends LoopDetector {// Claim synchronously before awaiting the external guard so teacher-mode// startup cannot race a run whose persisted teacher-state check is pending.this._runningTabs.add(tabId);+ this._watchRunDownloads();const monitoringRetry = runOptions.trustedContinuation === true? this._failureRecovery.takeMonitoringRetry(this._failureRecoveryBinding(tabId), String(runOptions.detachedRequestId || '')): null;@@ -7370,6 +7379,9 @@ export class Agent extends LoopDetector {if (data.videoLengthConfirmation) {display.videoLengthConfirmation = record(data.videoLengthConfirmation, ['estimatedSeconds', 'totalSeconds', 'clipCount', 'maxSeconds']);}+ if (data.downloadReadConfirmation) {+ display.downloadReadConfirmation = record(data.downloadReadConfirmation, ['filename', 'host'], 300);+ }if (data.researchEscalation) display.researchEscalation = record(data.researchEscalation, ['engine', 'request'], 6000);if (data.workflowHealing) {const target = value => record(value, ['role', 'name', 'label', 'ariaLabel', 'placeholder',@@ -7802,6 +7814,12 @@ export class Agent extends LoopDetector {}this._restorePersistedRichTextToolbarAudit(tabId, entry.richTextToolbarAudit);this._restoreTaskAttemptLedger(tabId, entry.taskAttemptLedger, attemptStored?.[attemptKey]);+ const savedDownloads = entry.conversationDownloads;+ if (typeof entry.conversationId === 'string' && entry.conversationId+ && savedDownloads?.conversationId === entry.conversationId && Array.isArray(savedDownloads.ids)) {+ const ids = savedDownloads.ids.filter(id => Number.isSafeInteger(id) && id >= 0).slice(-CONVERSATION_DOWNLOAD_LIMIT);+ if (ids.length) this._conversationDownloads.set(tabId, new Set(ids));+ }const savedVideoObligation = entry.videoDurationObligation;const videoDurationContract = normalizeVideoDurationContract(savedVideoObligation?.contract);if (videoDurationContract && typeof entry.conversationId === 'string' && entry.conversationId@@ -7987,6 +8005,10 @@ export class Agent extends LoopDetector {// The sites the current task attempted, so a correction after a restart// still knows them; never authorization.taskAttemptLedger: this._persistedTaskAttemptLedger(tabId),+ // Restored only into this conversation (_rememberConversationDownload).+ conversationDownloads: conversationId && this._conversationDownloads.get(tabId)?.size+ ? { conversationId, ids: [...this._conversationDownloads.get(tabId)] }+ : null,captchaGateState: captchaGateState?.cloudflareManagedChallenge === true|| captchaGateState?.publicGate?.cloudflareManagedChallenge === true? null@@ -8230,6 +8252,7 @@ export class Agent extends LoopDetector {this.conversationModes.set(forkId, 'ask');this.conversationIds.set(forkId, `conv_${forkId}_${Date.now().toString(36)}_${secureRandomBase36Token(12)}`);this._latestWorkflowDrafts.delete(forkId);+ this._conversationDownloads.delete(forkId);this.selectionGroundingScopes.delete(forkId);this.selectionGroundingRestorationPendingTabs.delete(forkId);this.progressLedgers.delete(forkId);@@ -34468,6 +34491,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._cancelUploadPickers(tabId, 'conversation cleared');this._cancelPendingPlans(tabId, 'conversation cleared');this.conversations.delete(tabId);+ this._conversationDownloads.delete(tabId);this.plannerFollowUpSkipTabs.delete(tabId);this.progressLedgers.delete(tabId);this.progressPageScopes.delete(tabId);@@ -36105,6 +36129,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d*/_pinDownloadId(tabId, downloadId) {if (downloadId == null) return;+ this._rememberConversationDownload(tabId, downloadId);this._autoScratchpadNote(tabId, `[auto] Downloaded file (downloadId ${downloadId}) — details are in list_downloads. Re-read with read_downloaded_file({downloadId: ${downloadId}}).`);}@@ -36127,12 +36152,128 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._pinDownloadId(tabId, result.downloadId);} else if (name === 'download_social_media') {const n = Number(result.completedCount || 0);- if (n > 0) this._autoScratchpadNote(tabId, `[auto] download_social_media saved ${n} file(s) — find their ids/paths via list_downloads.`);+ if (n > 0) this._autoScratchpadNote(tabId, `[auto] download_social_media saved ${n} file(s) — find their ids via list_downloads.`);} else if (this._activeSkillToolForName(tabId, name)?.requiresDownloadPermission) {this._pinDownloadId(tabId, result.downloadId);}} catch { /* best-effort */ }}++ /**+ * The downloads this tab's conversation produced: the ids WebBrain's own+ * download tools returned here (_pinDownloadId) and every download that+ * started while a run was active on this tab, such as a clicked "Export"+ * link or download_social_media's page-side saves (_watchRunDownloads).+ * Only these are listed by list_downloads and read by read_downloaded_file+ * without asking. The rest of the browser's download history is the user's+ * own: reading one of those files needs the user's approval of that exact+ * file (_authorizeDownloadRead). Saved with the conversation, so a worker+ * restart keeps them; a new, forked or cleared conversation starts empty.+ */+ _rememberConversationDownload(tabId, downloadId) {+ if (tabId == null || !Number.isSafeInteger(downloadId) || downloadId < 0) return;+ let ids = this._conversationDownloads.get(tabId);+ if (!ids) this._conversationDownloads.set(tabId, ids = new Set());+ if (ids.has(downloadId)) return;+ ids.add(downloadId);+ while (ids.size > CONVERSATION_DOWNLOAD_LIMIT) ids.delete(ids.values().next().value);+ this._persist(tabId);+ }++ _isConversationDownload(tabId, downloadId) {+ return this._conversationDownloads.get(tabId)?.has(downloadId) === true;+ }++ // Added with the first run and kept for the worker's lifetime; outside runs+ // nothing is recorded. A download names no tab, so one that starts while+ // several tabs run belongs to each of their conversations.+ _watchRunDownloads() {+ if (this._runDownloadListener) return;+ const listener = item => {+ for (const tabId of this._runningTabs) this._rememberConversationDownload(tabId, item?.id);+ };+ try {+ if (!browser.downloads?.onCreated?.addListener) return;+ browser.downloads.onCreated.addListener(listener);+ this._runDownloadListener = listener;+ } catch { /* without the event only tool-returned ids are kept */ }+ }++ /**+ * read_downloaded_file sends a local file's bytes to the model's provider.+ * A download this conversation produced is read as before. Any other+ * download is the user's own file: WebBrain names it on its own card and+ * reads it only on the user's "Read once". The model's arguments, page text+ * and an unattended run never approve it. Returns null when the read may go+ * ahead, otherwise the result for the model.+ */+ async _authorizeDownloadRead(tabId, downloadId, onUpdate = null) {+ // readDownloadedFile reports an invalid id itself.+ if (!Number.isSafeInteger(downloadId) || downloadId < 0 || this._isConversationDownload(tabId, downloadId)) return null;+ const refused = (error, extra = {}) => ({ success: false, code: 'download_not_from_conversation', ...extra, error });+ const find = async () => {+ try { return (await browser.downloads.search({ id: downloadId })).find(item => item.id === downloadId) || null; }+ catch { return null; }+ };+ const item = await find();+ // Firefox reads only a captured data: payload (readDownloadedFile), so a+ // card about any other file would approve nothing.+ if (!item || item.state !== 'complete' || item.exists === false || !item.filename+ || typeof item.url !== 'string' || !item.url.startsWith('data:')) {+ return refused(`Download #${downloadId} is not a file downloaded in this conversation. Use a downloadId from this conversation's download results or list_downloads; if the user wants another downloaded file read, ask them to attach it.`);+ }+ let host = '';+ try { host = new URL(item.finalUrl || item.url).hostname; } catch {}+ const choice = await this._promptDownloadReadConfirmation(tabId, { filename: downloadBasename(item.filename), host }, onUpdate);+ if (choice === null) return refused('The user stopped or corrected the task before approving this file, so nothing was read.', { cancelled: true });+ if (choice === 'unavailable') {+ return refused(`Download #${downloadId} is not a file downloaded in this conversation, and the user cannot be asked to approve reading it in this run, so nothing was read.`);+ }+ if (choice !== 'once') {+ return refused('The user did not approve reading this downloaded file, so nothing was read. Do not ask again; continue without it.', { readDeclined: true });+ }+ // The answer covers the file the card named.+ if ((await find())?.filename !== item.filename) return refused('The downloaded file changed while the user was deciding, so nothing was read.');+ return null;+ }++ /**+ * The card for _authorizeDownloadRead: the file's name (the download's own,+ * page-settable name, which the side panel shows as text only) and the site+ * it came from. Like a permission prompt it never times out and never+ * answers itself; an unattended scheduled run cannot ask. Returns 'once',+ * 'deny', 'unavailable', or null when Stop or a correction cancelled it.+ */+ async _promptDownloadReadConfirmation(tabId, details = {}, onUpdate = null) {+ const confirmation = {+ filename: String(details.filename || '').slice(0, 260),+ host: String(details.host || '').slice(0, 300),+ };+ if (this.scheduledRunPolicies.get(tabId)?.requireConsequentialConfirmation === false) return 'unavailable';+ if (typeof onUpdate !== 'function') return 'unavailable';+ const clarifyId = `download_read_${secureRandomBase36Token(12)}`;+ const tabPending = this._pendingClarifications.get(tabId) || new Map();+ this._pendingClarifications.set(tabId, tabPending);+ const responsePromise = new Promise((resolve) => {+ tabPending.set(clarifyId, { resolve, ts: Date.now(), timer: null, settled: false, timeoutSec: 0, deadlineTs: 0, onUpdate });+ });+ try {+ onUpdate('clarify', {+ promptKind: 'download_read',+ clarifyId,+ // English for traces and surfaces without the side panel's localized copy.+ question: `Let WebBrain read ${confirmation.filename || 'this file'} from your downloads? Its contents go to your AI provider.`,+ downloadReadConfirmation: confirmation,+ options: ['once', 'deny'],+ });+ } catch { /* UI emit must never break the run */ }+ const response = await responsePromise;+ tabPending.delete(clarifyId);+ if (tabPending.size === 0 && this._pendingClarifications.get(tabId) === tabPending) this._pendingClarifications.delete(tabId);+ if (response?.cancelled) return null;+ if (['timeout', 'auto'].includes(response?.source)) return 'deny';+ return String(response?.answer || '').trim().toLowerCase() === 'once' ? 'once' : 'deny';+ }_isCompressionPlaceholderResponse(text) {const normalized = String(text || '').trim().toLowerCase();return normalized === '[compressed]' || normalized === '[context compressed]';@@ -44413,10 +44554,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn await this._restrictedDomainScreenshotFallback(tabId, name, args.url, result);}if (name === 'list_downloads') {- return await listDownloads(args);+ return await listDownloads(args, { downloadIds: this._conversationDownloads.get(tabId) || [] });}if (name === 'read_downloaded_file') {const readOwner = this._pageFeedbackOwnerScope?.(tabId) || '';+ const refused = await this._authorizeDownloadRead(tabId, args.downloadId, onUpdate);+ if (refused) return refused;return await readDownloadedFile(args.downloadId, { tabId,signal: executionContext?._contentActionAbortSignal,checkStillActive: () => {diff --git a/src/firefox/src/agent/guard-policy.js b/src/firefox/src/agent/guard-policy.jsindex 63a8ff2fb..228041957 100644--- a/src/firefox/src/agent/guard-policy.js+++ b/src/firefox/src/agent/guard-policy.js@@ -303,6 +303,9 @@ export const GUARDS = Object.freeze({summary: "A trusted click (native button or click_ax trusted fallback) on this exact document+ref earlier in the task may have landed and was never verified: the same target is not clicked again (one trusted fallback per ref per run)." },"clickax-trusted-retry-vetoes": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",summary: "WebBrain's automatic trusted retry of a click_ax that produced no visible change is skipped for concurrent tab/network/download activity, mutating captions, changed or ineligible targets." },+ "downloaded-file-conversation-scope": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "read_downloaded_file of a download this conversation did not produce (WebBrain's download tools, or a download that started during one of its runs) reads nothing unless the user approves that exact file on WebBrain's card; an unattended run cannot ask and reads nothing.",+ mustNotBlock: "test/download-conversation-scope.mjs#a download from this conversation is listed and read without asking" },"downloaded-file-task-changed": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",summary: "read_downloaded_file discards bytes when steering arrived, the page-feedback owner, the download or the pinned document changed during the read, or the reader/document cannot be pinned." },"iframe-target-binding": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",diff --git a/src/firefox/src/agent/scheduler.js b/src/firefox/src/agent/scheduler.jsindex 1c9eba5cc..a8e8d2918 100644--- a/src/firefox/src/agent/scheduler.js+++ b/src/firefox/src/agent/scheduler.js@@ -198,6 +198,14 @@ function normalizePendingClarify(data, now = Date.now()) {maxSeconds: whole(videoLength.maxSeconds),};}+ // WebBrain's card about reading a file from the user's downloads: its name.+ const downloadRead = asObject(obj.downloadReadConfirmation);+ if (downloadRead.filename) {+ pending.downloadReadConfirmation = {+ filename: String(downloadRead.filename).slice(0, 260),+ host: String(downloadRead.host || '').slice(0, 300),+ };+ }return pending;}diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.jsindex 132e23401..b8eaa2d48 100644--- a/src/firefox/src/agent/tools.js+++ b/src/firefox/src/agent/tools.js@@ -959,7 +959,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'list_downloads',- description: 'List recent downloads with state, filename, and source URL.',+ description: 'List this conversation\'s downloads (files you downloaded, or that downloaded while you worked) with state, file name, and source URL. The user\'s other download history is not listed.',parameters: {type: 'object',properties: {@@ -973,7 +973,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'read_downloaded_file',- description: 'Read immutable data: payloads captured with a completed download. Firefox cannot verify saved bytes of HTTP(S) downloads; those return an unsupported result and are never fetched again. Returns bounded text or base64 with explicit immutable-payload provenance. Pass downloadId from list_downloads or download_files.',+ description: 'Read immutable data: payloads captured with a completed download. Firefox cannot verify saved bytes of HTTP(S) downloads; those return an unsupported result and are never fetched again. Returns bounded text or base64 with explicit immutable-payload provenance. Pass downloadId from list_downloads or download_files. A download from outside this conversation is read only if the user approves that exact file on WebBrain\'s card.',parameters: {type: 'object',properties: {diff --git a/src/firefox/src/network/network-tools.js b/src/firefox/src/network/network-tools.jsindex 324428c3e..ece827b43 100644--- a/src/firefox/src/network/network-tools.js+++ b/src/firefox/src/network/network-tools.js@@ -2305,21 +2305,32 @@ export async function researchUrl(url, opts = {}) {}}-export async function listDownloads(opts = {}) {+// The browser's download history is the user's own: unrelated files, their+// source URLs and full local paths (which name the OS account). The model+// sees only the downloads its conversation produced (`downloadIds`, kept by+// the agent), and each file only by its basename.+export function downloadBasename(filename) {+ return String(filename || '').split(/[\\/]/).pop() || '';+}++export async function listDownloads(opts = {}, { downloadIds = [] } = {}) {try {const limit = Math.min(opts.limit || 10, 50);- const items = await browser.downloads.search({- orderBy: ['-startTime'],- limit,- exists: true,- });+ const ids = [...new Set(downloadIds)].filter(id => Number.isSafeInteger(id) && id >= 0).sort((a, b) => b - a);+ const items = [];+ for (const id of ids) {+ if (items.length >= limit) break;+ const found = (await browser.downloads.search({ id })).find(item => item.id === id);+ if (found && found.exists !== false) items.push(found);+ }return {success: true,count: items.length,+ ...(items.length ? {} : { note: 'No downloads from this conversation. Only files WebBrain downloaded, or that downloaded while it was working, in this conversation are listed; the browser\'s download history is not. If the user wants another downloaded file read, ask them to attach it.' }),downloads: items.map(d => ({id: d.id,url: d.url,- filename: d.filename,+ filename: downloadBasename(d.filename),state: d.state,bytesReceived: d.bytesReceived,totalBytes: d.totalBytes,@@ -2367,7 +2378,7 @@ function downloadedFileContent(item, payload, contentSource, savedFileVerified)return { success: false, code: 'saved_download_read_incomplete', error: 'The downloaded-file byte window could not be verified.' };}const ct = String(item.mime || payload.mimeType || '').toLowerCase();- const common = { success: true, filename: item.filename, contentType: ct, sizeBytes: size,+ const common = { success: true, filename: downloadBasename(item.filename), contentType: ct, sizeBytes: size,contentSource, savedFileVerified, sourceRefetched: false, bytesRead: bytes.length };if (downloadedFileIsText(item, ct)) {// Do not invent the full character count of a bounded byte prefix. A@@ -2379,7 +2390,7 @@ function downloadedFileContent(item, payload, contentSource, savedFileVerified)}if (size > READ_FILE_BASE64_LIMIT * 0.75) {return { ...common, note: savedFileVerified- ? `Binary file too large to inline (${size} bytes). It is on disk at: ${item.filename}`+ ? `Binary file too large to inline (${size} bytes). It is saved as ${downloadBasename(item.filename)}.`: `Captured binary payload too large to inline (${size} bytes). Firefox cannot verify the current on-disk file.` };}if (payload.dataTruncated) return { success: false, code: 'saved_download_read_incomplete', error: 'The small binary payload was not read completely.' };diff --git a/src/firefox/src/ui/locales/ar.js b/src/firefox/src/ui/locales/ar.jsindex 7ba747643..81c47f716 100644--- a/src/firefox/src/ui/locales/ar.js+++ b/src/firefox/src/ui/locales/ar.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "إنشاء نسخة {total}","sp.video_length.dont": "عدم الإنشاء","sp.video_length.seconds": "{seconds} ث",+ "sp.download_read.question": "هل تسمح لـ WebBrain بقراءة هذا الملف من التنزيلات؟",+ "sp.download_read.reason": "لم يقم WebBrain بتنزيله في هذه المحادثة. إذا سمحت بذلك، فسيُرسَل محتوى الملف إلى مزوّد الذكاء الاصطناعي.",+ "sp.download_read.file_from": "{filename} (من {host})",+ "sp.download_read.read": "قراءة هذا الملف مرة واحدة",+ "sp.download_read.dont": "عدم القراءة","sp.unverified.question.commit": "هل تريد إيداع هذا على {host}؟","sp.unverified.question.submit": "هل تريد إرسال هذا على {host}؟","sp.unverified.question.publish": "هل تريد نشر هذا على {host}؟",diff --git a/src/firefox/src/ui/locales/bn.js b/src/firefox/src/ui/locales/bn.jsindex 6cb61a4f7..b1ed2ce3b 100644--- a/src/firefox/src/ui/locales/bn.js+++ b/src/firefox/src/ui/locales/bn.js@@ -463,6 +463,11 @@ export default {"sp.video_length.generate": "{total} সংস্করণ তৈরি করুন","sp.video_length.dont": "তৈরি করবেন না","sp.video_length.seconds": "{seconds} সে.",+ "sp.download_read.question": "WebBrain-কে আপনার ডাউনলোড থেকে এই ফাইলটি পড়তে দেবেন?",+ "sp.download_read.reason": "WebBrain এই চ্যাটে এটি ডাউনলোড করেনি। অনুমতি দিলে ফাইলের বিষয়বস্তু আপনার AI প্রদানকারীর কাছে পাঠানো হবে।",+ "sp.download_read.file_from": "{filename} ({host} থেকে)",+ "sp.download_read.read": "এই ফাইলটি একবার পড়ুন",+ "sp.download_read.dont": "পড়বেন না","sp.unverified.question.commit": "{host}-এ এটি কমিট করবেন?","sp.unverified.question.submit": "{host}-এ এটি জমা দেবেন?","sp.unverified.question.publish": "{host}-এ এটি প্রকাশ করবেন?",diff --git a/src/firefox/src/ui/locales/de.js b/src/firefox/src/ui/locales/de.jsindex 3cf6cf9a3..64be9a4c1 100644--- a/src/firefox/src/ui/locales/de.js+++ b/src/firefox/src/ui/locales/de.js@@ -481,6 +481,11 @@ export default {"sp.video_length.generate": "{total}-Version erstellen","sp.video_length.dont": "Nicht erstellen","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Darf WebBrain diese Datei aus den Downloads lesen?",+ "sp.download_read.reason": "WebBrain hat sie nicht in diesem Chat heruntergeladen. Bei Erlaubnis wird der Inhalt der Datei an den KI-Anbieter gesendet.",+ "sp.download_read.file_from": "{filename} (von {host})",+ "sp.download_read.read": "Diese Datei einmal lesen",+ "sp.download_read.dont": "Nicht lesen","sp.unverified.question.commit": "Das auf {host} committen?","sp.unverified.question.submit": "Das auf {host} absenden?","sp.unverified.question.publish": "Das auf {host} veröffentlichen?",diff --git a/src/firefox/src/ui/locales/en.js b/src/firefox/src/ui/locales/en.jsindex 3031ec611..eb96c6fed 100644--- a/src/firefox/src/ui/locales/en.js+++ b/src/firefox/src/ui/locales/en.js@@ -468,6 +468,11 @@ export default {"sp.video_length.generate": "Generate {total} version","sp.video_length.dont": "Don’t generate","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Let WebBrain read this file from your downloads?",+ "sp.download_read.reason": "WebBrain did not download it in this chat. If you allow it, the file’s contents are sent to your AI provider.",+ "sp.download_read.file_from": "{filename} (from {host})",+ "sp.download_read.read": "Read this file once",+ "sp.download_read.dont": "Don’t read it","sp.unverified.question.commit": "Commit this on {host}?","sp.unverified.question.submit": "Submit this on {host}?","sp.unverified.question.publish": "Publish this on {host}?",diff --git a/src/firefox/src/ui/locales/es.js b/src/firefox/src/ui/locales/es.jsindex 057cbd3f2..17a587b47 100644--- a/src/firefox/src/ui/locales/es.js+++ b/src/firefox/src/ui/locales/es.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Generar versión de {total}","sp.video_length.dont": "No generar","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "¿Permitir que WebBrain lea este archivo de tus descargas?",+ "sp.download_read.reason": "WebBrain no lo descargó en este chat. Si lo permites, el contenido del archivo se enviará a tu proveedor de IA.",+ "sp.download_read.file_from": "{filename} (de {host})",+ "sp.download_read.read": "Leer este archivo una vez",+ "sp.download_read.dont": "No leer","sp.unverified.question.commit": "¿Hacer commit de esto en {host}?","sp.unverified.question.submit": "¿Enviar esto en {host}?","sp.unverified.question.publish": "¿Publicar esto en {host}?",diff --git a/src/firefox/src/ui/locales/fa.js b/src/firefox/src/ui/locales/fa.jsindex 32f4c5c51..a80542851 100644--- a/src/firefox/src/ui/locales/fa.js+++ b/src/firefox/src/ui/locales/fa.js@@ -463,6 +463,11 @@ export default {"sp.video_length.generate": "ساخت نسخهٔ {total}","sp.video_length.dont": "نساز","sp.video_length.seconds": "{seconds} ثانیه",+ "sp.download_read.question": "اجازه میدهید WebBrain این فایل را از دانلودهای شما بخواند؟",+ "sp.download_read.reason": "WebBrain این فایل را در این گفتگو دانلود نکرده است. اگر اجازه دهید، محتوای فایل برای ارائهدهنده هوش مصنوعی شما ارسال میشود.",+ "sp.download_read.file_from": "{filename} (از {host})",+ "sp.download_read.read": "یک بار این فایل را بخوان",+ "sp.download_read.dont": "نخوان","sp.unverified.question.commit": "این در {host} کامیت شود؟","sp.unverified.question.submit": "این در {host} ارسال شود؟","sp.unverified.question.publish": "این در {host} منتشر شود؟",diff --git a/src/firefox/src/ui/locales/fr.js b/src/firefox/src/ui/locales/fr.jsindex 202b4de58..2261d20b8 100644--- a/src/firefox/src/ui/locales/fr.js+++ b/src/firefox/src/ui/locales/fr.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Générer la version de {total}","sp.video_length.dont": "Ne pas générer","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Autoriser WebBrain à lire ce fichier de vos téléchargements ?",+ "sp.download_read.reason": "WebBrain ne l’a pas téléchargé dans cette conversation. Si vous l’autorisez, le contenu du fichier est envoyé à votre fournisseur d’IA.",+ "sp.download_read.file_from": "{filename} (depuis {host})",+ "sp.download_read.read": "Lire ce fichier une fois",+ "sp.download_read.dont": "Ne pas lire","sp.unverified.question.commit": "Valider (commit) ceci sur {host} ?","sp.unverified.question.submit": "Envoyer ceci sur {host} ?","sp.unverified.question.publish": "Publier ceci sur {host} ?",diff --git a/src/firefox/src/ui/locales/he.js b/src/firefox/src/ui/locales/he.jsindex 3e9ffbcb9..00ccb084f 100644--- a/src/firefox/src/ui/locales/he.js+++ b/src/firefox/src/ui/locales/he.js@@ -454,6 +454,11 @@ export default {"sp.video_length.generate": "יצירת גרסה של {total}","sp.video_length.dont": "לא ליצור","sp.video_length.seconds": "{seconds} שנ׳",+ "sp.download_read.question": "לאפשר ל-WebBrain לקרוא את הקובץ הזה מההורדות שלך?",+ "sp.download_read.reason": "WebBrain לא הוריד אותו בצ׳אט הזה. אם תאפשר זאת, תוכן הקובץ יישלח לספק ה-AI שלך.",+ "sp.download_read.file_from": "{filename} (מ-{host})",+ "sp.download_read.read": "לקרוא את הקובץ הזה פעם אחת",+ "sp.download_read.dont": "לא לקרוא","sp.unverified.question.commit": "לבצע commit לזה ב-{host}?","sp.unverified.question.submit": "לשלוח את זה ב-{host}?","sp.unverified.question.publish": "לפרסם את זה ב-{host}?",diff --git a/src/firefox/src/ui/locales/hi.js b/src/firefox/src/ui/locales/hi.jsindex 113f5d08b..c92d42475 100644--- a/src/firefox/src/ui/locales/hi.js+++ b/src/firefox/src/ui/locales/hi.js@@ -463,6 +463,11 @@ export default {"sp.video_length.generate": "{total} संस्करण बनाएँ","sp.video_length.dont": "न बनाएँ","sp.video_length.seconds": "{seconds} से.",+ "sp.download_read.question": "क्या WebBrain को आपके डाउनलोड से यह फ़ाइल पढ़ने दें?",+ "sp.download_read.reason": "WebBrain ने इसे इस चैट में डाउनलोड नहीं किया। अनुमति देने पर फ़ाइल की सामग्री आपके AI प्रदाता को भेजी जाएगी।",+ "sp.download_read.file_from": "{filename} ({host} से)",+ "sp.download_read.read": "यह फ़ाइल एक बार पढ़ें",+ "sp.download_read.dont": "न पढ़ें","sp.unverified.question.commit": "{host} पर इसे कमिट करें?","sp.unverified.question.submit": "{host} पर इसे सबमिट करें?","sp.unverified.question.publish": "{host} पर इसे प्रकाशित करें?",diff --git a/src/firefox/src/ui/locales/id.js b/src/firefox/src/ui/locales/id.jsindex 4497cdfbb..352f51d85 100644--- a/src/firefox/src/ui/locales/id.js+++ b/src/firefox/src/ui/locales/id.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Buat versi {total}","sp.video_length.dont": "Jangan buat","sp.video_length.seconds": "{seconds} dtk",+ "sp.download_read.question": "Izinkan WebBrain membaca file ini dari unduhan Anda?",+ "sp.download_read.reason": "WebBrain tidak mengunduhnya di obrolan ini. Jika diizinkan, isi file akan dikirim ke penyedia AI Anda.",+ "sp.download_read.file_from": "{filename} (dari {host})",+ "sp.download_read.read": "Baca file ini sekali",+ "sp.download_read.dont": "Jangan baca","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Kirim ini di {host}?","sp.unverified.question.publish": "Publikasikan ini di {host}?",diff --git a/src/firefox/src/ui/locales/ja.js b/src/firefox/src/ui/locales/ja.jsindex 409d5553e..7eae46232 100644--- a/src/firefox/src/ui/locales/ja.js+++ b/src/firefox/src/ui/locales/ja.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "{total}版を作成","sp.video_length.dont": "作成しない","sp.video_length.seconds": "{seconds}秒",+ "sp.download_read.question": "ダウンロード済みのこのファイルを WebBrain に読み込ませますか?",+ "sp.download_read.reason": "このファイルは WebBrain がこのチャットでダウンロードしたものではありません。許可すると、ファイルの内容が AI プロバイダーに送信されます。",+ "sp.download_read.file_from": "{filename}({host} から)",+ "sp.download_read.read": "このファイルを 1 回読む",+ "sp.download_read.dont": "読まない","sp.unverified.question.commit": "{host} でこれをコミットしますか?","sp.unverified.question.submit": "{host} でこれを送信しますか?","sp.unverified.question.publish": "{host} でこれを公開しますか?",diff --git a/src/firefox/src/ui/locales/ko.js b/src/firefox/src/ui/locales/ko.jsindex 935e72070..9ea19e9e0 100644--- a/src/firefox/src/ui/locales/ko.js+++ b/src/firefox/src/ui/locales/ko.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "{total} 버전 만들기","sp.video_length.dont": "만들지 않기","sp.video_length.seconds": "{seconds}초",+ "sp.download_read.question": "WebBrain이 다운로드한 파일 중 이 파일을 읽도록 허용할까요?",+ "sp.download_read.reason": "WebBrain이 이 채팅에서 다운로드한 파일이 아닙니다. 허용하면 파일 내용이 AI 제공업체로 전송됩니다.",+ "sp.download_read.file_from": "{filename} ({host}에서)",+ "sp.download_read.read": "이 파일을 한 번 읽기",+ "sp.download_read.dont": "읽지 않기","sp.unverified.question.commit": "{host}에서 이 내용을 커밋할까요?","sp.unverified.question.submit": "{host}에서 이 내용을 제출할까요?","sp.unverified.question.publish": "{host}에서 이 내용을 게시할까요?",diff --git a/src/firefox/src/ui/locales/ms.js b/src/firefox/src/ui/locales/ms.jsindex 9c9da29fb..0f023af93 100644--- a/src/firefox/src/ui/locales/ms.js+++ b/src/firefox/src/ui/locales/ms.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Jana versi {total}","sp.video_length.dont": "Jangan jana","sp.video_length.seconds": "{seconds} saat",+ "sp.download_read.question": "Benarkan WebBrain membaca fail ini daripada muat turun anda?",+ "sp.download_read.reason": "WebBrain tidak memuat turunnya dalam sembang ini. Jika dibenarkan, kandungan fail akan dihantar kepada penyedia AI anda.",+ "sp.download_read.file_from": "{filename} (dari {host})",+ "sp.download_read.read": "Baca fail ini sekali",+ "sp.download_read.dont": "Jangan baca","sp.unverified.question.commit": "Commit ini di {host}?","sp.unverified.question.submit": "Serahkan ini di {host}?","sp.unverified.question.publish": "Terbitkan ini di {host}?",diff --git a/src/firefox/src/ui/locales/nl.js b/src/firefox/src/ui/locales/nl.jsindex 3c99fc0ed..9b66b8910 100644--- a/src/firefox/src/ui/locales/nl.js+++ b/src/firefox/src/ui/locales/nl.js@@ -451,6 +451,11 @@ export default {"sp.video_length.generate": "Versie van {total} maken","sp.video_length.dont": "Niet maken","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Mag WebBrain dit bestand uit je downloads lezen?",+ "sp.download_read.reason": "WebBrain heeft het niet in deze chat gedownload. Als je het toestaat, wordt de inhoud van het bestand naar je AI-provider gestuurd.",+ "sp.download_read.file_from": "{filename} (van {host})",+ "sp.download_read.read": "Dit bestand één keer lezen",+ "sp.download_read.dont": "Niet lezen","sp.unverified.question.commit": "Dit committen op {host}?","sp.unverified.question.submit": "Dit versturen op {host}?","sp.unverified.question.publish": "Dit publiceren op {host}?",diff --git a/src/firefox/src/ui/locales/pl.js b/src/firefox/src/ui/locales/pl.jsindex 609cc12e4..0c9c87d57 100644--- a/src/firefox/src/ui/locales/pl.js+++ b/src/firefox/src/ui/locales/pl.js@@ -354,6 +354,11 @@ export default {"sp.video_length.generate": "Utwórz wersję {total}","sp.video_length.dont": "Nie twórz","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Pozwolić WebBrain odczytać ten plik z pobranych?",+ "sp.download_read.reason": "WebBrain nie pobrał go w tym czacie. Jeśli pozwolisz, zawartość pliku zostanie wysłana do Twojego dostawcy AI.",+ "sp.download_read.file_from": "{filename} (z {host})",+ "sp.download_read.read": "Odczytaj ten plik raz",+ "sp.download_read.dont": "Nie odczytuj","sp.unverified.question.commit": "Zatwierdzić (commit) to w {host}?","sp.unverified.question.submit": "Wysłać to w {host}?","sp.unverified.question.publish": "Opublikować to w {host}?",diff --git a/src/firefox/src/ui/locales/pt.js b/src/firefox/src/ui/locales/pt.jsindex 5d8d96480..024f855b9 100644--- a/src/firefox/src/ui/locales/pt.js+++ b/src/firefox/src/ui/locales/pt.js@@ -463,6 +463,11 @@ export default {"sp.video_length.generate": "Gerar versão de {total}","sp.video_length.dont": "Não gerar","sp.video_length.seconds": "{seconds} s",+ "sp.download_read.question": "Permitir que o WebBrain leia este arquivo dos seus downloads?",+ "sp.download_read.reason": "O WebBrain não o baixou neste chat. Se você permitir, o conteúdo do arquivo será enviado ao seu provedor de IA.",+ "sp.download_read.file_from": "{filename} (de {host})",+ "sp.download_read.read": "Ler este arquivo uma vez",+ "sp.download_read.dont": "Não ler","sp.unverified.question.commit": "Fazer commit disto em {host}?","sp.unverified.question.submit": "Enviar isto em {host}?","sp.unverified.question.publish": "Publicar isto em {host}?",diff --git a/src/firefox/src/ui/locales/ru.js b/src/firefox/src/ui/locales/ru.jsindex 774610ff3..8140bfc7a 100644--- a/src/firefox/src/ui/locales/ru.js+++ b/src/firefox/src/ui/locales/ru.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Создать версию на {total}","sp.video_length.dont": "Не создавать","sp.video_length.seconds": "{seconds} с",+ "sp.download_read.question": "Разрешить WebBrain прочитать этот файл из загрузок?",+ "sp.download_read.reason": "WebBrain не скачивал его в этом чате. Если разрешить, содержимое файла будет отправлено вашему поставщику ИИ.",+ "sp.download_read.file_from": "{filename} (с {host})",+ "sp.download_read.read": "Прочитать этот файл один раз",+ "sp.download_read.dont": "Не читать","sp.unverified.question.commit": "Закоммитить это на {host}?","sp.unverified.question.submit": "Отправить это на {host}?","sp.unverified.question.publish": "Опубликовать это на {host}?",diff --git a/src/firefox/src/ui/locales/th.js b/src/firefox/src/ui/locales/th.jsindex 730ccd122..c212edfb1 100644--- a/src/firefox/src/ui/locales/th.js+++ b/src/firefox/src/ui/locales/th.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "สร้างเวอร์ชัน {total}","sp.video_length.dont": "ไม่สร้าง","sp.video_length.seconds": "{seconds} วินาที",+ "sp.download_read.question": "อนุญาตให้ WebBrain อ่านไฟล์นี้จากรายการดาวน์โหลดของคุณหรือไม่?",+ "sp.download_read.reason": "WebBrain ไม่ได้ดาวน์โหลดไฟล์นี้ในแชทนี้ หากอนุญาต เนื้อหาของไฟล์จะถูกส่งไปยังผู้ให้บริการ AI ของคุณ",+ "sp.download_read.file_from": "{filename} (จาก {host})",+ "sp.download_read.read": "อ่านไฟล์นี้หนึ่งครั้ง",+ "sp.download_read.dont": "ไม่อ่าน","sp.unverified.question.commit": "คอมมิตสิ่งนี้บน {host} ไหม?","sp.unverified.question.submit": "ส่งสิ่งนี้บน {host} ไหม?","sp.unverified.question.publish": "เผยแพร่สิ่งนี้บน {host} ไหม?",diff --git a/src/firefox/src/ui/locales/tl.js b/src/firefox/src/ui/locales/tl.jsindex ddeec62ae..b5c3ce0ea 100644--- a/src/firefox/src/ui/locales/tl.js+++ b/src/firefox/src/ui/locales/tl.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Gumawa ng {total} na bersyon","sp.video_length.dont": "Huwag gumawa","sp.video_length.seconds": "{seconds} seg",+ "sp.download_read.question": "Payagan ang WebBrain na basahin ang file na ito mula sa iyong mga download?",+ "sp.download_read.reason": "Hindi ito na-download ng WebBrain sa chat na ito. Kapag pinayagan mo, ipapadala ang nilalaman ng file sa iyong AI provider.",+ "sp.download_read.file_from": "{filename} (mula sa {host})",+ "sp.download_read.read": "Basahin ang file na ito nang isang beses",+ "sp.download_read.dont": "Huwag basahin","sp.unverified.question.commit": "I-commit ito sa {host}?","sp.unverified.question.submit": "Isumite ito sa {host}?","sp.unverified.question.publish": "I-publish ito sa {host}?",diff --git a/src/firefox/src/ui/locales/tr.js b/src/firefox/src/ui/locales/tr.jsindex a3beaab5b..9c9b8395c 100644--- a/src/firefox/src/ui/locales/tr.js+++ b/src/firefox/src/ui/locales/tr.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "{total} sürümünü üret","sp.video_length.dont": "Üretme","sp.video_length.seconds": "{seconds} sn",+ "sp.download_read.question": "WebBrain indirilenlerindeki bu dosyayı okusun mu?",+ "sp.download_read.reason": "WebBrain bu dosyayı bu sohbette indirmedi. İzin verirsen dosyanın içeriği yapay zekâ sağlayıcına gönderilir.",+ "sp.download_read.file_from": "{filename} ({host} kaynağından)",+ "sp.download_read.read": "Bu dosyayı bir kez oku",+ "sp.download_read.dont": "Okuma","sp.unverified.question.commit": "{host} üzerinde bu commit edilsin mi?","sp.unverified.question.submit": "{host} üzerinde bu gönderilsin mi?","sp.unverified.question.publish": "{host} üzerinde bu yayınlansın mı?",diff --git a/src/firefox/src/ui/locales/uk.js b/src/firefox/src/ui/locales/uk.jsindex 9c4b3b0f9..33ee272ef 100644--- a/src/firefox/src/ui/locales/uk.js+++ b/src/firefox/src/ui/locales/uk.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "Створити версію на {total}","sp.video_length.dont": "Не створювати","sp.video_length.seconds": "{seconds} с",+ "sp.download_read.question": "Дозволити WebBrain прочитати цей файл із завантажень?",+ "sp.download_read.reason": "WebBrain не завантажував його в цьому чаті. Якщо дозволити, вміст файлу буде надіслано вашому постачальнику ШІ.",+ "sp.download_read.file_from": "{filename} (з {host})",+ "sp.download_read.read": "Прочитати цей файл один раз",+ "sp.download_read.dont": "Не читати","sp.unverified.question.commit": "Закомітити це на {host}?","sp.unverified.question.submit": "Надіслати це на {host}?","sp.unverified.question.publish": "Опублікувати це на {host}?",diff --git a/src/firefox/src/ui/locales/vi.js b/src/firefox/src/ui/locales/vi.jsindex b5a8f959c..85fdf77c2 100644--- a/src/firefox/src/ui/locales/vi.js+++ b/src/firefox/src/ui/locales/vi.js@@ -463,6 +463,11 @@ export default {"sp.video_length.generate": "Tạo bản {total}","sp.video_length.dont": "Không tạo","sp.video_length.seconds": "{seconds} giây",+ "sp.download_read.question": "Cho phép WebBrain đọc tệp này từ thư mục tải xuống của bạn?",+ "sp.download_read.reason": "WebBrain không tải tệp này xuống trong cuộc trò chuyện này. Nếu bạn cho phép, nội dung tệp sẽ được gửi đến nhà cung cấp AI của bạn.",+ "sp.download_read.file_from": "{filename} (từ {host})",+ "sp.download_read.read": "Đọc tệp này một lần",+ "sp.download_read.dont": "Không đọc","sp.unverified.question.commit": "Commit nội dung này trên {host}?","sp.unverified.question.submit": "Gửi nội dung này trên {host}?","sp.unverified.question.publish": "Đăng nội dung này trên {host}?",diff --git a/src/firefox/src/ui/locales/zh.js b/src/firefox/src/ui/locales/zh.jsindex e06767ffa..bf41c5cd3 100644--- a/src/firefox/src/ui/locales/zh.js+++ b/src/firefox/src/ui/locales/zh.js@@ -95,6 +95,11 @@ export default {"sp.video_length.generate": "生成 {total} 版本","sp.video_length.dont": "不生成","sp.video_length.seconds": "{seconds} 秒",+ "sp.download_read.question": "允许 WebBrain 读取你下载的这个文件吗?",+ "sp.download_read.reason": "这个文件不是 WebBrain 在本次对话中下载的。如果允许,文件内容会发送给你的 AI 服务提供商。",+ "sp.download_read.file_from": "{filename}(来自 {host})",+ "sp.download_read.read": "读取此文件一次",+ "sp.download_read.dont": "不读取","sp.unverified.question.commit": "要在 {host} 上提交(commit)这些内容吗?","sp.unverified.question.submit": "要在 {host} 上提交这些内容吗?","sp.unverified.question.publish": "要在 {host} 上发布这些内容吗?",diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex 54ab3e2c3..71adfef12 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -6566,7 +6566,7 @@ function rebindClarifyCards() {// the card. Skip permission/form-submit cards (they never auto-timeout).if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'|| card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'- || card.dataset.videoLengthConfirmation === '1') return;+ || card.dataset.videoLengthConfirmation === '1' || card.dataset.downloadReadConfirmation === '1') return;const deadlineTs = Number(card.dataset.deadlineTs);if (!Number.isFinite(deadlineTs) || deadlineTs <= 0) return;const firstOption = card.dataset.firstOption@@ -11251,6 +11251,7 @@ function renderClarifyCard(data) {? 'scheduled_clarification': data.workflowHealing || data.pendingReconciliation === true || data.recipientConfirmation|| data.mutationConfirmation || data.unverifiedStepConfirmation || data.videoLengthConfirmation+ || data.downloadReadConfirmation? '': data.submitConfirmation? 'form_confirmation'@@ -11515,6 +11516,44 @@ function renderClarifyCard(data) {return;}+ // Downloaded-file read: the model asked to read a file from the browser's+ // download history that WebBrain did not download in this chat. The name is+ // the download's own (page-settable) name, shown as text only. Fixed choices+ // return stable values ('once'/'deny'); the card never times out.+ if (data.downloadReadConfirmation) {+ card.dataset.downloadReadConfirmation = '1';+ const file = data.downloadReadConfirmation || {};+ const filename = String(file.filename || '').slice(0, 260);+ const host = String(file.host || '').slice(0, 300);+ qEl.textContent = t('sp.download_read.question');+ const reasonEl = document.createElement('div');+ reasonEl.className = 'clarify-reason';+ reasonEl.textContent = t('sp.download_read.reason');+ card.appendChild(reasonEl);+ const fileEl = document.createElement('div');+ fileEl.className = 'clarify-subject';+ fileEl.textContent = host ? t('sp.download_read.file_from', { filename, host }) : filename;+ card.appendChild(fileEl);+ const optionsEl = document.createElement('div');+ optionsEl.className = 'clarify-options';+ for (const [value, label] of [['once', t('sp.download_read.read')], ['deny', t('sp.download_read.dont')]]) {+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'clarify-option';+ b.textContent = String(label).slice(0, 200);+ b.dataset.value = value;+ b.addEventListener('click', () => {+ card.dataset.answerLabel = b.textContent;+ submitClarify(card, tabId, clarifyId, value, 'option');+ });+ optionsEl.appendChild(b);+ }+ card.appendChild(optionsEl);+ content.appendChild(card);+ scrollToBottom({ force: true });+ return;+ }+// Unverifiable step: one of WebBrain's checks could not verify a commit,// publish or submit, so it asks instead of refusing. The text is what the// page showed when WebBrain asked: page content, shown as text only@@ -11864,7 +11903,7 @@ function lockClarifyCardFromAuto(data) {const unverifiedStep = card.dataset.unverifiedStepConfirmation === '1';if (card.dataset.permission === '1' || card.dataset.submitConfirmation === '1'|| card.dataset.recipientConfirmation === '1' || card.dataset.mutationConfirmation === '1'- || card.dataset.videoLengthConfirmation === '1') return;+ || card.dataset.videoLengthConfirmation === '1' || card.dataset.downloadReadConfirmation === '1') return;clearClarifyCountdown(card);card.classList.add('clarify-answered');for (const el of card.querySelectorAll('button, input')) {diff --git a/test/download-conversation-scope.mjs b/test/download-conversation-scope.mjsnew file mode 100644index 000000000..ac19b8897--- /dev/null+++ b/test/download-conversation-scope.mjs@@ -0,0 +1,259 @@+// list_downloads and read_downloaded_file see only the downloads of their own+// conversation: files WebBrain's download tools saved there, and downloads+// that started while one of its runs was active on the tab. The rest of the+// browser's download history is the user's own: it is never listed, and a+// file from it is read only after the user approves that exact file on+// WebBrain's card. Listed files carry their basename, never the local path.+import assert from 'node:assert/strict';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { after, before, test } from 'node:test';+import { chromium } from 'playwright';++let pw;+before(async () => { pw = await chromium.launch({ headless: true }); });+after(async () => { await pw?.close(); });++const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'webbrain-download-scope-'));+const owned = { id: 41, name: 'report.csv', text: 'region,total\nnorth,12\n' };+const later = { id: 43, name: 'export.json', text: '{"ok":true}' };+const private_ = { id: 7, name: 'tax-return-2025.txt', text: 'Private: not from this chat.' };+const outside = { id: 44, name: 'outside-run.txt', text: 'Downloaded between runs.' };+const records = new Map();+for (const file of [owned, later, private_, outside]) {+ const local = path.join(directory, file.name);+ await fs.writeFile(local, file.text);+ records.set(file.id, { id: file.id, state: 'complete', exists: true, filename: local, fileSize: Buffer.byteLength(file.text),+ mime: 'text/plain', startTime: new Date(2026, 9, file.id).toISOString(),+ url: `https://files.example/${file.name}`, dataUrl: `data:text/plain;base64,${Buffer.from(file.text).toString('base64')}` });+}++const searches = [];+let createdListeners = [];+let kind = 'chrome';+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+const api = {+ storage: { local: area, session: area, onChanged: { addListener() {} } },+ runtime: { id: 'webbrain-test', getURL: value => `chrome-extension://test/${value}`, sendMessage: async () => ({}) },+ tabs: { get: async id => ({ id, url: 'https://owned.example/', title: 'Owned' }), query: async () => [], sendMessage: async () => ({}) },+ webNavigation: { getAllFrames: async () => [{ frameId: 0, parentFrameId: -1, url: 'https://owned.example/', documentId: 'owned-document' }] },+ scripting: { executeScript: async () => [{ result: null }] },+ downloads: {+ // Firefox reads only the payload captured in the record (a data: URL).+ search: async query => {+ searches.push(query);+ const view = ({ dataUrl, ...item }) => ({ ...item, ...(kind === 'firefox' ? { url: dataUrl } : {}) });+ if (query.id == null) return [...records.values()].map(view);+ return records.has(query.id) ? [view(records.get(query.id))] : [];+ },+ onCreated: {+ addListener: listener => { createdListeners.push(listener); },+ removeListener: listener => { createdListeners = createdListeners.filter(item => item !== listener); },+ },+ },+};+globalThis.chrome = api;+globalThis.browser = api;++const { cdpClient } = await import('../src/chrome/src/cdp/cdp-client.js');+let localReads = [];+cdpClient.attach = async () => {};+cdpClient.probeLocalFile = async (_tabId, localPath, options) => {+ localReads.push(localPath);+ const data = await fs.readFile(localPath);+ const prefix = data.subarray(0, options.readPrefixBytes || options.maxBytes);+ return { exists: true, readable: true, size: data.length, base64: prefix.toString('base64'),+ dataBytesRead: prefix.length, dataTruncated: prefix.length < data.length };+};++const builds = await Promise.all(['chrome', 'firefox'].map(async build => ({+ build,+ Agent: (await import(`../src/${build}/src/agent/agent.js`)).Agent,+ network: await import(`../src/${build}/src/network/network-tools.js`),+})));++function setup(Agent) {+ const provider = { name: 'local test', model: 'test', promptTier: 'full', contextWindow: 128000, supportsTools: true, supportsVision: false };+ const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });+ agent._persist = () => {};+ agent._persistNow = async () => ({ ok: true });+ return agent;+}++// The side panel's side of a card: every 'clarify' update, answered by `answer`.+function panel(agent, tabId, answer) {+ const cards = [];+ const onUpdate = (type, data) => {+ if (type !== 'clarify') return;+ cards.push(data);+ if (answer === 'stop') setTimeout(() => agent._cancelClarifications(tabId, 'stopped'), 0);+ else if (answer) setTimeout(() => agent.submitClarifyResponse(tabId, data.clarifyId, answer), 0);+ };+ return { cards, onUpdate };+}++for (const { build, Agent, network } of builds) {+ test(`${build}: list_downloads never enumerates the browser's download history`, async () => {+ kind = build;+ searches.length = 0;+ const none = await network.listDownloads({}, {});+ assert.equal(none.success, true);+ assert.deepEqual(none.downloads, []);+ assert.match(none.note, /ask them to attach it/);+ const some = await network.listDownloads({ limit: 1 }, { downloadIds: new Set([owned.id, later.id]) });+ assert.deepEqual(some.downloads.map(item => item.id), [later.id], 'newest first, within the limit');+ const listed = await network.listDownloads({}, { downloadIds: [owned.id, later.id, 999] });+ assert.deepEqual(listed.downloads.map(item => [item.id, item.filename]), [[later.id, later.name], [owned.id, owned.name]]);+ for (const item of listed.downloads) assert.doesNotMatch(item.filename, /[\\/]/, 'basename only, never the local path');+ assert.ok(searches.length > 0 && searches.every(query => Number.isSafeInteger(query.id)),+ `every lookup names one conversation download: ${JSON.stringify(searches)}`);+ });++ test(`${build}: a download from this conversation is listed and read without asking`, async () => {+ kind = build;+ const agent = setup(Agent);+ const tabId = build === 'chrome' ? 5101 : 5102;+ agent._pinDownloadHandles(tabId, 'download_files', { success: true, downloads: [{ success: true, downloadId: owned.id, state: 'complete' }] });+ const { cards, onUpdate } = panel(agent, tabId, null);+ const listed = await agent.executeTool(tabId, 'list_downloads', {}, onUpdate);+ assert.deepEqual(listed.downloads.map(item => [item.id, item.filename]), [[owned.id, owned.name]]);+ localReads = [];+ const read = await agent.executeTool(tabId, 'read_downloaded_file', { downloadId: owned.id }, onUpdate);+ assert.equal(read.success, true, JSON.stringify(read));+ assert.equal(read.text, owned.text);+ assert.equal(read.filename, owned.name, 'the read names the file by its basename');+ assert.equal(cards.length, 0, 'no card for a file this conversation downloaded');+ });++ test(`${build}: downloads that start during a run belong to its conversation, and survive a worker restart`, async () => {+ kind = build;+ createdListeners = [];+ const agent = setup(Agent);+ const tabId = build === 'chrome' ? 5111 : 5112;+ agent.conversations.set(tabId, [{ role: 'system', content: 'test' }]);+ agent.conversationIds.set(tabId, `conv_${tabId}`);+ for (const listener of createdListeners) listener({ id: outside.id });+ await agent._claimRunEntry(tabId, 'interactive', {});+ agent._watchRunDownloads();+ assert.equal(createdListeners.length, 1, 'one listener for the worker, added with the first run');+ for (const listener of createdListeners) listener({ id: later.id });+ agent._releaseRunEntry(tabId);+ for (const listener of createdListeners) listener({ id: outside.id });+ const listed = await agent.executeTool(tabId, 'list_downloads', {});+ assert.deepEqual(listed.downloads.map(item => item.id), [later.id], 'a download outside a run is not the conversation\'s');++ const entry = agent._conversationStorageEntry(tabId);+ assert.deepEqual(entry.conversationDownloads, { conversationId: `conv_${tabId}`, ids: [later.id] });+ const restored = setup(Agent);+ const stored = { [`agentConv:${tabId}`]: entry };+ const session = api.storage.session;+ api.storage.session = { ...session, get: async key => (typeof key === 'string' && key in stored ? { [key]: stored[key] } : {}) };+ try {+ await restored._hydrate(tabId);+ assert.deepEqual([...restored._conversationDownloads.get(tabId)], [later.id]);+ const other = setup(Agent);+ stored[`agentConv:${tabId}`] = { ...entry, conversationDownloads: { conversationId: 'conv_other', ids: [private_.id] } };+ await other._hydrate(tabId);+ assert.equal(other._conversationDownloads.has(tabId), false, 'another conversation\'s ids are not restored');+ } finally { api.storage.session = session; }+ restored.clearConversation(tabId);+ assert.equal(restored._conversationDownloads.has(tabId), false, 'a cleared conversation starts empty');+ });++ test(`${build}: a file from outside this conversation is read only after the user approves that exact file`, async () => {+ kind = build;+ const tabId = build === 'chrome' ? 5121 : 5122;++ const declined = setup(Agent);+ const deny = panel(declined, tabId, 'deny');+ localReads = [];+ const refused = await declined.executeTool(tabId, 'read_downloaded_file', { downloadId: private_.id }, deny.onUpdate);+ assert.equal(refused.success, false);+ assert.equal(refused.code, 'download_not_from_conversation');+ assert.equal(refused.readDeclined, true);+ assert.equal(refused.text, undefined);+ assert.deepEqual(localReads, [], 'no bytes read');+ assert.equal(deny.cards.length, 1);+ assert.equal(deny.cards[0].promptKind, 'download_read');+ assert.deepEqual(deny.cards[0].downloadReadConfirmation, { filename: private_.name, host: build === 'chrome' ? 'files.example' : '' });+ assert.deepEqual(deny.cards[0].options, ['once', 'deny']);+ assert.doesNotMatch(JSON.stringify(deny.cards[0]), new RegExp(directory.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&').slice(0, 40)),+ 'the card names the file, not its local path');++ const approved = setup(Agent);+ const once = panel(approved, tabId, 'once');+ const read = await approved.executeTool(tabId, 'read_downloaded_file', { downloadId: private_.id }, once.onUpdate);+ assert.equal(read.success, true, JSON.stringify(read));+ assert.equal(read.text, private_.text);+ assert.equal(once.cards.length, 1);+ const again = await approved.executeTool(tabId, 'read_downloaded_file', { downloadId: private_.id }, panel(approved, tabId, 'deny').onUpdate);+ assert.equal(again.readDeclined, true, '"Read this file once" covers one read');+ assert.deepEqual((await approved.executeTool(tabId, 'list_downloads', {})).downloads, [], 'an approved read does not list the file');++ const stopped = setup(Agent);+ const stop = panel(stopped, tabId, 'stop');+ const cancelled = await stopped.executeTool(tabId, 'read_downloaded_file', { downloadId: private_.id }, stop.onUpdate);+ assert.equal(cancelled.success, false);+ assert.equal(cancelled.cancelled, true);++ const unattended = setup(Agent);+ unattended.scheduledRunPolicies.set(tabId, { requireConsequentialConfirmation: false });+ const nobody = panel(unattended, tabId, 'once');+ const unasked = await unattended.executeTool(tabId, 'read_downloaded_file', { downloadId: private_.id }, nobody.onUpdate);+ assert.equal(unasked.success, false);+ assert.match(unasked.error, /cannot be asked/);+ assert.equal(nobody.cards.length, 0, 'an unattended run shows no card and reads nothing');++ const guessed = setup(Agent);+ const guess = panel(guessed, tabId, 'once');+ const missing = await guessed.executeTool(tabId, 'read_downloaded_file', { downloadId: 999 }, guess.onUpdate);+ assert.equal(missing.code, 'download_not_from_conversation');+ assert.equal(guess.cards.length, 0, 'no card for an id that names no readable download');+ });++ test(`${build}: the side panel names the file as text on fixed choices that never time out`, async () => {+ const source = (await fs.readFile(new URL(`../src/${build}/src/ui/sidepanel.js`, import.meta.url), 'utf8')).replace(/\r\n/g, '\n');+ assert.equal((source.match(/card\.dataset\.downloadReadConfirmation === '1'\) return;/g) || []).length, 2,+ 'neither a restored card nor an auto-answer times it out');+ const extract = name => {+ const start = source.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));+ assert.ok(start >= 0, name);+ return source.slice(start, source.indexOf('\n}', start) + 2);+ };+ const english = (await import(`../src/${build}/src/ui/locales/en.js`)).default;+ const page = await pw.newPage();+ try {+ await page.setContent('<div id="messages"><div class="message assistant" data-run-request-id="read-request"><div class="message-content"><div class="message-text"></div></div></div></div>');+ await page.evaluate(({ functions, dictionary }) => {+ const noop = () => {};+ Object.assign(window, {+ messagesEl: document.querySelector('#messages'), currentAssistantEl: document.querySelector('.assistant'), currentTabId: 7,+ submittedClarificationIds: new Set(), answers: [],+ t: (key, params) => String(dictionary[key] ?? key).replace(/\{(\w+)\}/g, (_, name) => (params?.[name] != null ? String(params[name]) : `{${name}}`)),+ submitClarify: (_card, _tab, clarifyId, value, source) => window.answers.push({ clarifyId, value, source }),+ hideRecommendedActions: noop, resetChatNavigation: noop, hideActivity: noop, scrollToBottom: noop, applyClarifyTimeoutExtension: noop,+ addMessage: () => { throw new Error('no new message'); },+ });+ (0, eval)(functions);+ window.renderClarifyCard({ clarifyId: 'download_read_1', promptKind: 'download_read', question: 'English fallback',+ downloadReadConfirmation: { filename: '<img src=x onerror=alert(1)>.txt', host: 'files.example' }, options: ['once', 'deny'] });+ }, { functions: ['renderClarifyCard', 'clarificationSubmissionKey'].map(extract).join('\n'), dictionary: english });+ const card = page.locator('.clarify-card[data-download-read-confirmation="1"]');+ assert.equal(await card.locator('.clarify-question').innerText(), english['sp.download_read.question']);+ assert.equal(await card.locator('.clarify-subject').innerText(), '<img src=x onerror=alert(1)>.txt (from files.example)');+ assert.equal(await card.locator('img').count(), 0, 'the page-settable name is text, not markup');+ assert.deepEqual(await card.locator('.clarify-option').allInnerTexts(), [english['sp.download_read.read'], english['sp.download_read.dont']]);+ assert.equal(await card.locator('.clarify-input').count(), 0, 'fixed choices, no free text');+ assert.equal(await card.getAttribute('data-memory-source'), '', 'the answer is not remembered as a clarification');+ await card.locator('.clarify-option[data-value="once"]').click();+ assert.deepEqual(await page.evaluate(() => window.answers), [{ clarifyId: 'download_read_1', value: 'once', source: 'option' }]);+ } finally { await page.close(); }+ });+}++test.after(async () => {+ const real = await fs.realpath(directory);+ assert.ok(real.startsWith(path.resolve(await fs.realpath(os.tmpdir())) + path.sep + 'webbrain-download-scope-'));+ await fs.rm(real, { recursive: true, force: true });+});diff --git a/test/downloaded-file-saved-bytes.mjs b/test/downloaded-file-saved-bytes.mjsindex 14dee0cda..362a77988 100644--- a/test/downloaded-file-saved-bytes.mjs+++ b/test/downloaded-file-saved-bytes.mjs@@ -209,14 +209,22 @@ for (const kind of ['chrome', 'firefox']) {const start = source.indexOf(" if (name === 'read_downloaded_file') {");const end = source.indexOf(" if (name === 'download_resource_from_page')", start);assert.ok(start >= 0 && end > start);- let owner = 'original-current-owner', pending = false, cancelled = false, captured;+ let owner = 'original-current-owner', pending = false, cancelled = false, captured, authorized, refusal = null;const signal = new AbortController().signal;const abort = () => { if (cancelled) throw new Error('Stopped by user'); };- const run = new Function('tabId', 'name', 'args', 'executionContext', 'cdpClient', 'readDownloadedFile',+ const onUpdate = () => {};+ const run = new Function('tabId', 'name', 'args', 'onUpdate', 'executionContext', 'cdpClient', 'readDownloadedFile','throwIfEarlyCdpAborted', 'throwIfContentPipelineAborted', `return (async()=>{${source.slice(start, end)}})();`);- const agent = { _pageFeedbackOwnerScope: () => owner, _hasPendingSteering: () => pending };+ const agent = { _pageFeedbackOwnerScope: () => owner, _hasPendingSteering: () => pending,+ _authorizeDownloadRead: async (...values) => { authorized = values; return refusal; } };+ const read = async (id, ctx) => { captured = { id, ctx }; return { success: true }; };+ refusal = { success: false, code: 'download_not_from_conversation' };+ assert.equal(await run.call(agent, 71, 'read_downloaded_file', { downloadId: 19 }, onUpdate, { _contentActionAbortSignal: signal },+ cdpClient, read, abort, abort), refusal, 'a download outside the conversation is not read without approval');+ assert.deepEqual(authorized, [71, 19, onUpdate]); assert.equal(captured, undefined);+ refusal = null;await run.call(agent, 71, 'read_downloaded_file', { downloadId: 19, cdpClient: 'forged', signal: 'forged', checkStillActive: 'forged' },- { _contentActionAbortSignal: signal }, cdpClient, async (id, ctx) => { captured = { id, ctx }; return { success: true }; }, abort, abort);+ onUpdate, { _contentActionAbortSignal: signal }, cdpClient, read, abort, abort);assert.equal(captured.id, 19); assert.equal(captured.ctx.signal, signal);assert.equal(captured.ctx.cdpClient, kind === 'chrome' ? cdpClient : undefined);assert.equal(typeof captured.ctx.checkStillActive, 'function');diff --git a/test/run.js b/test/run.jsindex 62cf7d479..e0fdd7cd0 100644--- a/test/run.js+++ b/test/run.js@@ -57770,8 +57770,8 @@ test('sidepanel long replies use reading-first turn navigation', () => {);assert.equal((clarifySource.match(/scrollToBottom\(\{ force: true \}\);/g) || []).length,- 8,- `${label}: workflow healing, submit, recipient, deletion, video-length, unverified-step, permission, and clarify prompts should override reading-first scroll suppression`,+ 9,+ `${label}: workflow healing, submit, recipient, deletion, video-length, download-read, unverified-step, permission, and clarify prompts should override reading-first scroll suppression`,);assert.match(panel,