capybara-lightpanda 0.16.0 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a8f6c1cfdad13de4569b3d79828d9d19848b166e220b6a91329c7c0cb2fa9781
4
- data.tar.gz: 2f7c90bb35b746682f5533c9d7ebfe1b64fbf7aea1f53a6c93f563428d9f3b46
3
+ metadata.gz: f73305ebb70a014b9b5345eade37ec044e2b07cbe99cf30a9eaa2bdbdb80eca5
4
+ data.tar.gz: '095323a36971553487cfa1517df1e08bf67f7a188599e5d93c7db4d44d58868b'
5
5
  SHA512:
6
- metadata.gz: 1d1632dc29185af1e1d1c594abd7a9fe4b0af584585aa6c6534428d59b23316174db581d901bd7d67430b2e708c664c9c7175918cfeca4d386ba95453816b910
7
- data.tar.gz: 76a79eed2e960c294a09c1ee8882014d543c5695cd519d51c3d9560ca7b153b085ae4161f18e2a11a301465b95c0cc71140a269c3c8970c86e93d291430630cb
6
+ metadata.gz: eba98666f4f06a68d008bd04248aa8be99a0b2f03ec5d214cd3f2b02fee2f2685085c5fe44c2045faa2e992a090f8b25c13a21e8a703e799d079461aa20bb5ac
7
+ data.tar.gz: 483d3b13353f17e76378a3a0d991a1d5951779a4ea9f4e51b7b6c99485ca66ff1b3efecbdce65c51bb49e49ee11a83e2d7a5da0c7ec2d79d93de0c036e029118
data/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.17.1] - 2026-11-08
4
+
5
+ ### Fixed
6
+
7
+ - **Clicks no longer stall after Turbo cancels a request.** When Turbo aborted a fetch (a newer click or visit replacing it), or a Turbo Stream render was cancelled or raised, the driver kept thinking the page was busy. Every later `click`, `send_keys` or `go_back` then waited the full driver timeout. Each request and each stream render is now counted out exactly once, whatever way it ends.
8
+ - **A crashed browser is restarted instead of failing the next test.** If Lightpanda died during a navigation, the driver didn't notice, and the next `visit` raised `DeadBrowserError`. It now detects the crash and starts a fresh browser. Each restart also used to leave the dead browser's process tracked and running; it is now cleaned up, and a browser that fails partway through startup no longer leaves a process behind.
9
+ - **`accept_alert` / `accept_confirm` only match a dialog opened inside their block.** An earlier, unhandled alert could satisfy a later `accept_alert` whose block opened nothing, so the test passed when it should have failed. And after an `accept_confirm` that timed out, the next unwrapped `confirm` was silently accepted; it is now dismissed and reported like any unexpected dialog.
10
+ - **`status_code` and `response_headers` describe the page, not an iframe.** A page that embedded an iframe returning 404 reported `status_code == 404`, along with the iframe's headers. They now always come from the top-level page.
11
+ - **A failing key in `send_keys` no longer leaves modifiers held down.** If a key in a chord like `[:shift, "a"]` raised, Shift stayed pressed for the rest of the test.
12
+ - **Commands cut off by a dying browser raise `DeadBrowserError`, not `TimeoutError`.** And shutting down a browser that has stopped responding now always finishes, instead of raising partway through.
13
+ - **Lightpanda release candidates are accepted.** An RC build (for example `1.0.4-rc1`) was rejected as "too old" even when it was newer than the required version.
14
+
15
+ ## [0.17.0] - 2026-11-05
16
+
17
+ > **Update Lightpanda before upgrading.** This release requires Lightpanda **1.0.3** or a nightly build ≥ 11647. The driver refuses anything older and names the version it found. Pin `1.0.3` for a reproducible browser.
18
+
19
+ ### Changed
20
+
21
+ - **`<a download>` links download natively on Lightpanda 1.0.3.** The driver used to wait for a 1.1 release before letting the browser handle a link's `download` attribute itself, so on 1.0.3 it also went to the link's URL. Every supported browser now handles it natively, and the driver leaves the download to it.
22
+
23
+ ### Fixed
24
+
25
+ - **`reset_session!` no longer starts a browser just to reset it.** Resetting a session that never opened a page used to launch Lightpanda first. When that launch failed, the reset waited for the full process timeout a second time.
26
+ - **Contenteditable elements are detected as browsers detect them.** `contenteditable="plaintext-only"` now counts as editable. An unrecognised value such as `contenteditable="bogus"` now inherits from its parent instead of making the element editable. A page with `document.designMode = "on"` is editable throughout. SVG elements are ignored. This affects which element a click focuses and where `send_keys` types.
27
+ - **A stalled browser can no longer hang a command past its timeout.** The timeout used to cover only the wait for the reply, so a browser that had stopped reading could hold the call much longer while it was still being sent. Sending and waiting now share one deadline.
28
+
3
29
  ## [0.16.0] - 2026-10-26
4
30
 
5
31
  ### Fixed
data/README.md CHANGED
@@ -57,7 +57,7 @@ driven_by :lightpanda
57
57
  > Lightpanda is a headless agentic browser, not a layout engine. External `<link rel="stylesheet">` **are** fetched and applied (the gem enables this by default), and `@media` / `window.matchMedia()` evaluate against the `window_size` you configure — so a mobile-only CTA gated by `@media (max-width: …)` resolves at the width you ask for. What's missing is *layout*: nothing reflows, `getBoundingClientRect` stays synthetic, and there is no real scroll. Specs that assert on pixel geometry, scrolling, or screenshots can't pass here, nor can the two that catch people out: a second browser tab and a menu revealed purely by CSS `:hover`. See [known limitations](https://navidemad.github.io/capybara-lightpanda/docs/#limits).
58
58
 
59
59
  > [!TIP]
60
- > For reproducible CI, pin the browser: `Capybara::Lightpanda::Binary.required_version = "1.0.2"` (the tagged release the gem's current floor is pinned to — nightly build 10965 is that release's commit). Without a pin the driver tracks Lightpanda's rolling `nightly` tag, which moves under you. See [Pinning the browser version](https://navidemad.github.io/capybara-lightpanda/docs/#pinning).
60
+ > For reproducible CI, pin the browser: `Capybara::Lightpanda::Binary.required_version = "1.0.3"` (the tagged release the gem's current floor is pinned to — nightly build 11647 is that release's commit). Without a pin the driver tracks Lightpanda's rolling `nightly` tag, which moves under you. See [Pinning the browser version](https://navidemad.github.io/capybara-lightpanda/docs/#pinning).
61
61
 
62
62
  ## Credits
63
63
 
@@ -93,16 +93,41 @@ module Capybara
93
93
  end
94
94
  claimed[:message]
95
95
  rescue TimeoutError
96
+ disarm_modal
96
97
  raise_modal_not_found(type, text, last_seen_message)
97
98
  end
98
99
 
99
100
  private
100
101
 
102
+ # The dialog find_modal claims must come from the block about to run,
103
+ # so anything queued before the arm (a dialog nobody wrapped, already
104
+ # reported as unhandled) is dropped here. Kept, it satisfied the next
105
+ # accept_* even when that block opened no dialog at all.
101
106
  def arm_modal
102
- @modal_messages_mutex.synchronize { @modal_armed = true }
107
+ @modal_messages_mutex.synchronize do
108
+ @modal_messages.clear
109
+ @modal_armed = true
110
+ end
103
111
  yield
104
112
  end
105
113
 
114
+ # find_modal gave up while still armed: the block opened no dialog, and
115
+ # Lightpanda still holds the pre-armed answer for the next one — a
116
+ # dialog nobody wrapped would get it silently. LP has no command to
117
+ # clear the slot, so overwrite it with Lightpanda's own default
118
+ # (confirm false, prompt null) and stop claiming it: that next dialog
119
+ # then behaves, and is reported, exactly as if nothing had been armed.
120
+ def disarm_modal
121
+ armed = @modal_messages_mutex.synchronize do
122
+ was = @modal_armed
123
+ @modal_armed = false
124
+ was
125
+ end
126
+ page_command("LP.handleJavaScriptDialog", accept: false) if armed
127
+ rescue Error
128
+ nil # the session is gone; ModalNotFound is the error worth raising
129
+ end
130
+
106
131
  LIGHTPANDA_DIALOG_DEFAULTS = {
107
132
  "confirm" => "cancelled it",
108
133
  "prompt" => "answered null",
@@ -122,9 +122,27 @@ module Capybara
122
122
  start
123
123
  end
124
124
 
125
+ # A step that fails after the process or the connection is up (an old
126
+ # ws_url browser, a command timing out on a slow machine) must not leave
127
+ # them behind: Browser.new raises, nobody holds this object to quit it,
128
+ # and the next attempt would compete with the orphan for the port. The
129
+ # `ensure` covers Interrupt too.
125
130
  def start
126
131
  return if @started
127
132
 
133
+ begin
134
+ connect
135
+ create_browser_context
136
+ create_page
137
+ @started = true
138
+ ensure
139
+ quit unless @started
140
+ end
141
+
142
+ self.class.track(self)
143
+ end
144
+
145
+ def connect
128
146
  if @options.ws_url?
129
147
  @client = Client.new(@options.ws_url, @options)
130
148
  check_remote_version
@@ -133,12 +151,6 @@ module Capybara
133
151
  @process.start
134
152
  @client = Client.new(@process.ws_url, @options)
135
153
  end
136
-
137
- create_browser_context
138
- create_page
139
-
140
- @started = true
141
- self.class.track(self)
142
154
  end
143
155
 
144
156
  # Per-session BrowserContext (Chrome's incognito-profile primitive).
@@ -521,7 +533,7 @@ module Capybara
521
533
 
522
534
  # Internal lifecycle steps defined above near their topical groups —
523
535
  # calling them out of order corrupts session state, so they are not API.
524
- private :create_browser_context, :create_page, :clear_session_state,
536
+ private :connect, :create_browser_context, :create_page, :clear_session_state,
525
537
  :enable_page_events
526
538
 
527
539
  private
@@ -5,6 +5,7 @@ require "socket"
5
5
  require "websocket/driver"
6
6
 
7
7
  require_relative "../utils/attempt"
8
+ require_relative "../utils/wait"
8
9
 
9
10
  module Capybara
10
11
  module Lightpanda
@@ -26,17 +27,27 @@ module Capybara
26
27
  connect
27
28
  end
28
29
 
29
- # `timeout` bounds how long the browser may go without taking any of
30
- # the frame's bytes (see #write); nil falls back to options.timeout.
31
- def send_message(message, timeout: nil)
30
+ # The frame must be sent by `deadline` (monotonic seconds; Client#command
31
+ # passes the command's own deadline) or within `timeout` seconds; both
32
+ # nil fall back to options.timeout. A frame still queued behind the
33
+ # socket lock at the deadline wrote nothing, so it raises TimeoutError
34
+ # and the connection stays usable; one cut off mid-write kills the
35
+ # connection (see #write).
36
+ def send_message(message, timeout: nil, deadline: nil)
32
37
  raise DeadBrowserError, "WebSocket is not open" unless @status == :open
33
38
 
39
+ deadline ||= Utils::Wait.deadline(timeout || @options.timeout)
34
40
  @logger&.puts("\n\n▶ #{@logger.elapsed_time} #{message}")
35
- @driver_mutex.synchronize do
36
- @write_timeout = timeout
41
+ unless acquire_driver_lock?(deadline)
42
+ raise TimeoutError, "Frame not sent before its deadline: another frame held the socket"
43
+ end
44
+
45
+ begin
46
+ @write_deadline = deadline
37
47
  @driver.text(message)
38
48
  ensure
39
- @write_timeout = nil
49
+ @write_deadline = nil
50
+ @driver_mutex.unlock
40
51
  end
41
52
  end
42
53
 
@@ -45,19 +56,31 @@ module Capybara
45
56
  # connection (status :closed or :error) without closing the socket,
46
57
  # and an early return here then left the TCPSocket — one descriptor
47
58
  # per crashed browser — open until GC finalized it (ferrum #639).
59
+ #
60
+ # A close frame that cannot be written (buffers full, browser not
61
+ # reading) is given up on, not raised: abandon_stalled_write already
62
+ # marked the connection dead, and an error escaping here would cut
63
+ # Client#close short before it released its thread and pending commands.
48
64
  def close
49
65
  unless @status == :closed
50
66
  @status = :closing
51
67
  @messages.close
52
- @driver_mutex.synchronize { @driver&.close }
68
+ begin
69
+ @driver_mutex.synchronize { @driver&.close }
70
+ rescue DeadBrowserError
71
+ nil
72
+ end
53
73
  @thread&.join(1) || @thread&.kill
54
74
  end
55
75
  close_socket
56
76
  @status = :closed
57
77
  end
58
78
 
79
+ # :closing counts: no reply can arrive once close has begun, and a
80
+ # command released by it must report the connection gone
81
+ # (DeadBrowserError), not a timeout that never happened.
59
82
  def closed?
60
- @status == :closed || @status == :error
83
+ %i[closed closing error].include?(@status)
61
84
  end
62
85
 
63
86
  # Called by websocket-driver, always under @driver_mutex. A browser
@@ -65,11 +88,11 @@ module Capybara
65
88
  # on Lightpanda's single thread) would block a plain write forever
66
89
  # once the frame outgrows the socket buffers, holding the lock that
67
90
  # every other command, the reader's parse and #close need — and the
68
- # command timeout only starts after the write returns. So the write
69
- # gives up once the browser takes no byte for the timeout; the wait
70
- # restarts on every partial write, so a slow but moving peer is fine
71
- # (ferrum #644). Close and pong frames have no command timeout and
72
- # fall back to options.timeout rather than waiting forever.
91
+ # command would never time out. So the write gives up at the frame's
92
+ # deadline even when the peer is still taking bytes: a trickling peer
93
+ # must not hold the lock past the caller's budget (ferrum #644). Close
94
+ # and pong frames have no command deadline; they give up once the
95
+ # browser takes no byte for options.timeout.
73
96
  def write(data)
74
97
  until data.empty?
75
98
  written = @socket.write_nonblock(data, exception: false)
@@ -96,7 +119,9 @@ module Capybara
96
119
  private
97
120
 
98
121
  def wait_for_socket(state)
99
- timeout = @write_timeout || @options.timeout
122
+ timeout = @write_deadline ? Utils::Wait.remaining(@write_deadline) : @options.timeout
123
+ return false if timeout <= 0
124
+
100
125
  state == :wait_readable ? @socket.wait_readable(timeout) : @socket.wait_writable(timeout)
101
126
  end
102
127
 
@@ -104,10 +129,28 @@ module Capybara
104
129
  # mark it dead (the reader and message threads stop, pending commands
105
130
  # are released) and close the socket.
106
131
  def abandon_stalled_write
107
- timeout = @write_timeout || @options.timeout
132
+ reason = if @write_deadline
133
+ "Browser did not take the whole frame before the command's deadline"
134
+ else
135
+ "Browser accepted no data for #{@options.timeout}s"
136
+ end
108
137
  mark_dead(:error)
109
138
  close_socket
110
- raise DeadBrowserError, "Browser accepted no data for #{timeout}s and is likely stuck; connection closed"
139
+ raise DeadBrowserError, "#{reason} and is likely stuck; connection closed"
140
+ end
141
+
142
+ # Mutex has no timed lock. Poll try_lock with a short capped backoff:
143
+ # the lock is normally held for one frame write or one parse.
144
+ def acquire_driver_lock?(deadline)
145
+ delay = 0.0005
146
+ until @driver_mutex.try_lock
147
+ remaining = Utils::Wait.remaining(deadline)
148
+ return false if remaining <= 0
149
+
150
+ sleep([delay, remaining].min)
151
+ delay = [delay * 2, 0.01].min
152
+ end
153
+ true
111
154
  end
112
155
 
113
156
  def close_socket
@@ -20,21 +20,26 @@ module Capybara
20
20
  start_message_thread
21
21
  end
22
22
 
23
+ # `timeout` bounds the whole command: waiting for the socket lock, writing
24
+ # the frame and waiting for the response all draw on one deadline, so a
25
+ # slow send can't stretch a command past its budget.
23
26
  def command(method, params = {}, async: false, session_id: nil, timeout: nil)
24
27
  message = build_message(method, params, session_id: session_id)
25
28
  effective_timeout = timeout || @options.timeout
29
+ deadline = Utils::Wait.deadline(effective_timeout)
26
30
 
27
31
  if async
28
- @ws.send_message(JSON.generate(message), timeout: effective_timeout)
32
+ @ws.send_message(JSON.generate(message), deadline: deadline)
29
33
  return true
30
34
  end
31
35
 
32
36
  pending = Concurrent::IVar.new
33
37
  @pendings[message[:id]] = pending
34
38
 
35
- @ws.send_message(JSON.generate(message), timeout: effective_timeout)
39
+ @ws.send_message(JSON.generate(message), deadline: deadline)
36
40
 
37
- response = pending.value!(effective_timeout)
41
+ # value!(0) still returns a response that landed during the send.
42
+ response = pending.value!(Utils::Wait.remaining(deadline))
38
43
 
39
44
  if response.nil?
40
45
  raise DeadBrowserError, "Browser closed during #{method}" if @ws.closed?
@@ -13,8 +13,8 @@ module Capybara
13
13
  # a blocking `wait`, the way ferrum's Downloads does.
14
14
  #
15
15
  # Navigation downloads require Content-Disposition: attachment, not just a
16
- # MIME type. New browsers also honor an anchor's download attribute (build
17
- # 11097 / 1.1 release line); Node#click lets that native activation finish.
16
+ # MIME type. The floor also honors an anchor's download attribute (upstream
17
+ # #4124, 11097); Node#click lets that native activation finish.
18
18
  # Capybara's MIME-only :download shared spec still stays in capybara_skip.
19
19
  #
20
20
  # Structure deliberately mirrors Network (same browser ref, same mutex +
@@ -20,8 +20,16 @@ module Capybara
20
20
  @started = false
21
21
  end
22
22
 
23
+ # A browser whose CDP connection died still owns a process (running, or a
24
+ # zombie after a crash), its output pipes and an at_exit registry slot.
25
+ # Quit it before spawning the replacement, or every respawn leaves one
26
+ # more Lightpanda running until the suite exits.
23
27
  def browser
24
- @browser = nil if @browser && !browser_alive?
28
+ if @browser && !browser_alive?
29
+ dead = @browser
30
+ @browser = nil
31
+ dead.quit
32
+ end
25
33
  @browser ||= Browser.new(@options)
26
34
  end
27
35
 
@@ -322,7 +330,14 @@ module Capybara
322
330
  # turns programmer errors (e.g. a NoMethodError in browser.rb) into a
323
331
  # silent quit-and-respawn on every example with zero signal. The warn
324
332
  # keeps repeated respawns visible.
333
+ #
334
+ # With no browser (never visited, or the launch itself failed) there is
335
+ # nothing to reset: `browser` would spawn Lightpanda just to reset it,
336
+ # and a failed launch would cost a second process timeout in teardown.
337
+ # The next visit launches as usual.
325
338
  def reset!
339
+ return unless @browser
340
+
326
341
  browser.reset
327
342
  rescue Error, SystemCallError, IOError => e
328
343
  warn "[capybara-lightpanda] reset! failed (#{e.class}: #{e.message}); respawning browser"
@@ -11,6 +11,7 @@ window._lightpanda = {
11
11
  isVisible: isVisible,
12
12
  isObscured: isObscured,
13
13
  isDisabled: isDisabled,
14
+ contentEditableState: contentEditableState,
14
15
  isContentEditable: isContentEditable,
15
16
  pointerFocusTarget: pointerFocusTarget,
16
17
  visibleText: visibleText,
@@ -92,19 +92,32 @@ function isDisabled(el) {
92
92
  return false;
93
93
  }
94
94
 
95
- // True if the element is the host of a contenteditable region: it (or any
96
- // ancestor) has a non-"false" `contenteditable` attribute. Lightpanda's
97
- // native `HTMLElement.isContentEditable` (PR #2310) is hardwired to return
98
- // `false` for every element — it has no caret/keyboard editing pipeline —
99
- // so the IDL property is useless here and we walk ancestors ourselves.
95
+ // The element's own contenteditable state: true for the "", "true" and
96
+ // "plaintext-only" values, false for "false", null for inherit (no attribute,
97
+ // an invalid value, or a non-HTML element — the attribute is HTML-only).
98
+ // Mirrors upstream Element.contentEditableState.
99
+ function contentEditableState(el) {
100
+ if (el.namespaceURI !== 'http://www.w3.org/1999/xhtml') return null;
101
+ if (!el.hasAttribute || !el.hasAttribute('contenteditable')) return null;
102
+ var v = (el.getAttribute('contenteditable') || '').toLowerCase();
103
+ if (v === '' || v === 'true' || v === 'plaintext-only') return true;
104
+ if (v === 'false') return false;
105
+ return null;
106
+ }
107
+
108
+ // True if the element can be edited: the nearest contenteditable attribute in
109
+ // a true or false state decides, then the document's designMode. The native
110
+ // `isContentEditable` agrees from upstream #4210 (11229, in the floor; checked
111
+ // on 1.0.3), but SVG elements have no such getter and pointerFocusTarget needs
112
+ // each element's own state, so the walk stays.
100
113
  function isContentEditable(el) {
101
- var n = el;
102
- while (n && n.nodeType === 1) {
103
- if (n.hasAttribute && n.hasAttribute('contenteditable')) {
104
- var v = (n.getAttribute('contenteditable') || '').toLowerCase();
105
- return v !== 'false';
114
+ for (var n = el; n; n = n.parentNode) {
115
+ if (n.nodeType === 1) {
116
+ var state = contentEditableState(n);
117
+ if (state !== null) return state;
118
+ } else if (n.nodeType === 9) {
119
+ return String(n.designMode).toLowerCase() === 'on';
106
120
  }
107
- n = n.parentElement;
108
121
  }
109
122
  return false;
110
123
  }
@@ -116,9 +129,15 @@ function isContentEditable(el) {
116
129
  // only kind CLICK_JS can dispatch — never runs the focus default, so the
117
130
  // driver has to apply it itself or `click` then `page.send_keys` types nowhere.
118
131
  function pointerFocusTarget(el) {
132
+ // A contenteditable attribute in the true state, or the body of a
133
+ // designMode document (Chrome edits and focuses the body, not <html>).
119
134
  function isEditingHost(n) {
120
- if (!n.hasAttribute || !n.hasAttribute('contenteditable')) return false;
121
- return (n.getAttribute('contenteditable') || '').toLowerCase() !== 'false';
135
+ var state = contentEditableState(n);
136
+ if (state !== null) return state;
137
+ var root = n.parentNode, doc = root && root.parentNode;
138
+ return (n.tagName || '').toUpperCase() === 'BODY' &&
139
+ (root.tagName || '').toUpperCase() === 'HTML' &&
140
+ !!doc && doc.nodeType === 9 && String(doc.designMode).toLowerCase() === 'on';
122
141
  }
123
142
  function isFocusable(n) {
124
143
  if (isDisabled(n)) return false;
@@ -12,6 +12,7 @@
12
12
  // Pages without Turbo never trigger _turboStart, so no sentinels fire and the
13
13
  // Ruby Event stays set (idle by default) — wait_for_turbo returns immediately.
14
14
  var _pendingTurboOps = 0;
15
+ var _turboGeneration = 0;
15
16
  function _signalTurbo(state) {
16
17
  try { console.debug('__lightpanda_turbo_' + state); } catch (e) {}
17
18
  }
@@ -26,10 +27,50 @@ function _turboEnd() {
26
27
  }
27
28
  }
28
29
 
29
- // Fetch requests (covers Drive, Frames, and Form submission fetches)
30
- document.addEventListener('turbo:before-fetch-request', _turboStart);
31
- document.addEventListener('turbo:before-fetch-response', _turboEnd);
32
- document.addEventListener('turbo:fetch-request-error', _turboEnd);
30
+ // Fetch requests (covers Drive, Frames, and Form submission fetches).
31
+ //
32
+ // A fetch ends in one of three ways, and must be counted out exactly once:
33
+ // a response (turbo:before-fetch-response), a network error
34
+ // (turbo:fetch-request-error) or an abort. Turbo aborts fetches routinely — a
35
+ // frame whose src is removed or replaced, a visit superseded by another, a
36
+ // stopped form submission — and swallows the AbortError without dispatching
37
+ // either event (FetchRequest#perform), so the abort signal is the only trace.
38
+ // Counting on the two events alone left the counter stuck above zero and every
39
+ // later driver action waiting out its full timeout.
40
+ //
41
+ // Each fetch gets a token. The response and error events carry the request's
42
+ // target, not the request, so they close the oldest open token for that target;
43
+ // the abort listener closes its own token, and a token closes once — an abort
44
+ // after the response has been counted is a no-op.
45
+ var _turboFetches = [];
46
+ function _turboFetchEnd(token) {
47
+ if (!token.open) return;
48
+ token.open = false;
49
+ var index = _turboFetches.indexOf(token);
50
+ if (index !== -1) _turboFetches.splice(index, 1);
51
+ _turboEnd();
52
+ }
53
+ function _turboFetchSettled(event) {
54
+ for (var i = 0; i < _turboFetches.length; i++) {
55
+ if (_turboFetches[i].target === event.target) return _turboFetchEnd(_turboFetches[i]);
56
+ }
57
+ }
58
+ document.addEventListener('turbo:before-fetch-request', function(event) {
59
+ var token = { target: event.target, open: true };
60
+ _turboFetches.push(token);
61
+ _turboStart();
62
+ var options = event.detail && event.detail.fetchOptions;
63
+ var signal = options && options.signal;
64
+ if (signal && typeof signal.addEventListener === 'function') {
65
+ if (signal.aborted) {
66
+ _turboFetchEnd(token);
67
+ } else {
68
+ signal.addEventListener('abort', function() { _turboFetchEnd(token); });
69
+ }
70
+ }
71
+ });
72
+ document.addEventListener('turbo:before-fetch-response', _turboFetchSettled);
73
+ document.addEventListener('turbo:fetch-request-error', _turboFetchSettled);
33
74
 
34
75
  // Form submissions (can outlast their underlying fetch)
35
76
  document.addEventListener('turbo:submit-start', _turboStart);
@@ -39,21 +80,33 @@ document.addEventListener('turbo:submit-end', _turboEnd);
39
80
  document.addEventListener('turbo:before-frame-render', _turboStart);
40
81
  document.addEventListener('turbo:frame-render', _turboEnd);
41
82
 
42
- // Stream rendering (no symmetric end event — wrap the render function)
83
+ // Only count renders that actually run: Turbo skips the renderer when the
84
+ // before-stream-render event is canceled. Each invocation owns its completion,
85
+ // and a completion from before turbo:load must not decrement newer activity.
43
86
  document.addEventListener('turbo:before-stream-render', function(event) {
44
- _turboStart();
45
87
  if (event.detail && event.detail.render) {
46
88
  var originalRender = event.detail.render;
47
89
  event.detail.render = function(streamElement) {
48
- var result = originalRender(streamElement);
49
- if (result && typeof result.then === 'function') {
50
- return result.finally(_turboEnd);
90
+ var generation = _turboGeneration;
91
+ var open = true;
92
+ function finish() {
93
+ if (!open) return;
94
+ open = false;
95
+ if (generation === _turboGeneration) _turboEnd();
96
+ }
97
+ _turboStart();
98
+ try {
99
+ var result = originalRender(streamElement);
100
+ if (result && typeof result.then === 'function') {
101
+ return Promise.resolve(result).finally(finish);
102
+ }
103
+ finish();
104
+ return result;
105
+ } catch (error) {
106
+ finish();
107
+ throw error;
51
108
  }
52
- _turboEnd();
53
- return result;
54
109
  };
55
- } else {
56
- _turboEnd();
57
110
  }
58
111
  });
59
112
 
@@ -62,6 +115,11 @@ document.addEventListener('turbo:before-stream-render', function(event) {
62
115
  // Always re-signal idle so the Ruby Event re-arms even if some `_turboEnd`
63
116
  // call dropped on the floor mid-navigation.
64
117
  document.addEventListener('turbo:load', function() {
118
+ _turboGeneration++;
65
119
  _pendingTurboOps = 0;
120
+ // Forget open fetches too: their late abort/response must not count down
121
+ // operations that started after this reset.
122
+ for (var i = 0; i < _turboFetches.length; i++) _turboFetches[i].open = false;
123
+ _turboFetches = [];
66
124
  _signalTurbo('idle');
67
125
  });
@@ -104,25 +104,43 @@ module Capybara
104
104
  # only the Tab went out.
105
105
  def type(*keys)
106
106
  active_mods = []
107
- keys.each do |key|
108
- case key
109
- when Symbol
110
- if MODIFIERS.key?(key)
111
- press_modifier(key, active_mods)
107
+ holding_modifiers(active_mods) do
108
+ keys.each do |key|
109
+ case key
110
+ when Symbol
111
+ if MODIFIERS.key?(key)
112
+ press_modifier(key, active_mods)
113
+ else
114
+ dispatch_key_with_mods(key, active_mods)
115
+ end
116
+ when Array
117
+ type_with_modifiers(key)
112
118
  else
113
- dispatch_key_with_mods(key, active_mods)
119
+ type_text(key, active_mods)
114
120
  end
115
- when Array
116
- type_with_modifiers(key)
117
- else
118
- type_text(key, active_mods)
119
121
  end
120
122
  end
121
- release_modifiers(active_mods)
122
123
  end
123
124
 
124
125
  private
125
126
 
127
+ # Every modifier keyDown gets its keyUp, even when a key in the chord
128
+ # raises (an unknown key name, a CDP timeout): otherwise page code that
129
+ # tracks modifier state sees Shift or Ctrl stuck down. A release that
130
+ # fails too must not replace the error that explains the failure.
131
+ def holding_modifiers(active_mods)
132
+ yield
133
+ rescue StandardError
134
+ begin
135
+ release_modifiers(active_mods)
136
+ rescue StandardError
137
+ nil
138
+ end
139
+ raise
140
+ else
141
+ release_modifiers(active_mods)
142
+ end
143
+
126
144
  def press_modifier(mod, active_mods)
127
145
  return if active_mods.include?(mod)
128
146
 
@@ -166,15 +184,16 @@ module Capybara
166
184
  modifiers, rest = keys.partition { |k| k.is_a?(Symbol) && MODIFIERS.key?(k) }
167
185
 
168
186
  active_mods = []
169
- modifiers.each { |m| press_modifier(m, active_mods) }
170
- rest.each do |key|
171
- if key.is_a?(Symbol)
172
- dispatch_key_with_mods(key, active_mods)
173
- else
174
- type_text(key, active_mods)
187
+ holding_modifiers(active_mods) do
188
+ modifiers.each { |m| press_modifier(m, active_mods) }
189
+ rest.each do |key|
190
+ if key.is_a?(Symbol)
191
+ dispatch_key_with_mods(key, active_mods)
192
+ else
193
+ type_text(key, active_mods)
194
+ end
175
195
  end
176
196
  end
177
- release_modifiers(active_mods)
178
197
  end
179
198
 
180
199
  def type_text(key, active_mods)
@@ -10,7 +10,7 @@ module Capybara
10
10
 
11
11
  attr_reader :browser
12
12
 
13
- # Status/headers of the last top-level document navigation; nil before
13
+ # Status/headers of the last main-frame document navigation; nil before
14
14
  # the first navigation completes. Backs Browser#status_code /
15
15
  # #response_headers. Captured by #subscribe's handlers.
16
16
  attr_reader :last_navigation_response
@@ -176,7 +176,7 @@ module Capybara
176
176
  # hop, and the redirected requestWillBeSent resets it below anyway.
177
177
  def build_request_handler
178
178
  lambda do |params|
179
- if params["type"] == "Document"
179
+ if main_frame_document?(params)
180
180
  @document_request_id = params["requestId"]
181
181
  @last_navigation_response = nil
182
182
  end
@@ -235,6 +235,14 @@ module Capybara
235
235
  end
236
236
  end
237
237
 
238
+ # Iframes load by default (Browser#configure_loading) and their document
239
+ # requests are typed "Document" too; counting them made the last iframe's
240
+ # response the page's status_code. The main frame shares the target's id,
241
+ # the same test Browser#main_frame_document_request? applies.
242
+ def main_frame_document?(params)
243
+ params["type"] == "Document" && params["frameId"] == browser.target_id
244
+ end
245
+
238
246
  # Caller holds @traffic_mutex.
239
247
  def last_open_entry(request_id)
240
248
  @traffic.reverse_each.find { |t| t[:request_id] == request_id && open?(t) }
@@ -135,7 +135,7 @@ module Capybara
135
135
  end
136
136
 
137
137
  def click(_keys = [], **_options)
138
- call(CLICK_JS, native_anchor_downloads?)
138
+ call(CLICK_JS)
139
139
  driver.browser.wait_for_idle
140
140
  end
141
141
 
@@ -376,18 +376,6 @@ module Capybara
376
376
 
377
377
  private
378
378
 
379
- # Below #4124 a download attribute suppresses native activation entirely,
380
- # so the manual navigation is still needed for attachment responses.
381
- # The API has no feature marker: keep the floor path through 1.0.x and
382
- # enable native download activation on build 11097 / the 1.1 release line.
383
- def native_anchor_downloads?
384
- browser = driver.browser
385
- build = browser.nightly_build
386
- return build >= Gem::Version.new("11097") if build
387
-
388
- browser.release && browser.release >= Gem::Version.new("1.1.0")
389
- end
390
-
391
379
  def find_hinted(method, selector, hints)
392
380
  driver.browser.find_within_hinted(@remote_object_id, method, selector, self.class.hint_spec(**hints))
393
381
  .map { |oid, cache| self.class.new(driver, oid, cache, frame_scoped: @frame_scoped) }
@@ -607,7 +595,7 @@ module Capybara
607
595
  # 6167 as duplicate `turbo:submit-start` events; the first request
608
596
  # gets aborted by the second and Turbo never renders the response.
609
597
  CLICK_JS = <<~JS
610
- function(nativeAnchorDownloads) {
598
+ function() {
611
599
  var EventCtor = (typeof MouseEvent !== 'undefined') ? MouseEvent : Event;
612
600
  // Emulate coordinate hit-testing without a layout engine. In a real
613
601
  // browser a pointer click on a container lands on its frontmost
@@ -672,11 +660,11 @@ module Capybara
672
660
  var external = !!scheme && !/^(https?|about|blob|data|file|javascript)$/i.test(scheme[1]);
673
661
  var notCancelled = hit.dispatchEvent(clickEvt);
674
662
  if (external || !notCancelled || clickEvt.defaultPrevented) return;
675
- // Native activation has already started the download. Navigating
676
- // again cancels it and replaces the document. Keep the complete
677
- // synthetic event sequence and its cancellation, but stop here on
678
- // browsers that support the download attribute.
679
- if (nativeAnchorDownloads && link && link.hasAttribute('download')) return;
663
+ // Native activation has already started the download (upstream
664
+ // #4124, 11097, in the floor). Navigating again cancels it and
665
+ // replaces the document. Keep the complete synthetic event sequence
666
+ // and its cancellation, but stop here.
667
+ if (link && link.hasAttribute('download')) return;
680
668
  var tag = hit.tagName;
681
669
  // A `javascript:` link never navigates: the click's own activation
682
670
  // behavior has already run its code. Assigning it to location.href
@@ -302,7 +302,19 @@ module Capybara
302
302
  # #3658 (10657) client rects follow the scroll and
303
303
  # DOM.scrollIntoViewIfNeeded is real — HTML5_DRAG_JS centers the
304
304
  # drop target itself because scrollIntoView ignores `block`.
305
- MINIMUM_NIGHTLY_BUILD = Gem::Version.new("10965")
305
+ #
306
+ # 2026-11-05 bump 10965 -> 11647 (= release 1.0.3, the new lockstep cap;
307
+ # the bad-port block #4430 at 11651, CORS exposed headers #4242 at 11663
308
+ # and the x86_64 macOS CPU baseline #4450 at 11672 stay above it).
309
+ # Retired or ungated by it:
310
+ # #4124 (11097) native anchor downloads — Node#click no longer asks a
311
+ # version gate before skipping its own navigation for a download
312
+ # link; that gate wanted release 1.1.0 although 1.0.3 carries it.
313
+ # Rides along: CSS nesting #3962 (10976), blank-page timers #4148
314
+ # (11012), ShadowRoot hit testing #4184 (11071), same-document
315
+ # navigateToHistoryEntry #3903 (11113), native isContentEditable #4210
316
+ # (11229), contenteditable Backspace/Delete/Ctrl+A #4415 (11610).
317
+ MINIMUM_NIGHTLY_BUILD = Gem::Version.new("11647")
306
318
 
307
319
  # Lines of browser output #output keeps (ferrum keeps the same 100).
308
320
  OUTPUT_LINES = 100
@@ -314,36 +326,47 @@ module Capybara
314
326
  # bare "0.3.6" carrying no commit counter at all, and MINIMUM_NIGHTLY_BUILD
315
327
  # has nothing to compare against. Releases are cut from the same trunk, so
316
328
  # a release is acceptable exactly when its own commit count clears the
317
- # nightly floor. 1.0.2 (2026-10-23) is build 10965 — exactly the nightly
329
+ # nightly floor. 1.0.3 (2026-11-05) is build 11647 — exactly the nightly
318
330
  # floor, which is no accident: the floor was raised *to* the release so
319
- # both channels gate the same commit. (1.0.1 = 10641 predates fixes the
331
+ # both channels gate the same commit. (1.0.2 = 10965 predates fixes the
320
332
  # floor exists for.)
321
333
  #
322
334
  # INVARIANT: every MINIMUM_NIGHTLY_BUILD bump must also move this to the
323
335
  # first release containing that build (`git rev-list --count <tag>` in the
324
336
  # browser repo tells you). Leaving it behind would let the release channel
325
337
  # silently accept a binary the nightly channel rejects.
326
- MINIMUM_RELEASE = Gem::Version.new("1.0.2")
338
+ MINIMUM_RELEASE = Gem::Version.new("1.0.3")
339
+
340
+ # A release-candidate binary: "<x.y.z>-rc<N>.<git rev-list --count>+<hash>".
341
+ # Captures the commit counter.
342
+ RC_VERSION = /\A\d+\.\d+\.\d+-rc\d+\.(\d+)\+\h+\z/
327
343
 
328
344
  class << self
329
- # `lightpanda version` prints one of two shapes, and the gem supports
330
- # both so a suite can either track nightly or pin a reproducible
331
- # release:
345
+ # `lightpanda version` prints one of three shapes, and the gem supports
346
+ # all of them so a suite can track nightly, try a release candidate or
347
+ # pin a reproducible release:
332
348
  #
333
349
  # "1.0.0-nightly.8285+de85a51d" rolling nightly (also "dev.NNNN" for
334
350
  # a locally compiled tree — same
335
351
  # `git rev-list --count HEAD` counter,
336
352
  # different label). Checked against
337
353
  # MINIMUM_NIGHTLY_BUILD.
354
+ # "1.0.4-rc1.11801+1b60dcc7a" a release candidate (tag x.y.z-rcN,
355
+ # upstream #4480). build.zig's
356
+ # resolveVersion enriches any
357
+ # pre-release tag with the same commit
358
+ # counter, so it is checked against
359
+ # MINIMUM_NIGHTLY_BUILD like a nightly
360
+ # — its x.y.z is the release it leads
361
+ # up to, not one that exists yet.
338
362
  # "0.3.5" a tagged release: bare semver, no
339
363
  # build metadata. Checked against
340
364
  # MINIMUM_RELEASE.
341
365
  #
342
- # The release form is matched anchored — a bare semver and nothing else
343
- # — so a stray "1.2.3" inside some other string can never be mistaken
344
- # for a release. Anything that matches neither shape stays a hard
345
- # failure: a version we cannot identify is never assumed to be new
346
- # enough.
366
+ # The release and RC forms are matched anchored, so a stray "1.2.3" or
367
+ # "rc1.99999" inside some other string can never be mistaken for one.
368
+ # Anything that matches none of the shapes stays a hard failure: a
369
+ # version we cannot identify is never assumed to be new enough.
347
370
  #
348
371
  # Lives on the class, not the instance, because there are two ways to
349
372
  # learn a version and only one of them involves a Process: the spawn
@@ -359,7 +382,7 @@ module Capybara
359
382
  def check_version!(raw)
360
383
  version = raw.to_s.strip
361
384
 
362
- if (build = version[/(?:nightly|dev)\.(\d+)/, 1])
385
+ if (build = version[/(?:nightly|dev)\.(\d+)/, 1] || version[RC_VERSION, 1])
363
386
  nightly_build = Gem::Version.new(build)
364
387
  return [version, nightly_build, nil] if nightly_build >= MINIMUM_NIGHTLY_BUILD
365
388
  elsif (tag = version[/\A\d+\.\d+\.\d+\z/])
@@ -389,6 +412,7 @@ module Capybara
389
412
  @stderr_r = nil
390
413
  @stderr_w = nil
391
414
  @finalizer_registered = false
415
+ @reaped = false
392
416
  @output = []
393
417
  @output_partial = {}
394
418
  @output_mutex = Mutex.new
@@ -414,20 +438,34 @@ module Capybara
414
438
  attempt_start(binary_path)
415
439
  end
416
440
 
441
+ # A reaped pid is never signalled: the kernel may already have handed it
442
+ # (and its process group id) to an unrelated process. The finalizer is
443
+ # disarmed for the same reason — left armed, it TERMed whatever owned the
444
+ # stale pid whenever GC got round to this object.
417
445
  def stop
418
446
  return unless @pid
419
447
 
420
- self.class.send(:terminate, @pid)
448
+ self.class.send(:terminate, @pid) unless @reaped
449
+ disarm_finalizer
421
450
  cleanup_pipes
422
451
  @pid = nil
423
452
  end
424
453
 
454
+ # A crashed Lightpanda is a zombie until someone reaps it, and `kill(0)`
455
+ # succeeds on a zombie, so probing with a signal reported a dead browser
456
+ # as alive and Browser#restart_process_if_dead never restarted it. Reap
457
+ # instead: `waitpid(WNOHANG)` returns the pid once the child has exited.
458
+ # ECHILD means it was already reaped elsewhere — gone either way.
425
459
  def alive?
426
460
  return false unless @pid
461
+ return false if @reaped
427
462
 
428
- ::Process.kill(0, @pid)
429
- true
430
- rescue Errno::ESRCH, Errno::EPERM
463
+ return true unless ::Process.wait(@pid, ::Process::WNOHANG)
464
+
465
+ @reaped = true
466
+ false
467
+ rescue Errno::ECHILD
468
+ @reaped = true
431
469
  false
432
470
  end
433
471
 
@@ -448,6 +486,7 @@ module Capybara
448
486
  @stderr_r, @stderr_w = IO.pipe
449
487
 
450
488
  @pid = spawn_process(binary_path)
489
+ @reaped = false
451
490
  register_finalizer(@pid)
452
491
 
453
492
  @stdout_w.close
@@ -704,11 +743,16 @@ module Capybara
704
743
  # `undefine_finalizer + define_finalizer` so the finalizer always
705
744
  # references the most recently started process.
706
745
  def register_finalizer(pid)
707
- ObjectSpace.undefine_finalizer(self) if @finalizer_registered
746
+ disarm_finalizer
708
747
  ObjectSpace.define_finalizer(self, self.class.send(:weak_kill, pid))
709
748
  @finalizer_registered = true
710
749
  end
711
750
 
751
+ def disarm_finalizer
752
+ ObjectSpace.undefine_finalizer(self) if @finalizer_registered
753
+ @finalizer_registered = false
754
+ end
755
+
712
756
  def cleanup_pipes
713
757
  [@stdout_r, @stdout_w, @stderr_r, @stderr_w].each do |pipe|
714
758
  pipe&.close unless pipe&.closed?
@@ -42,6 +42,16 @@ module Capybara
42
42
  def self.monotonic_time
43
43
  ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
44
44
  end
45
+
46
+ # A point `seconds` from now on the monotonic clock.
47
+ def self.deadline(seconds)
48
+ monotonic_time + seconds
49
+ end
50
+
51
+ # Seconds left before `deadline`, never negative.
52
+ def self.remaining(deadline)
53
+ [deadline - monotonic_time, 0].max
54
+ end
45
55
  end
46
56
  end
47
57
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Capybara
4
4
  module Lightpanda
5
- VERSION = "0.16.0"
5
+ VERSION = "0.17.1"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: capybara-lightpanda
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.16.0
4
+ version: 0.17.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Navid Emad