Skip to content

[rb] add BiDi alert handlers and apply unhandledPromptBehavior on the client (ADR 18283) - #18384

Open
titusfortner wants to merge 2 commits into
SeleniumHQ:trunkfrom
titusfortner:rb-bidi-alert-handlers
Open

titusfortner wants to merge 2 commits into
SeleniumHQ:trunkfrom
titusfortner:rb-bidi-alert-handlers

Conversation

@titusfortner

@titusfortner titusfortner commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

🔗 Related Issues

Implements ADR #18283 (as written, the option that keeps unhandledPromptBehavior)
Builds on #18388 (session context tree) and #18389 (listener error store)

  • Note: The first commit is "Option 2" from that ADR (it raises ArgumentError when unhandledPromptBehavior is set), and the second commit adds what is necessary for option 3

💥 What does this PR do?

Implements the ADR for Ruby BiDi sessions:

  • driver.alerts.add_handler { |alert| ... } and driver.alerts.remove_handler(handle); the handler receives a WebDriver::Alert
  • Alert#type and Alert#default_value, which raise without BiDi

🔧 Implementation Notes

  • The remote end is always started with unhandledPromptBehavior: {default: 'ignore'} so prompts stay open for the binding to handle.
  • BiDi commands are checked for an open alert in WebSocketConnection#send_cmd, because Chrome does not reply to most of them while one is open; the older BiDi::* classes are covered too.
  • BiDiBridge implements the Alert API from the userPromptOpened event, because BiDi has no command that reads an open prompt.
  • Prompts are kept by the window the context tree traces them to, so an alert opened in a frame is found from its window and blocks commands to any context in it.
  • Chromedriver refuses the next classic command with invalid argument while a beforeunload prompt is being accepted, so that command is sent again once the prompt closes.
  • target_locator_spec.rb now runs in BiDi sessions, and the Chromium pending_if guards on the handle_user_prompt specs are removed.

🤖 AI assistance

  • AI assisted (complete below)
    • Tool(s): Claude Code (Claude Fable 5.2, Claude Opus 5.5)
    • What was generated: implementation, specs, signatures, and this description
    • I reviewed all AI output and can explain the change

🔄 Types of changes

  • New feature (non-breaking change which adds functionality and tests!)
  • Breaking change (in a BiDi session an unhandled alert now raises as it does in classic, instead of being dismissed silently by the remote end)

@selenium-ci

Copy link
Copy Markdown
Member

/agentic_describe

@selenium-ci selenium-ci added C-rb Ruby Bindings B-build Includes scripting, bazel and CI integrations B-devtools Includes everything BiDi or Chrome DevTools related labels Nov 24, 2026
@qodo-code-review

qodo-code-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Add Ruby BiDi alert handlers and client-side prompt behavior

✨ Enhancement 🐞 Bug fix 🧪 Tests 🕐 40+ Minutes

Grey Divider

AI Description

• Add BiDi alert handlers and expose prompt type and default value through the Alert API.
• Keep prompts open remotely, then apply unhandledPromptBehavior when commands encounter them.
• Cover prompt handling, interrupted commands, and classic Alert API compatibility with expanded
 specs.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: BiDi prompt management.
  • The public Driver#alerts API, Alert objects, prompt event records, handler selection, prompt closure and unhandledPromptBehavior all implement one bounded browser-prompt interaction behavior.
  • The WebSocket and bridge changes are supporting runtime coordination for that same behavior, not independent user capabilities.
  • This is a distinct end-to-end outcome within the same bounded integration: commands sent during a prompt are matched to the prompt's window, waiting command responses can be released, and navigation methods translate prompt interruption into their existing return semantics.
  • These are command-continuation semantics rather than another storage or deployment scope.
Behavioral complexity 🔴 High 🧩 Multiple interactions

  • The changed logic materially adds prompt lifecycle state and cross-thread coordination.
  • Before, BiDi commands used the existing WebSocket request/response flow and classic alert commands acted on the current window.
  • After, a prompt-open event records one prompt per top-level window, invokes the newest handler on a listener thread, intercepts later commands, and can release already-waiting commands by matching both payload identity and prompt window.
  • New correctness conditions are: prompt records must be inserted before handler commands are sent; close events and explicit Alert actions must not delete a newer prompt in the same window; commands for other windows must remain unaffected; handleUserPrompt must bypass recursive interception; and released waiters must receive the interruption exception exactly once while normal responses still complete.
  • The Before/After/New condition analysis supports interacting_branches_or_states and coordinated_invariants.
  • It also introduces genuine concurrency/order dependencies between the event listener, handler thread, command-sending threads, WebSocket pending-response mutex, and remote prompt lifecycle, supporting concurrency_or_ordering.
  • The use of Mutex and ConditionVariable alone is not treated as complexity; the new cross-thread prompt/open/close/release protocol is the changed condition.
Potential damage 🟡 Medium 🩹 Temporary loss

  • If the changed alert bookkeeping or action dispatch regresses, users may temporarily lose the ability to inspect, accept, dismiss, or enter text into BiDi prompts, or commands may be rejected while the prompt remains open.
  • The supported recovery is to close the prompt through the Alert API or handler, then continue the session; reverting the client code restores the previous implementation for future sessions but does not undo an already accepted, dismissed, or text-submitted browser prompt.
  • Recoverable by closing or otherwise resolving the active browser prompt and, if necessary, restarting the affected session.
  • No persistent application-state write or external service compensation path is introduced by this PR.
Assessed commit 23954e4
Diagram

graph TD
  Driver["Driver API"] --> Bridge["BiDi bridge"] --> Alerts["Alert manager"] --> Socket["WebSocket"] --> Browser["Browser"]
  Browser --> Socket --> Alerts --> Alert["Alert object"] --> Bridge
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Reject unhandledPromptBehavior in BiDi sessions
  • ➕ Avoids client-side policy enforcement and its command-interception complexity.
  • ➖ Breaks existing capability usage and does not preserve classic-style handling of unhandled prompts.

Recommendation: Keep the PR's client-side approach: leaving prompts open is necessary for handlers and the Alert API, while local policy preserves unhandledPromptBehavior. The simpler rejection approach sacrifices compatibility; review the event-to-command synchronization closely.

Files changed (24) +1090 / -37

Enhancement (15) +558 / -23
error.rbIdentify BiDi commands interrupted by alerts +4/-0

Identify BiDi commands interrupted by alerts

• Adds a local UnexpectedAlertOpenError subclass for commands released when an open prompt prevents a reply.

rb/lib/selenium/webdriver/bidi/error.rb

common.rbLoad the alert handler API +1/-0

Load the alert handler API

• Requires the new Alerts class with the common WebDriver components.

rb/lib/selenium/webdriver/common.rb

alert.rbBind Alert instances to BiDi prompts +26/-6

Bind Alert instances to BiDi prompts

• Allows handler-provided Alert objects to act on their originating prompt and adds BiDi-only type and default_value accessors.

rb/lib/selenium/webdriver/common/alert.rb

alerts.rbManage BiDi prompts and alert handlers +267/-0

Manage BiDi prompts and alert handlers

• Introduces handler registration, event-backed prompt storage, and client-side unhandledPromptBehavior. It also handles blocked commands, handler errors, and beforeunload prompts.

rb/lib/selenium/webdriver/common/alerts.rb

driver.rbExpose alert handlers on Driver +9/-0

Expose alert handlers on Driver

• Adds driver.alerts as the entry point for the bridge's alert manager.

rb/lib/selenium/webdriver/common/driver.rb

websocket_connection.rbIntercept and release pending WebSocket commands +43/-6

Intercept and release pending WebSocket commands

• Adds pre-send callbacks and tracks pending payloads so alert handling can refuse commands or wake commands that will not receive a reply.

rb/lib/selenium/webdriver/common/websocket_connection.rb

bidi_bridge.rbImplement BiDi Alert operations in the bridge +54/-1

Implement BiDi Alert operations in the bridge

• Installs the alert manager at session creation, routes Alert operations through BiDi, and reports the locally applied prompt policy. It retries classic commands after eligible prompt-related refusals.

rb/lib/selenium/webdriver/remote/bidi_bridge.rb

bridge.rbAlign classic bridge alert methods with prompt-aware calls +8/-4

Align classic bridge alert methods with prompt-aware calls

• Accepts optional prompt arguments without changing classic command behavior and raises a BiDi-required error for unsupported alert APIs.

rb/lib/selenium/webdriver/remote/bridge.rb

error.rbsType the alert-interruption error +5/-0

Type the alert-interruption error

• Declares InterruptedByAlertError as an UnexpectedAlertOpenError subclass.

rb/sig/lib/selenium/webdriver/bidi/error.rbs

alert.rbsType prompt-bound Alert methods +7/-1

Type prompt-bound Alert methods

• Adds the optional prompt reference and signatures for type and default_value.

rb/sig/lib/selenium/webdriver/common/alert.rbs

alerts.rbsDeclare the Alerts API and prompt state +91/-0

Declare the Alerts API and prompt state

• Types handler registration, prompt data, subscriptions, and internal prompt-management methods.

rb/sig/lib/selenium/webdriver/common/alerts.rbs

driver.rbsType Driver#alerts +2/-0

Type Driver#alerts

• Declares the Driver accessor for the new Alerts API.

rb/sig/lib/selenium/webdriver/common/driver.rbs

websocket_connection.rbsType WebSocket command interception +12/-0

Type WebSocket command interception

• Adds signatures for pre-send callbacks, pending payload inspection, and selective release.

rb/sig/lib/selenium/webdriver/common/websocket_connection.rbs

bidi_bridge.rbsType BiDi bridge alert support +19/-1

Type BiDi bridge alert support

• Declares prompt-aware Alert methods, the Alerts accessor, and bridge command handling.

rb/sig/lib/selenium/webdriver/remote/bidi_bridge.rbs

bridge.rbsType classic bridge alert compatibility +10/-4

Type classic bridge alert compatibility

• Updates Alert method signatures for optional prompts and declares BiDi-only accessors.

rb/sig/lib/selenium/webdriver/remote/bridge.rbs

Bug fix (1) +8 / -0
bidi_commands.rbReturn from navigation interrupted by a prompt +8/-0

Return from navigation interrupted by a prompt

• Treats an alert-interrupted BiDi navigation, history traversal, or refresh as a completed navigation call rather than waiting for its reply.

rb/lib/selenium/webdriver/remote/bidi_commands.rb

Tests (8) +524 / -14
BUILD.bazelSchedule BiDi alert and locator specs +2/-0

Schedule BiDi alert and locator specs

• Adds the new alert suite to BiDi-only runs and runs target locator specs against both implementations.

rb/spec/integration/selenium/webdriver/BUILD.bazel

alerts_spec.rbExercise BiDi alert handling end to end +418/-0

Exercise BiDi alert handling end to end

• Tests handlers, Alert operations, prompt policies, blocked commands, multiple windows, and beforeunload behavior. Frame access through the unbound Alert API remains explicitly pending.

rb/spec/integration/selenium/webdriver/alerts_spec.rb

browsing_context_spec.rbTest prompt handling under the default capability +0/-3

Test prompt handling under the default capability

• Removes the explicit ignore capability because BiDi prompts now remain open for handling by default.

rb/spec/integration/selenium/webdriver/bidi/browsing_context_spec.rb

browsing_context_spec.rbUse default capability in protocol prompt specs +0/-3

Use default capability in protocol prompt specs

• Removes the prompt-specific ignore override from protocol browsing-context tests.

rb/spec/integration/selenium/webdriver/bidi/protocol/browsing_context_spec.rb

navigation_spec.rbWait for BiDi history navigation to load +4/-2

Wait for BiDi history navigation to load

• Waits for expected titles after back and forward traversal before asserting navigation results.

rb/spec/integration/selenium/webdriver/navigation_spec.rb

target_locator_spec.rbRun target locator specs with BiDi +12/-1

Run target locator specs with BiDi

• Removes the suite-wide BiDi exclusion and verifies that type and default_value raise without BiDi.

rb/spec/integration/selenium/webdriver/target_locator_spec.rb

websocket_connection_spec.rbTest WebSocket interception and waiter release +72/-0

Test WebSocket interception and waiter release

• Covers pre-send refusal, selective pending-command release, payload tracking, and cleanup.

rb/spec/unit/selenium/webdriver/common/websocket_connection_spec.rb

bidi_bridge_spec.rbVerify BiDi session prompt setup +16/-5

Verify BiDi session prompt setup

• Checks that session creation requests remote prompt ignore behavior and adapts bridge mocks to alert-event subscription.

rb/spec/unit/selenium/webdriver/remote/bidi_bridge_spec.rb

@qodo-code-review

qodo-code-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (11) 📘 Rule violations (2) 📜 Skill insights (0)

Grey Divider


Action required

1. Interrupted commands can still execute 🐞 Bug ≡ Correctness ⭐ New
Description
WebSocketConnection#register adds a command to the waiting set before before_send runs, so
Alerts#release_commands can mark a command interrupted before it has been written to the socket.
If that callback later finishes, send_cmd still writes the frame, then raises the stored
interruption to its caller despite sending a command that may have side effects.
Code

rb/lib/selenium/webdriver/common/websocket_connection.rb[R182-185]

+          next_id.tap do |new_id|
+            pending_responses[new_id] = ConditionVariable.new
+            pending_payloads[new_id] = payload
+          end
Evidence
Registration puts the payload in pending_payloads before callbacks and the socket write. Alert
release selects from that set, but releasing records an exception rather than cancelling the send,
which continues to write_frame after callbacks return.

rb/lib/selenium/webdriver/common/websocket_connection.rb[118-133]
rb/lib/selenium/webdriver/common/websocket_connection.rb[135-153]
rb/lib/selenium/webdriver/common/websocket_connection.rb[178-187]
rb/lib/selenium/webdriver/common/alerts.rb[162-172]
rb/lib/selenium/webdriver/common/alerts.rb[216-223]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The waiting set includes commands still in `before_send`, allowing alert interruption to be reported for a frame that is written afterward.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/websocket_connection.rb[118-133]
- rb/lib/selenium/webdriver/common/websocket_connection.rb[139-146]
- rb/lib/selenium/webdriver/common/websocket_connection.rb[178-187]
- rb/lib/selenium/webdriver/common/alerts.rb[216-223]
## Recommended Fix
Track whether each registered command has actually been sent and exclude unsent commands from alert release. Coordinate the sent-state transition with release so a command cannot be marked interrupted just before its frame is written; test a command held in `before_send` while an alert opens.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


2. Frame alerts cannot be handled normally ✓ Resolved

Resolving commit: 23954e4

Resolution reason
The prompt is keyed by its top-level window (Prompt.new receives
context_tree.top_level(event.context)), and all lookups (current, before_bidi_command,
release_commands, window_of) use the same top-level mapping, so frame alerts are found by
switch_to.alert and by unhandled-prompt handling. An integration spec 'acts on an alert opened in a
frame' was also added.
Description
Alerts#current looks up prompts by the top-level current_window, although listen_prompt_opened
stores a frame prompt under its frame context. When a page opens an alert inside an iframe,
switch_to.alert cannot find it, and classic-command handling cannot apply the configured
unhandled-prompt behavior.

3. Some sessions receive invalid capabilities 🐞 Bug ≡ Correctness
Description
manage_prompts_locally selects alwaysMatch or the outer hash, never an existing firstMatch
candidate, before writing unhandledPromptBehavior. When a caller uses Capabilities.first_match,
it adds the setting outside both matching sections and leaves the candidate's requested behavior
unchanged, so session creation can be rejected or use the remote behavior instead.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R156-157]

+        capabilities = capabilities['alwaysMatch'] || capabilities
+        behavior = capabilities['unhandledPromptBehavior']
Evidence
Ruby exposes a firstMatch-only serialized payload, and Bridge passes W3C-shaped payloads through.
The new code writes to the enclosing hash when alwaysMatch is absent.

rb/spec/unit/selenium/webdriver/remote/capabilities_spec.rb[114-123]
rb/lib/selenium/webdriver/common/alerts.rb[155-165]
rb/lib/selenium/webdriver/remote/bridge.rb[690-693]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The supported firstMatch capability shape is modified at the outer level rather than in its selectable candidates.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[155-165]
## Recommended Fix
Normalize W3C capability payloads before extracting the requested behavior and place the remote ignore setting in valid matching sections, accounting for candidate-specific values and conflicts. Test session creation with firstMatch.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗



Remediation recommended

4. Closed alerts can remain open to the client 🐞 Bug ≡ Correctness ⭐ New
Description
listen_prompt_opened and listen_prompt_closed update the same prompt record from separately
dispatched listener threads without preserving event order. If a prompt closes quickly and the
closed callback runs first, the opened callback stores a stale prompt that later alert lookups and
commands treat as open.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R178-179]

+          window = @bridge.context_tree.top_level(event.context)
+          @mutex.synchronize { @prompts.delete(window) }
Evidence
Each dispatch creates a thread, while the closed callback deletes the current window entry and the
opened callback inserts it independently. Both alert lookup and command interception subsequently
consult that entry.

rb/lib/selenium/webdriver/bidi/dispatcher/listener.rb[24-29]
rb/lib/selenium/webdriver/common/alerts.rb[162-180]
rb/lib/selenium/webdriver/common/alerts.rb[103-105]
rb/lib/selenium/webdriver/common/alerts.rb[230-246]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Opened and closed callbacks run on independent threads, so a closed event can delete nothing before its opened event stores a stale prompt.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[162-180]
## Recommended Fix
Serialize prompt state updates in event-delivery order, or retain enough event identity and ordering information to prevent an older opened callback from restoring a closed prompt. Add a test that delays opened-event processing until after the closed callback.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


5. Retrying a session changes prompt behavior 🐞 Bug ≡ Correctness ⭐ New
Description
manage_prompts_locally overwrites unhandledPromptBehavior in the capabilities hash supplied by
the caller before session creation. If that attempt fails and the caller reuses the hash, the next
attempt reads the injected ignore value instead of the requested behavior and applies it locally.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R158-159]

+        capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'}
+        behavior || 'dismiss and notify'
Evidence
The bridge passes the capabilities object to Alerts.new before creating the session;
manage_prompts_locally writes into that object or its nested alwaysMatch hash. The next call
therefore reads the replacement map's default value.

rb/lib/selenium/webdriver/remote/bidi_bridge.rb[31-35]
rb/lib/selenium/webdriver/common/alerts.rb[149-159]
rb/lib/selenium/webdriver/remote/bridge.rb[691-693]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Session creation mutates the caller's capabilities, causing a retry with the same object to use a different local prompt behavior.
## Fix Focus Areas
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[31-35]
- rb/lib/selenium/webdriver/common/alerts.rb[149-159]
## Recommended Fix
Read the requested behavior from the original capabilities, but replace the remote-end value only in a copied capabilities structure, including a copy of `alwaysMatch` when present. Test two session attempts with the same capabilities object.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


6. Alert notifications can disappear on retry 🐞 Bug ≡ Correctness ⭐ New
Description
manage_exception returns without raising an UnexpectedAlertOpenError when refusing_prompt
cannot find a recorded prompt, even if the selected behavior ends in notify. If the prompt has
already closed or its event is not recorded within the lookup timeout, BiDiBridge#execute retries
the command and can return success instead of exposing the original error.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R126-128]

+          prompt = refusing_prompt
+          # chromedriver can refuse a command for an alert BiDi has just closed
+          return unless prompt
Evidence
A missing prompt returns before the notify check; prompt lookup explicitly returns nil after
timeout. The bridge retries every error for which manage_exception returns normally.

rb/lib/selenium/webdriver/common/alerts.rb[123-131]
rb/lib/selenium/webdriver/common/alerts.rb[192-197]
rb/lib/selenium/webdriver/remote/bidi_bridge.rb[106-113]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A remote alert error is discarded when no matching prompt remains recorded, bypassing an explicit notify behavior.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[123-131]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[108-113]
## Recommended Fix
When the requested behavior includes `notify`, preserve and raise the remote alert error even if prompt lookup returns nil. Retry only the cases whose behavior permits retry, and test an alert error arriving after the prompt record is gone.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


View medium (7)
7. Next BiDi command can dismiss a beforeunload prompt 🐞 Bug ≡ Correctness
Description
before_bidi_command handles every recorded prompt the same way, so a beforeunload prompt that the
default handler is still accepting on its callback thread gets dismissed when 'dismiss and notify'
is in effect, and an UnexpectedAlertOpenError is raised. The classic path waits out this window
(wait_for_beforeunload_to_close in manage_exception), but a BiDi command sent right after a
click that opened beforeunload (e.g. driver.get or navigate.refresh) races the default handler:
the page stays, the command fails, and the handler's late accept fails with no such alert, which is
stored and raised again on a later command.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R245-252]

+        prompt = prompt_in(context)
+        return unless prompt
+
+        error = Error::UnexpectedAlertOpenError.new("unexpected alert open: {Alert text : #{prompt.text}}")
+        raise error if behavior == 'ignore'
+
+        behavior.start_with?('accept') ? @bridge.accept_alert(prompt) : @bridge.dismiss_alert(prompt)
+        raise error if behavior.end_with?('notify')
Evidence
The default handler accepts beforeunload on the event thread, since classic never leaves one open.
manage_exception copes with the chromedriver beforeunload window on classic commands by waiting
until the prompt closes. before_bidi_command has no such check for beforeunload, so it applies the
user's dismiss/notify behavior to a prompt that is meant to be auto-accepted, and both threads then
call handleUserPrompt on the same prompt.

rb/lib/selenium/webdriver/common/alerts.rb[121-143]
rb/lib/selenium/webdriver/common/alerts.rb[168-181]
rb/lib/selenium/webdriver/common/alerts.rb[215-218]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
before_bidi_command applies unhandledPromptBehavior to a beforeunload prompt that the default handler is still accepting. The prompt gets dismissed, the command raises, and the handler's accept fails.

## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[238-253]
- rb/lib/selenium/webdriver/common/alerts.rb[189-196]

## Recommended Fix
In before_bidi_command, when no user handler is registered and `prompt.type == 'beforeunload'`, call `wait_for_beforeunload_to_close` (or wait until this specific prompt is gone) and return without dismissing or raising. Only apply the behavior if the prompt is still open after the wait.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


8. Realm commands bypass open-alert handling 🐞 Bug ≡ Correctness
Description
Alerts#context_of extracts only a context field, so before_bidi_command returns before applying
prompt behavior to commands targeted at a script realm. When a caller sends a valid realm-targeted
command while its context has an open alert, the configured accept, dismiss, or notify behavior is
not applied.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R241-243]

+        context = context_of(payload)
+        return unless context
+
Evidence
The protocol's realm target contains a realm identifier rather than a context. The new extractor
checks only context keys, causing the early return ahead of the behavior branch.

rb/lib/selenium/webdriver/bidi/protocol/script.rb[820-839]
rb/lib/selenium/webdriver/common/alerts.rb[237-264]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Valid realm-targeted script commands have no context field and skip the new open-alert check.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[237-253]
- rb/lib/selenium/webdriver/common/alerts.rb[255-264]
## Recommended Fix
Resolve the target realm to its browsing context before the prompt lookup, or handle realm-targeted commands through an equivalent prompt-aware path. Test a realm-targeted script command while its context has an open prompt.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


9. A newer alert can disappear from lookup 🐞 Bug ☼ Reliability
Description
Alerts#closed and the closed-event listener delete a prompt solely by context, without checking
which prompt is stored there. If another prompt opens in that context before either cleanup runs,
the cleanup removes the newer prompt and subsequent Alert API lookups report no alert.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R148-149]

+      def closed(prompt)
+        @mutex.synchronize { @prompts.delete(prompt.context) }
Evidence
Each opened event replaces the context entry, while both cleanup paths delete that entry
unconditionally. BiDi listener invocations run on independent threads, permitting delayed event
callbacks.

rb/lib/selenium/webdriver/common/alerts.rb[168-172]
rb/lib/selenium/webdriver/common/alerts.rb[145-150]
rb/lib/selenium/webdriver/common/alerts.rb[183-186]
rb/lib/selenium/webdriver/remote/bidi_bridge.rb[95-99]
rb/lib/selenium/webdriver/bidi/dispatcher/listener.rb[23-31]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Cleanup for one prompt can delete a newer prompt stored under the same browsing context.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[145-150]
- rb/lib/selenium/webdriver/common/alerts.rb[183-186]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[95-99]
## Recommended Fix
Delete an explicitly closed prompt only if the stored object is that prompt. Serialize or correlate opened and closed event processing per context so a delayed close event cannot remove a later prompt; test consecutive prompts in one context.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


10. Interrupted commands can appear successful 🐞 Bug ☼ Reliability
Description
WebSocketConnection#release stores an interruption exception and signals its waiter, but
process_frame can subsequently overwrite that exception before the waiter resumes. If a response
arrives in that interval, await_response consumes the response instead of raising the alert
interruption.
Code

rb/lib/selenium/webdriver/common/websocket_connection.rb[R128-129]

+            messages[id] = error
+            pending_responses[id].signal
Evidence
Release writes the exception under the mutex and signals, but the response path unconditionally
assigns the same message slot while the pending waiter remains registered. The waiter raises only
when the value it finally reads is an exception.

rb/lib/selenium/webdriver/common/websocket_connection.rb[122-130]
rb/lib/selenium/webdriver/common/websocket_connection.rb[188-203]
rb/lib/selenium/webdriver/common/websocket_connection.rb[287-294]
rb/lib/selenium/webdriver/common/alerts.rb[220-228]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A late socket response can replace the exception used to interrupt a command waiting on an alert.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/websocket_connection.rb[122-131]
- rb/lib/selenium/webdriver/common/websocket_connection.rb[287-295]
## Recommended Fix
Have response processing retain an existing released exception under the same mutex rather than overwrite it. Add a test that delivers a response after release but before the waiting thread consumes the result.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


11. A failed alert handler makes quit skip ending the session 🐞 Bug ☼ Reliability
Description
BiDiBridge#execute checks for stored alert-handler errors before sending every command, including
the :delete_session command issued by Bridge#quit. If a handler error is pending when
driver.quit runs, it escapes Bridge#quit's transport-error rescue before deletion is sent; the
local service stops, but the remote or Grid session remains until it times out.
Code

rb/lib/selenium/webdriver/remote/bidi_bridge.rb[R101-105]

+        def execute(*)
+          # TODO: check a session-wide store of errors raised on listener threads, not only the alert handlers'
+          @alerts.check_errors
+          begin
+            super
Evidence
The listener stores handler exceptions for @alerts.check_errors to raise, and Bridge#quit sends
execute :delete_session while rescuing only IOError, EOFError, and WebSocket::Error. The
BiDiBridge#execute override raises the stored error before calling super, so the DELETE request
is never made; Driver#quit still stops the local service in its ensure block.

rb/lib/selenium/webdriver/remote/bridge.rb[207-222]
rb/lib/selenium/webdriver/common/alerts.rb[98-105]
rb/lib/selenium/webdriver/common/driver.rb[191-196]
rb/lib/selenium/webdriver/common/alerts.rb[168-180]
rb/lib/selenium/webdriver/common/alerts.rb[102-105]
rb/lib/selenium/webdriver/remote/bidi_bridge.rb[101-109]
rb/lib/selenium/webdriver/remote/bridge.rb[207-219]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A pending alert-handler exception can prevent `driver.quit` from sending `:delete_session`, leaving the remote or Grid session running.

## Fix Focus Areas
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[101-110]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[49-55]

## Recommended Fix
Exempt `:delete_session` from the pre-command `@alerts.check_errors` call and from `manage_exception`, so session deletion proceeds even when a handler error is pending. Alternatively, handle the pending error in `BiDiBridge#quit` before calling `super`, or defer surfacing it until after session cleanup. Test quitting immediately after an alert handler raises.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


12. Removes the classic alert= setter without deprecation 📘 Rule violation ⚙ Maintainability
Description
Remote::Bridge#alert= is deleted and replaced by send_alert_text(keys, _prompt = nil), and its
RBS signature is removed as well. Code that calls bridge.alert = 'text' on a released client now
raises NoMethodError on upgrade, and nothing marks the old setter as deprecated or points to the
replacement. The change removes a public surface, so it should first be deprecated with a message
that names send_alert_text.
Code

rb/lib/selenium/webdriver/remote/bridge.rb[143]

-        def alert=(keys)
+        def send_alert_text(keys, _prompt = nil)
Evidence
The removed def alert=(keys) is replaced by def send_alert_text(keys, _prompt = nil).
Common::Alert#send_keys was switched to send_alert_text, so the old setter has no remaining
caller in this PR, but external code that used it breaks silently.

AGENTS.md: Preserve Public API and ABI Compatibility and Deprecate Before Removal
rb/lib/selenium/webdriver/remote/bridge.rb[143-145]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR removes `Selenium::WebDriver::Remote::Bridge#alert=` and replaces it with `send_alert_text`, without deprecation. Released code that calls `bridge.alert = keys` will break on upgrade.

## Fix Focus Areas
- rb/lib/selenium/webdriver/remote/bridge.rb[135-150]
- rb/sig/lib/selenium/webdriver/remote/bridge.rbs[101-118]

## Recommended Fix
Restore `alert=` as a method that forwards to `send_alert_text(keys)` and emits a deprecation through `WebDriver.logger.deprecate` (the same helper used for the `unhandledPromptBehavior` map form in `alerts.rb`), naming `send_alert_text` as the replacement. Keep the RBS signature for `alert=` until removal, and add a spec that asserts the deprecation is emitted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


13. Unhandled BiDi alerts now raise instead of dismissing silently 📘 Rule violation ⚙ Maintainability
Description
Alerts#manage_prompts_locally forces unhandledPromptBehavior to {'default' => 'ignore'} for
every BiDi session, and the client then applies dismiss and notify itself, so an alert that used
to be dismissed silently by the remote end now raises UnexpectedAlertOpenError on the next
command. Existing BiDi users whose scripts never handled alerts will see new exceptions after
upgrading, and the PR does not deprecate the old behavior before making the change. The PR labels
this a breaking change, but the compliance rule requires a deprecation step before behavior that
released users depend on is changed.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R164-165]

+        capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'}
+        behavior || 'dismiss and notify'
Evidence
manage_prompts_locally overwrites the capability to ignore and returns 'dismiss and notify'
when none is given, and create_session stores that value as the reported capability. Previously
the remote end's own default settled the prompt, so BiDi sessions with no explicit setting now get a
different outcome for the same page.

AGENTS.md: Preserve Public API and ABI Compatibility and Deprecate Before Removal
rb/lib/selenium/webdriver/common/alerts.rb[155-166]
rb/lib/selenium/webdriver/remote/bidi_bridge.rb[31-36]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR changes the effective default for BiDi sessions from silently dismissing an unhandled alert to raising `UnexpectedAlertOpenError`. Released users who rely on the old behavior break on upgrade, and no deprecation precedes the change.

## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[155-166]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[31-36]

## Recommended Fix
Follow the Selenium deprecation policy: when no `unhandledPromptBehavior` is given in a BiDi session, log a deprecation through `WebDriver.logger.deprecate` that says the default will change to `dismiss and notify` and names the explicit capability to keep the old behavior. Alternatively, gate the new default behind an opt-in until the next major release. Add a unit or integration spec that asserts the deprecation is emitted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗



Informational

14. Per-type prompt behaviors are silently dropped 🐞 Bug ≡ Correctness
Description
When unhandledPromptBehavior is a map, manage_prompts_locally keeps only the default key and
throws away the per-type entries such as alert, confirm, prompt and beforeUnload. A user who
configured e.g. {alert: 'accept'} with no default now gets 'dismiss and notify' for alerts in BiDi
sessions, and the only notice is a deprecation warning that doesn't say those values were ignored.
Code

rb/lib/selenium/webdriver/common/alerts.rb[R158-165]

+        if behavior.is_a?(Hash)
+          WebDriver.logger.deprecate('a map for unhandledPromptBehavior',
+                                     'its classic String value or use Alerts#add_handler',
+                                     id: :unhandled_prompt_behavior)
+          behavior = behavior.transform_keys(&:to_s)['default']
+        end
+        capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'}
+        behavior || 'dismiss and notify'
Evidence
Options#process_unhandled_prompt_behavior_value keeps maps as maps, with camelized keys like 'alert'
and 'beforeUnload'. The new code reads only ['default'] and falls back to 'dismiss and notify', so
every other key is lost.

rb/lib/selenium/webdriver/common/options.rb[162-176]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
manage_prompts_locally drops every key of an unhandledPromptBehavior map except 'default', so per-type settings silently change behavior.

## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[155-166]
- rb/lib/selenium/webdriver/common/alerts.rb[210-213]

## Recommended Fix
Store the map and work out the behavior per prompt type (`behavior(prompt)`, falling back to 'default'). If you'd rather not support that, log a clear warning that lists the ignored per-type keys.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗


Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #18283
✅ REVIEW.md
Review mode: Auto: ⚖️ Balanced: Comparison failure: full PR diff.

Grey Divider

⚠️ Warning | Comment size exceeded, non finding content trimmed Learn more

Grey Divider

Qodo Logo

execute :dismiss_alert
end

def alert=(keys)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

3. Removes the classic alert= setter without deprecation 📘 Rule violation ⚙ Maintainability

Remote::Bridge#alert= is deleted and replaced by send_alert_text(keys, _prompt = nil), and its
RBS signature is removed as well. Code that calls bridge.alert = 'text' on a released client now
raises NoMethodError on upgrade, and nothing marks the old setter as deprecated or points to the
replacement. The change removes a public surface, so it should first be deprecated with a message
that names send_alert_text.
Agent Prompt
## Issue description
The PR removes `Selenium::WebDriver::Remote::Bridge#alert=` and replaces it with `send_alert_text`, without deprecation. Released code that calls `bridge.alert = keys` will break on upgrade.

## Fix Focus Areas
- rb/lib/selenium/webdriver/remote/bridge.rb[135-150]
- rb/sig/lib/selenium/webdriver/remote/bridge.rbs[101-118]

## Recommended Fix
Restore `alert=` as a method that forwards to `send_alert_text(keys)` and emits a deprecation through `WebDriver.logger.deprecate` (the same helper used for the `unhandledPromptBehavior` map form in `alerts.rb`), naming `send_alert_text` as the replacement. Keep the RBS signature for `alert=` until removal, and add a spec that asserts the deprecation is emitted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +164 to +165
capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'}
behavior || 'dismiss and notify'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

4. Unhandled bidi alerts now raise instead of dismissing silently 📘 Rule violation ⚙ Maintainability

Alerts#manage_prompts_locally forces unhandledPromptBehavior to {'default' => 'ignore'} for
every BiDi session, and the client then applies dismiss and notify itself, so an alert that used
to be dismissed silently by the remote end now raises UnexpectedAlertOpenError on the next
command. Existing BiDi users whose scripts never handled alerts will see new exceptions after
upgrading, and the PR does not deprecate the old behavior before making the change. The PR labels
this a breaking change, but the compliance rule requires a deprecation step before behavior that
released users depend on is changed.
Agent Prompt
## Issue description
The PR changes the effective default for BiDi sessions from silently dismissing an unhandled alert to raising `UnexpectedAlertOpenError`. Released users who rely on the old behavior break on upgrade, and no deprecation precedes the change.

## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[155-166]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[31-36]

## Recommended Fix
Follow the Selenium deprecation policy: when no `unhandledPromptBehavior` is given in a BiDi session, log a deprecation through `WebDriver.logger.deprecate` that says the default will change to `dismiss and notify` and names the explicit capability to keep the old behavior. Alternatively, gate the new default behind an opt-in until the next major release. Add a unit or integration spec that asserts the deprecation is emitted.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +156 to +157
capabilities = capabilities['alwaysMatch'] || capabilities
behavior = capabilities['unhandledPromptBehavior']

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. Some sessions receive invalid capabilities 🐞 Bug ≡ Correctness

manage_prompts_locally selects alwaysMatch or the outer hash, never an existing firstMatch
candidate, before writing unhandledPromptBehavior. When a caller uses Capabilities.first_match,
it adds the setting outside both matching sections and leaves the candidate's requested behavior
unchanged, so session creation can be rejected or use the remote behavior instead.
Agent Prompt
## Issue description
The supported firstMatch capability shape is modified at the outer level rather than in its selectable candidates.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[155-165]
## Recommended Fix
Normalize W3C capability payloads before extracting the requested behavior and place the remote ignore setting in valid matching sections, accounting for candidate-specific values and conflicts. Test session creation with firstMatch.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +148 to +149
def closed(prompt)
@mutex.synchronize { @prompts.delete(prompt.context) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

5. A newer alert can disappear from lookup 🐞 Bug ☼ Reliability

Alerts#closed and the closed-event listener delete a prompt solely by context, without checking
which prompt is stored there. If another prompt opens in that context before either cleanup runs,
the cleanup removes the newer prompt and subsequent Alert API lookups report no alert.
Agent Prompt
## Issue description
Cleanup for one prompt can delete a newer prompt stored under the same browsing context.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[145-150]
- rb/lib/selenium/webdriver/common/alerts.rb[183-186]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[95-99]
## Recommended Fix
Delete an explicitly closed prompt only if the stored object is that prompt. Serialize or correlate opened and closed event processing per context so a delayed close event cannot remove a later prompt; test consecutive prompts in one context.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +128 to +129
messages[id] = error
pending_responses[id].signal

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

6. Interrupted commands can appear successful 🐞 Bug ☼ Reliability

WebSocketConnection#release stores an interruption exception and signals its waiter, but
process_frame can subsequently overwrite that exception before the waiter resumes. If a response
arrives in that interval, await_response consumes the response instead of raising the alert
interruption.
Agent Prompt
## Issue description
A late socket response can replace the exception used to interrupt a command waiting on an alert.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/websocket_connection.rb[122-131]
- rb/lib/selenium/webdriver/common/websocket_connection.rb[287-295]
## Recommended Fix
Have response processing retain an existing released exception under the same mutex rather than overwrite it. Add a test that delivers a response after release but before the waiting thread consumes the result.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +241 to +243
context = context_of(payload)
return unless context

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

7. Realm commands bypass open-alert handling 🐞 Bug ≡ Correctness

Alerts#context_of extracts only a context field, so before_bidi_command returns before applying
prompt behavior to commands targeted at a script realm. When a caller sends a valid realm-targeted
command while its context has an open alert, the configured accept, dismiss, or notify behavior is
not applied.
Agent Prompt
## Issue description
Valid realm-targeted script commands have no context field and skip the new open-alert check.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[237-253]
- rb/lib/selenium/webdriver/common/alerts.rb[255-264]
## Recommended Fix
Resolve the target realm to its browsing context before the prompt lookup, or handle realm-targeted commands through an equivalent prompt-aware path. Test a realm-targeted script command while its context has an open prompt.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +101 to +105
def execute(*)
# TODO: check a session-wide store of errors raised on listener threads, not only the alert handlers'
@alerts.check_errors
begin
super

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

8. A failed alert handler makes quit skip ending the session 🐞 Bug ☼ Reliability

BiDiBridge#execute checks for stored alert-handler errors before sending every command, including
the :delete_session command issued by Bridge#quit. If a handler error is pending when
driver.quit runs, it escapes Bridge#quit's transport-error rescue before deletion is sent; the
local service stops, but the remote or Grid session remains until it times out.
Agent Prompt
## Issue description
A pending alert-handler exception can prevent `driver.quit` from sending `:delete_session`, leaving the remote or Grid session running.

## Fix Focus Areas
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[101-110]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[49-55]

## Recommended Fix
Exempt `:delete_session` from the pre-command `@alerts.check_errors` call and from `manage_exception`, so session deletion proceeds even when a handler error is pending. Alternatively, handle the pending error in `BiDiBridge#quit` before calling `super`, or defer surfacing it until after session cleanup. Test quitting immediately after an alert handler raises.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +245 to +252
prompt = prompt_in(context)
return unless prompt

error = Error::UnexpectedAlertOpenError.new("unexpected alert open: {Alert text : #{prompt.text}}")
raise error if behavior == 'ignore'

behavior.start_with?('accept') ? @bridge.accept_alert(prompt) : @bridge.dismiss_alert(prompt)
raise error if behavior.end_with?('notify')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

9. Next bidi command can dismiss a beforeunload prompt 🐞 Bug ≡ Correctness

before_bidi_command handles every recorded prompt the same way, so a beforeunload prompt that the
default handler is still accepting on its callback thread gets dismissed when 'dismiss and notify'
is in effect, and an UnexpectedAlertOpenError is raised. The classic path waits out this window
(wait_for_beforeunload_to_close in manage_exception), but a BiDi command sent right after a
click that opened beforeunload (e.g. driver.get or navigate.refresh) races the default handler:
the page stays, the command fails, and the handler's late accept fails with no such alert, which is
stored and raised again on a later command.
Agent Prompt
## Issue description
before_bidi_command applies unhandledPromptBehavior to a beforeunload prompt that the default handler is still accepting. The prompt gets dismissed, the command raises, and the handler's accept fails.

## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[238-253]
- rb/lib/selenium/webdriver/common/alerts.rb[189-196]

## Recommended Fix
In before_bidi_command, when no user handler is registered and `prompt.type == 'beforeunload'`, call `wait_for_beforeunload_to_close` (or wait until this specific prompt is gone) and return without dismissing or raising. Only apply the behavior if the prompt is still open after the wait.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +158 to +165
if behavior.is_a?(Hash)
WebDriver.logger.deprecate('a map for unhandledPromptBehavior',
'its classic String value or use Alerts#add_handler',
id: :unhandled_prompt_behavior)
behavior = behavior.transform_keys(&:to_s)['default']
end
capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'}
behavior || 'dismiss and notify'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Informational

10. Per-type prompt behaviors are silently dropped 🐞 Bug ≡ Correctness

When unhandledPromptBehavior is a map, manage_prompts_locally keeps only the default key and
throws away the per-type entries such as alert, confirm, prompt and beforeUnload. A user who
configured e.g. {alert: 'accept'} with no default now gets 'dismiss and notify' for alerts in BiDi
sessions, and the only notice is a deprecation warning that doesn't say those values were ignored.
Agent Prompt
## Issue description
manage_prompts_locally drops every key of an unhandledPromptBehavior map except 'default', so per-type settings silently change behavior.

## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[155-166]
- rb/lib/selenium/webdriver/common/alerts.rb[210-213]

## Recommended Fix
Store the map and work out the behavior per prompt type (`behavior(prompt)`, falling back to 'default'). If you'd rather not support that, log a clear warning that lists the ignored per-type keys.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

@titusfortner
titusfortner force-pushed the rb-bidi-alert-handlers branch from da76701 to 23954e4 Compare November 25, 2026 18:43
@selenium-ci

Copy link
Copy Markdown
Member

/agentic_review

Comment on lines +178 to +179
window = @bridge.context_tree.top_level(event.context)
@mutex.synchronize { @prompts.delete(window) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

4. Closed alerts can remain open to the client 🐞 Bug ≡ Correctness

listen_prompt_opened and listen_prompt_closed update the same prompt record from separately
dispatched listener threads without preserving event order. If a prompt closes quickly and the
closed callback runs first, the opened callback stores a stale prompt that later alert lookups and
commands treat as open.
Agent Prompt
## Issue description
Opened and closed callbacks run on independent threads, so a closed event can delete nothing before its opened event stores a stale prompt.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[162-180]
## Recommended Fix
Serialize prompt state updates in event-delivery order, or retain enough event identity and ordering information to prevent an older opened callback from restoring a closed prompt. Add a test that delays opened-event processing until after the closed callback.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +158 to +159
capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'}
behavior || 'dismiss and notify'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

5. Retrying a session changes prompt behavior 🐞 Bug ≡ Correctness

manage_prompts_locally overwrites unhandledPromptBehavior in the capabilities hash supplied by
the caller before session creation. If that attempt fails and the caller reuses the hash, the next
attempt reads the injected ignore value instead of the requested behavior and applies it locally.
Agent Prompt
## Issue description
Session creation mutates the caller's capabilities, causing a retry with the same object to use a different local prompt behavior.
## Fix Focus Areas
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[31-35]
- rb/lib/selenium/webdriver/common/alerts.rb[149-159]
## Recommended Fix
Read the requested behavior from the original capabilities, but replace the remote-end value only in a copied capabilities structure, including a copy of `alwaysMatch` when present. Test two session attempts with the same capabilities object.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +182 to +185
next_id.tap do |new_id|
pending_responses[new_id] = ConditionVariable.new
pending_payloads[new_id] = payload
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. Interrupted commands can still execute 🐞 Bug ≡ Correctness

WebSocketConnection#register adds a command to the waiting set before before_send runs, so
Alerts#release_commands can mark a command interrupted before it has been written to the socket.
If that callback later finishes, send_cmd still writes the frame, then raises the stored
interruption to its caller despite sending a command that may have side effects.
Agent Prompt
## Issue description
The waiting set includes commands still in `before_send`, allowing alert interruption to be reported for a frame that is written afterward.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/websocket_connection.rb[118-133]
- rb/lib/selenium/webdriver/common/websocket_connection.rb[139-146]
- rb/lib/selenium/webdriver/common/websocket_connection.rb[178-187]
- rb/lib/selenium/webdriver/common/alerts.rb[216-223]
## Recommended Fix
Track whether each registered command has actually been sent and exclude unsent commands from alert release. Coordinate the sent-state transition with release so a command cannot be marked interrupted just before its frame is written; test a command held in `before_send` while an alert opens.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

Comment on lines +126 to +128
prompt = refusing_prompt
# chromedriver can refuse a command for an alert BiDi has just closed
return unless prompt

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

6. Alert notifications can disappear on retry 🐞 Bug ≡ Correctness

manage_exception returns without raising an UnexpectedAlertOpenError when refusing_prompt
cannot find a recorded prompt, even if the selected behavior ends in notify. If the prompt has
already closed or its event is not recorded within the lookup timeout, BiDiBridge#execute retries
the command and can return success instead of exposing the original error.
Agent Prompt
## Issue description
A remote alert error is discarded when no matching prompt remains recorded, bypassing an explicit notify behavior.
## Fix Focus Areas
- rb/lib/selenium/webdriver/common/alerts.rb[123-131]
- rb/lib/selenium/webdriver/remote/bidi_bridge.rb[108-113]
## Recommended Fix
When the requested behavior includes `notify`, preserve and raise the remote alert error even if prompt lookup returns nil. Retry only the cases whose behavior permits retry, and test an alert error arriving after the prompt record is gone.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Dismiss ↗ | View ↗

@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 23954e4

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

B-build Includes scripting, bazel and CI integrations B-devtools Includes everything BiDi or Chrome DevTools related C-rb Ruby Bindings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants