Skip to content

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

Fix slash command responses at the live conversation position

Barack Sokullu1fe38c875d1a
diff --git a/package.json b/package.json
index 5375dcaf7..a9a20503f 100644
--- a/package.json
+++ b/package.json
@@ -68,7 +68,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/history-recovery.mjs test/history-recovery-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",
+ "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-pre-enter-veto.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/guard-reading-carry-over.mjs test/trusted-retry-readings.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/lifecycle-steering-restart.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/run-ui-hidden-panel.mjs test/clarify-timeout-policy.mjs test/guard-ask-cards.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/guard-policy.mjs test/lean-mode.mjs test/prompt-unverified-pages.mjs test/prompt-missing-values.mjs test/lifecycle-planner-digest.mjs test/planner-clarify-loop.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/sidepanel-permission-gate-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/slash-command-timeline-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && 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",
@@ -101,9 +101,9 @@
"test:quality:whatsapp": "node test/quality/whatsapp-contact-matrix.mjs",
"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/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:quick": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/guard-policy.mjs test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-bridge-registration.mjs test/cookie-banner-host.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/slash-command-tab-ownership.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:provider-instances:ui && npm run test:settings-pages:ui && npm run test:openrouter-capabilities && npm run test:anthropic && npm run test:browser-batch && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs",
"test:shard:runtime-unit": "node --test test/skill-download-wait.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-click-guard.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-pre-enter-veto.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/guard-reading-carry-over.mjs test/trusted-retry-readings.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/run-ui-hidden-panel.mjs test/clarify-timeout-policy.mjs test/guard-ask-cards.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/auto-mode.mjs test/plan-when-needed.mjs test/model-picker-icon.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/video-upload-attachment.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/lean-mode.mjs test/prompt-unverified-pages.mjs test/prompt-missing-values.mjs test/lifecycle-planner-digest.mjs test/planner-clarify-loop.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-vision-fallback.mjs test/delivery-click-locks.mjs test/guards-steering-receipts.mjs test/terminal-user-messages.mjs test/improver-providers.mjs test/improver-providers-agent.mjs test/improver-guards-ledger.mjs test/improver-guards-tools.mjs test/improver-clarify.mjs test/improver-clarify-scheduler.mjs test/improver-misc.mjs test/improver-forms.mjs test/improver-forms-strict-secrets.mjs test/improver-content-press-keys-hint.mjs && npm run test:plan-notifications",
- "test:shard:browser-a": "node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs && node test/bot-memory-dom.mjs && node test/bot-memory-click-dom.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/sidepanel-permission-gate-ui.mjs test/model-picker-status-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/native-button-preparation.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/activity-brain-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs test/delivery-cdp-input.mjs test/delivery-click-ax-response-loss.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-native-button-route.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/submit-probe-readings.mjs test/declined-submission-identity.mjs test/improver-content-account-chrome.mjs test/improver-content-recipient.mjs test/improver-content-truncated-replacement.mjs test/improver-forms-probe.mjs test/improver-misc-trace-browser.mjs test/page-feedback-held-time.mjs test/page-monitor-held-observation.mjs",
+ "test:shard:browser-a": "node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs && node test/bot-memory-dom.mjs && node test/bot-memory-click-dom.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/sidepanel-permission-gate-ui.mjs test/model-picker-status-ui.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-chat-selection.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/native-button-preparation.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/activity-brain-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/slash-command-timeline-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs test/delivery-cdp-input.mjs test/delivery-click-ax-response-loss.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-native-button-route.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/submit-probe-readings.mjs test/declined-submission-identity.mjs test/improver-content-account-chrome.mjs test/improver-content-recipient.mjs test/improver-content-truncated-replacement.mjs test/improver-forms-probe.mjs test/improver-misc-trace-browser.mjs test/page-feedback-held-time.mjs test/page-monitor-held-observation.mjs",
"test:shard:browser-b1": "node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/integration-mv3.mjs --batch && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs",
"test:shard:browser-b2": "node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs --selector-recovery && node test/quality/upload-release-binding-mv3.mjs --sequential-assets && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/shared-action-guards-mv3.mjs && node test/quality/video-upload-attachment-mv3.mjs && node --test test/iframe-probe-match-index.mjs",
"test:shard:browser-c": "node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/mastodon-delete-after-correction-mv3.mjs && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.js
index 5cac6039d..e59dd06ad 100644
--- a/src/chrome/src/ui/sidepanel.js
+++ b/src/chrome/src/ui/sidepanel.js
@@ -3450,19 +3450,22 @@ function roleFromMessageElement(el) {
if (el.classList.contains('user')) return 'user';
if (el.classList.contains('assistant')) return 'assistant';
if (el.classList.contains('error')) return 'error';
- if (el.classList.contains('system')) return 'system';
+ if (el.classList.contains('system') || el.classList.contains('slash-command-output')) return 'system';
return 'unknown';
}
function extractChatHistoryMessages(root = messagesEl) {
if (!root) return [];
- return Array.from(root.querySelectorAll(':scope > .message')).filter((msgEl) => (
+ return Array.from(root.querySelectorAll(':scope > .message')).flatMap(msgEl => [
+ ...msgEl.querySelectorAll('.slash-command-output'), msgEl,
+ ]).filter((msgEl) => (
msgEl.querySelector('.message-text')?.dataset.responseIncomplete !== 'true'
)).map((msgEl, index) => {
const clone = msgEl.cloneNode(true);
clone.querySelectorAll('button, input, textarea, select, .msg-copy-btn, .code-copy-btn, .error-retry-btn')
.forEach((el) => el.remove());
- const textEl = clone.querySelector('.message-text') || clone.querySelector('.message-content') || clone;
+ const textEl = clone.querySelector('.message-text') || clone.querySelector('.slash-command-text')
+ || clone.querySelector('.message-content') || clone;
const role = roleFromMessageElement(msgEl);
const format = role === 'assistant' || role === 'error' ? 'markdown' : 'text';
const attachments = role === 'user' ? messageAttachmentMetadata(msgEl) : [];
@@ -4752,7 +4755,7 @@ async function renderScheduleComposer(prefillPrompt = '', tabId = currentTabId)
bindScheduleComposer(form);
content.appendChild(form);
promptInput.focus();
- scrollToBottom();
+ scrollToBottom({ force: true });
}
async function showScratchpad(tabId = currentTabId) {
@@ -5112,7 +5115,7 @@ async function showSavedWorkflows(tabId = currentTabId) {
const msgEl = addPersistentSlashMessage(systemHtml(t('sp.workflows.title_html')));
const manager = document.createElement('div');
manager.className = 'workflow-manager';
- msgEl.querySelector('.message-text')?.appendChild(manager);
+ msgEl.querySelector('.message-text, .slash-command-text')?.appendChild(manager);
renderSavedWorkflowManager(manager, workflows, tabId);
} catch (error) {
if (currentTabId === tabId) addPersistentSlashMessage(t('sp.workflows.error', { msg: error.message }));
@@ -5350,7 +5353,7 @@ function renderSavedWorkflowParameterForm(workflow, tabId = currentTabId) {
bindSavedWorkflowParameterForm(form);
content.appendChild(form);
form.querySelector('input')?.focus();
- scrollToBottom();
+ scrollToBottom({ force: true });
}
async function prepareSavedWorkflowRun(id, tabId = currentTabId) {
@@ -9252,8 +9255,31 @@ function showComposerToast(message, { duration = 2600, effect = '' } = {}) {
}
function addPersistentSlashMessage(content) {
- const msgEl = addMessage('system', content, { beforeCurrentAssistant: true });
- scrollToBottom({ force: true });
+ const assistantContent = isProcessing && currentAssistantEl?.parentNode === messagesEl
+ ? currentAssistantEl.querySelector('.message-content') : null;
+ const textCursor = [...(assistantContent?.children || [])]
+ .find(child => child.classList.contains('message-text'));
+ let msgEl;
+ if (textCursor) {
+ // Keep the run's event target and streaming cursor intact. A separate
+ // message before the assistant would precede the entire run; one after it
+ // would leave all subsequent tool output above the command's response.
+ msgEl = document.createElement('div');
+ msgEl.className = 'slash-command-output';
+ const contentEl = document.createElement('div');
+ contentEl.className = 'slash-command-content';
+ const textEl = document.createElement('div');
+ textEl.className = 'slash-command-text';
+ if (isSystemHtml(content)) textEl.innerHTML = content.__systemHtml;
+ else textEl.textContent = content || '';
+ contentEl.appendChild(textEl);
+ msgEl.appendChild(contentEl);
+ assistantContent.insertBefore(msgEl, textCursor);
+ syncAssistantMessageElementVisibility(currentAssistantEl);
+ } else {
+ msgEl = addMessage('system', content);
+ }
+ scrollToBottom({ force: true, reveal: msgEl });
return msgEl;
}
@@ -9666,7 +9692,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
} else {
resolvePendingPermissionPromptsForTab(tabId);
}
- addPersistentSlashMessage(systemHtml(t('sp.permissions.disabled_html')));
+ if (currentTabId === tabId) addPersistentSlashMessage(systemHtml(t('sp.permissions.disabled_html')));
return payload;
}
@@ -9880,9 +9906,9 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 7000);
}
- addPersistentSlashMessage(t('sp.export_config.done'));
+ if (currentTabId === tabId) addPersistentSlashMessage(t('sp.export_config.done'));
} catch (error) {
- addPersistentSlashMessage(t('sp.export_config.error', { error: error?.message || 'unknown error' }));
+ if (currentTabId === tabId) addPersistentSlashMessage(t('sp.export_config.error', { error: error?.message || 'unknown error' }));
}
return '';
}
@@ -9899,15 +9925,15 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
res = { ok: true, ...await exportRecordedSession(store, res.sessionId, chrome.runtime.getManifest().version || '') };
}
} catch (e) {
- addPersistentSlashMessage(`${t('sp.export_traces.error')} (${e?.message || e})`);
+ if (currentTabId === tabId) addPersistentSlashMessage(`${t('sp.export_traces.error')} (${e?.message || e})`);
return '';
}
if (!res?.ok) {
- addPersistentSlashMessage(`${t('sp.export_traces.error')} (${res?.error || 'unknown error'})`);
+ if (currentTabId === tabId) addPersistentSlashMessage(`${t('sp.export_traces.error')} (${res?.error || 'unknown error'})`);
return '';
}
if (!(res.json || res.markdown) || res.turnCount === 0) {
- addPersistentSlashMessage(
+ if (currentTabId === tabId) addPersistentSlashMessage(
res.reason === 'no-conversation'
? t('sp.export_traces.no_conversation')
: t('sp.export_traces.none'),
@@ -9926,6 +9952,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 7000);
}
+ if (currentTabId !== tabId) return '';
if (res.recordingTruncated) {
addPersistentSlashMessage(t('sp.export_traces.recording_truncated'));
} else if (res.partial) {
@@ -9939,11 +9966,13 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
}
if (command.value === '/export' && action === 'conversation') {
- const messages = messagesEl.querySelectorAll('.message');
+ const messages = Array.from(messagesEl.querySelectorAll(':scope > .message')).flatMap(msgEl => [
+ ...msgEl.querySelectorAll('.slash-command-output'), msgEl,
+ ]);
const webbrainVersion = chrome.runtime.getManifest().version || 'unknown';
let md = `# WebBrain Conversation\n\n_Exported with WebBrain v${webbrainVersion}_\n\n`;
for (const msg of messages) {
- const textEl = msg.querySelector('.message-text');
+ const textEl = msg.querySelector('.message-text') || msg.querySelector('.slash-command-text');
if (!textEl) continue;
const content = textEl.textContent.trim();
if (!content) continue;
@@ -9951,7 +9980,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
md += `**You:** ${content}\n\n`;
} else if (msg.classList.contains('assistant')) {
md += `**WebBrain:** ${content}\n\n`;
- } else if (msg.classList.contains('system')) {
+ } else if (msg.classList.contains('system') || msg.classList.contains('slash-command-output')) {
md += `*${content}*\n\n`;
}
}
@@ -10237,7 +10266,6 @@ async function sendMessage(extraChatParams = {}) {
syncSendButtonState();
await parseSlashCommands(text, tabId, { permissionSkipContext });
if (currentTabId === tabId) {
- scrollToBottom({ force: true });
if (!inputEl.value.trim() || inputEl.value.trim() === text) {
inputEl.value = '';
autoResizeInput();
@@ -10319,7 +10347,6 @@ async function sendMessage(extraChatParams = {}) {
// left to send to the agent — bail out after the side effect.
if (!text) {
await releaseOwnedContextMenuClaim({ reason: 'preflight-empty', retryAfterMs: 1_000 });
- scrollToBottom({ force: true });
inputEl.value = '';
autoResizeInput();
syncSendButtonState();
@@ -12673,15 +12700,15 @@ function getOrCreateStepsContainer(assistantEl = currentAssistantEl) {
.find(child => child.classList.contains('message-text')) || null;
if (!textEl) return null;
- // Each answered clarification is a timeline boundary. Reusing a compact
- // steps container from before that boundary would place resumed events above
- // the Q&A, so only reuse a segment between the latest answered card and the
+ // Answered clarifications and slash responses are timeline boundaries.
+ // Reusing an earlier compact steps container would place resumed events
+ // above the response, so only reuse a segment after the latest boundary and before the
// final-text cursor.
- const latestAnsweredCard = [...content.children]
+ const latestBoundary = [...content.children]
.reverse()
- .find(child => child.matches('.clarify-card.clarify-answered')) || null;
- let candidate = latestAnsweredCard
- ? latestAnsweredCard.nextElementSibling
+ .find(child => child.matches('.clarify-card.clarify-answered, .slash-command-output')) || null;
+ let candidate = latestBoundary
+ ? latestBoundary.nextElementSibling
: content.firstElementChild;
let container = null;
while (candidate && candidate !== textEl) {
@@ -12758,9 +12785,11 @@ function appendCompactStep(toolName, args) {
}
if (isTerminalDoneTool(toolName)) {
- const rejectedSteps = currentAssistantEl?.querySelectorAll?.(
+ // Collapse retries only within this segment, never across a user-visible
+ // slash response or answered clarification.
+ const rejectedSteps = container.querySelectorAll(
'.step-item[data-tool="done"][data-rejected-completion="true"], .step-item[data-tool="done_json"][data-rejected-completion="true"]',
- ) || [];
+ );
const priorRejected = rejectedSteps[rejectedSteps.length - 1];
if (priorRejected) {
priorRejected.classList.remove('done');
@@ -12926,7 +12955,10 @@ function appendVerboseToolCall(name, args) {
const rejectedTools = content.querySelectorAll(
'.tool-call[data-tool-name="done"][data-rejected-completion="true"]',
);
- const priorRejected = rejectedTools[rejectedTools.length - 1];
+ const latestBoundary = [...content.children].reverse()
+ .find(child => child.matches('.clarify-card.clarify-answered, .slash-command-output'));
+ const priorRejected = [...rejectedTools].reverse().find(tool => !latestBoundary
+ || (latestBoundary.compareDocumentPosition(tool) & Node.DOCUMENT_POSITION_FOLLOWING));
if (priorRejected) {
priorRejected.querySelector('.tool-call-body').textContent = JSON.stringify(args, null, 2);
priorRejected.querySelector('.tool-result')?.remove();
@@ -13116,7 +13148,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
textEl.innerHTML = t('sp.stopped_by_user_html');
clearStreamedAssistantText(textEl);
delete textEl.dataset.suppressToolCallStream;
- if (!assistantEl.querySelector('.msg-copy-btn')) addMessageCopyButton(assistantEl);
+ if (!assistantEl.querySelector('.msg-copy-btn:not(.scratchpad-copy-btn)')) addMessageCopyButton(assistantEl);
return;
}
@@ -13137,7 +13169,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
if (renderSubscribeError(textEl, content)) {
clearStreamedAssistantText(textEl);
delete textEl.dataset.suppressToolCallStream;
- if (!assistantEl.querySelector('.msg-copy-btn')) addMessageCopyButton(assistantEl);
+ if (!assistantEl.querySelector('.msg-copy-btn:not(.scratchpad-copy-btn)')) addMessageCopyButton(assistantEl);
return;
}
@@ -13177,7 +13209,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
delete textEl.dataset.suppressToolCallStream;
// Add copy button if not already present
- if (!assistantEl.querySelector('.msg-copy-btn')) {
+ if (!assistantEl.querySelector('.msg-copy-btn:not(.scratchpad-copy-btn)')) {
addMessageCopyButton(assistantEl);
}
}
@@ -14126,7 +14158,7 @@ function addContextCompactedNote(data) {
} else {
messagesEl.appendChild(note);
}
- scrollToBottom();
+ scrollToBottom({ force: data?.manual === true });
}
/**
@@ -14639,7 +14671,7 @@ function pinChatToBottom(container) {
container.style.scrollBehavior = previousScrollBehavior;
}
-function scrollToBottom({ force = false } = {}) {
+function scrollToBottom({ force = false, reveal = null } = {}) {
const container = chatContainerEl;
if (!container) return;
// A forced jump deliberately takes the reader to the live edge (blocking
@@ -14655,12 +14687,26 @@ function scrollToBottom({ force = false } = {}) {
return;
}
- pinChatToBottom(container);
+ const pinAndReveal = () => {
+ pinChatToBottom(container);
+ // The final-text cursor may already contain a long streamed answer below
+ // an inline command. Reveal the requested card and preserve that reading
+ // position instead of immediately pulling it away on the next delta.
+ if (reveal?.isConnected
+ && reveal.getBoundingClientRect().top < container.getBoundingClientRect().top) {
+ reveal.scrollIntoView({ block: 'nearest', behavior: 'instant' });
+ if (chatTurnIsConnected()) {
+ chatAutoFollow = false;
+ chatUserChoseReadingPosition = true;
+ }
+ }
+ };
+ pinAndReveal();
if (scrollToBottomFrame != null) cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = requestAnimationFrame(() => {
scrollToBottomFrame = null;
if (container.isConnected && (force || chatAutoFollow || !chatTurnIsConnected())) {
- pinChatToBottom(container);
+ pinAndReveal();
}
scheduleChatNavigationUpdate();
});
@@ -14879,7 +14925,7 @@ function addMessageCopyButton(msgEl) {
function addScratchpadCopyButton(msgEl) {
if (!msgEl) return;
- const content = msgEl.querySelector('.message-content');
+ const content = msgEl.querySelector('.message-content, .slash-command-content');
const pre = content?.querySelector('pre.scratchpad-dump');
if (!content || !pre) return;
const existing = content.querySelector('.scratchpad-copy-btn');
@@ -14897,7 +14943,7 @@ function addScratchpadCopyButton(msgEl) {
}
function getMessageCopyText(btn) {
- const content = btn?.closest('.message-content');
+ const content = btn?.closest('.message-content, .slash-command-content');
if (!content) return null;
if (btn.classList.contains('scratchpad-copy-btn')) {
return content.querySelector('pre.scratchpad-dump')?.textContent || '';
diff --git a/src/chrome/styles/sidepanel.css b/src/chrome/styles/sidepanel.css
index 34eac0623..8f94339b1 100644
--- a/src/chrome/styles/sidepanel.css
+++ b/src/chrome/styles/sidepanel.css
@@ -1845,7 +1845,8 @@ html[dir="rtl"] .language-picker-menu {
font-size: 12px;
}
-.message-content {
+.message-content,
+.slash-command-content {
padding: 10px 14px;
border-radius: var(--radius);
line-height: 1.5;
@@ -2001,12 +2002,18 @@ html[dir="rtl"] .language-picker-menu {
opacity: 0.9;
}
-.message.system .message-content {
+.message.system .message-content,
+.slash-command-content {
background: var(--accent-dim);
border: 1px solid rgba(108, 99, 255, 0.2);
font-size: 12px;
}
+.slash-command-output {
+ margin: 10px 0;
+ cursor: auto;
+}
+
.screenshot-result {
display: flex;
flex-direction: column;
diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.js
index 27dbcb289..12f2d1589 100644
--- a/src/firefox/src/ui/sidepanel.js
+++ b/src/firefox/src/ui/sidepanel.js
@@ -2624,19 +2624,22 @@ function roleFromMessageElement(el) {
if (el.classList.contains('user')) return 'user';
if (el.classList.contains('assistant')) return 'assistant';
if (el.classList.contains('error')) return 'error';
- if (el.classList.contains('system')) return 'system';
+ if (el.classList.contains('system') || el.classList.contains('slash-command-output')) return 'system';
return 'unknown';
}
function extractChatHistoryMessages(root = messagesEl) {
if (!root) return [];
- return Array.from(root.querySelectorAll(':scope > .message')).filter((msgEl) => (
+ return Array.from(root.querySelectorAll(':scope > .message')).flatMap(msgEl => [
+ ...msgEl.querySelectorAll('.slash-command-output'), msgEl,
+ ]).filter((msgEl) => (
msgEl.querySelector('.message-text')?.dataset.responseIncomplete !== 'true'
)).map((msgEl, index) => {
const clone = msgEl.cloneNode(true);
clone.querySelectorAll('button, input, textarea, select, .msg-copy-btn, .code-copy-btn, .error-retry-btn')
.forEach((el) => el.remove());
- const textEl = clone.querySelector('.message-text') || clone.querySelector('.message-content') || clone;
+ const textEl = clone.querySelector('.message-text') || clone.querySelector('.slash-command-text')
+ || clone.querySelector('.message-content') || clone;
const role = roleFromMessageElement(msgEl);
const format = role === 'assistant' || role === 'error' ? 'markdown' : 'text';
const attachments = role === 'user' ? messageAttachmentMetadata(msgEl) : [];
@@ -4616,7 +4619,7 @@ async function renderScheduleComposer(prefillPrompt = '', tabId = currentTabId)
bindScheduleComposer(form);
content.appendChild(form);
promptInput.focus();
- scrollToBottom();
+ scrollToBottom({ force: true });
}
async function showScratchpad(tabId = currentTabId) {
@@ -4976,7 +4979,7 @@ async function showSavedWorkflows(tabId = currentTabId) {
const msgEl = addPersistentSlashMessage(systemHtml(t('sp.workflows.title_html')));
const manager = document.createElement('div');
manager.className = 'workflow-manager';
- msgEl.querySelector('.message-text')?.appendChild(manager);
+ msgEl.querySelector('.message-text, .slash-command-text')?.appendChild(manager);
renderSavedWorkflowManager(manager, workflows, tabId);
} catch (error) {
if (currentTabId === tabId) addPersistentSlashMessage(t('sp.workflows.error', { msg: error.message }));
@@ -5214,7 +5217,7 @@ function renderSavedWorkflowParameterForm(workflow, tabId = currentTabId) {
bindSavedWorkflowParameterForm(form);
content.appendChild(form);
form.querySelector('input')?.focus();
- scrollToBottom();
+ scrollToBottom({ force: true });
}
async function prepareSavedWorkflowRun(id, tabId = currentTabId) {
@@ -9033,8 +9036,31 @@ function showComposerToast(message, { duration = 2600, effect = '' } = {}) {
}
function addPersistentSlashMessage(content) {
- const msgEl = addMessage('system', content, { beforeCurrentAssistant: true });
- scrollToBottom({ force: true });
+ const assistantContent = isProcessing && currentAssistantEl?.parentNode === messagesEl
+ ? currentAssistantEl.querySelector('.message-content') : null;
+ const textCursor = [...(assistantContent?.children || [])]
+ .find(child => child.classList.contains('message-text'));
+ let msgEl;
+ if (textCursor) {
+ // Keep the run's event target and streaming cursor intact. A separate
+ // message before the assistant would precede the entire run; one after it
+ // would leave all subsequent tool output above the command's response.
+ msgEl = document.createElement('div');
+ msgEl.className = 'slash-command-output';
+ const contentEl = document.createElement('div');
+ contentEl.className = 'slash-command-content';
+ const textEl = document.createElement('div');
+ textEl.className = 'slash-command-text';
+ if (isSystemHtml(content)) textEl.innerHTML = content.__systemHtml;
+ else textEl.textContent = content || '';
+ contentEl.appendChild(textEl);
+ msgEl.appendChild(contentEl);
+ assistantContent.insertBefore(msgEl, textCursor);
+ syncAssistantMessageElementVisibility(currentAssistantEl);
+ } else {
+ msgEl = addMessage('system', content);
+ }
+ scrollToBottom({ force: true, reveal: msgEl });
return msgEl;
}
@@ -9299,7 +9325,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
showSlashInvocationError(invocation);
return '';
}
- const { command, action, payload } = invocation;
+ const { command, action, payload, optionValues } = invocation;
if (action === 'help') {
addPersistentSlashMessage(systemHtml(buildSlashCommandDetailHtml(command)));
@@ -9432,7 +9458,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
} else {
resolvePendingPermissionPromptsForTab(tabId);
}
- addPersistentSlashMessage(systemHtml(t('sp.permissions.disabled_html')));
+ if (currentTabId === tabId) addPersistentSlashMessage(systemHtml(t('sp.permissions.disabled_html')));
return payload;
}
@@ -9605,9 +9631,9 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 7000);
}
- addPersistentSlashMessage(t('sp.export_config.done'));
+ if (currentTabId === tabId) addPersistentSlashMessage(t('sp.export_config.done'));
} catch (error) {
- addPersistentSlashMessage(t('sp.export_config.error', { error: error?.message || 'unknown error' }));
+ if (currentTabId === tabId) addPersistentSlashMessage(t('sp.export_config.error', { error: error?.message || 'unknown error' }));
}
return '';
}
@@ -9624,15 +9650,15 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
res = { ok: true, ...await exportRecordedSession(store, res.sessionId, browser.runtime.getManifest().version || '') };
}
} catch (e) {
- addPersistentSlashMessage(`${t('sp.export_traces.error')} (${e?.message || e})`);
+ if (currentTabId === tabId) addPersistentSlashMessage(`${t('sp.export_traces.error')} (${e?.message || e})`);
return '';
}
if (!res?.ok) {
- addPersistentSlashMessage(`${t('sp.export_traces.error')} (${res?.error || 'unknown error'})`);
+ if (currentTabId === tabId) addPersistentSlashMessage(`${t('sp.export_traces.error')} (${res?.error || 'unknown error'})`);
return '';
}
if (!(res.json || res.markdown) || res.turnCount === 0) {
- addPersistentSlashMessage(
+ if (currentTabId === tabId) addPersistentSlashMessage(
res.reason === 'no-conversation'
? t('sp.export_traces.no_conversation')
: t('sp.export_traces.none'),
@@ -9651,6 +9677,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 7000);
}
+ if (currentTabId !== tabId) return '';
if (res.recordingTruncated) {
addPersistentSlashMessage(t('sp.export_traces.recording_truncated'));
} else if (res.partial) {
@@ -9664,11 +9691,13 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
}
if (command.value === '/export' && action === 'conversation') {
- const messages = messagesEl.querySelectorAll('.message');
+ const messages = Array.from(messagesEl.querySelectorAll(':scope > .message')).flatMap(msgEl => [
+ ...msgEl.querySelectorAll('.slash-command-output'), msgEl,
+ ]);
const webbrainVersion = browser.runtime.getManifest().version || 'unknown';
let md = `# WebBrain Conversation\n\n_Exported with WebBrain v${webbrainVersion}_\n\n`;
for (const msg of messages) {
- const textEl = msg.querySelector('.message-text');
+ const textEl = msg.querySelector('.message-text') || msg.querySelector('.slash-command-text');
if (!textEl) continue;
const content = textEl.textContent.trim();
if (!content) continue;
@@ -9676,7 +9705,7 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
md += `**You:** ${content}\n\n`;
} else if (msg.classList.contains('assistant')) {
md += `**WebBrain:** ${content}\n\n`;
- } else if (msg.classList.contains('system')) {
+ } else if (msg.classList.contains('system') || msg.classList.contains('slash-command-output')) {
md += `*${content}*\n\n`;
}
}
@@ -9923,7 +9952,6 @@ async function sendMessage(extraChatParams = {}) {
syncSendButtonState();
await parseSlashCommands(text, tabId, { permissionSkipContext });
if (currentTabId === tabId) {
- scrollToBottom({ force: true });
if (!inputEl.value.trim() || inputEl.value.trim() === text) {
inputEl.value = '';
autoResizeInput();
@@ -10000,7 +10028,6 @@ async function sendMessage(extraChatParams = {}) {
}
if (!text) {
await releaseOwnedContextMenuClaim({ reason: 'preflight-empty', retryAfterMs: 1_000 });
- scrollToBottom({ force: true });
inputEl.value = '';
autoResizeInput();
syncSendButtonState();
@@ -12301,15 +12328,15 @@ function getOrCreateStepsContainer(assistantEl = currentAssistantEl) {
.find(child => child.classList.contains('message-text')) || null;
if (!textEl) return null;
- // Each answered clarification is a timeline boundary. Reusing a compact
- // steps container from before that boundary would place resumed events above
- // the Q&A, so only reuse a segment between the latest answered card and the
+ // Answered clarifications and slash responses are timeline boundaries.
+ // Reusing an earlier compact steps container would place resumed events
+ // above the response, so only reuse a segment after the latest boundary and before the
// final-text cursor.
- const latestAnsweredCard = [...content.children]
+ const latestBoundary = [...content.children]
.reverse()
- .find(child => child.matches('.clarify-card.clarify-answered')) || null;
- let candidate = latestAnsweredCard
- ? latestAnsweredCard.nextElementSibling
+ .find(child => child.matches('.clarify-card.clarify-answered, .slash-command-output')) || null;
+ let candidate = latestBoundary
+ ? latestBoundary.nextElementSibling
: content.firstElementChild;
let container = null;
while (candidate && candidate !== textEl) {
@@ -12386,9 +12413,11 @@ function appendCompactStep(toolName, args) {
}
if (isTerminalDoneTool(toolName)) {
- const rejectedSteps = currentAssistantEl?.querySelectorAll?.(
+ // Collapse retries only within this segment, never across a user-visible
+ // slash response or answered clarification.
+ const rejectedSteps = container.querySelectorAll(
'.step-item[data-tool="done"][data-rejected-completion="true"], .step-item[data-tool="done_json"][data-rejected-completion="true"]',
- ) || [];
+ );
const priorRejected = rejectedSteps[rejectedSteps.length - 1];
if (priorRejected) {
priorRejected.classList.remove('done');
@@ -12554,7 +12583,10 @@ function appendVerboseToolCall(name, args) {
const rejectedTools = content.querySelectorAll(
'.tool-call[data-tool-name="done"][data-rejected-completion="true"]',
);
- const priorRejected = rejectedTools[rejectedTools.length - 1];
+ const latestBoundary = [...content.children].reverse()
+ .find(child => child.matches('.clarify-card.clarify-answered, .slash-command-output'));
+ const priorRejected = [...rejectedTools].reverse().find(tool => !latestBoundary
+ || (latestBoundary.compareDocumentPosition(tool) & Node.DOCUMENT_POSITION_FOLLOWING));
if (priorRejected) {
priorRejected.querySelector('.tool-call-body').textContent = JSON.stringify(args, null, 2);
priorRejected.querySelector('.tool-result')?.remove();
@@ -12744,7 +12776,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
textEl.innerHTML = t('sp.stopped_by_user_html');
clearStreamedAssistantText(textEl);
delete textEl.dataset.suppressToolCallStream;
- if (!assistantEl.querySelector('.msg-copy-btn')) addMessageCopyButton(assistantEl);
+ if (!assistantEl.querySelector('.msg-copy-btn:not(.scratchpad-copy-btn)')) addMessageCopyButton(assistantEl);
return;
}
@@ -12765,7 +12797,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
if (renderSubscribeError(textEl, content)) {
clearStreamedAssistantText(textEl);
delete textEl.dataset.suppressToolCallStream;
- if (!assistantEl.querySelector('.msg-copy-btn')) addMessageCopyButton(assistantEl);
+ if (!assistantEl.querySelector('.msg-copy-btn:not(.scratchpad-copy-btn)')) addMessageCopyButton(assistantEl);
return;
}
@@ -12805,7 +12837,7 @@ function renderAssistantTextUpdate(assistantEl, content, options = {}) {
delete textEl.dataset.suppressToolCallStream;
// Add copy button if not already present
- if (!assistantEl.querySelector('.msg-copy-btn')) {
+ if (!assistantEl.querySelector('.msg-copy-btn:not(.scratchpad-copy-btn)')) {
addMessageCopyButton(assistantEl);
}
}
@@ -13755,7 +13787,7 @@ function addContextCompactedNote(data) {
} else {
messagesEl.appendChild(note);
}
- scrollToBottom();
+ scrollToBottom({ force: data?.manual === true });
}
/**
@@ -14259,7 +14291,7 @@ function pinChatToBottom(container) {
container.style.scrollBehavior = previousScrollBehavior;
}
-function scrollToBottom({ force = false } = {}) {
+function scrollToBottom({ force = false, reveal = null } = {}) {
const container = chatContainerEl;
if (!container) return;
// A forced jump deliberately takes the reader to the live edge (blocking
@@ -14275,12 +14307,26 @@ function scrollToBottom({ force = false } = {}) {
return;
}
- pinChatToBottom(container);
+ const pinAndReveal = () => {
+ pinChatToBottom(container);
+ // The final-text cursor may already contain a long streamed answer below
+ // an inline command. Reveal the requested card and preserve that reading
+ // position instead of immediately pulling it away on the next delta.
+ if (reveal?.isConnected
+ && reveal.getBoundingClientRect().top < container.getBoundingClientRect().top) {
+ reveal.scrollIntoView({ block: 'nearest', behavior: 'instant' });
+ if (chatTurnIsConnected()) {
+ chatAutoFollow = false;
+ chatUserChoseReadingPosition = true;
+ }
+ }
+ };
+ pinAndReveal();
if (scrollToBottomFrame != null) cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = requestAnimationFrame(() => {
scrollToBottomFrame = null;
if (container.isConnected && (force || chatAutoFollow || !chatTurnIsConnected())) {
- pinChatToBottom(container);
+ pinAndReveal();
}
scheduleChatNavigationUpdate();
});
@@ -14492,7 +14538,7 @@ function addMessageCopyButton(msgEl) {
function addScratchpadCopyButton(msgEl) {
if (!msgEl) return;
- const content = msgEl.querySelector('.message-content');
+ const content = msgEl.querySelector('.message-content, .slash-command-content');
const pre = content?.querySelector('pre.scratchpad-dump');
if (!content || !pre) return;
const existing = content.querySelector('.scratchpad-copy-btn');
@@ -14510,7 +14556,7 @@ function addScratchpadCopyButton(msgEl) {
}
function getMessageCopyText(btn) {
- const content = btn?.closest('.message-content');
+ const content = btn?.closest('.message-content, .slash-command-content');
if (!content) return null;
if (btn.classList.contains('scratchpad-copy-btn')) {
return content.querySelector('pre.scratchpad-dump')?.textContent || '';
diff --git a/src/firefox/styles/sidepanel.css b/src/firefox/styles/sidepanel.css
index 26165989c..371326615 100644
--- a/src/firefox/styles/sidepanel.css
+++ b/src/firefox/styles/sidepanel.css
@@ -1677,7 +1677,8 @@ html[dir="rtl"] .language-picker-menu {
font-size: 12px;
}
-.message-content {
+.message-content,
+.slash-command-content {
padding: 10px 14px;
border-radius: var(--radius);
line-height: 1.5;
@@ -1833,12 +1834,18 @@ html[dir="rtl"] .language-picker-menu {
opacity: 0.9;
}
-.message.system .message-content {
+.message.system .message-content,
+.slash-command-content {
background: var(--accent-dim);
border: 1px solid rgba(108, 99, 255, 0.2);
font-size: 12px;
}
+.slash-command-output {
+ margin: 10px 0;
+ cursor: auto;
+}
+
.screenshot-result {
display: flex;
flex-direction: column;
diff --git a/test/run.js b/test/run.js
index bfecdb5f3..d5272daf9 100644
--- a/test/run.js
+++ b/test/run.js
@@ -57642,7 +57642,7 @@ test('sidepanel auto-follow bypasses smooth-scroll lag while messages grow', ()
);
assert.match(
panel,
- /function scrollToBottom\(\{ force = false \} = \{\}\) \{[\s\S]*?if \(force && chatTurnIsConnected\(\)\) \{[\s\S]*?chatAutoFollow = true;[\s\S]*?chatUserChoseReadingPosition = false;[\s\S]*?if \(!force && chatTurnIsConnected\(\) && !chatAutoFollow[\s\S]*?chatUserChoseReadingPosition \|\| chatTurnIsRunning\(\) \|\| chatTurnNeedsReadingNavigation\(\)[\s\S]*?pinChatToBottom\(container\);[\s\S]*?requestAnimationFrame\(\(\) => \{[\s\S]*?pinChatToBottom\(container\);[\s\S]*?\}\);[\s\S]*?\}/,
+ /function scrollToBottom\(\{ force = false, reveal = null \} = \{\}\) \{[\s\S]*?if \(force && chatTurnIsConnected\(\)\) \{[\s\S]*?chatAutoFollow = true;[\s\S]*?chatUserChoseReadingPosition = false;[\s\S]*?if \(!force && chatTurnIsConnected\(\) && !chatAutoFollow[\s\S]*?chatUserChoseReadingPosition \|\| chatTurnIsRunning\(\) \|\| chatTurnNeedsReadingNavigation\(\)[\s\S]*?pinChatToBottom\(container\);[\s\S]*?requestAnimationFrame\(\(\) => \{[\s\S]*?pinAndReveal\(\);[\s\S]*?\}\);[\s\S]*?\}/,
`${label}: auto-follow should re-pin after the next layout frame`,
);
}
@@ -57795,7 +57795,7 @@ test('sidepanel long replies use reading-first turn navigation', () => {
);
assert.match(
compactStepsSource,
- /latestAnsweredCard[\s\S]*?latestAnsweredCard\.nextElementSibling[\s\S]*?candidate !== textEl[\s\S]*?classList\.contains\('steps-container'\)[\s\S]*?content\.insertBefore\(container, textEl\);/,
+ /latestBoundary[\s\S]*?latestBoundary\.nextElementSibling[\s\S]*?candidate !== textEl[\s\S]*?classList\.contains\('steps-container'\)[\s\S]*?content\.insertBefore\(container, textEl\);/,
`${label}: compact resumed events should use a steps segment after the latest answered clarification`,
);
const compactLifecycleSource = panel.slice(
@@ -57847,18 +57847,18 @@ test('sidepanel long replies use reading-first turn navigation', () => {
);
assert.match(
panel,
- /function addPersistentSlashMessage\(content\) \{[\s\S]*?addMessage\('system', content, \{ beforeCurrentAssistant: true \}\);[\s\S]*?scrollToBottom\(\{ force: true \}\);[\s\S]*?return msgEl;/,
+ /function addPersistentSlashMessage\(content\) \{[\s\S]*?assistantContent\.insertBefore\(msgEl, textCursor\);[\s\S]*?addMessage\('system', content\);[\s\S]*?scrollToBottom\(\{ force: true, reveal: msgEl \}\);[\s\S]*?return msgEl;/,
`${label}: persistent slash-command output should override reading-first scroll suppression`,
);
- assert.match(
+ assert.doesNotMatch(
panel,
/await parseSlashCommands\(text, tabId, \{ permissionSkipContext \}\);\s*if \(currentTabId === tabId\) \{\s*scrollToBottom\(\{ force: true \}\);/,
- `${label}: out-of-band slash commands should reveal their output while a run is active`,
+ `${label}: out-of-band slash commands must preserve their targeted output reveal`,
);
- assert.match(
+ assert.doesNotMatch(
panel,
- /if \(!text\) \{[\s\S]*?scrollToBottom\(\{ force: true \}\);\s*inputEl\.value = '';/,
- `${label}: fully consumed slash commands should reveal synchronous UI output`,
+ /if \(!text\) \{\s*await releaseOwnedContextMenuClaim\([^\n]+\);\s*scrollToBottom\(\{ force: true \}\);\s*inputEl\.value = '';/,
+ `${label}: fully consumed slash commands must preserve their targeted output reveal`,
);
assert.match(
panel,
diff --git a/test/slash-command-tab-ownership.mjs b/test/slash-command-tab-ownership.mjs
new file mode 100644
index 000000000..c10d64c7a
--- /dev/null
+++ b/test/slash-command-tab-ownership.mjs
@@ -0,0 +1,99 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import { test } from 'node:test';
+
+function fixture(build, invocation) {
+ const source = fs.readFileSync(new URL(`../src/${build}/src/ui/sidepanel.js`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
+ const start = source.indexOf('async function parseSlashCommands(');
+ const end = source.indexOf('\n}', start);
+ assert.ok(start >= 0 && end > start);
+ let release, reject;
+ const pending = new Promise((resolve, fail) => { release = resolve; reject = fail; });
+ const notices = [], requests = [], downloads = [], resolvedTabs = [];
+ const context = vm.createContext({
+ currentTabId: 7,
+ PERMISSION_GATE_KEY: 'askBeforeConsequential',
+ askBeforeConsequential: true,
+ parseSlashInvocation: () => ({ payload: '', optionValues: new Set(), ...invocation }),
+ sendToBackground: (action, payload) => { requests.push({ action, payload }); return pending; },
+ addPersistentSlashMessage: content => notices.push(content),
+ t: key => key,
+ systemHtml: text => text,
+ getLocale: () => 'en',
+ updateActWarning() {},
+ updateInputPlaceholder() {},
+ resolvePendingPermissionPromptsForTab: tabId => resolvedTabs.push(tabId),
+ Blob,
+ URL: { createObjectURL: () => 'blob:export', revokeObjectURL() {} },
+ setTimeout() {},
+ document: {
+ createElement: () => ({ click() { downloads.push(this.download); }, remove() {} }),
+ body: { appendChild() {} },
+ },
+ });
+ context[build === 'chrome' ? 'chrome' : 'browser'] = {
+ storage: { local: { set: data => { requests.push({ action: 'storage.set', payload: data }); return pending; } } },
+ };
+ vm.runInContext(source.slice(start, end + 2), context);
+ return { context, release, reject, notices, requests, downloads, resolvedTabs };
+}
+
+for (const build of ['chrome', 'firefox']) {
+ for (const switched of [false, true]) {
+ const suffix = switched ? 'after switching tabs' : 'on the initiating tab';
+ for (const [name, response, expectedNotice, downloaded] of [
+ ['configuration', { ok: true, json: '{"settings":{}}' }, 'sp.export_config.done', true],
+ ['invalid configuration', { ok: false, error: 'unavailable' }, 'sp.export_config.error', false],
+ ['configuration transport error', new Error('disconnected'), 'sp.export_config.error', false],
+ ]) {
+ test(`${build}: ${name} export ${suffix}`, async () => {
+ const harness = fixture(build, { command: { value: '/export' }, action: 'config' });
+ const result = harness.context.parseSlashCommands('/export --config', 7);
+ assert.equal(harness.requests[0].action, 'export_config');
+ if (switched) harness.context.currentTabId = 9;
+ if (response instanceof Error) harness.reject(response);
+ else harness.release(response);
+ assert.equal(await result, '');
+ assert.equal(harness.downloads.length, Number(downloaded), 'A tab switch must not cancel an already requested download');
+ assert.deepEqual(harness.notices, switched ? [] : [expectedNotice]);
+ });
+ }
+
+ for (const [name, response, expectedNotice, downloaded] of [
+ ['trace Markdown', { ok: true, markdown: '# Original tab', turnCount: 1 }, 'sp.export_traces.done', true],
+ ['partial trace', { ok: true, json: '{}', turnCount: 1, partial: true }, 'sp.export_traces.partial', true],
+ ['truncated trace', { ok: true, markdown: 'trace', turnCount: 1, truncated: true }, 'sp.export_traces.truncated', true],
+ ['truncated recording', { ok: true, json: '{}', turnCount: 1, recordingTruncated: true }, 'sp.export_traces.recording_truncated', true],
+ ['empty trace', { ok: true, turnCount: 0 }, 'sp.export_traces.none', false],
+ ['missing conversation', { ok: true, reason: 'no-conversation' }, 'sp.export_traces.no_conversation', false],
+ ['failed trace', { ok: false, error: 'unavailable' }, 'sp.export_traces.error (unavailable)', false],
+ ['trace transport error', new Error('disconnected'), 'sp.export_traces.error (disconnected)', false],
+ ]) {
+ test(`${build}: ${name} export ${suffix}`, async () => {
+ const harness = fixture(build, { command: { value: '/export' }, action: 'traces' });
+ const result = harness.context.parseSlashCommands('/export --traces', 7);
+ assert.equal(harness.requests[0].action, 'export_traces');
+ assert.equal(harness.requests[0].payload.tabId, 7);
+ if (switched) harness.context.currentTabId = 9;
+ if (response instanceof Error) harness.reject(response);
+ else harness.release(response);
+ assert.equal(await result, '');
+ assert.equal(harness.downloads.length, Number(downloaded), 'Export must finish for the initiating tab');
+ assert.deepEqual(harness.notices, switched ? [] : [expectedNotice]);
+ });
+ }
+
+ test(`${build}: permission-skip confirmation ${suffix}`, async () => {
+ const harness = fixture(build, { command: { value: '/dangerously-skip-permissions' }, payload: 'continue task' });
+ const result = harness.context.parseSlashCommands('/dangerously-skip-permissions continue task', 7);
+ assert.equal(harness.requests[0].action, 'storage.set');
+ if (switched) harness.context.currentTabId = 9;
+ harness.release();
+ assert.equal(await result, 'continue task');
+ assert.equal(harness.context.askBeforeConsequential, false, 'The requested global setting must still update');
+ assert.deepEqual(harness.resolvedTabs, [7], 'Resolve permissions only for the originating tab');
+ assert.deepEqual(harness.notices, switched ? [] : ['sp.permissions.disabled_html']);
+ });
+ }
+}
diff --git a/test/slash-command-timeline-ui.mjs b/test/slash-command-timeline-ui.mjs
new file mode 100644
index 000000000..5a902c958
--- /dev/null
+++ b/test/slash-command-timeline-ui.mjs
@@ -0,0 +1,393 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import { test } from 'node:test';
+import { chromium, firefox } from 'playwright';
+
+const read = (build, file) => fs.readFileSync(new URL(`../src/${build}/${file}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
+
+function extract(source, name) {
+ const start = source.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));
+ assert.ok(start >= 0, `Missing function: ${name}`);
+ const end = source.indexOf('\n}', start);
+ assert.ok(end > start, `Missing end of function: ${name}`);
+ return source.slice(start, end + 2);
+}
+
+for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
+ test(`${build}: slash outputs preserve the live conversation timeline`, async t => {
+ const source = read(build, 'src/ui/sidepanel.js');
+ const metadataStart = source.indexOf('const SLASH_COMMANDS = [');
+ const metadataEnd = source.indexOf('function showSlashInvocationError(', metadataStart);
+ const visibilityStart = source.indexOf('const ASSISTANT_RENDERABLE_ELEMENT_SELECTOR =');
+ const observerStart = source.indexOf('const persistObserver =', visibilityStart);
+ const observerEnd = source.indexOf('\n});', observerStart) + '\n});'.length;
+ const observeCall = source.match(/persistObserver\.observe\(messagesEl, \{[^\n]+\}\);/)?.[0];
+ assert.ok(metadataStart >= 0 && metadataEnd > metadataStart && observeCall);
+ const functions = [
+ 'parseSlashCommands', 'addMessage', 'addPersistentSlashMessage',
+ 'showProgress', 'showScratchpad', 'showUserMemory', 'showTeacherModeStatus',
+ 'showSavedWorkflows', 'systemHtml', 'isSystemHtml', 'tSystemHtml',
+ 'getOrCreateStepsContainer', 'appendVerboseToolCall', 'appendVerboseToolResult',
+ 'placeAnsweredClarifyCardInTimeline', 'syncProgressDisplayMode', 'setCompactProgressVisible',
+ 'getStreamedAssistantText', 'hasStreamedAssistantText', 'clearStreamedAssistantText',
+ 'renderAssistantTextUpdate', 'isStoppedByUserStatus', 'clearTransientAssistantTextForToolCall',
+ 'addMessageCopyButton', 'addScratchpadCopyButton', 'getMessageCopyText', 'bindMessageCopyButton',
+ 'extractChatHistoryMessages', 'roleFromMessageElement', 'normalizeHistoryText',
+ 'scrollToBottom', 'pinChatToBottom', 'appendCompactStep', 'markLastStepDone',
+ 'findLastActiveCompactStep', 'restoreStepFriendlyLabel', 'isTerminalDoneTool', 'bindCompactStepDetailsToggle',
+ ].map(name => extract(source, name)).join('\n');
+ const browser = await engine.launch({ headless: true });
+ try {
+ async function fixture(run, mode = 'compact') {
+ const page = await browser.newPage({ viewport: { width: 420, height: 500 } });
+ await page.bringToFront();
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ try {
+ await page.setContent(`<style>${read(build, 'styles/sidepanel.css')}
+ body { display: block; margin: 0; }
+ #transcript { height: 480px; overflow: auto; }
+ .message { animation: none; }
+ .step-item { min-height: 30px; }
+ </style><div id="transcript"><main id="messages"></main></div>`);
+ await page.addScriptTag({ content: `
+ var messagesEl = document.getElementById('messages');
+ var transcript = document.getElementById('transcript');
+ var chatContainerEl = transcript, chatAutoFollow = true, chatUserChoseReadingPosition = false;
+ var scrollToBottomFrame = null;
+ var currentAssistantEl = null, currentTabId = 7, isProcessing = true;
+ var verboseMode = ${mode === 'verbose'}, compactProgressVisible = ${mode !== 'status-only'};
+ var activityProgressToggle = null, agentActivity = null;
+ var streamedAssistantTextByEl = new WeakMap(), streamedAssistantRenderFrameByEl = new WeakMap();
+ var scrollRequests = [], backgroundRequests = [], responseOverrides = {};
+ function schedulePersist() {}
+ function chatTurnIsConnected() { return !!currentAssistantEl?.isConnected; }
+ function chatTurnIsRunning() { return isProcessing; }
+ function chatTurnNeedsReadingNavigation() { return true; }
+ function scheduleChatNavigationUpdate() {}
+ function safeLabelArgs(args) { return JSON.stringify(args); }
+ function friendlyToolLabel(name) { return name; }
+ function setMessageCreatedAt() {}
+ function messageCreatedAt() { return null; }
+ function messageAttachmentMetadata() { return []; }
+ function historyRecoveryMetadata() { return {}; }
+ function historyTextFromElement(element) { return element.textContent; }
+ function bindMessageInfoToggle() {}
+ function renderCostAllowanceError() { return false; }
+ function renderSubscribeError() { return false; }
+ function parseCostAllowanceError() { return null; }
+ function formatSelectionPromptForDisplay(text) { return text; }
+ function formatMarkdown(text) { return escapeHtml(text); }
+ function escapeHtml(value) { return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
+ function truncate(text, limit) { return text.slice(0, limit); }
+ function t(key) { return key; }
+ function isSelectionGroundedForTab() { return false; }
+ function showComposerToast() {}
+ function visibleScheduledJobs(jobs) { return jobs; }
+ async function refreshScheduledJobs() { return []; }
+ async function sendToBackground(action, params = {}) {
+ backgroundRequests.push({ action, params });
+ if (action in responseOverrides) return await responseOverrides[action];
+ if (action === 'get_progress') return { ok: true, sessionId: 'live-session', counts: { total: 1, acted: 1 }, rows: [{ id: 'row-1', status: 'acted' }] };
+ if (action === 'get_scratchpad') return { exists: true, body: 'Saved scratchpad notes' };
+ if (action === 'get_user_memory') return { ok: true, records: [{ id: 'memory-1', text: 'Saved preference' }] };
+ if (action === 'get_teacher_mode') return { ok: true, session: { active: true, name: 'Example', actionCount: 2 } };
+ if (action === 'list_saved_workflows') return { ok: true, workflows: [] };
+ throw new Error('Unexpected background request: ' + action);
+ }
+ ${source.slice(metadataStart, metadataEnd)}
+ ${source.slice(visibilityStart, observerEnd)}
+ ${functions}
+ const productionScrollToBottom = scrollToBottom;
+ scrollToBottom = (options = {}) => { scrollRequests.push(options); productionScrollToBottom(options); };
+ ${observeCall}
+ function beginRun() {
+ addMessage('user', 'Process all items');
+ currentAssistantEl = addMessage('assistant', '');
+ currentAssistantEl.dataset.runRequestId = 'run-original';
+ currentAssistantEl.dataset.runId = 'execution-original';
+ window.originalAssistant = currentAssistantEl;
+ const steps = getOrCreateStepsContainer();
+ steps.dataset.testPosition = 'before-command';
+ for (let i = 0; i < 25; i++) {
+ const step = document.createElement('div');
+ step.className = 'step-item done';
+ step.textContent = 'Earlier action ' + i;
+ steps.appendChild(step);
+ }
+ syncProgressDisplayMode();
+ }
+ function addLaterStep(label) {
+ const step = document.createElement('div');
+ step.className = 'step-item done';
+ step.textContent = label;
+ getOrCreateStepsContainer().appendChild(step);
+ return step;
+ }
+ beginRun();
+ ` });
+ await run(page);
+ assert.deepEqual(errors, [], 'Production handlers must not throw browser errors');
+ } finally { await page.close(); }
+ }
+
+ for (const mode of ['compact', 'status-only', 'verbose']) {
+ await t.test(`/progress is visible after prior activity and later output follows it in ${mode} mode`, () => fixture(async page => {
+ await page.evaluate(() => parseSlashCommands('/progress'));
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ const first = await page.evaluate(() => {
+ const card = messagesEl.querySelector('.slash-command-output');
+ const before = messagesEl.querySelector('[data-test-position="before-command"]');
+ const rect = card?.getBoundingClientRect();
+ const viewport = transcript.getBoundingClientRect();
+ return {
+ present: !!card,
+ inLiveRun: card?.closest('.message.assistant') === originalAssistant,
+ afterPrior: !!card && !!(before.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING),
+ visible: !!rect && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom,
+ forced: scrollRequests.some(request => request.force === true),
+ systemCount: messagesEl.querySelectorAll(':scope > .message.system').length,
+ };
+ });
+ assert.deepEqual(first, { present: true, inLiveRun: true, afterPrior: true, visible: true, forced: true, systemCount: 0 });
+ const continuation = await page.evaluate(() => {
+ const card = currentAssistantEl.querySelector('.slash-command-output');
+ const initialContent = card.textContent;
+ const later = addLaterStep('Later action');
+ appendVerboseToolCall('read_page', { fresh: true });
+ appendVerboseToolResult('read_page', { text: 'Fresh result' });
+ renderAssistantTextUpdate(currentAssistantEl, 'Finished processing items.', { replace: true });
+ const text = currentAssistantEl.querySelector('.message-text');
+ return {
+ sameAssistant: currentAssistantEl === originalAssistant,
+ requestId: currentAssistantEl.dataset.runRequestId,
+ runId: currentAssistantEl.dataset.runId,
+ cardIntact: card.textContent === initialContent,
+ stepAfter: !!(card.compareDocumentPosition(later) & Node.DOCUMENT_POSITION_FOLLOWING),
+ toolAfter: !!(card.compareDocumentPosition(currentAssistantEl.querySelector('.tool-call')) & Node.DOCUMENT_POSITION_FOLLOWING),
+ textAfter: !!(card.compareDocumentPosition(text) & Node.DOCUMENT_POSITION_FOLLOWING),
+ text: text.textContent,
+ };
+ });
+ assert.deepEqual(continuation, {
+ sameAssistant: true, requestId: 'run-original', runId: 'execution-original', cardIntact: true,
+ stepAfter: true, toolAfter: true, textAfter: true, text: 'Finished processing items.',
+ });
+ }, mode));
+ }
+
+ await t.test('persistent command handlers and every advertised help option use the current timeline', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ const commands = ['/help', '/progress', '/scratchpad', '/memory', '/schedule --list', '/teach', '/workflow'];
+ commands.push(...SLASH_COMMANDS.filter(slashCommandIsDiscoverable).map(command => command.value + ' --help'));
+ const counts = [];
+ for (const command of commands) {
+ const count = currentAssistantEl.querySelectorAll('.slash-command-output').length;
+ await parseSlashCommands(command);
+ const cards = currentAssistantEl.querySelectorAll('.slash-command-output');
+ counts.push({ command, added: cards.length - count });
+ }
+ return { counts, rootSystems: messagesEl.querySelectorAll(':scope > .message.system').length };
+ });
+ for (const entry of result.counts) assert.equal(entry.added, 1, entry.command);
+ assert.equal(result.rootSystems, 0);
+ }));
+
+ await t.test('repeated commands and answered clarifications keep separate step segments after restoration', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ await parseSlashCommands('/progress');
+ addLaterStep('Between commands');
+ await parseSlashCommands('/scratchpad');
+ const card = document.createElement('div');
+ card.className = 'clarify-card clarify-answered';
+ card.textContent = 'Answered clarification';
+ currentAssistantEl.querySelector('.message-content').appendChild(card);
+ placeAnsweredClarifyCardInTimeline(card);
+ addLaterStep('After clarification');
+ // Session snapshots restore markup; no in-memory marker should be needed.
+ messagesEl.innerHTML = messagesEl.innerHTML;
+ currentAssistantEl = messagesEl.querySelector('.message.assistant');
+ await parseSlashCommands('/memory');
+ addLaterStep('After restoration');
+ return [...currentAssistantEl.querySelector('.message-content').children]
+ .filter(node => node.matches('.steps-container, .slash-command-output, .clarify-card'))
+ .map(node => node.classList.contains('steps-container') ? node.lastElementChild.textContent : node.className);
+ });
+ assert.deepEqual(result, [
+ 'Earlier action 24', 'slash-command-output', 'Between commands', 'slash-command-output',
+ 'clarify-card clarify-answered', 'After clarification', 'slash-command-output', 'After restoration',
+ ]);
+ }));
+
+ await t.test('scratchpad and memory copy buttons stay scoped to their own cards', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ await parseSlashCommands('/scratchpad');
+ await parseSlashCommands('/memory');
+ renderAssistantTextUpdate(currentAssistantEl, 'Assistant answer', { replace: true });
+ return {
+ cardCopies: [...currentAssistantEl.querySelectorAll('.slash-command-output .scratchpad-copy-btn')].map(getMessageCopyText),
+ assistantCopies: [...currentAssistantEl.querySelectorAll('.msg-copy-btn:not(.scratchpad-copy-btn)')].map(getMessageCopyText),
+ };
+ });
+ assert.deepEqual(result, { cardCopies: ['Saved scratchpad notes', 'memory-1 [preference] Saved preference'], assistantCopies: ['Assistant answer'] });
+ }));
+
+ await t.test('streamed text keeps its original cursor and state across a slash response', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ const cursor = currentAssistantEl.querySelector('.message-text');
+ cursor.textContent = 'Response already streaming';
+ cursor.dataset.streamedAssistantActive = 'true';
+ streamedAssistantTextByEl.set(cursor, 'Response already streaming');
+ await parseSlashCommands('/progress');
+ const intact = currentAssistantEl.querySelector('.message-text') === cursor
+ && getStreamedAssistantText(cursor) === 'Response already streaming'
+ && hasStreamedAssistantText(cursor);
+ renderAssistantTextUpdate(currentAssistantEl, 'Response completed', { replace: true });
+ return {
+ intact,
+ final: cursor.textContent,
+ card: currentAssistantEl.querySelector('.slash-command-text').textContent.includes('live-session'),
+ assistantCopies: currentAssistantEl.querySelectorAll('.msg-copy-btn:not(.scratchpad-copy-btn)').length,
+ };
+ });
+ assert.deepEqual(result, { intact: true, final: 'Response completed', card: true, assistantCopies: 1 });
+ }));
+
+ await t.test('durable history retains slash results as system records without duplicating the assistant reply', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ await parseSlashCommands('/scratchpad');
+ await parseSlashCommands('/memory');
+ renderAssistantTextUpdate(currentAssistantEl, 'Final assistant reply', { replace: true });
+ const complete = extractChatHistoryMessages().map(({ role, text }) => ({ role, text }));
+ currentAssistantEl.querySelector('.message-text').dataset.responseIncomplete = 'true';
+ const incomplete = extractChatHistoryMessages().map(({ role, text }) => ({ role, text }));
+ return { complete, incomplete };
+ });
+ const prefix = [
+ { role: 'user', text: 'Process all items' },
+ { role: 'system', text: 'sp.scratchpad.title_htmlSaved scratchpad notes' },
+ { role: 'system', text: 'sp.memory.title_htmlmemory-1 [preference] Saved preference' },
+ ];
+ assert.deepEqual(result, { complete: [...prefix, { role: 'assistant', text: 'Final assistant reply' }], incomplete: prefix });
+ }));
+
+ await t.test('a slash response is revealed above a long in-flight answer without replacing the stream cursor', () => fixture(async page => {
+ const initial = await page.evaluate(async () => {
+ const cursor = currentAssistantEl.querySelector('.message-text');
+ cursor.innerHTML = Array.from({ length: 100 }, (_, i) => '<p>Streaming answer line ' + i + '</p>').join('');
+ streamedAssistantTextByEl.set(cursor, 'Original streaming state');
+ window.streamCursor = cursor;
+ await parseSlashCommands('/progress');
+ const card = currentAssistantEl.querySelector('.slash-command-output');
+ const rect = card.getBoundingClientRect(), viewport = transcript.getBoundingClientRect();
+ return { visible: rect.bottom > viewport.top && rect.top < viewport.bottom, sameCursor: currentAssistantEl.querySelector('.message-text') === cursor };
+ });
+ assert.deepEqual(initial, { visible: true, sameCursor: true });
+ await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
+ const afterFrame = await page.evaluate(() => {
+ scrollToBottom(); // Subsequent stream events must respect the revealed card.
+ const rect = currentAssistantEl.querySelector('.slash-command-output').getBoundingClientRect();
+ const viewport = transcript.getBoundingClientRect();
+ return {
+ visible: rect.bottom > viewport.top && rect.top < viewport.bottom,
+ stream: getStreamedAssistantText(streamCursor),
+ paragraphs: streamCursor.querySelectorAll('p').length,
+ reading: chatUserChoseReadingPosition && !chatAutoFollow,
+ };
+ });
+ assert.deepEqual(afterFrame, { visible: true, stream: 'Original streaming state', paragraphs: 100, reading: true });
+ }));
+
+ await t.test('Markdown export keeps inline system output and the final assistant reply distinct', () => fixture(async page => {
+ const exported = await page.evaluate(async () => {
+ window.chrome = { runtime: { getManifest: () => ({ version: 'test' }) } };
+ window.browser = window.chrome;
+ const blobs = [];
+ URL.createObjectURL = blob => { blobs.push(blob); return 'blob:test'; };
+ HTMLAnchorElement.prototype.click = () => {};
+ await parseSlashCommands('/scratchpad');
+ await parseSlashCommands('/memory');
+ renderAssistantTextUpdate(currentAssistantEl, 'Final exported answer', { replace: true });
+ await parseSlashCommands('/export');
+ return await blobs[0].text();
+ });
+ assert.match(exported, /\*\*WebBrain:\*\* Final exported answer/);
+ assert.equal(exported.match(/Saved scratchpad notes/g)?.length, 1);
+ assert.equal(exported.match(/Saved preference/g)?.length, 1);
+ }));
+
+ await t.test('completion retries reuse their own segment and never rewrite output before a timeline boundary', () => fixture(async page => {
+ const results = await page.evaluate(async () => {
+ const outcomes = [];
+ for (const kind of ['compact', 'verbose']) {
+ for (const boundary of ['none', 'slash', 'clarify']) {
+ messagesEl.replaceChildren();
+ beginRun();
+ const append = kind === 'compact' ? appendCompactStep : appendVerboseToolCall;
+ const finish = kind === 'compact' ? markLastStepDone : appendVerboseToolResult;
+ const selector = kind === 'compact' ? '.step-item[data-tool="done"]' : '.tool-call[data-tool-name="done"]';
+ append('done', { summary: 'Before boundary' });
+ finish('done', { blockedDone: true });
+ let marker = null;
+ if (boundary === 'slash') {
+ await parseSlashCommands('/progress');
+ marker = currentAssistantEl.querySelector('.slash-command-output');
+ } else if (boundary === 'clarify') {
+ marker = document.createElement('div');
+ marker.className = 'clarify-card clarify-answered';
+ currentAssistantEl.querySelector('.message-content').appendChild(marker);
+ placeAnsweredClarifyCardInTimeline(marker);
+ }
+ append('done', { summary: 'After boundary' });
+ const calls = [...currentAssistantEl.querySelectorAll(selector)];
+ outcomes.push({
+ kind, boundary, count: calls.length,
+ latestAfterBoundary: !marker || !!(marker.compareDocumentPosition(calls.at(-1)) & Node.DOCUMENT_POSITION_FOLLOWING),
+ previousStillRejected: !marker || calls[0].dataset.rejectedCompletion === 'true',
+ });
+ }
+ }
+ return outcomes;
+ });
+ for (const result of results) {
+ assert.equal(result.count, result.boundary === 'none' ? 1 : 2, `${result.kind}/${result.boundary}: completion count`);
+ assert.equal(result.latestAfterBoundary, true, `${result.kind}/${result.boundary}: continuation order`);
+ assert.equal(result.previousStillRejected, true, `${result.kind}/${result.boundary}: history preserved`);
+ }
+ }));
+
+ await t.test('idle commands append after completed replies, even with a retained assistant reference', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ isProcessing = false;
+ renderAssistantTextUpdate(currentAssistantEl, 'Completed response', { replace: true });
+ await parseSlashCommands('/progress');
+ return {
+ lastRole: messagesEl.lastElementChild.className,
+ nested: currentAssistantEl.querySelectorAll('.slash-command-output').length,
+ finalText: currentAssistantEl.querySelector('.message-text').textContent,
+ };
+ });
+ assert.deepEqual(result, { lastRole: 'message system', nested: 0, finalText: 'Completed response' });
+ }));
+
+ await t.test('asynchronous progress respects the visible tab and handles empty/error replies at the live edge', () => fixture(async page => {
+ const result = await page.evaluate(async () => {
+ let resolveProgress;
+ responseOverrides.get_progress = new Promise(resolve => { resolveProgress = resolve; });
+ const pending = showProgress(7);
+ currentTabId = 8;
+ resolveProgress({ ok: true, rows: [{ id: 'wrong-tab' }] });
+ await pending;
+ const staleCount = messagesEl.querySelectorAll('.slash-command-output, .message.system').length;
+ currentTabId = 7;
+ responseOverrides.get_progress = { ok: true, rows: [] };
+ await showProgress(7);
+ responseOverrides.get_progress = { ok: false, error: 'unavailable' };
+ await showProgress(7);
+ return { staleCount, contents: [...currentAssistantEl.querySelectorAll('.slash-command-text')].map(node => node.textContent) };
+ });
+ assert.deepEqual(result, { staleCount: 0, contents: ['sp.progress.empty', 'sp.progress.error'] });
+ }));
+ } finally { await browser.close(); }
+ });
+}
diff --git a/test/trace-full-export.mjs b/test/trace-full-export.mjs
index 7daf8e5d5..487f452a3 100644
--- a/test/trace-full-export.mjs
+++ b/test/trace-full-export.mjs
@@ -113,7 +113,7 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {
const end = source.indexOf(" if (command.value === '/export' && action === 'conversation') {", start);
assert.ok(start >= 0 && end > start);
const harness = `export async function run(response, full = true) {
- const tabId = 1, command = { value: '/export' }, action = 'traces', optionValues = new Set(full ? ['--full'] : []);
+ const tabId = 1, currentTabId = tabId, command = { value: '/export' }, action = 'traces', optionValues = new Set(full ? ['--full'] : []);
const sendToBackground = async () => response === undefined ? globalThis.backgroundExport() : response;
const t = key => key, addPersistentSlashMessage = message => globalThis.exportMessages.push(message);
${source.slice(start, end)}