Repository navigation
[rb] add BiDi alert handlers and apply unhandledPromptBehavior on the client (ADR 18283) - #18384
titusfortner wants to merge 2 commits into
Conversation
|
/agentic_describe |
PR Summary by QodoAdd Ruby BiDi alert handlers and client-side prompt behavior
AI Description
Merge Risk
|
Code Review by Qodo
1. Interrupted commands can still execute
|
| execute :dismiss_alert | ||
| end | ||
|
|
||
| def alert=(keys) |
There was a problem hiding this comment.
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
| capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'} | ||
| behavior || 'dismiss and notify' |
There was a problem hiding this comment.
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
| capabilities = capabilities['alwaysMatch'] || capabilities | ||
| behavior = capabilities['unhandledPromptBehavior'] |
There was a problem hiding this comment.
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
| def closed(prompt) | ||
| @mutex.synchronize { @prompts.delete(prompt.context) } |
There was a problem hiding this comment.
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
| messages[id] = error | ||
| pending_responses[id].signal |
There was a problem hiding this comment.
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
| context = context_of(payload) | ||
| return unless context | ||
|
|
There was a problem hiding this comment.
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
| def execute(*) | ||
| # TODO: check a session-wide store of errors raised on listener threads, not only the alert handlers' | ||
| @alerts.check_errors | ||
| begin | ||
| super |
There was a problem hiding this comment.
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
| 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') |
There was a problem hiding this comment.
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
| 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' |
There was a problem hiding this comment.
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
…PromptBehavior (ADR 18283 option 2)
da76701 to
23954e4
Compare
|
/agentic_review |
| window = @bridge.context_tree.top_level(event.context) | ||
| @mutex.synchronize { @prompts.delete(window) } |
There was a problem hiding this comment.
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
| capabilities['unhandledPromptBehavior'] = {'default' => 'ignore'} | ||
| behavior || 'dismiss and notify' |
There was a problem hiding this comment.
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
| next_id.tap do |new_id| | ||
| pending_responses[new_id] = ConditionVariable.new | ||
| pending_payloads[new_id] = payload | ||
| end |
There was a problem hiding this comment.
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
| prompt = refusing_prompt | ||
| # chromedriver can refuse a command for an alert BiDi has just closed | ||
| return unless prompt |
There was a problem hiding this comment.
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
|
Code review by qodo was updated up to the latest commit 23954e4 |
🔗 Related Issues
Implements ADR #18283 (as written, the option that keeps
unhandledPromptBehavior)Builds on #18388 (session context tree) and #18389 (listener error store)
ArgumentErrorwhenunhandledPromptBehavioris 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| ... }anddriver.alerts.remove_handler(handle); the handler receives aWebDriver::AlertAlert#typeandAlert#default_value, which raise without BiDi🔧 Implementation Notes
unhandledPromptBehavior: {default: 'ignore'}so prompts stay open for the binding to handle.WebSocketConnection#send_cmd, because Chrome does not reply to most of them while one is open; the olderBiDi::*classes are covered too.BiDiBridgeimplements the Alert API from theuserPromptOpenedevent, because BiDi has no command that reads an open prompt.invalid argumentwhile abeforeunloadprompt is being accepted, so that command is sent again once the prompt closes.target_locator_spec.rbnow runs in BiDi sessions, and the Chromiumpending_ifguards on thehandle_user_promptspecs are removed.🤖 AI assistance
🔄 Types of changes