capybara-lightpanda 0.17.0 → 0.18.0

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: c3e05fa2b4d3b676fc6dfdd88fb5c4c65b7c2d84ae979a3c6b2cc6bcfddbd712
4
- data.tar.gz: ded427c3ae0148dc351d7b43ade13daf7c4f8aebc1c6492c0480b5a146d116f9
3
+ metadata.gz: 9462d0c1ee74b98cb8422cd7cefd2f6b332ca792c13ebddfb60b9b609cf40d4c
4
+ data.tar.gz: 617842c42afe642ce0e9509199a990a4202437c6dbd4744899307bc973766095
5
5
  SHA512:
6
- metadata.gz: a7d53b5fa0e8d971ca16b9d82a96b65c313e1663313775959b226f97d530e8c84ee19d33b4ec085983bb5d659ff262de97aa6d2501b24ffe0df25755589dae9b
7
- data.tar.gz: c2bf56759b971c045a46a589c0b6bcfa31ee2de84c6f995b62731c973b99dec8b03fb9d10f22c4e4a445673ae3c1659ddfc87dd2ea19a5a32ccc9491097993d6
6
+ metadata.gz: c5e7dd3c1e2ed78bfc47f060b28a60960dbea91b34e830f32d4f0630b478fe5dc960554bf7de2c1be565f1b71061e29517c6d164570f61230d49220a963cef17
7
+ data.tar.gz: f3fb19c8dba1b2e93755de720bc90e86cd51657ec80864f8cfd696ddcd89732d2921f6a159c3fde58215614f639122d54cff1de87d9054f4a2492492e36c774a
data/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.18.0] - 2026-11-16
4
+
5
+ > **Update Lightpanda before upgrading.** This release requires Lightpanda **1.0.4** or a nightly build ≥ 12015. The driver refuses anything older and names the version it found. Pin `1.0.4` for a reproducible browser. On Intel Macs, Lightpanda 1.0.3 crashes on the first HTTPS request; 1.0.4 fixes that.
6
+
7
+ ### Fixed
8
+
9
+ - **`visit` waits for the page's JavaScript.** With a recent Lightpanda, `visit` could return before deferred and module scripts (Stimulus controllers, Turbo) had run, when the page took more than 2 seconds to load. The next `click` or `fill_in` then hit a page whose handlers weren't attached yet and was silently lost. `visit` now waits until those scripts have run.
10
+ - **`send_keys` on a rich-text editor types after the existing text.** On a `contenteditable` element that already held text, `send_keys` used to type in front of it ("xEdit me" instead of "Edit mex"). It now appends, as Chrome and WebDriver do.
11
+ - **A page with an iframe no longer lets `visit` or `click` move on too early.** When an iframe (an embedded widget, a video, a tweet) finished loading before the page itself, `visit` and a `click` that navigated returned while the page's own scripts were still pending, so the next click could do nothing. Seen on Forem: the comment menu never opened. They now wait for the page itself.
12
+ - **Text failure messages say what was searched for.** When no element held the text, `find("li", text: "…")` failed with just `Unable to find css "li"`. It now reads `Unable to find visible css "li" with text "…"`, and `assert_selector` lists the elements it rejected ("Also found …").
13
+
14
+ ## [0.17.1] - 2026-11-08
15
+
16
+ ### Fixed
17
+
18
+ - **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.
19
+ - **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.
20
+ - **`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.
21
+ - **`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.
22
+ - **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.
23
+ - **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.
24
+ - **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.
25
+
3
26
  ## [0.17.0] - 2026-11-05
4
27
 
5
28
  > **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.
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.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).
60
+ > For reproducible CI, pin the browser: `Capybara::Lightpanda::Binary.required_version = "1.0.4"` (the tagged release the gem's current floor is pinned to — nightly build 12015 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,8 +122,13 @@ module Capybara
122
122
 
123
123
  # Common navigation lifecycle shared by `wait_for_page_load` (fresh
124
124
  # `Page.navigate`) and `wait_for_navigation` (reload).
125
- # Subscribes to Page.loadEventFired, runs the trigger, waits briefly for
126
- # the event, falls back to readyState polling for the remaining budget.
125
+ # Subscribes to the main frame's load, runs the trigger, waits briefly
126
+ # for it, falls back to readyState polling for the remaining budget.
127
+ # The load is Page.frameStoppedLoading for the main frame, which
128
+ # Lightpanda sends right after Page.loadEventFired: that one carries no
129
+ # frameId and comes for every frame, so an iframe that loaded first
130
+ # made `visit` return while the page's deferred scripts were pending
131
+ # (forem's comment dropdown; visit_readiness_test.rb).
127
132
  # The handler is unsubscribed via `ensure` so a raising trigger doesn't
128
133
  # leak a subscription onto the next navigation. Returns the deadline so
129
134
  # the caller can decide whether to attempt crash recovery.
@@ -131,8 +136,8 @@ module Capybara
131
136
  starting_url = safe_current_url
132
137
  deadline = monotonic_time + @options.timeout
133
138
  loaded = Utils::Event.new
134
- handler = proc { loaded.set }
135
- @client.on("Page.loadEventFired", &handler)
139
+ handler = proc { |params| loaded.set if params["frameId"] == @target_id }
140
+ @client.on("Page.frameStoppedLoading", &handler)
136
141
 
137
142
  begin
138
143
  yield
@@ -142,7 +147,7 @@ module Capybara
142
147
  poll_ready_state(remaining, loaded_event: loaded, starting_url: starting_url) if remaining.positive?
143
148
  end
144
149
  ensure
145
- @client.off("Page.loadEventFired", handler)
150
+ @client.off("Page.frameStoppedLoading", handler)
146
151
  end
147
152
 
148
153
  deadline
@@ -169,7 +174,18 @@ module Capybara
169
174
  # decide whether the session is recoverable.
170
175
  end
171
176
 
172
- POLL_STATE_JS = "(function(){return{r:document.readyState,u:location.href}})()"
177
+ # `d` says whether DOMContentLoaded has fired, read from the navigation
178
+ # timing entry (null when the page has none). Since Lightpanda #4554
179
+ # (11988) readyState is `interactive` from the end of parsing, while
180
+ # deferred and module scripts (Stimulus, Turbo) are still pending;
181
+ # DOMContentLoaded waits for them. Legacy `performance.timing` can't
182
+ # stand in: Lightpanda keeps every field at 0.
183
+ POLL_STATE_JS = <<~JS.delete("\n")
184
+ (function(){
185
+ var p=window.performance,e=p&&p.getEntriesByType?p.getEntriesByType("navigation")[0]:null;
186
+ return{r:document.readyState,u:location.href,d:e?e.domContentLoadedEventStart>0:null}
187
+ })()
188
+ JS
173
189
  private_constant :POLL_STATE_JS
174
190
 
175
191
  def page_ready?(cmd_timeout, starting_url)
@@ -183,10 +199,19 @@ module Capybara
183
199
  return false unless state
184
200
 
185
201
  url_changed = starting_url.nil? || state["u"] != starting_url
186
- url_changed && %w[complete interactive].include?(state["r"])
202
+ url_changed && ready_state_loaded?(state["r"], state["d"])
187
203
  rescue Error
188
204
  false
189
205
  end
206
+
207
+ # `interactive` still counts once DOMContentLoaded fired: a page whose
208
+ # load event never comes (a hanging subresource) is usable then, and
209
+ # must not cost the whole timeout. Without a timing entry, trust it.
210
+ def ready_state_loaded?(ready_state, dom_content_loaded)
211
+ return true if ready_state == "complete"
212
+
213
+ ready_state == "interactive" && dom_content_loaded != false
214
+ end
190
215
  end
191
216
  end
192
217
  end
@@ -91,8 +91,14 @@ module Capybara
91
91
  evaluate_async(script.to_s.strip, *, frame: frame_stack.last)
92
92
  end
93
93
 
94
- # Selenium's raw-CDP escape hatch, as used by
95
- # `page.driver.browser.execute_cdp("Network.setBlockedURLs", urls: [...])`.
94
+ # Selenium's raw-CDP escape hatch,
95
+ # `page.driver.browser.execute_cdp(method, **params)`. The parameters
96
+ # are Lightpanda's, not Chrome's: a suite's
97
+ # `execute_cdp("Network.setBlockedURLs", urls: [...])` gets InvalidParams,
98
+ # because Lightpanda takes only
99
+ # `urlPatterns: [{ urlPattern: "*.png", block: true }]`. That list is
100
+ # also browser-wide and survives `reset!`, so clear it
101
+ # (`urlPatterns: []`) when the test that set it is done.
96
102
  # Scoped to the page session, matching Selenium — that covers the
97
103
  # Page / Runtime / DOM / Network / Emulation domains a suite would
98
104
  # reach for. Browser-scoped commands (Target.*, Browser.*) still go
@@ -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).
@@ -307,6 +319,11 @@ module Capybara
307
319
  return if @page_events_enabled
308
320
 
309
321
  page_command("Page.enable")
322
+ # Page.domContentEventFired and Page.loadEventFired carry no frameId
323
+ # and Lightpanda sends them for every frame: an iframe's load reads
324
+ # as the page's. Page.lifecycleEvent names its frame, so readiness
325
+ # waits use it instead (see #subscribe_to_document_ready).
326
+ page_command("Page.setLifecycleEventsEnabled", enabled: true)
310
327
  @page_events_enabled = true
311
328
  end
312
329
 
@@ -521,7 +538,7 @@ module Capybara
521
538
 
522
539
  # Internal lifecycle steps defined above near their topical groups —
523
540
  # calling them out of order corrupts session state, so they are not API.
524
- private :create_browser_context, :create_page, :clear_session_state,
541
+ private :connect, :create_browser_context, :create_page, :clear_session_state,
525
542
  :enable_page_events
526
543
 
527
544
  private
@@ -672,9 +689,17 @@ module Capybara
672
689
  end
673
690
 
674
691
  # The new document's context exists before its deferred and module
675
- # scripts have run: this event marks the end of that phase, at
676
- # Page.domContentEventFired or anything later that proves it is over
677
- # (load, the frame stopping, the document request failing).
692
+ # scripts have run: this event marks the end of that phase, at the main
693
+ # frame's DOMContentLoaded or anything later that proves it is over
694
+ # (load, the frame stopping, the document request failing). Only the
695
+ # main frame counts: Page.domContentEventFired/loadEventFired carry no
696
+ # frameId and Lightpanda also sends them for iframes, so an iframe that
697
+ # finished first ended this wait while the page's deferred scripts were
698
+ # still pending (visit_readiness_test.rb). Page.lifecycleEvent names its
699
+ # frame; enable_page_events turns it on.
700
+ MAIN_FRAME_READY_EVENTS = %w[DOMContentLoaded load].freeze
701
+ private_constant :MAIN_FRAME_READY_EVENTS
702
+
678
703
  def subscribe_to_document_ready
679
704
  @document_ready_event = Utils::Event.new
680
705
  @document_ready_event.set
@@ -682,8 +707,11 @@ module Capybara
682
707
  on("Page.frameStartedNavigating") do |params|
683
708
  @document_ready_event.reset if main_frame_navigation_start?(params)
684
709
  end
685
- on("Page.domContentEventFired") { @document_ready_event.set }
686
- on("Page.loadEventFired") { @document_ready_event.set }
710
+ on("Page.lifecycleEvent") do |params|
711
+ next unless params["frameId"] == @target_id
712
+
713
+ @document_ready_event.set if MAIN_FRAME_READY_EVENTS.include?(params["name"])
714
+ end
687
715
  on("Page.frameStoppedLoading") do |params|
688
716
  @document_ready_event.set if params["frameId"] == @target_id
689
717
  end
@@ -56,19 +56,31 @@ module Capybara
56
56
  # connection (status :closed or :error) without closing the socket,
57
57
  # and an early return here then left the TCPSocket — one descriptor
58
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.
59
64
  def close
60
65
  unless @status == :closed
61
66
  @status = :closing
62
67
  @messages.close
63
- @driver_mutex.synchronize { @driver&.close }
68
+ begin
69
+ @driver_mutex.synchronize { @driver&.close }
70
+ rescue DeadBrowserError
71
+ nil
72
+ end
64
73
  @thread&.join(1) || @thread&.kill
65
74
  end
66
75
  close_socket
67
76
  @status = :closed
68
77
  end
69
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.
70
82
  def closed?
71
- @status == :closed || @status == :error
83
+ %i[closed closing error].include?(@status)
72
84
  end
73
85
 
74
86
  # Called by websocket-driver, always under @driver_mutex. A browser
@@ -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
 
@@ -192,6 +192,8 @@ function visibleText(el) {
192
192
  // indexed loops: an overridden map must never detach cache rows from node IDs.
193
193
  var hintStringify = JSON.stringify;
194
194
  var hintLowerCase = Function.prototype.call.bind(String.prototype.toLowerCase);
195
+ // Candidates kept when none holds the searched text (see findHints).
196
+ var HINT_FAILURE_CANDIDATES = 10;
195
197
 
196
198
  // Capybara keeps Result candidates for lazy enumeration, possibly after the DOM
197
199
  // changes. Only immutable tag names belong in initial_cache; mutable visibility,
@@ -236,6 +238,21 @@ function findHints(nodes, spec) {
236
238
  kept[kept.length] = el;
237
239
  }
238
240
  }
241
+ // No candidate holds the text: hand Capybara the first few anyway. It
242
+ // builds its failure message from the candidates it filtered out itself,
243
+ // so an empty array drops "visible"/"with text" and the "Also found" list.
244
+ // Capybara still rejects each one on its own text check, so results don't
245
+ // change. The cap bounds what a passing negative assertion pays: each kept
246
+ // candidate costs a visibility and a text read.
247
+ if (needles.length && kept.length === 0) {
248
+ var shown = nodes.length < HINT_FAILURE_CANDIDATES ? nodes.length : HINT_FAILURE_CANDIDATES;
249
+ for (var m = 0; m < shown; m++) {
250
+ var node = nodes[m];
251
+ hints[m] = { tag_name: node.nodeType === 11 ? 'ShadowRoot' :
252
+ (node.tagName ? hintLowerCase(node.tagName) : '') };
253
+ kept[m] = node;
254
+ }
255
+ }
239
256
  // Publish only after every read succeeds. Any exception returns the exact
240
257
  // original array, without partial filtering or partially constructed hints.
241
258
  kept.__lightpandaHints = hintStringify(hints);
@@ -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) }
@@ -1019,6 +1019,13 @@ module Capybara
1019
1019
  # A non-focusable target (focus() is a no-op on those since upstream
1020
1020
  # #3592, build 9646) must not leave the previous field focused, or its
1021
1021
  # keys land there: blur it so they go to the body, as in Chrome.
1022
+ #
1023
+ # An editing host gets the same treatment: Lightpanda's focus() collapses
1024
+ # the caret at the host's first position (upstream #4538), so a draft
1025
+ # already in the editor took the keys in front of it. The caret goes
1026
+ # after the last non-blank text, inside its <p>, the position Chrome
1027
+ # normalizes WebDriver's collapsed end-of-contents range to; a host with
1028
+ # no text gets the end of its children.
1022
1029
  SEND_KEYS_FOCUS_JS = <<~JS
1023
1030
  function() {
1024
1031
  var doc = this.ownerDocument;
@@ -1035,6 +1042,16 @@ module Capybara
1035
1042
  var end = String(this.value || '').length;
1036
1043
  this.setSelectionRange(end, end);
1037
1044
  } catch (e) {}
1045
+ } else if (this.isContentEditable) {
1046
+ var sel = doc.defaultView && doc.defaultView.getSelection();
1047
+ if (!sel) return;
1048
+ var last = null;
1049
+ var walker = doc.createTreeWalker(this, 4 /* NodeFilter.SHOW_TEXT */);
1050
+ while (walker.nextNode()) {
1051
+ if (/\\S/.test(walker.currentNode.data)) last = walker.currentNode;
1052
+ }
1053
+ if (last) sel.collapse(last, last.data.length);
1054
+ else sel.collapse(this, this.childNodes.length);
1038
1055
  }
1039
1056
  }
1040
1057
  JS
@@ -314,7 +314,20 @@ module Capybara
314
314
  # (11012), ShadowRoot hit testing #4184 (11071), same-document
315
315
  # navigateToHistoryEntry #3903 (11113), native isContentEditable #4210
316
316
  # (11229), contenteditable Backspace/Delete/Ctrl+A #4415 (11610).
317
- MINIMUM_NIGHTLY_BUILD = Gem::Version.new("11647")
317
+ #
318
+ # 2026-11-16 bump 11647 -> 12015 (= release 1.0.4, the new lockstep cap;
319
+ # inert-aware hit testing #4548 at 12019 and xhr.upload events #4529 at
320
+ # 12116 stay above it). The reason: 1.0.3's x86_64-macos binary has no
321
+ # CPU baseline and dies with SIGILL on the first HTTPS request on CPUs
322
+ # without ADX (#4433); the baseline #4450 (11672) first ships in 1.0.4.
323
+ # Rides along: bad-port block #4430 (11651), CORS exposed headers #4242
324
+ # (11663), postMessage targetOrigin #4382 (11676), cross-site SameSite
325
+ # cookies #4442 (11688), multi-target CDP #3945 (11844), apple_m1 CPU pin
326
+ # #4533 (11915), readyState `interactive` before deferred scripts #4554
327
+ # (11988), CSS animation events opt-in #4559 (11991). No version gate
328
+ # sat between the two floors, so nothing is retired. Validated on the
329
+ # 1.0.4 aarch64-macos binary: test:all and spec:shared:parallel green.
330
+ MINIMUM_NIGHTLY_BUILD = Gem::Version.new("12015")
318
331
 
319
332
  # Lines of browser output #output keeps (ferrum keeps the same 100).
320
333
  OUTPUT_LINES = 100
@@ -326,36 +339,47 @@ module Capybara
326
339
  # bare "0.3.6" carrying no commit counter at all, and MINIMUM_NIGHTLY_BUILD
327
340
  # has nothing to compare against. Releases are cut from the same trunk, so
328
341
  # a release is acceptable exactly when its own commit count clears the
329
- # nightly floor. 1.0.3 (2026-11-05) is build 11647 — exactly the nightly
342
+ # nightly floor. 1.0.4 (2026-11-13) is build 12015 — exactly the nightly
330
343
  # floor, which is no accident: the floor was raised *to* the release so
331
- # both channels gate the same commit. (1.0.2 = 10965 predates fixes the
332
- # floor exists for.)
344
+ # both channels gate the same commit. (1.0.3 = 11647 predates the
345
+ # x86_64-macos CPU baseline the floor exists for.)
333
346
  #
334
347
  # INVARIANT: every MINIMUM_NIGHTLY_BUILD bump must also move this to the
335
348
  # first release containing that build (`git rev-list --count <tag>` in the
336
349
  # browser repo tells you). Leaving it behind would let the release channel
337
350
  # silently accept a binary the nightly channel rejects.
338
- MINIMUM_RELEASE = Gem::Version.new("1.0.3")
351
+ MINIMUM_RELEASE = Gem::Version.new("1.0.4")
352
+
353
+ # A release-candidate binary: "<x.y.z>-rc<N>.<git rev-list --count>+<hash>".
354
+ # Captures the commit counter.
355
+ RC_VERSION = /\A\d+\.\d+\.\d+-rc\d+\.(\d+)\+\h+\z/
339
356
 
340
357
  class << self
341
- # `lightpanda version` prints one of two shapes, and the gem supports
342
- # both so a suite can either track nightly or pin a reproducible
343
- # release:
358
+ # `lightpanda version` prints one of three shapes, and the gem supports
359
+ # all of them so a suite can track nightly, try a release candidate or
360
+ # pin a reproducible release:
344
361
  #
345
362
  # "1.0.0-nightly.8285+de85a51d" rolling nightly (also "dev.NNNN" for
346
363
  # a locally compiled tree — same
347
364
  # `git rev-list --count HEAD` counter,
348
365
  # different label). Checked against
349
366
  # MINIMUM_NIGHTLY_BUILD.
367
+ # "1.0.4-rc1.11801+1b60dcc7a" a release candidate (tag x.y.z-rcN,
368
+ # upstream #4480). build.zig's
369
+ # resolveVersion enriches any
370
+ # pre-release tag with the same commit
371
+ # counter, so it is checked against
372
+ # MINIMUM_NIGHTLY_BUILD like a nightly
373
+ # — its x.y.z is the release it leads
374
+ # up to, not one that exists yet.
350
375
  # "0.3.5" a tagged release: bare semver, no
351
376
  # build metadata. Checked against
352
377
  # MINIMUM_RELEASE.
353
378
  #
354
- # The release form is matched anchored — a bare semver and nothing else
355
- # — so a stray "1.2.3" inside some other string can never be mistaken
356
- # for a release. Anything that matches neither shape stays a hard
357
- # failure: a version we cannot identify is never assumed to be new
358
- # enough.
379
+ # The release and RC forms are matched anchored, so a stray "1.2.3" or
380
+ # "rc1.99999" inside some other string can never be mistaken for one.
381
+ # Anything that matches none of the shapes stays a hard failure: a
382
+ # version we cannot identify is never assumed to be new enough.
359
383
  #
360
384
  # Lives on the class, not the instance, because there are two ways to
361
385
  # learn a version and only one of them involves a Process: the spawn
@@ -371,7 +395,7 @@ module Capybara
371
395
  def check_version!(raw)
372
396
  version = raw.to_s.strip
373
397
 
374
- if (build = version[/(?:nightly|dev)\.(\d+)/, 1])
398
+ if (build = version[/(?:nightly|dev)\.(\d+)/, 1] || version[RC_VERSION, 1])
375
399
  nightly_build = Gem::Version.new(build)
376
400
  return [version, nightly_build, nil] if nightly_build >= MINIMUM_NIGHTLY_BUILD
377
401
  elsif (tag = version[/\A\d+\.\d+\.\d+\z/])
@@ -401,6 +425,7 @@ module Capybara
401
425
  @stderr_r = nil
402
426
  @stderr_w = nil
403
427
  @finalizer_registered = false
428
+ @reaped = false
404
429
  @output = []
405
430
  @output_partial = {}
406
431
  @output_mutex = Mutex.new
@@ -426,20 +451,34 @@ module Capybara
426
451
  attempt_start(binary_path)
427
452
  end
428
453
 
454
+ # A reaped pid is never signalled: the kernel may already have handed it
455
+ # (and its process group id) to an unrelated process. The finalizer is
456
+ # disarmed for the same reason — left armed, it TERMed whatever owned the
457
+ # stale pid whenever GC got round to this object.
429
458
  def stop
430
459
  return unless @pid
431
460
 
432
- self.class.send(:terminate, @pid)
461
+ self.class.send(:terminate, @pid) unless @reaped
462
+ disarm_finalizer
433
463
  cleanup_pipes
434
464
  @pid = nil
435
465
  end
436
466
 
467
+ # A crashed Lightpanda is a zombie until someone reaps it, and `kill(0)`
468
+ # succeeds on a zombie, so probing with a signal reported a dead browser
469
+ # as alive and Browser#restart_process_if_dead never restarted it. Reap
470
+ # instead: `waitpid(WNOHANG)` returns the pid once the child has exited.
471
+ # ECHILD means it was already reaped elsewhere — gone either way.
437
472
  def alive?
438
473
  return false unless @pid
474
+ return false if @reaped
475
+
476
+ return true unless ::Process.wait(@pid, ::Process::WNOHANG)
439
477
 
440
- ::Process.kill(0, @pid)
441
- true
442
- rescue Errno::ESRCH, Errno::EPERM
478
+ @reaped = true
479
+ false
480
+ rescue Errno::ECHILD
481
+ @reaped = true
443
482
  false
444
483
  end
445
484
 
@@ -460,6 +499,7 @@ module Capybara
460
499
  @stderr_r, @stderr_w = IO.pipe
461
500
 
462
501
  @pid = spawn_process(binary_path)
502
+ @reaped = false
463
503
  register_finalizer(@pid)
464
504
 
465
505
  @stdout_w.close
@@ -716,11 +756,16 @@ module Capybara
716
756
  # `undefine_finalizer + define_finalizer` so the finalizer always
717
757
  # references the most recently started process.
718
758
  def register_finalizer(pid)
719
- ObjectSpace.undefine_finalizer(self) if @finalizer_registered
759
+ disarm_finalizer
720
760
  ObjectSpace.define_finalizer(self, self.class.send(:weak_kill, pid))
721
761
  @finalizer_registered = true
722
762
  end
723
763
 
764
+ def disarm_finalizer
765
+ ObjectSpace.undefine_finalizer(self) if @finalizer_registered
766
+ @finalizer_registered = false
767
+ end
768
+
724
769
  def cleanup_pipes
725
770
  [@stdout_r, @stdout_w, @stderr_r, @stderr_w].each do |pipe|
726
771
  pipe&.close unless pipe&.closed?
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Capybara
4
4
  module Lightpanda
5
- VERSION = "0.17.0"
5
+ VERSION = "0.18.0"
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.17.0
4
+ version: 0.18.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Navid Emad